How to store objectIDs of other collection inside an array using mongoose schema?

Viewed 89

I have two collections where one holds list of systems and the other holds list of battery attached to the system. I want to store an array of ObjectIDs of batteries inside a document so that I can populate it later. Also how will I structure my post request in postman?

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 add route is as follows:

const addDevice = async systemData => {
  try {
    const { serialNumber, location, BPIDs } = systemData;
    const createDevice = new Systems({
      serialNumber,
      location,
      BPIDs
    });
    await createDevice.save();
    return {
      status: 200,
      message: 'System added successfully!'
    };
  } catch (error) {
    console.error(error);
  }
};
1 Answers

I don't understand, you actually did what you ask here:

BPIDs: [
    {
        type: Schema.Types.ObjectId,
        ref: 'batteryPack'
    }
]

That's the way to do it.


Btw, your battery model won't work since there's some syntax errors (the bracket before your timestamps variable)

Related