6

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

how about for querying an array of text items

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.