I could use some help here, I can’t figure out why the populate method doesn’t work as expected.
I want to model some “rooms” with people inside them.
var PersonSchema = new Schema({
_id : Schema.ObjectId,
name : String,
});
var Person = mongoose.model('Person', PersonSchema, 'Person');
var RoomSchema = new Schema({
_id : Schema.ObjectId,
name : String,
People : [{ type: Schema.ObjectId, ref: 'Person' }],
});
var Room = mongoose.model('Room', RoomSchema, 'Room');
So, I have a Person collection with one entry:
{
"name" : "person1",
"_id" : ObjectId("4f9e5bb68bcd69fb0c000002")
}
and a Room collection with one entry:
{
"_id" : ObjectId("4f9e5bb68bcd69fb0c000001"),
"name" : "room1",
"People" : [ ObjectId("4f9e5bb68bcd69fb0c000002") ]
}
When I try to execute this query:
Room.findOne({ 'name': 'room1' }).populate('People').run(function (err, result) {
if(err) console.log(err);
console.log(result);
});
I get as output:
{ _id: 4f9e5bb68bcd69fb0c000001,
name: 'room1',
People: []
}
Why doesn’t Mongoose populate the people field? I just don’t understand what could be wrong.
This problem was a bug in 2.x version of mongoose. It has been fixed: https://github.com/LearnBoost/mongoose/issues/877