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.
- query into database if user exists
- if it exists get the values of the database
- compare the values of the database with the form values sent from user
- if values from database are equals, discard the operation
- if values from database are different, update the values with the form values
- close db and send response
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
- See if the record exists in the database.
- If it doesn't, INSERT the object and go to step 3
- If it does, go to step 2
- Compare the values in the database object with the values supplied by the user.
- If the values are different (in ways that you want), update each field as required.
- If the values are the same then there's nothing to do, go to step 3
- Close db and send response to user
Hope this helps.