Can't get Mongoose.js Subdocument Array to populate

前端 未结 5 387
孤独总比滥情好
孤独总比滥情好 2021-02-04 06:23

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:          


        
5条回答
  •  悲哀的现实
    2021-02-04 06:56

    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
                     });
                 });
    

提交回复
热议问题