PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] How to use populate in mongoose?

 October 20, 2022     mongodb, mongoose, node.js     No comments   

Issue

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


Solution

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


Answered By - naved17
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing