【问题标题】:Querying an array inside a mongoose document查询 mongoose 文档中的数组
【发布时间】:2013-07-15 11:03:07
【问题描述】:

我在用户和设备之间有 1 - many 关系(嵌入在用户架构中)

var UserSchema = new Schema({
    devices: [DeviceSchema] //list of devices for the user      
})

var DeviceSchema = new Schema({
    deviceRegistrationId: String,
    deviceOSType: String
});

我在 express POST /api/device 中有一个 Rest 调用(用户 ID 在标题中提供)以将设备添加到用户集合中,我只想在用户模型中不存在该设备的情况下添加设备。 post call 的正文类似于

{ deviceRegistrationId : "xx2233", 
  deviceOSType: "Android"
}

我检查标题中的用户 ID 是否存在于用户集合中,如果确实存在,则仅当设备不在数据库中时才添加设备。

我目前的实现如下。

var userId = req.header('UserId');
        var deviceRegistrationId = req.body.deviceRegistrationId;
        User.findById({_id: userId}, function(err, user) {
             if (user && user!==undefined) {
                if (UserController.containsDevice(user.devices, deviceRegistrationId)) {
                    console.log('contains device - do nothing ');
                    res.send({errors: [{code: 666, message: 'Device Already Registered'}]})
                } else {
                    user.devices.addToSet(req.body);
                    user.save();
                    //todo check what to send back.. 
                    res.send(user);
                }
             } else {
                res.send({errors: [{code: 666, message: 'User not found in the database'}]});
             }

             if (err) 
                res.send({errors: [{code: 666, message: 'Unexpected issue in User Collection'}]});
        });


UserController.containsDevice = function(devices, deviceRegistrationId){
        console.log('UserController::containsDevice devices: ' + JSON.stringify(devices) + 
                    " deviceRegistrationId: " + deviceRegistrationId);
        var strDeviceRegistrationId = "" + deviceRegistrationId;
        for (var i = 0; i < devices.length; i++) {
            console.log(' device id :' + JSON.stringify(devices[i].deviceRegistrationId)); 
            if (devices[i].deviceRegistrationId == strDeviceRegistrationId) {
                console.log('id matched');
                return true;
            }
        }

            return false;          

    }

我想检查是否有一种方法不是设备数组来确定设备是否已经存在。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您可以在查询中使用点分隔的路径,如下所示:User.find({'devices.deviceRegistrationId': deviceRegistrationId})。如果该查询不匹配任何文档,则没有用户拥有该设备。请注意,当给定这样的查询时,mongo 足够聪明,可以测试devices 数组的所有成员。如果要检查特定用户,还可以在查询条件中添加用户 ID。

    【讨论】:

    • 如何查询文本项数组
    猜你喜欢
    • 2014-07-01
    • 2020-07-16
    • 2021-04-28
    • 2015-04-27
    • 2015-04-18
    • 2021-11-12
    • 1970-01-01
    • 2022-10-01
    • 2012-08-26
    相关资源
    最近更新 更多