Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is mongo dot notation replacing an entire subdocument?

I've got the following doc 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 at the same time using dot notation, like so:

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 results in:

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

Specifically, my pre-existing date.created field is getting clobbered even though I'm using dot notation.

Why is this only partially working? The options sub-document retains its pre-existing data (options.another), why doesn't the date sub-document retain its pre-existing data?

like image 827
AJB Avatar asked Oct 17 '22 18:10

AJB


1 Answers

The behavior described typically happens when the object passed in the $set operator is of the form { "data" : { "updated" : 1234567890 } } rather than { "data.updated" : 1234567890 }, but I'm not familiar with dots in JavaScript enough to tell if that could be the cause on JS's side.

Also, it wouldn't explain why it happens with data and not options.

If you could print the object stored in the variable updates and that is sent to MongoDB in the update field, that would allow to tell on which side the issue is (JS or MongoDB).

like image 112
Ghislain Fourny Avatar answered Oct 21 '22 03:10

Ghislain Fourny