Skip to content

Rewriting the entire object when you change only one field in EmbeddedDocument #1954

Closed
archangel-irk opened this Issue Mar 11, 2014 · 0 comments

1 participant

@archangel-irk

mongoose 3.8.8
When using the method Document.prototype.$__set the index of the array and the target field of the object will be overwritten whole EmbeddedDocument.

var schema = new Schema({
  schedule: [ new Schema({open: Number, close: Number}) ]
});

Created by the scheme of the model and...

console.log( myModel.schedule[5].close );  //"18:00"
myModel.set('schedule.5.close', 1500);
console.log( myModel.schedule[5] ); // Object {close: 1500} (is not EmbeddedDocument)

Cause in the method Document.prototype.$__set, which checks only for simple object.
The problem is solved by adding checks constructor.name of EmbeddedDocument

Document.prototype.$__set = function (
...
f (obj[parts[i]] && 'Object' === obj[parts[i]].constructor.name) {
  obj = obj[parts[i]];
} else if (obj[parts[i]] && 'EmbeddedDocument' === obj[parts[i]].constructor.name) {  // here
  obj = obj[parts[i]];
} else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
  obj = obj[parts[i]];
} else {
  obj = obj[parts[i]] = {};
}
...
};

After this little fix the $__set() works as expected:

console.log( myModel.schedule[5].close );  //"18:00"
myModel.set('schedule.5.close', 1500);
console.log( myModel.schedule[5] ); // EmbeddedDocument with fields {close: 1500, open: 1200}

Tests (document.test.js), setter on nested paths

var doc = new TestDocument();
doc.init({
    schedule: [{
      open: 1000,
      close: 1900
    }]
});

doc.set('schedule.0.open', 1100);
assert.ok(doc.schedule);
assert.equal('MongooseDocumentArray', doc.schedule.constructor.name);
assert.equal('EmbeddedDocument', doc.schedule[0].constructor.name);
assert.equal(1100, doc.schedule[0].open);
assert.equal(1900, doc.schedule[0].close);
@archangel-irk archangel-irk pushed a commit that referenced this issue Mar 11, 2014
@chetverikov chetverikov fix gh-1954 3b934b7
@archangel-irk archangel-irk added a commit that referenced this issue Mar 11, 2014
@archangel-irk archangel-irk fixes gh-1954 d5dc40f
@archangel-irk archangel-irk added a commit that referenced this issue May 19, 2014
@archangel-irk archangel-irk fix #1954 1fa2ee7
@vkarpov15 vkarpov15 pushed a commit that closed this issue May 29, 2014
@archangel-irk archangel-irk fix #1954 5b4490d
@vkarpov15 vkarpov15 closed this in 5b4490d May 29, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.