Skip to content

Commit

Permalink
Merge pull request #14673 from Automattic/vkarpov15/gh-14394-perf-jun17
Browse files Browse the repository at this point in the history
perf: avoid unnecesary get() call and use faster approach for converting to string
  • Loading branch information
vkarpov15 authored Jun 18, 2024
2 parents b955724 + 20d1500 commit e7a6e31
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 6 deletions.
5 changes: 3 additions & 2 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion lib/helpers/schema/idGetter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 2 additions & 3 deletions test/document.unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit e7a6e31

Please sign in to comment.