我有 1 - 用户和设备之间的许多关系(嵌入在用户模式中)
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 在标题中提供)以将设备添加到用户集合中,我只想在用户模型中不存在该设备的情况下添加设备。邮政电话的正文类似于
{ 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;
}
我想检查是否有一种方法不是设备数组来确定设备是否已经存在。