Recently asked such a question.
What is faster in Mongo: a populate or individual assync requests?
Example
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var FeedPostCommentSchema = new Schema({
feedPost: {type: Schema.Types.ObjectId, ref: 'FeedPost', index: true},
user: {type: Schema.Types.ObjectId, ref: 'User'},
comment: {
type: String,
trim: true
},
updated: {type: Date, default: Date.now},
created: {type: Date, default: Date.now, index: true}
});
mongoose.model('FeedPostComment', FeedPostCommentSchema);
When displaying all the comments, we also need to get user data
We can make it standard populate method:
FeedPostComment.find({feedPost: req.params.postId}).populate('user')
.skip(skip)
.limit(limit)
.sort({created: -1})
.lean()
.exec()
We can also do this with parallel queries:
FeedPostComment.find({feedPost: req.params.postId})
.skip(skip)
.limit(limit)
.sort({created: -1})
.lean()
.exec(function (err, comments) {
async.each(comments, function (comment, cb) {
User.findById(comment.user, function (err, composer) {
if (err) {
return cb(err);
}
comment.user = utils.getPublicDataOfUser(composer);
cb();
});
}, function (err) {
comments.reverse();
});
});