Home > front end >  Populate array inside object in mongoose
Populate array inside object in mongoose

Time:10-23

I have a company model which looks like this:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const CompanySchema = new Schema(
  {
    companyName: String,
    settings: {
      type: {
        priceVisible: Boolean,
        allowPickupAddressAddition: Boolean,
        paymentMethodsAvailable: [
          { type: Schema.Types.ObjectId, ref: "PaymentMethod" },
        ],
      },
    },    
  }
);

const Company = mongoose.model("Company", CompanySchema);

module.exports = Company;

And I want to populate the values store in paymentMethodsAvailable array. Here is relevant controller code:

const company = await Company.findOne({ _id: id }).populate([
      {
        path: "settings",
        populate: [{path: "paymentMethodsAvailable"}]
      },
    ]);

But this doesn't work as expected. I can see that it might be trying to populate settings object, and fails there. Is there a way in which I can tell mongoose to populate settings.paymentMethodsAvailable ?

CodePudding user response:

Try this

const company = await Company.findOne({ _id: id }).populate(
    "settings.paymentMethodsAvailable"
);

You can find more examples in the documentation. I was using this section as a reference https://mongoosejs.com/docs/populate.html#populating-maps

CodePudding user response:

Mongoose provides clear syntax The following code will work fine

const company = await Company.findOne({ _id: id }).populate(
    "settings.paymentMethodsAvailable"
);

if(!company) {
    // if there is no company with that id
    // this acully not error it's simply
    // return `null` to tell you company not found.
    res.status(404).send()
}

Also: you can go further and populate specific fields inside settings.paymentMethodsAvailable

const company = await Company.findOne({ _id: id }).populate(
    "settings.paymentMethodsAvailable",
    "field1 filed2 filed3"
);
  • Related