diff --git a/lib/helpers/populate/setPopulatedVirtualValue.js b/lib/helpers/populate/setPopulatedVirtualValue.js new file mode 100644 index 00000000000..b99ff798f22 --- /dev/null +++ b/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]; +}; diff --git a/lib/schema.js b/lib/schema.js index 48ca4365bfd..5941b8ebf5e 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -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'); @@ -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') {