Mongoose populate returning empty array

后端 未结 4 966
我寻月下人不归
我寻月下人不归 2021-01-28 04:25

I am trying to use mongoose populate function but in response I am getting empty array, I have seen multiple posts regarding this

var MerchantSchema = new mongo         


        
相关标签:
4条回答
  • 2021-01-28 04:29

    Can you try by removing second parameter from the findBbyId:

    Merchant
    .findById( req.params.id)
    .populate('packages')
    .exec(function (err, merchant) {
        if (err)
            next(err);
        else
            res.status(200).json(merchant);
    });
    
    0 讨论(0)
  • 2021-01-28 04:38

    Well because your packages field on your Schema is an array you should populate it as an array as well.

    Try

    .populate([
        {path:'packages', model:Package}
    ])
    

    wher Package is the instance of your Package Model.

    0 讨论(0)
  • 2021-01-28 04:41

    Use type insted of $type in MerchantSchema.

    var MerchantSchema = new mongoose.Schema({
      packages: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Package'}]
    },
    {
        typeKey: '$type',
        timestamps: { createdAt: 'created_at', updatedAt: 'updated_at'}
    });
    
    module.exports = mongoose.model('Merchant', MerchantSchema);
    

    Verify there is an array of ObjectId against packages in your Merchant document.

    0 讨论(0)
  • 2021-01-28 04:49

    Make sure that packages array in Merchant schema contains ObjectIds of type string, (not number). You can ensure this with something like:

    merchant.packages.map(r => { r._id = r._id + ''; });
    
    0 讨论(0)
提交回复
热议问题