diff --git a/lib/document.js b/lib/document.js index fa290a7a376..74d953ae898 100644 --- a/lib/document.js +++ b/lib/document.js @@ -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; @@ -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 @@ -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; @@ -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];