Skip to content

Commit 45f5c4c

Browse files
committed
perf(model): make insertMany() lean option skip hydrating Mongoose docs
Fix #14372
1 parent 5dfb62f commit 45f5c4c

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

lib/model.js

+16-11
Original file line numberDiff line numberDiff line change
@@ -3430,6 +3430,13 @@ Model.$__insertMany = function(arr, options, callback) {
34303430
const results = ordered ? null : new Array(arr.length);
34313431
const toExecute = arr.map((doc, index) =>
34323432
callback => {
3433+
// If option `lean` is set to true bypass validation and hydration
3434+
if (lean) {
3435+
// we have to execute callback at the nextTick to be compatible
3436+
// with parallelLimit, as `results` variable has TDZ issue if we
3437+
// execute the callback synchronously
3438+
return immediate(() => callback(null, doc));
3439+
}
34333440
if (!(doc instanceof _this)) {
34343441
try {
34353442
doc = new _this(doc);
@@ -3440,13 +3447,6 @@ Model.$__insertMany = function(arr, options, callback) {
34403447
if (options.session != null) {
34413448
doc.$session(options.session);
34423449
}
3443-
// If option `lean` is set to true bypass validation
3444-
if (lean) {
3445-
// we have to execute callback at the nextTick to be compatible
3446-
// with parallelLimit, as `results` variable has TDZ issue if we
3447-
// execute the callback synchronously
3448-
return immediate(() => callback(null, doc));
3449-
}
34503450
doc.$validate({ __noPromise: true }, function(error) {
34513451
if (error) {
34523452
// Option `ordered` signals that insert should be continued after reaching
@@ -3510,7 +3510,7 @@ Model.$__insertMany = function(arr, options, callback) {
35103510
callback(null, []);
35113511
return;
35123512
}
3513-
const docObjects = docAttributes.map(function(doc) {
3513+
const docObjects = lean ? docAttributes : docAttributes.map(function(doc) {
35143514
if (doc.$__schema.options.versionKey) {
35153515
doc[doc.$__schema.options.versionKey] = 0;
35163516
}
@@ -3572,6 +3572,9 @@ Model.$__insertMany = function(arr, options, callback) {
35723572
return !isErrored;
35733573
}).
35743574
map(function setIsNewForInsertedDoc(doc) {
3575+
if (lean) {
3576+
return doc;
3577+
}
35753578
doc.$__reset();
35763579
_setIsNew(doc, false);
35773580
return doc;
@@ -3588,9 +3591,11 @@ Model.$__insertMany = function(arr, options, callback) {
35883591
return;
35893592
}
35903593

3591-
for (const attribute of docAttributes) {
3592-
attribute.$__reset();
3593-
_setIsNew(attribute, false);
3594+
if (!lean) {
3595+
for (const attribute of docAttributes) {
3596+
attribute.$__reset();
3597+
_setIsNew(attribute, false);
3598+
}
35943599
}
35953600

35963601
if (rawResult) {

0 commit comments

Comments
 (0)