我在用 mongoose 嵌套一些子文档时遇到了一点问题。我阅读了很多关于此的内容并尝试了几乎所有内容。
我真的不知道出了什么问题。我知道网络上有很多关于这个的问题。很多都是相似的,但没有解决我的问题。
问题是,我填充的文档总是空的。
- 我检查了我的架构
- 我删除了整个数据库
- 之后,我再次重写了整个架构和代码。
没有任何帮助。我认为这是一个非常小的问题,但我不明白。
这是我的架构:
探针.js
const ProbeShema = new mongoose.Schema({
device: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Device'
},
value: {
type: String,
required: true,
enum: ['Energy', 'Consumption', 'Voltage', 'Current', 'Frequency', 'Time', 'Date']
},
unit: {
type: String,
required: true,
enum: ['kWh', 'kW', 'V', 'A', 'Hz', 'time', 'date']
},
oid: {
type: String,
required: true
},
measurement: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Measurement'
}
});
const Probe = mongoose.model('Probe', ProbeShema,'probe');
module.exports = Probe;
设备.js
var mongoose = require('mongoose');
const DeviceShema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
ip: {
type: String,
required: true,
unique: true,
trim: true
},
port: {
type: String,
required: true,
trim: true
},
secret: {
type: String,
required: true,
trim: true
},
probe: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Probe'
}]
});
const Device = mongoose.model('Device', DeviceShema,'device');
module.exports = Device;
var express = require('express');
var router = express.Router();
var Device = require('../../models/devices')
Device.find()
.populate( 'probe')
.exec()
.then(devices => {
console.log(devices)
res.render('./snmp/snmp', { "title": "SNMP-Devices", "devices": devices });
})
.catch(err => {
console.log(err)
});
输出:
[{
probe: [],
_id: 5db94f22d8fb641c18fc05b9,
name: 'test',
ip: '1.11.1.1',
port: '111',
secret:
'$2b$10$2umat9QqHSFF9/zVih9LU.UKX4sPh/Lmq5XjSai0/pt42QfLXQb6u',
__v: 0
}]
我期待什么:
_id: 5db94f22d8fb641c18fc05b9,
name: 'test',
ip: '1.11.1.1',
port: '111',
secret:
'$2b$10$2umat9QqHSFF9/zVih9LU.UKX4sPh/Lmq5XjSai0/pt42QfLXQb6u',
probe: [
{
device: '5db94f22d8fb641c18fc05b9',
value: 'Energy',
unit: 'kWh',
oid:'1.1.1.1.11',
measurement: 11
},{
device: '5db94f22d8fb641c18fc05b9',
value: 'Consumption',
unit: 'kW',
oid:'1.1.1.1.12',
measurement: 500
}
]
MongoDB 文档
{
"_id":"5db95821d3a65d20200cda64",
"device":"5db9581fd3a65d20200cda63",
"oid":"asd",
"value":"Energy",
"unit":"kWh","__v":0
}
{
"_id":"5db9581fd3a65d20200cda63",
"probe":[],
"name":"asd",
"ip":"1.1.1.1",
"port":"1",
"secret":"$2b$10$mr4x4ls0J2CqdNxnk/ih2.FAHpj1fsXT2NsgrzDXF9y4LCnZBNfXa",
"__v":0
}