Why does the Mongo dot notation replace the entire subdocument?

I have the following document in my db:

{ "_id": ObjectId("ABCDEFG12345"), "options" : { "foo": "bar", "another": "something" }, "date" : { "created": 1234567890, "updated": 0 } } 

And I want to update options.foo and date.updated simultaneously using dot notation, for example:

 var mongojs = require('mongojs'); var optionName = 'foo'; var optionValue = 'baz'; var updates = {}; updates['options.' + optionName] = optionValue; updates['date.updated'] = new Date().getTime(); db.myCollection.findAndModify({ query : { _id : ObjectId('ABCDEFG12345') }, update : { $set : updates }, upsert : false, new : true }, function(error, doc, result) { console.log(doc.options); console.log(doc.date); }); 

And this leads to:

 { foo : 'baz', another : 'something' } { updated : 1234567890 } 

In particular, my preexisting date.created field date.created getting knocked down, although I use dot notation.

Why does this only partially work? The options subdocument saves its pre-existing data ( options.another ), why is the existing data saved in the date subdocument?

+5
source share
2 answers

The described behavior usually occurs when the object passed in the $set operator has the form { "data" : { "updated" : 1234567890 } } , and not { "data.updated" : 1234567890 } , but I am not familiar with the points in JavaScript to determine if this could be the cause on the JS side.

Also, this does not explain why this happens with data , not options .

If you can print the object stored in the updates variable and sent to MongoDB in the update field, which allows you to indicate which side the problem is (JS or MongoDB).

+2
source

I pass your code to the test environment and use the same library that you use. The mongojs library for a query using native ObjectId looks like this: mongojs.ObjectId ("####") Can see the official documentation .

for the callback function in the findAndModify function, the docs parameter is an array, so I move as an array enter image description here

Note: [I use template literals to concatenate the string] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals )

Everything works great ...

+1
source

Source: https://habr.com/ru/post/1263240/


All Articles