node.js - How to effectively fetch comments for posts with MongoDB/mongoose? -
i have following post , collection documents:
// posts { "_id" : objectid("56978d8cdbc511a81e7e2ea8"), "body" : "post body 1", "created_at" : 1452772748737 }, { "_id" : objectid("56978d3cdbc655b81e7e2e10"), "body" : "post body 2", "created_at" : 1452772759731 } // comments { "_post" : objectid("56978d8cdbc511a81e7e2ea8"), "body" : "comment 1" }, { "_post" : objectid("56978d3cdbc655b81e7e2e10"), "body" : "comment 2" }
i need query posts comments following result:
{ "_id" : objectid("56978d8cdbc511a81e7e2ea8"), "body" : "post body 1", "created_at" : 1452772748737, "comments": [{ "_post" : objectid("56978d8cdbc511a81e7e2ea8"), "body" : "comment 1" }] }, { "_id" : objectid("56978d3cdbc655b81e7e2e10"), "body" : "post body 2", "created_at" : 1452772759731, "comments": [{ "_post" : objectid("56978d3cdbc655b81e7e2e10"), "body" : "comment 2" }] }
my schema post , collections following:
// post var postschema = mongoose.schema({ },{ strict: "throw", collection: "posts" }); postschema.add({ created_at: { type: number, 'default': date.now } }); postschema.add({ title: { type: string } }); postschema.add({ body: { type: string } }); // comment var commentschema = mongoose.schema({ },{ strict: "throw", collection: "comments" }); commentschema.add({ _post: { type: mongoose.schema.types.objectid, ref: 'post' } }); commentschema.add({ body: { type: string } });
what way result above?
try through mongoose populate , aggregate. sample codes 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); }); });
Comments
Post a Comment