Skip to content

Commit

Permalink
refactor: move populate virtual setter logic into populate helper
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Feb 1, 2024
1 parent 9739dfc commit f2e4d64
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 19 deletions.
23 changes: 23 additions & 0 deletions lib/helpers/populate/setPopulatedVirtualValue.js
@@ -0,0 +1,23 @@
'use strict';

module.exports = function setPopulatedVirtualValue(populatedVirtuals, name, v, options) {
if (options.justOne || options.count) {
populatedVirtuals[name] = Array.isArray(v) ?
v[0] :
v;

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

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

return populatedVirtuals[name];
};
26 changes: 7 additions & 19 deletions lib/schema.js
Expand Up @@ -20,6 +20,7 @@ const handleReadPreferenceAliases = require('./helpers/query/handleReadPreferenc
const idGetter = require('./helpers/schema/idGetter');
const merge = require('./helpers/schema/merge');
const mpath = require('mpath');
const setPopulatedVirtualValue = require('./helpers/populate/setPopulatedVirtualValue');
const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
const utils = require('./utils');
const validateRef = require('./helpers/populate/validateRef');
Expand Down Expand Up @@ -2293,25 +2294,12 @@ Schema.prototype.virtual = function(name, options) {
this.$$populatedVirtuals = {};
}

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';
});
}

return this.$$populatedVirtuals[name];
return setPopulatedVirtualValue(
this.$$populatedVirtuals,
name,
v,
options
);
});

if (typeof options.get === 'function') {
Expand Down

0 comments on commit f2e4d64

Please sign in to comment.