Skip to content

Instantly share code, notes, and snippets.

@pretentiousgit
Last active August 29, 2015 14:06
Show Gist options
  • Save pretentiousgit/53064db01118fed66d50 to your computer and use it in GitHub Desktop.
Save pretentiousgit/53064db01118fed66d50 to your computer and use it in GitHub Desktop.
Populate grandchildren in arrays, Mongoose 3.8.x
Parent.findById(req.params._id).populate('children').exec(function(err, doc){
// note that you have to populate the children here
// or they won't turn up properly later
// even if you substitute all of them with a new document set.
Child.find({'_parent':req.params._id}).populate('grandchildren').exec(function(err, docs){
// note that the child has to know it belongs to the parent in its own schema
// this is technically a totally separate document set.
if(err) res.send(err);
Child.populate(docs, {path: 'grandchildren.greatGrandChildren', model:'GreatGrandChild'}, function(err, data){
// now that you have the technically separate top-level doc set
// you can populate the subdocs and they'll go out just fine.
parent.children = data;
res.json({'parent' : parent})
})
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment