Mongoose的精简使用与填充和嵌套查询
我在使用MongoDB的Node.js中编写一个应用程序。 我selectMongooseJS来处理我的数据库查询。
我有两个相互引用的集合( Room
集合中包含的“上级”集合和DeviceGroups
)。
我有一个查询从Room
集合中获取所有房间的列表,填充deviceGroups
字段(这是Rooms
参考到DeviceGroup
集合),里面有一个map
方法,通过Room
集合中find的每个房间,每个房间都会进行另一个查询 – 它会查找DeviceGroup
集合中的任何deviceGroups
组,这些设备组是在地图方法中引用到当前房间的。
我的目标是返回所有包含deviceGroups
字段的房间的列表,而不仅仅是引用。
在查询之后(在then
方法中)我得到的是一个Mongoose文档。 整个algorithm被用作GET
方法的处理程序,所以我需要一个纯JavaScript对象作为响应。
我想实现的主要目标是将所有的查询和人口的结果作为纯javascript对象,所以我可以创build一个响应对象,并发送它(我不想发送数据库返回的一切,因为不是所有的这种情况下需要数据)
编辑:
我很抱歉,我删除了我的代码,并没有意识到这一点。
我目前的代码如下:
架构:
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' } ] }, { collection: 'deviceGroups' });
查询:
app.get('/api/id/rooms', function(req, res) { Room.find({}).populate('deviceGroups').lean().exec(function(err, parentRoom) { parentRoom.map(function(currentRoom) { DeviceGroup.findOne({ parentRoomId: currentRoom._id }, function (err, devices) { return devices; }); }); }).then(function(roomList) { res.send(roomList); }); });
你在哪里混乱。 这里是一个简单而有效的代码片段
Room.findById(req.params.id) .select("roomname") .populate({ path: 'deviceGroup', select: 'devicename', model:'DeviceGroups' populate:{ path: 'device', select: 'devicename', model:'Device' } }) .lean() .exec((err, data)=>{ console.log(data); })