From 2991d7b8eb46e8649dd1338d27c650ac9bfe5637 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 17 Jun 2024 14:32:46 -0400 Subject: [PATCH 1/2] perf: avoid unnecesary get() call and use faster approach for converting to string Re: #14394 --- lib/document.js | 5 +++-- lib/helpers/schema/idGetter.js | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/document.js b/lib/document.js index bdb6e2e57df..d907886ece3 100644 --- a/lib/document.js +++ b/lib/document.js @@ -4066,7 +4066,8 @@ Document.prototype.toObject = function(options) { function applyVirtuals(self, json, options, toObjectOptions) { const schema = self.$__schema; - const paths = Object.keys(schema.virtuals); + const virtuals = schema.virtuals; + const paths = Object.keys(virtuals); let i = paths.length; const numPaths = i; let path; @@ -4117,7 +4118,7 @@ function applyVirtuals(self, json, options, toObjectOptions) { assignPath = path.substring(options.path.length + 1); } if (assignPath.indexOf('.') === -1 && assignPath === path) { - v = self.get(path, null, { noDottedPath: true }); + v = virtuals[path].applyGetters(void 0, self); v = clone(v, options); if (v === void 0) { continue; diff --git a/lib/helpers/schema/idGetter.js b/lib/helpers/schema/idGetter.js index 1fe7cc77ab3..5b576531272 100644 --- a/lib/helpers/schema/idGetter.js +++ b/lib/helpers/schema/idGetter.js @@ -27,7 +27,7 @@ module.exports = function addIdGetter(schema) { function idGetter() { if (this._id != null) { - return String(this._id); + return this._id.toString(); } return null; From 20d1500f274da5226a4b12bc9c95e1a5a823bfa6 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 17 Jun 2024 14:39:02 -0400 Subject: [PATCH 2/2] fix tests --- test/document.unit.test.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/document.unit.test.js b/test/document.unit.test.js index dbae16908ac..d5b84176a35 100644 --- a/test/document.unit.test.js +++ b/test/document.unit.test.js @@ -37,12 +37,11 @@ describe('toObject()', function() { beforeEach(function() { Stub = function() { - const schema = this.$__schema = { + this.$__schema = { options: { toObject: { minimize: false, virtuals: true } }, - virtuals: { virtual: 'test' } + virtuals: { virtual: { applyGetters: () => 'test' } } }; this._doc = { empty: {} }; - this.get = function(path) { return schema.virtuals[path]; }; this.$__ = {}; }; Stub.prototype = Object.create(mongoose.Document.prototype);