diff --git a/lib/model.js b/lib/model.js index 1c361bcb49..e2c4d68c7f 100644 --- a/lib/model.js +++ b/lib/model.js @@ -75,8 +75,7 @@ const subclassedSymbol = Symbol('mongoose#Model#subclassed'); const { VERSION_INC, VERSION_WHERE, VERSION_ALL } = Document; const saveToObjectOptions = Object.assign({}, internalToObjectOptions, { - bson: true, - flattenObjectIds: false + bson: true }); /** diff --git a/lib/options.js b/lib/options.js index 3bae58e120..bbdcda8b97 100644 --- a/lib/options.js +++ b/lib/options.js @@ -12,5 +12,6 @@ exports.internalToObjectOptions = { depopulate: true, flattenDecimals: false, useProjection: false, - versionKey: true + versionKey: true, + flattenObjectIds: false }; diff --git a/test/document.test.js b/test/document.test.js index 7150ffe64b..84f0a73ebf 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -13926,6 +13926,32 @@ describe('document', function() { cur.subdocs[0] = { test: 'updated' }; await savedDoc.save(); }); + + it('avoids flattening objectids on insertMany (gh-14935)', async function() { + const TestSchema = new Schema( + { + professionalId: { + type: Schema.Types.ObjectId + }, + firstName: { + type: String + }, + nested: { + test: String + } + }, + { + toObject: { flattenObjectIds: true } + } + ); + const Test = db.model('Test', TestSchema); + + const professionalId = new mongoose.Types.ObjectId(); + await Test.insertMany([{ professionalId, name: 'test' }]); + + const doc = await Test.findOne({ professionalId }).lean().orFail(); + assert.ok(doc.professionalId instanceof mongoose.Types.ObjectId); + }); }); describe('Check if instance function that is supplied in schema option is available', function() {