naved17
naved17

Reputation: 168

How to use populate in mongoose?

I have two collections where one holds list of systems and the other holds list of battery attached to the system. I want to use populate method so that when I run the query using system id it shows me the details of battery is also shown. My schema for system and battery are as follows.

const mongoose = require('mongoose');

const { Schema } = mongoose;

const SystemSchema = new Schema(
  {
    serialNumber: String,
    location: String,
    BPIDs: [
      {
        type: Schema.Types.ObjectId,
        ref: 'batteryPack'
      }
    ]
  },
  {
    timestamps: true
  }
);

const Systems = mongoose.model('system', SystemSchema);

module.exports = Systems;

My battery model is as follows:

const mongoose = require('mongoose');

const { Schema } = mongoose;

const batteryPackSchema = new Schema(
  {
    systemSerialNumber: String,
    batteryID: Number,
    batteryVoltage: Number,
    totalCurrent: Number,
    stateOfCharge: Number
  {
    timestamps: true
  }
);

const BatteryPacks = mongoose.model('batteryPack', batteryPackSchema);

module.exports = BatteryPacks;

My query route is as follows:

router.get('/details/:id', async (req, res) => {
  try {
    const deviceDetails = await Systems.findOne({ _id: req.params.id }).populate('batteryPack').lean();
    return res.status(200).send({
      deviceDetails
    });
  } catch (error) {
    return res.status(500).send(error.stack);
  }
});

On running query through postman it shows the following error:

MongooseError: Cannot populate path batteryPack because it is not in your schema. Set the strictPopulate option to false to override. at getModelsMapForPopulate

Upvotes: 0

Views: 1999

Answers (2)

emmanuel uchewa
emmanuel uchewa

Reputation: 11

const deviceDetails = await Systems.findOne({ _id: req.params.id },{},{
  populate: { path: 'BPIDs' },
  lean: true,
})

Upvotes: 0

naved17
naved17

Reputation: 168

I was passing wrong argument inside populate method. The code is working flawlessly now.

const deviceDetails = await Systems.findOne({ _id: req.params.id }).populate('BPIDs').lean();

Upvotes: 2

Related Questions