【发布时间】:2016-10-30 03:40:35
【问题描述】:
我有两个架构:设备和地图。
设备:
var DeviceSchema = mongoose.Schema({
deviceName:{
type: String,
required: true,
index: true
},
roomCapacity: {
type: Number
},
roomImagePath:{
type: String,
},
mapId:{
type: Schema.Types.ObjectId,
ref: 'Map',
required: true
},
coords:{
type: [Number], //[xcoord, ycoord]
required: true
},
createdAt: { type: Date, default: Date.now }
});
地图
var MapSchema = mongoose.Schema({
ownerId:{
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
mapName: {
type: String
},
mapImagePath:{
type: String,
required: true
},
createdAt: { type: Date, default: Date.now },
devices: [{type: Schema.Types.ObjectId, ref: 'Device'}]
});
如您所见,我的地图有一个引用设备的数组,我的设备有一个引用地图的 mapId 字段。现在,我正在尝试调用 .populate() 以便可以检索地图及其设备数组。我在做:
module.exports.getMapByIdAndPopulate = function(mapId, callback){
Map.findOne({_id: mapId}).populate('devices').exec(callback);
};
这会返回地图,但设备数组不应该是空的。另外,我在我的数据库中创建设备,如下所示:
var device = new Device({ //create the device
deviceName: req.body.deviceName,
roomCapacity: req.body.roomCapacity,
roomImagePath: roomImagePath,
mapId: req.body.mapId,
coords: [req.body.xcoord, req.body.ycoord]
});
如何检索包含设备数组的地图?另外,我不知道我的理解是否正确,但我从未将任何设备插入到 Map 数组中。
【问题讨论】:
标签: node.js mongodb mongoose mongoose-populate