How to effectively fetch comments for posts with MongoDB/mongoose? How to effectively fetch comments for posts with MongoDB/mongoose? mongoose mongoose

How to effectively fetch comments for posts with MongoDB/mongoose?


Try to do it through mongoose populate and aggregate. Sample codes as below.

var Post = mongoose.model('Post', PostSchema);var Comment = mongoose.model('Comment', CommentSchema);Comment.aggregate([    {$group: {_id: '$_post', comments: {$push: '$body'}}}    // ...    ], function(err, result) {        if (err)           // error handling        Post.populate(result, {path: "_id"}, function(err, ret) {            if(err)                console.log(err);            else                console.log(ret);        });});