Skip to content

Commit

Permalink
perf(model): make insertMany() lean option skip hydrating Mongoos…
Browse files Browse the repository at this point in the history
…e docs

Fix #14372
  • Loading branch information
vkarpov15 committed Feb 25, 2024
1 parent 5dfb62f commit 45f5c4c
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand Down

0 comments on commit 45f5c4c

Please sign in to comment.