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 }); 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" } 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.
My current implementation is something as follows.
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.