I am trying to search data from collection.
Model for 'USER' collection:
var model = new Schema({
userName: String,
password: String
});
module.exports = mongoose.model('user', model);
Model for 'BLOG'
var model = new Schema({
title: String,
createdBy: { type: Object, ref: 'user' }
});
module.exports = mongoose.model('blog', model);
My search code for blog collection:
objModel.find({ 'createdBy.userName': 'test_user' }).populate('createdBy')
.exec(function (err, lstBlog) {
console.log(lstBlog.length);
});
But not able to get any record. There are 2 record in database for 'test_user'.
You need to make some changes in your 'BLOG' model :
var mongoose = require('mongoose');
var SCHEMA = mongoose.Schema;
var model = new Schema({
title: String,
createdBy: { type: SCHEMA.Types.ObjectId, ref: 'user' }
});
module.exports = mongoose.model('blog', model);
and then the following query will work
blog.find({}).populate(
{
path: 'createdBy',
match: {'userName': 'test_user' }
}
).exec(function (err, lstBlog) {
console.log(lstBlog.length);
});;
Related
I have a student collection when I want to report on a particular student with
studentId the report must be stored in report collection along with studentId
and what report I gave.I want to use individual collections
here is student schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var studentSchema = new Schema({
name: {
type: String,
required: true
},
dateofbirth: {
type: Date,
required: true
},
schoolname:
{
type:String,
required:true
},
standard:
{
type: Number,
required:true
}
}, {
timestamps: true
});
and here is report schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var reportSchema = new Schema({
date: {
type:Date,
required:true
},
comment:
{
type:String,
required:true
}
},
{
timestamps: true
});
var Report = mongoose.model('report', reportSchema);
module.exports = Report;
So how can I retrive studenId from student collection ?And how can I give report to a particular student?
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var studentSchema = new Schema({
name: {type: String, required: true},
dateofbirth: {type: Date, required: true},
schoolname: {type:String, required:true},
standard: {type: Number, required:true},
timestamps: true
});
var reportSchema = new Schema({
date: {type:Date,required:true},
comment: {type:String,required:true}
timestamps: true,
student_id: [{type: String, ref:'student',required: true}] //store your student{_id} relation here ref ==> is just a Collection name
});
mongoose.connect('mongodb://localhost/your_db_name_here', {
// using mongoose client to avoid promises exception
useMongoClient: true,
});
//just making your collection available to next controller.js file
module.exports= {
student : mongoose.model('student',studentSchema ),
report: mongoose.model('report', reportSchema)
};
controller.js I have been using express.js for your case
var db = require("./db.js");
var app = require("express")();
app.post("/api/student/register", (req, res) => {
var dbdata = {
name: req.body.name,
.......
}
db.student.create(dbdata, (er, callback) => {
if(er)return res.json("error");
return res.json("successfully inserted");
});
});
app.post("/api/student/report/create", (req, res) => {
//while creating a report you have to pass a Student primary key
var dbdata = {
date: req.body.data;
comment: req.body.comment,
student_id: req.body.student_id
// similar to foreign key relation ship}
}
db.report.create(dbdata, function(er, callback){
if(er)return res.json("err");
return res.json("successfully inserted");
});
});
your answer here
app.post("/particular/student/report", function(req, res){
db.report.find({student_id:"your student id here"}).populate('student_id').exec(function(err, data){
if(err)return res.json("db exception");
return res.json(data); //you will get all your student report for the particular student
});
});
here is
mongoose populate official docs
still if you have some other basic thing about mongoose or mean stack means kinldy refer to https://github.com/Muthukumars1994/Meanapp
I am learning Mongoose, and got struct on pushing data into array blogs.
my schema is
module.exports = function(mongoose) {
var UserSchema = new Schema({
count:String,
_id : {id:false},
blogs: [{ type: Schema.Types.ObjectId, ref: 'Blog' }]
},
{
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
});
var BlogSchema = new Schema({
blogs:[{
post : String,
title: String,
author : String,
userId: {
type: String,
default: function() {
return crypto.randomBytes(12).toString('hex');
}
},
_id: {type: String, required: true}
}],
});
var models = {
User : mongoose.model('User', UserSchema),
Blog : mongoose.model('Blog', BlogSchema)
};
return models;
}
Problem is here userSchema will always have/be a single object, whcih will keep track of count of total blogs.
I know it can be done using findOneAndUpdate but I don't have id/object created for UserSchema.
Any help is appreciated. Thanks
I succeed to make a deep population with find and the search key in first model, but now i want to find by key on the sub object generated by the deep populate.
I have three models : Product, Category, and Event
I want to find my Products by e_fk_club_id that is in Event model
I tried two solutions but they didn't work
First solution in find :
model.find({'categories.events.e_fk_club_id':id})`
Second solution with match :
`$match : { e_fk_club_id : id }`
these are my models
product.js
var ProductSchema = new mongoose.Schema({
p_id: Number,
p_name: String,
p_fk_category: {type: mongoose.Schema.Types.ObjectId, ref: 'categories'},
}
, {collection: 'products'});
module.exports = mongoose.model('products', ProductSchema);
Category.js
var CategorySchema = new mongoose.Schema({
c_id: Number,
c_name: String,
c_fk_event: {type: mongoose.Schema.Types.ObjectId, ref: 'events'},
}
, {collection: 'categories'});
module.exports = mongoose.model('categories', CategorySchema);
Event.js
var EventSchema = new mongoose.Schema({
e_id: Number,
e_name: String,
e_fk_club_id: Number,
}
, {collection: 'events'});
module.exports = mongoose.model('events', EventSchema);
This is the code which i am trying to fetch the data :
getProductsByClub:function (id, callback){
var model = require("Product");
//model
model .find({'categories.events.e_fk_club_id':id})
.populate({
path:'p_fk_category',
model:'categories',
populate:
{
path:'e_fk_event',
model:'events',
//$match : { e_fk_club_id : id }
}
})
.exec (function(err, doc){
if (err) {
callback(err) ;
} else {
callback(doc) ;
}
})
},
Is There any solution.
Thank you in advance.
Below is the code for User model, Post model and the route. I need to query the DB and then pass to the view through the router. What am I missing?
User model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
Posts model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new Schema({
postTitle: {
type: String,
required: true
},
postStory: {
type: String
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model('Post', postSchema);
And here is the query in the router that I'm trying but apparently it's not the way to go...
My GET route:
router.get('/dashboard', isLoggedIn, function(req, res) {
Post.find({author:req.user._id}, (err, posts) => {
if(err) {
console.log(err);
} else {
res.render('users/dashboard', {currentUser: req.user, posts: posts});
}
});
});
What am I missing here?
You may want to change the find query to match the proper attribute in the following line:
Post.find({author: req.user._id}, (err, posts) => {
to be:
Post.find({'author.id': req.user._id}, (err, posts) => {
Read more: http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html
I have two similar parent-child relationship trees in my data model and I am using Mongoose's middleware to handle cascade of deletes.
The first hierarchy is represented as follows:
blog hierarchy
//blog.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.js');
var Entry = require('./entry.js');
var Follower = require('./follower.js');
var Blog = new Schema({
author: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
name: {
type: String,
required: true
},
headerImageUrl: String,
description: {
type: String,
required: true
}
}, {
timestamps: true
});
Blog.pre('remove', function(next) {
Entry.find({"blogId": this._id})
.exec(function(err, entries) {
console.log("found entries " + entries);
for(var i = entries.length -1; i >= 0; i--) {
entries[i].remove();
}
});
Follower.remove({"blogId": this._id}).exec();
next();
});
module.exports = mongoose.model('Blog', Blog);
//entry.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Blog = require('./blog.js');
var Comment = require('./comment.js');
var Entry = new Schema({
blogId: {
type: Schema.Types.ObjectId,
ref: 'Blog'
},
title: String,
thumbnailUrl: String,
content: String
}, {
timestamps: true
});
Entry.pre('remove', function(next) {
Comment.remove({"entryId": this._id}).exec();
next();
});
module.exports = mongoose.model('Entry', Entry);
//comment.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.js');
var Entry = require('./entry.js');
var Post = require('./post.js');
var Comment = new Schema({
text: {
type: String,
required: true
},
postedBy: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
parentComment: this,
entryId: {
type: Schema.Types.ObjectId,
ref: 'Entry'
},
postId: {
type: Schema.Types.ObjectId,
ref: 'Post'
},
type: {
type: String,
enum: ['BLOG', 'FORUM', 'COMMENT'],
required: true
}
}, {
timestamps: true
});
module.exports = mongoose.model('Comment', Comment);
In this case, when remove is called on a blog instance, the Blog.pre('remove'... functionality does what it is intended to do and cleans up all children of the blog instance.
The calling code is as follows:
blogRouter.route('/:blogId')
//delete a specific blog by blog id: [OWNER OR ADMIN USER]
.delete(Verify.verifyOrdinaryUser, Verify.verifyBlogOwnerOrAdmin, function(req, res, next) {
Blog.findById(req.params.blogId, function(err, blog) {
if(err) return next(err);
blog.remove();
res.json(blog);
});
});
I am doing exactly the same thing for the second hierarchy, visually represented here: forum hierarchy and with the following code:
//forum.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.js');
var Post = require('./post.js');
var Subscription = require('./subscription.js');
var Forum = new Schema({
title: {
type: String,
required: true
},
description: String,
moderators: [
{
type: Schema.Types.ObjectId,
ref: 'User'
}
]
}, {
timestamps: true
});
Forum.pre('remove', function(next) {
Post.find({"forumId": this._id})
.exec(function(err, posts) {
console.log("found posts " + posts);
for(var i = posts.length -1; i >= 0; i--) {
posts[i].remove();
}
});
Subscription.remove({"forumId": this._id}).exec();
next();
});
module.exports = mongoose.model('Forum', Forum);
//post.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.js');
var Forum = require('./forum.js');
var Comment = require('./comment.js');
var Post = new Schema({
createdBy: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
postText: {
type: String,
required: true
},
forumId: {
type: Schema.Types.ObjectId,
ref: 'Forum'
},
}, {
timestamps: true
});
Post.pre('remove', function(next) {
Comment.remove({"postId": this._id}).exec();
next();
});
module.exports = mongoose.model('Post', Post);
//comment.js [SAME AS INCLUDED ABOVE]
But in this case, when remove is called on a forum instance, the Forum.pre('remove'... functionality causes an error to be thrown: TypeError: Post.find is not a function. The error is thrown at forum.js line 24 (second line in the Forum.pre(...) block)
The calling code is as follows:
forumRouter.route('/:forumId')
//delete forum by id: [ADMIN]
.delete(Verify.verifyOrdinaryUser, Verify.verifyAdmin, function(req, res, next) {
Forum.findById(req.params.forumId, function(err, forum) {
if(err) return next(err);
forum.remove();
res.json(forum);
});
});
While I have found instance of this error being thrown in my online research here and elsewhere, the causes there were incorrectly exported models or incorrectly defined schemas. The Post schema is being used successfully throughout the rest of my code with no issues, it is only this call to Post.find that is causing the error. And in fact, my postRouter code calls the following successfully:
postRouter.route('/')
// retrieve all forum posts: [ALL USERS]
.get(function(req, res, next) {
Post.find({})
.populate({
path: 'forumId',
model: 'Forum',
populate: {
path: 'moderators',
model: 'User'
}
})
.populate('createdBy')
.exec(function(err, posts){
if(err) return next(err);
res.json(posts);
});
});