Hi,
I have a question about Collection update, here an example
I declare two objects
var obj1 = {a:1, b:1, c:{d:1} }
var obj2 = {a:2, b:2, c:{d:2}, e:2}
I insert the first object in a collection
myCollection.insert(obj1)
If i fetch the doc (_id = ID) i have obviously the exact object obj1:
myCollection.find({_id:ID})
–>
{a:1, b:1, c:{d:1} }
Now i update the doc with obj2
myCollection.update({_id: ID}, {$set:obj2}})
myCollection.find({_id:ID})
–>
{a:2, b:2, c:{d:2}, e:2}
Everything works as expected.
I do a redundant step here
myCollection.update({_id: ID, {$set:obj1}})
myCollection.find({_id:ID})
–>
{a:1, b:1, c:{d:1}, e:2 }
and that’s fine.
Now, i define a third obj
var subObj3 = {f:3}
and i try to update the key c of the doc, which contains an object ({d:1})
myCollection.update({_id: ID}, { $set : { c: subObj3 }});
I have
myCollection.find({_id:ID})
–>
{a:1, b:1, c:{f:3}, e:2 }
Instead i would expect
{a:1, b:1, c:{d:1, f:3}, e:2 }
is this the correct behaviour?
If so, what would be the best pattern to update a subobject like in this case?
Let’s assume i have an object like
var subObj4 = {g:4,h:4,i:4}
How can i update the key ‘c’ of the doc in the collection keeping the previous unmatched values if any (in this example it would be {f:3} ) ?
Thanks for your help.