Parichit
Parichit

Reputation: 257

Mongoose populate returning empty array

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

This is my schema definition for the base model.

var mongoose = require('mongoose');

var PackageSchema = new mongoose.Schema({
    merchant_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Merchant' },
    name: String,
    original_price: Number,
    discounted_price: Number
});

module.exports = mongoose.model('Package', PackageSchema);

And this is the model I am referring to. The data inside the Package model and Merchant model is being saved just fine.

Merchant document

Package document

But if I query using populate function I am being returned an empty string

Merchant
.findById( req.params.id, 'packages')
.populate('packages')
.exec(function (err, merchant) {
    if (err)
        next(err);
    else
        res.status(200).json(merchant);
});

Output:

{
  "_id": "579b3b2dc2e8d61c0ecd2731",
  "packages": []
}

Can anyone help me

Update:

Ok something really odd is happening. If I try to populate the Package document with merchant_id it is working but not the other way around.

Package
    .find()
    .populate('merchant_id')
    .exec(function (err, packages) {
        if(err)
            next(err);
        else
            res.status(200).json(packages);
    });

Output:

[
  {
    "_id": "579b3b51c2e8d61c0ecd2732",
    "name": "Hair + Nails",
    "original_price": 600,
    "discounted_price": 400,
    "merchant_id": {
      "_id": "579b3b2dc2e8d61c0ecd2731",
      "updated_at": "2016-07-29T11:17:37.474Z",
      "created_at": "2016-07-29T11:17:01.216Z",
      "name": "VLCC",
      "logo_image": "http://vlccwellness.com/India/wp-content/uploads/2015/09/logo1.png?",
      "cover_image": "http://image3.mouthshut.com/images/imagesp/925053993s.jpg?",
      "__v": 1,
      "tags": [],
      "packages": [
        "579b3b51c2e8d61c0ecd2732"
      ],
      "work_hours": {
        "opening_time": 1000,
        "closing_time": 2100,
        "holiday": "Sunday"
      },
      "information": {
        "description": "Lorem Ipsum",
        "gender": "Men",
        "services": [
          "Hair"
        ],

Upvotes: 1

Views: 1935

Answers (4)

frane
frane

Reputation: 75

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

Upvotes: 0

jofftiquez
jofftiquez

Reputation: 7708

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.

Upvotes: 0

Azeem Malik
Azeem Malik

Reputation: 490

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.

Upvotes: 2

Arun Ghosh
Arun Ghosh

Reputation: 7734

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

Upvotes: 0

Related Questions