【问题标题】:How to store objectIDs of other collection inside an array using mongoose schema?如何使用 mongoose 模式将其他集合的 objectID 存储在数组中?
【发布时间】:2022-01-28 07:32:38
【问题描述】:

我有两个集合,一个包含系统列表,另一个包含连接到系统的电池列表。我想在文档中存储一组电池的 ObjectID,以便以后可以填充它。另外,我将如何在邮递员中构建我的发帖请求?

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;

我的电池型号如下:

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;

我的添加路线如下:

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

【问题讨论】:

    标签: node.js mongodb mongoose postman


    【解决方案1】:

    我不明白,你实际上做了你在这里问的:

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

    就是这样。


    顺便说一句,您的电池模型将无法工作,因为存在一些语法错误(timestamps 变量之前的括号)

    【讨论】:

    • 你能告诉我如何通过邮递员发出邮寄请求吗?我的意思是我想存储电池组的 objectID。
    猜你喜欢
    • 2018-06-11
    • 2017-11-22
    • 2017-03-16
    • 1970-01-01
    • 2019-07-18
    • 2021-11-04
    • 1970-01-01
    • 2019-05-23
    • 2021-02-25
    相关资源
    最近更新 更多