Skip to content

Commit

Permalink
fix(virtualtype): always get populated virtual value before running g…
Browse files Browse the repository at this point in the history
…etters, better fix for #9343
  • Loading branch information
vkarpov15 committed Nov 7, 2020
1 parent abb2e74 commit e0c7006
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 31 deletions.
53 changes: 22 additions & 31 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1717,40 +1717,31 @@ Schema.prototype.virtual = function(name, options) {

const virtual = this.virtual(name);
virtual.options = options;
process.nextTick(() => {
virtual.
get(function(_v) {
if (this.$$populatedVirtuals &&
this.$$populatedVirtuals.hasOwnProperty(name)) {
return this.$$populatedVirtuals[name];
}
if (_v == null) return undefined;
return _v;
}).
set(function(_v) {
if (!this.$$populatedVirtuals) {
this.$$populatedVirtuals = {};
}

if (options.justOne || options.count) {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v[0] :
_v;
virtual.
set(function(_v) {
if (!this.$$populatedVirtuals) {
this.$$populatedVirtuals = {};
}

if (typeof this.$$populatedVirtuals[name] !== 'object') {
this.$$populatedVirtuals[name] = options.count ? _v : null;
}
} else {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v :
_v == null ? [] : [_v];

this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
return doc && typeof doc === 'object';
});
if (options.justOne || options.count) {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v[0] :
_v;

if (typeof this.$$populatedVirtuals[name] !== 'object') {
this.$$populatedVirtuals[name] = options.count ? _v : null;
}
});
});
} else {
this.$$populatedVirtuals[name] = Array.isArray(_v) ?
_v :
_v == null ? [] : [_v];

this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
return doc && typeof doc === 'object';
});
}
});

if (typeof options.get === 'function') {
virtual.get(options.get);
Expand Down
8 changes: 8 additions & 0 deletions lib/virtualtype.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const utils = require('./utils');

/**
* VirtualType constructor
*
Expand Down Expand Up @@ -137,6 +139,12 @@ VirtualType.prototype.set = function(fn) {
*/

VirtualType.prototype.applyGetters = function(value, doc) {
if (utils.hasUserDefinedProperty(this.options, ['ref', 'refPath']) &&
doc.$$populatedVirtuals &&
doc.$$populatedVirtuals.hasOwnProperty(this.path)) {
value = doc.$$populatedVirtuals[this.path];
}

let v = value;
for (let l = this.getters.length - 1; l >= 0; l--) {
v = this.getters[l].call(doc, v, this, doc);
Expand Down

0 comments on commit e0c7006

Please sign in to comment.