我有1-用户和设备之间的关系(嵌入在用户架构中) var UserSchema = new Schema({ devices: [DeviceSchema] //list of devices for the user })var DeviceSchema = new Schema({ deviceRegistrationId: String, deviceOSType: String}); 我有
var UserSchema = new Schema({ devices: [DeviceSchema] //list of devices for the user }) var DeviceSchema = new Schema({ deviceRegistrationId: String, deviceOSType: String });
我有快速POST / api /设备中的Rest调用(标头中提供了用户ID)以将设备添加到用户集合中,我想仅在设备尚未存在于用户模型中时才添加设备.电话会议的主体就像是
{ deviceRegistrationId : "xx2233", deviceOSType: "Android" }
我检查标头中的用户标识是否存在于用户集合中,如果存在,则仅在设备尚未存在于数据库中时才添加设备.
我目前的实现如下.
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; }
我想检查是否有一种方法不是设备阵列来确定设备是否已经存在.
您可以在查询中使用点分隔路径,如下所示:User.find({‘devices.deviceRegistrationId’:deviceRegistrationId}).如果该查询与任何文档都不匹配,则没有用户拥有该设备.请注意,当给出诸如此类的查询时,mongo足够智能以测试设备数组的所有成员.如果要检查特定用户,还可以在查询条件中添加用户ID.