node.js - 将文档数组传递到另一个文档节点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%'
}
]
我想念什么?
解决方案
像这样试试。
//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)
推荐阅读
- amazon-dynamodb - 如何从 DynamoDB 中的分区键列表中获取属性 - 扫描是我唯一的选择吗?
- php - WooCommerce 存档待售产品不具备所有功能
- jquery - 如何制作动态选项标签html
- haskell - 通过独立导出导出
- django - CORS 在 dockerized Django REST + Angular 项目中被阻止
- android - 如何在工具栏菜单中居中(水平)图标
- php - Podio filter_by_view 返回太多信息
- c# - 现有的 Windows 服务省略了“new System.ComponentModel.Container()”,但仍然有效。这是做什么的?
- javascript - ReactJS 的本地版本无法在 IE11、Edge 上运行,但远程版本可以运行
- jquery - 为下拉菜单制作 jquery