Skip to content

Commit

Permalink
fix(document): allow new Model(doc) to set immutable properties whe…
Browse files Browse the repository at this point in the history
…n doc is a mongoose document

Fix #8642
  • Loading branch information
vkarpov15 committed Mar 8, 2020
1 parent 7b0bd36 commit dfe41e2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,16 @@ function Document(obj, fields, skipId, options) {
}

if (obj) {
if (obj instanceof Document) {
this.isNew = obj.isNew;
}
// Skip set hooks
if (this.$__original_set) {
this.$__original_set(obj, undefined, true);
} else {
this.$set(obj, undefined, true);
}

if (obj instanceof Document) {
this.isNew = obj.isNew;
}
}

// Function defaults get applied **after** setting initial values so they
Expand Down
11 changes: 11 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8829,4 +8829,15 @@ describe('document', function() {
assert.ok(!err.errors['nested.age']);
});
});

it('copies immutable fields when constructing new doc from old doc (gh-8642)', function() {
const schema = Schema({ name: { type: String, immutable: true } });
const Model = db.model('Test', schema);

const doc = new Model({ name: 'test' });
doc.isNew = false;

const newDoc = new Model(doc);
assert.equal(newDoc.name, 'test');
});
});

0 comments on commit dfe41e2

Please sign in to comment.