1

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"
        ],
2
  • What is the version of Mongoose? Commented Jul 29, 2016 at 12:00
  • I'm having this same exact problem, but my models look just like yours. What was the fix in the end? type is not my problem. Commented Mar 14, 2018 at 16:33

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm having the same problem. But my model is using type not $type.
@TheValyreanGroup check your ref type it should be same as model name .
0

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

1 Comment

Tried that, still getting an empty array
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.