【问题标题】:Find nested array elements查找嵌套数组元素
【发布时间】:2017-01-13 06:22:43
【问题描述】:

这是我的架构:

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._id': appliance_id}) 将返回整个文档。 $ 运营商将无法工作,我不得不想象。

是否可以接收该特定设备或仅退回该特定房间和设备的整个文档?

我如何找到特定的设备并退回该设备?

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    在这里,您在主架构定义中使用了mongoose subdocs 架构。所以你可以检索任何特定的房间:

    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)
    });
    

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 2020-12-04
      相关资源
      最近更新 更多