Search code examples
node.jsmongodbmongoosemongoose-populate

populate fields of nested object in mongoose schema


I have these two models

var postSchema = new Schema({
  content : String,
  author : [{
    user : {
    type: Schema.ObjectId,
    ref: 'user'
    },
    bool: Boolean
  }]
});


var userSchema = new Schema({
  name : String
});

I'm trying to populate Post with user name instead of the just showing [Object] or the id if i .toString it

what i'm getting at the moment :

{ author: [ [Object], [Object], [Object] ],
    _id: 5aedc4d3c534213279faec79,
    content: 'hello',
    __v: 0 } ]

with .toString() i get

{ author: 
   [ { _id: 5aedc364ce3b022d4ff74922,
       user: 5aedb9e47e055d1ac26aa572,
       bool: true } ]

what i want :

{ author: 
   [ { _id: 5aedc4d3c534213279faec7c,
       user: "Some name here", //( name instead of user _id )
       bool: true },
     { _id: 5aedc4d3c534213279faec7b,
       user: "Some name here",
       bool: false },
     { _id: 5aedc4d3c534213279faec7a,
       user: "Some name here",
       bool: true } ],
  _id: 5aedc4d3c534213279faec79,
  content: 'hello',
  __v: 0 }

is this possible ?


Solution

  • You can use the populate method with the nested syntax

    const Post = mongoose.model('Post', postSchema);
    const User = mongoose.model('User', userSchema);
    
    Post
        .find({})
        .populate({path:'author.user', 'model':'User'})
        .exec((err, posts) => {
            if (err) return next(err);
            posts.forEach(post => {
              console.log(JSON.stringify( post, null, 2) ); // spacing level = 2
            }
        });
    

    Will output for each post (this is not exactly what you required, but hopefully you may have flexibility in the User format

    { 
      _id: 5aedc4d3c534213279faec79,
      content: 'some content',
      author: [ 
        {
        user: {_id: 5aedc4d3c534213279faec7c, "user name here"}
        bool: true 
        },
        {
        user: {_id: 5aedc4d3c534213279faec7b, "user name 2 here"}
        bool: true 
        }
    __v: 0 
    }
    

    Reference for mongoose.populate http://mongoosejs.com/docs/populate.html