Skip to content

Commit

Permalink
perf(document): only loop over doc once when shallow cloning re: #14719
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jul 8, 2024
1 parent 69de006 commit 517f27b
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -3868,17 +3868,21 @@ Document.prototype.$toObject = function(options, json) {
if (hasOnlyPrimitiveValues) {
// Fast path: if we don't have any nested objects or arrays, we only need a
// shallow clone.
ret = this._doc
? options.minimize ? (minimize({ ...this._doc }) || {}) : { ...this._doc }
: {};
if (!options.minimize || options.flattenObjectIds) {
const keys = Object.keys(ret);
for (const key of keys) {
// If `minimize` is false, still need to remove undefined keys
if (!options.minimize && ret[key] === undefined) {
if (this._doc == null) {
ret = {};
}
ret = {};
if (this._doc != null) {
for (const key of Object.keys(this._doc)) {
const value = this._doc[key];
if (value instanceof Date) {
ret[key] = new Date(value);
} else if (value === undefined) {
delete ret[key];
} else if (options.flattenObjectIds && isBsonType(ret[key], 'ObjectId')) {
ret[key] = ret[key].toJSON();
} else if (options.flattenObjectIds && isBsonType(value, 'ObjectId')) {
ret[key] = value.toJSON();
} else {
ret[key] = value;
}
}
}
Expand Down

0 comments on commit 517f27b

Please sign in to comment.