Mongoose populate within an object?

The first solution is possible.

Mongoose currently has limitations (see this ticket here) populating multiple levels of embedded documents, however is very good at understanding nested paths within a single document - what you're after in this case.

Example syntax would be:

YourSchema.find().populate('map_data.location').exec(...)

Other features, such as specifying getters / setters on paths, orderBy and where clauses, etc. also accept a nested paths, like this example from the docs:

personSchema.virtual('name.full').get(function () {
  return this.name.first + ' ' + this.name.last;
});

Internally Mongoose splits the string at the dots and sorts everything out for you.


First option is ok, but if someone would have problems with that query map_data.location - Mongoose returns empty array instead of object - I found that this will work:

.populate({
     path: 'map_data.location',
     model: 'Location'
})

i think you will need this:

if you schema is this:

var sampleSchema = new Schema({
name: String,
map_data: [{
location: {type: Schema.Types.ObjectId, ref: 'location'},
count: Number
}]
});

you monggosse query have to be:

const responseMap=await YourSchema.find()
.populate(
path: 'map_data._id',
model: 'location'
select:['nameLocation','geoPoints','count'],
).exec();
console.log(responseMap);

but you count variable have to be in location schema, and map_data have to containt only id location.


   YourSchema.find()
       .populate({
            path: 'map_data',
            populate: {
                path: 'location' 
            }
    }).exec(...)

The above statement will populate array of map_data and also the location object of each map_data.

hope this helps someone.