Skip to content

Instantly share code, notes, and snippets.

@paulsocal
Created June 9, 2013 19:17
Show Gist options
  • Save paulsocal/5744799 to your computer and use it in GitHub Desktop.
Save paulsocal/5744799 to your computer and use it in GitHub Desktop.
mongoose populate 3 levels deep
var Blogpost = new Schema({
story: 'String',
comments: [{type: ObjectId, ref:'comment', unique: true}]
});
var Comment = new Schema({
comment: 'String',
upvotes: [{type: ObjectId, ref:'user', unique: true}]
});
var User = new Schema({
name: 'String',
friends: [{type: ObjectId, ref:'user'}]
});
db.model('blogpost', Blogpost);
db.model('comment', Comment);
db.model('user', User);
db.models.blogpost.find({}).populate('comment').exec(function(err, posts){
db.models.comment.populate(posts.comment, 'upvotes', function(err, comments){
// populates upvotes with user objects
db.models.user(posts.comment.upvotes, 'friends', function(err, friends){
// doesnt populate friends;
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment