chrishawn chrishawn - 23 days ago 6
Node.js Question

Can't get Mongoose.js Subdocument Array to populate

I'm using mongoose.js on a node.js server connecting to mongodb and
I have a mongoose model like the following

SubSchema = new Schema({
_member: {type: ObjectId, ref: 'Member'},
members: [{type: ObjectId, ref: 'Member'}],
created: { type: Date, default: Date.now }
});
mongoose.model('SubModel', SubSchema);

MainSchema = new Schema({
_member: {type: ObjectId, ref: 'Member'},
subs: [SubSchema],
members: [{type: ObjectId, ref: 'Member'}],
created: { type: Date, default: Date.now }
});
var MainModel mongoose.model('MainModel', MainSchema);


which i pull with a command like this

var q = MainModel.find({})
.sort('created', -1)
.limit(25)
.populate("_member")
.populate("subs._member")
.populate("subs.members");

q.execFind(function(err, mains){
//mains[0].subs[0].members - will always be empty why?
});


my problem is that i can't get subs.members array to populate or even load, it just keeps showing as an empty array.

I've tried .populate("subs.members") to no avail even though subs._member loads just fine

Answer

try this

    SubSchema = new Schema({
        _member:     {type: ObjectId, ref: 'Member'},
        members:     [{type: ObjectId, ref: 'Member'}],
        created:     { type: Date, default: Date.now }
    });
    var SubModel = mongoose.model('SubModel', SubSchema);//add

    MainSchema = new Schema({
        _member:     {type: ObjectId, ref: 'Member'},
        subs:        [SubSchema],
        members:     [{type: ObjectId, ref: 'Member'}],
        created:     { type: Date, default: Date.now }
    });

    var MainModel = mongoose.model('MainModel', MainSchema);

    MainModel.find({})
             .sort('created', -1)
             .limit(25)
             .populate("_member")
             .populate("subs._member")
             .exec(function(err, mains){

                 //add
                 SubModel.populate(mains,{
                     path:'subs.members'
                 },function(err,mains){
                    //mains[0].subs[0].members - is not empty
                 });
             });