首页 > 解决方案 > 将文档数组传递到另一个文档节点JS mongodb的问题

问题描述


我在 MongoDB 和 NodeJS 中使用 Schemas 时遇到一些问题:

我有两个模式,每个模式都在 file.js 中。第一个(粘贴在这里)包含第二个的数组。

    const mongoose = require('mongoose')
const Schema = mongoose.Schema

const installationSchema = new Schema({
  name: {
    type: String,
    unique: true,
    required: true
  },
  }],
  // Array of services
  services: [{
    name: String,
  }],
  // Array of sensors
  sensors: [{
    type : mongoose.Schema.Types.ObjectId,
    ref : 'SensorSchema'
  }]

})
module.exports = mongoose.model('Installation', installationSchema)

事情是,当我手动创建一个 SensorSchema 数组以将其推送到 installationSchema 时,一旦在 MongoDB 中我只看到一个 ObjectID 数组,同时其他数组同时具有 ObjectId 和 String 值。我觉得奇怪的是数组我曾经在控制台登录时临时存储 SensorSchema 工作正常。

我在 MongoDB 中看到的:

> db.installations.find().pretty()                                               
{
        "_id" : ObjectId("60813e8ca4718487d91f8a37"),
        "sensors" : [
                ObjectId("60813e8ca4718487d91f8a40"),
                ObjectId("60813e8ca4718487d91f8a41"),
                ObjectId("60813e8ca4718487d91f8a42")
        ],
        "name" : "Test",
        "equipments" : [
                {
                        "_id" : ObjectId("60813e8ca4718487d91f8a38"),
                        "name" : "Equip1"
                }
        ],
        "services" : [
                {
                        "_id" : ObjectId("60813e8ca4718487d91f8a39"),
                        "name" : "Service1"
                },
                {
                        "_id" : ObjectId("60813e8ca4718487d91f8a3a"),
                        "name" : "Service2"
                }
        ],

我的数组显示在控制台中:

[
  {
    _id: 60813e8ca4718487d91f8a40,
    name: 'Termometer',
    tag: 'T-R1/12',
    range: '-5ºC / 140ºC ±2ºC'
  },
  {
    _id: 60813e8ca4718487d91f8a41,
    name: 'Manometer',
    tag: 'P-R1/12',
    range: '70mbar / PATM ±15mbar'
  },
  {
    _id: 60813e8ca4718487d91f8a42,
    name: 'Tacometer',
    tag: 'V-R1/12',
    range: '5-100 RPM ±10%'
  }
]

我想念什么?

标签: node.jsmongodbschemacrud

解决方案


像这样试试。

//IMPORT SensorSchema HERE
const mongoose = require('mongoose')
const Schema = mongoose.Schema

const installationSchema = new Schema({
  name: {
    type: String,
    unique: true,
    required: true
  },
  }],
  // Array of services
  services: [{
    name: String,
  }],
  // Array of sensors
  sensors: [{
    type: SensorSchema
    default: {}
  }]

})
module.exports = mongoose.model('Installation', installationSchema)

推荐阅读