Search code examples
node.jsmongodbmongoosemongoose-populate

Mongoose Populate - array


can someone please help me with population of this schema? I need to populate array of Staff by their userId.

var PlaceSchema = new Schema ({
    name:       { type: String, required: true, trim: true },
    permalink:  { type: String },
    country:    { type: String, required: true },
         ...long story :D...
    staff:      [staffSchema],
    admins:     [adminSchema],
    masterPlace:{ type: Boolean },
    images:     []

});

var staffSchema = new Schema ({
    userId: { type: Schema.Types.ObjectId, ref: 'Account' },
    role: { type: Number }
});

var adminSchema = new Schema ({
    userId: { type: Schema.Types.ObjectId, ref: 'Account'}
})

var Places = mongoose.model('Places', PlaceSchema);

I tried to use this query, but without success.

Places.findOne({'_id' : placeId}).populate('staff.userId').exec(function(err, doc){
    console.log(doc);
});

Solution

  • Polpulation is intended as a method for "pulling in" information from the related models in the collection. So rather than specifying a related field "directly", instead reference the related fields so the document appears to have all of those sub-documents embedded in the response:

    Places.findOne({'_id' : placeId}).populate('staff','_id')
        .exec(function(err, doc){
        console.log(doc);
    });
    

    The second argument just returns the field that you want. So it "filters" the response.

    There is more information on populate in the documentation.