diff --git a/lib/model.js b/lib/model.js index c5e54c46f67..d6a3026c7fd 100644 --- a/lib/model.js +++ b/lib/model.js @@ -3430,6 +3430,13 @@ Model.$__insertMany = function(arr, options, callback) { const results = ordered ? null : new Array(arr.length); const toExecute = arr.map((doc, index) => callback => { + // If option `lean` is set to true bypass validation and hydration + if (lean) { + // we have to execute callback at the nextTick to be compatible + // with parallelLimit, as `results` variable has TDZ issue if we + // execute the callback synchronously + return immediate(() => callback(null, doc)); + } if (!(doc instanceof _this)) { try { doc = new _this(doc); @@ -3440,13 +3447,6 @@ Model.$__insertMany = function(arr, options, callback) { if (options.session != null) { doc.$session(options.session); } - // If option `lean` is set to true bypass validation - if (lean) { - // we have to execute callback at the nextTick to be compatible - // with parallelLimit, as `results` variable has TDZ issue if we - // execute the callback synchronously - return immediate(() => callback(null, doc)); - } doc.$validate({ __noPromise: true }, function(error) { if (error) { // Option `ordered` signals that insert should be continued after reaching @@ -3510,7 +3510,7 @@ Model.$__insertMany = function(arr, options, callback) { callback(null, []); return; } - const docObjects = docAttributes.map(function(doc) { + const docObjects = lean ? docAttributes : docAttributes.map(function(doc) { if (doc.$__schema.options.versionKey) { doc[doc.$__schema.options.versionKey] = 0; } @@ -3572,6 +3572,9 @@ Model.$__insertMany = function(arr, options, callback) { return !isErrored; }). map(function setIsNewForInsertedDoc(doc) { + if (lean) { + return doc; + } doc.$__reset(); _setIsNew(doc, false); return doc; @@ -3588,9 +3591,11 @@ Model.$__insertMany = function(arr, options, callback) { return; } - for (const attribute of docAttributes) { - attribute.$__reset(); - _setIsNew(attribute, false); + if (!lean) { + for (const attribute of docAttributes) { + attribute.$__reset(); + _setIsNew(attribute, false); + } } if (rawResult) { diff --git a/test/connection.test.js b/test/connection.test.js index 36290280b47..446f4b0ccff 100644 --- a/test/connection.test.js +++ b/test/connection.test.js @@ -1542,7 +1542,12 @@ describe('connections:', function() { it('should not throw an error when attempting to mutate unmutable options object gh-13335', async function() { const m = new mongoose.Mongoose(); const opts = Object.preventExtensions({}); - const conn = await m.connect('mongodb://127.0.0.1:27017/db?retryWrites=true&w=majority&readPreference=secondaryPreferred', opts); + + const uri = start.uri.lastIndexOf('?') === -1 ? + start.uri + '?retryWrites=true&w=majority&readPreference=primaryPreferred' : + start.uri.slice(0, start.uri.lastIndexOf('?')) + '?retryWrites=true&w=majority&readPreference=primaryPreferred'; + + const conn = await m.connect(uri, opts); assert.ok(conn); }); });