0

Consider this schema:

UUID is a unique and one time created per device.

CNUID is a unique number also, but consider it as a token, which means it updates from time to time.

username: {type: String, unique: true, required: true},
devices: [
    {
        ip:{type:String},
        meta:{type:String},
        type: {type: String, default: 'none', enum: ['android', 'ios', 'web', 'none']},
        cnuid: {type: String},
        uuid:{type:String, unique:true}
    }
]

I am trying to do so:

If username does not exist, create a username and attach its device to this array,

If it exists try to attach this device to the array, as long as there isn't a uuid like this already,

If there is a uuid like this overwrite the cnuid with the cnuid provided.

So basically I've tried couple of options resulting in only 2 out of 3 in one query.

I'm trying to avoid doing multiple queries for this if possible.

The query I'm stuck with is:

db.devices.update(
{username:user.username, 'devices.uuid':device.uuid},
{$set:{username:username, 'devices.$.cnuid':cnuid}},{upsert:true})

This will create a new device if user exists. It will update cnuid on existing uuid, but will not create a new username with new device.

Suggestions?

Linial
  • 1,154
  • 9
  • 22
  • This looks pretty solid, I'll try that soon. I didn't understand though if those 3 cases can be done in one query only, or does that resolves in 2 queries. – Linial May 25 '15 at 20:36
  • 3 separate queries -- that may be send as a batch using the [`update` database command](http://docs.mongodb.org/manual/reference/command/update/#dbcmd.update). Take a look at the comments regarding that. – Sylvain Leroux May 25 '15 at 20:40
  • Do you think this is possible in mongoose? since I'm not pleased with the fact that I've to use 2 Mongodb clients in my app. – Linial May 26 '15 at 07:37

0 Answers0