查询猫鼬文档中的数组 [英] Querying an array inside a mongoose document

查看:65
本文介绍了查询猫鼬文档中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1-用户和设备之间的许多关系(嵌入在用户模式中)

I have 1 - many relationship between users and device (embedded in the user schema)

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),以将设备添加到用户集合中,我只想在用户模型中不存在该设备的情况下添加设备.帖子的正文类似于

I have a Rest calls in express POST /api/device (user id is provided in header) to add devices to user collection, I would like to add device only if the device is not already there in the user model. The body of the post call would something like

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

我检查标题中的用户ID是否在用户集合中,并且如果确实存在,则仅在该设备尚未在数据库中时添加该设备.

I check whether or not user id in the header exists in user collection and if it does exist add the device only if the device is not already in the database.

我当前的实现如下.

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;          

    }

我想检查设备阵列是否可以确定该设备是否已存在.

I wanted to check if there was a way not the devices array to determine if the device already existed.

推荐答案

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

You can use dot-separated paths in a query like so: User.find({'devices.deviceRegistrationId': deviceRegistrationId}). If that query doesn't match any documents, no user has that device. Note that mongo is smart enough to test all members of the devices array when given a query such as this. You can also add a user ID to your query conditions if you want to check a specific user.

这篇关于查询猫鼬文档中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆