Node.js 查找嵌套数组元素
这是我的模式:Node.js 查找嵌套数组元素,node.js,mongodb,mongoose,mongodb-query,Node.js,Mongodb,Mongoose,Mongodb Query,这是我的模式: Appliance = new Schema({ appliance_name: {type:String}, appliance_id: {type:String}, appliance_description: {type:String}, keywords: [{ type: String}], appliance_type: { type: String}, appliance_status: { light: { writ
Appliance = new Schema({
appliance_name: {type:String},
appliance_id: {type:String},
appliance_description: {type:String},
keywords: [{ type: String}],
appliance_type: { type: String},
appliance_status: { light: { write_state: Number, read_state: Number },
fan: {write_state: Number, read_state: Number, write_speed: Number, read_speed: Number}
}
});
Room= new Schema({
name: {type: String, required:true},
device_auth_code: {type: String},
alt_name: {type:String},
keywords: [{type: String}],
appliance: [Appliance]
});
Home = new Schema({
name: { type: String, required: true},
description: {type: String},
administrator: {type : mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
users: [{
_id: {type : mongoose.Schema.Types.ObjectId, ref: 'User'},
email: {type: String},
name: { type: String},
status: { type: Number}
}],
rooms: [Room]
});
这里是典型的家
"type": true,
"code": "GET_SUCCESS",
"homes": {
"_id": "58760ff6045e332b81449b42",
"description": "",
"administrator": "586df1e06485de5fc48b72a5",
"name": "CM",
"__v": 9,
"rooms": [
{
"name": "RK",
"alt_name": "RKa",
"_id": "58775437234451346ce3d967",
"appliance": [
{
"_id": "5877546f234451346ce3d968",
"appliance_type": "Light",
"appliance_name": "TubeLights",
"keywords": []
}
],
"keywords": []
}
],
"users": []
}
}
Home
有嵌套的房间阵列,每个房间都有嵌套的电器阵列
Home.findOne({'room.appliance.\u id':appliance\u id})
将返回整个文档。我不得不想象,$
操作符无法工作
是否有可能接收特定的设备或整个文件,而仅返回特定的房间和设备
如何查找特定的设备并返回该设备?这里您已经在家庭模式定义中使用了体系结构。因此,您可以检索任何特定的房间:
Home.findById(home_id, function(err, home){
var room = home.rooms.id(room_id);
res.json(room)
});
或特定设备:
Home.findById(home_id, function(err, home){
var room = home.rooms.id(room_id);
var appliance = room.appliance.id(appliance_id);
res.json(appliance)
});