Skip to content

Commit

Permalink
fix(document): handle dotted virtuals in toJSON output
Browse files Browse the repository at this point in the history
Fix #5473
  • Loading branch information
vkarpov15 committed Jul 25, 2017
1 parent 6e02dbb commit 2ede28b
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ var Schema = require('./schema');
var ObjectExpectedError = require('./error/objectExpected');
var StrictModeError = require('./error/strict');
var ValidatorError = require('./schematype').ValidatorError;
var VirtualType = require('./virtualtype');
var utils = require('./utils');
var clone = utils.clone;
var isMongooseObject = utils.isMongooseObject;
Expand Down Expand Up @@ -948,9 +949,13 @@ Document.prototype.get = function(path, type) {
adhoc = Schema.interpretAsType(path, type, this.schema.options);
}

var schema = this.$__path(path) || this.schema.virtualpath(path),
pieces = path.split('.'),
obj = this._doc;
var schema = this.$__path(path) || this.schema.virtualpath(path);
var pieces = path.split('.');
var obj = this._doc;

if (schema instanceof VirtualType) {
return schema.applyGetters(null, this);
}

for (var i = 0, l = pieces.length; i < l; i++) {
obj = obj === null || obj === void 0
Expand Down Expand Up @@ -2328,6 +2333,7 @@ function applyGetters(self, json, type, options) {
var schema = self.schema;
var paths = Object.keys(schema[type]);
var i = paths.length;
var numPaths = i;
var path;
var cur = self._doc;
var v;
Expand All @@ -2336,6 +2342,26 @@ function applyGetters(self, json, type, options) {
return json;
}

if (type === 'virtuals') {
for (i = 0; i < numPaths; ++i) {
path = paths[i];
parts = path.split('.');
v = self.get(path);
if (v === void 0) {
continue;
}
plen = parts.length;
cur = json;
for (var j = 0; j < plen - 1; ++j) {
cur[parts[j]] = cur[parts[j]] || {};
cur = cur[parts[j]];
}
cur[parts[plen - 1]] = v;
}

return json;
}

while (i--) {
path = paths[i];

Expand Down

0 comments on commit 2ede28b

Please sign in to comment.