diff --git a/lib/helpers/schema/idGetter.js b/lib/helpers/schema/idGetter.js index 31ea2ec8659..d521fe32240 100644 --- a/lib/helpers/schema/idGetter.js +++ b/lib/helpers/schema/idGetter.js @@ -12,8 +12,8 @@ module.exports = function addIdGetter(schema) { if (!autoIdGetter) { return schema; } - schema.virtual('id').get(idGetter); + schema.virtual('id').set(idSetter); return schema; }; @@ -30,3 +30,14 @@ function idGetter() { return null; } + +/** + * + * @param {String} v the id to set + * @api private + */ + +function idSetter(v) { + this._id = v; + return; +} diff --git a/test/document.test.js b/test/document.test.js index 1e6c9ef7afd..ec6c496d043 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -12212,6 +12212,18 @@ describe('document', function() { const fromDb = await Test.findById(x._id).lean(); assert.equal(fromDb.c.x.y, 1); }); + it('can change the value of the id property on documents gh-10096', async function() { + const testSchema = new Schema({ + name: String + }); + const Test = db.model('Test', testSchema); + const doc = new Test({ name: 'Test Testerson ' }); + const oldVal = doc.id; + doc.id = '648b8aa6a97549b03835c0b3'; + await doc.save(); + assert.notEqual(oldVal, doc.id); + assert.equal(doc.id, '648b8aa6a97549b03835c0b3'); + }); }); describe('Check if instance function that is supplied in schema option is availabe', function() {