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
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);
});
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.
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.
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 + ''; });