I have a document in a mongodatabase
user:{
name:'bruce',
surname:'wayne',
job:'batman',
email:'onlyifdanger@batman.com',
}
so when user update info, I have to:
so in this case if the user sends this:
form.newUserInfo:{
name:'bruce albert',
surname:'wayne',
job:'batman only at night',
email:'onlyifdanger@batman.com',
}
just update name and job.
Is there any way to do this in less than 6 steps? I'm using nodejs v0.10, mongodb 2.2.3, expressjs and mongoskin v0.5
It sounds like you're looking to update the specific fields of a result rather than the entire object itself. I.e. if a user only provides update parameters for the name, you only want to update the name in the database. Using your name:'bruce albert' example, the newUserInfo would be
newUserInfo: {
name: 'bruce albert',
surname: '',
job: '',
email: ''
}
and you don't want to simply upsert with those values, because you'd either wipe the information you already have, or add a duplicate record with less information.
In this case, you can only optimise so far.
Steps 1 and 2 could be combined, since findOne() (or something to that effect) will return a record matching parameters but only if the object exists. If it doesn't exist, you might want to insert the values passed by the user.
Step 4 can be removed because in essence it's doing nothing anyway.
Step 5 is probably the most important, as you'll have to define how values can be 'different'. Think, do you want to update with job=''? Because that IS 'different' from 'batman', although you might not want to update with that value.
My steps would be
Hope this helps.
You may have got the info you need from other comments/answers. But this is quite a robust way of upsert the data you have.
Using $findAndModify you can control optimistic concurrency and upsert.
If you wanted to you could find the differences, but if you can be sure the document is the same as when the user opened it, you would use findAndModify to atomically update the document where the values were the same as the document when it was loaded.
The update part in this command updates all the value, but you could easily restrict it based on differences if you wanted to.
The query matches all the values of the document prior to it being modified. This ensures it's not been changed since the user opened it.
db.people.findAndModify( {
query: {
name:'bruce',
surname:'wayne',
job:'batman',
email:'onlyifdanger@batman.com',
},
update: {
name:'bruce',
surname:'wayne',
job:'business owner',
email:'bruce@wayne.com',
},
upsert: true
// uncomment next line to get the updated / new document return
// ,new : true
} );