【发布时间】:2018-06-04 13:19:02
【问题描述】:
我正在编写一个使用 Node.js 和 MongooseJS 作为处理数据库调用的中间件的应用程序。
我的问题是我有一些嵌套模式,其中一个以错误的方式填充。当我跟踪人口的每一步时 - 所有数据都很好,除了 devices 数组,它是空的。我仔细检查了数据库,该数组中有数据,所以应该没问题。
我有 Room 架构。 Room 的每个对象都有一个名为 DeviceGroups 的字段。该字段包含一些信息,其中之一是一个名为Devices 的数组,其中存储了分配给父房间的设备。
正如您在代码中看到的,我正在根据服务器请求中的 ID 找到一个房间。一切都很好,数据与数据库中的数据一致。问题是devices 数组是空的。
这是 MongooseJS 的某种怪癖,还是我在这里做错了什么,devices 数组返回为空?我检查了数据库本身,里面有一些数据,所以数据很好,错误在粘贴代码的某个地方。
代码:
架构:
const roomSchema = Schema({
name: {
type: String,
required: [true, 'Room name not provided']
},
deviceGroups: [{
type: Schema.Types.ObjectId,
ref: 'DeviceGroup'
}]
}, { collection: 'rooms' });
const deviceGroupSchema = Schema({
parentRoomId: {
type: Schema.Types.ObjectId,
ref: 'Room'
},
groupType: {
type: String,
enum: ['LIGHTS', 'BLINDS', 'ALARM_SENSORS', 'WEATHER_SENSORS']
},
devices: [
{
type: Schema.Types.ObjectId,
ref: 'LightBulb'
},
{
type: Schema.Types.ObjectId,
ref: 'Blind'
}
]
}, { collection: 'deviceGroups' });
const lightBulbSchema = Schema({
name: String,
isPoweredOn: Boolean,
currentColor: Number
}, { collection: 'lightBulbs' });
const blindSchema = Schema({
name: String,
goingUp: Boolean,
goingDown: Boolean
}, { collection: 'blinds' });
数据库调用:
Room
.findOne({ _id: req.params.roomId })
.populate({
path: 'deviceGroups',
populate: {
path: 'devices'
}
})
.lean()
.exec(function(err, room) {
if (err) {
res.send(err);
} else {
room.deviceGroups.map(function(currentDeviceGroup, index) {
if (currentDeviceGroup.groupType === "BLINDS") {
var blinds = room.deviceGroups[index].devices.map(function(currentBlind) {
return {
_id: currentBlind._id,
name: currentBlind.name,
goingUp: currentBlind.goingUp,
goingDown: currentBlind.goingDown
}
});
res.send(blinds);
}
});
}
})
【问题讨论】:
-
我不认为您定义
devices的方式是正确的。在一个数组中拥有多个模式引用的一种方法是使用discriminator 看到这个answer -
@Molda 你能提供一个简单的例子吗?当然,
discriminator正是我要找的,但你链接的另一篇文章有点复杂,因为它使用了所有中间件,对我来说不是很清楚。你能想出一个在我的例子中如何使用它的例子吗?谢谢
标签: javascript node.js mongoose