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 d3c3f4a86f..f3869b8e58 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -13927,6 +13927,29 @@ describe('document', function() { 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 + } + }, + { + toObject: { flattenObjectIds: true } + } + ); + const Test = db.model('Test', TestSchema); + + const professionalId = new mongoose.Types.ObjectId(); + await Test.insertMany([{ professionalId, firstName: 'test' }]); + + const doc = await Test.findOne({ professionalId }).lean().orFail(); + assert.ok(doc.professionalId instanceof mongoose.Types.ObjectId); + }); + it('handles buffers stored as EJSON POJO (gh-14911)', async function() { const pdfSchema = new mongoose.Schema({ pdfSettings: {