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?