diff --git a/lib/document.js b/lib/document.js index bdb6e2e57df..d907886ece3 100644 --- a/lib/document.js +++ b/lib/document.js @@ -4066,7 +4066,8 @@ Document.prototype.toObject = function(options) { function applyVirtuals(self, json, options, toObjectOptions) { const schema = self.$__schema; - const paths = Object.keys(schema.virtuals); + const virtuals = schema.virtuals; + const paths = Object.keys(virtuals); let i = paths.length; const numPaths = i; let path; @@ -4117,7 +4118,7 @@ function applyVirtuals(self, json, options, toObjectOptions) { assignPath = path.substring(options.path.length + 1); } if (assignPath.indexOf('.') === -1 && assignPath === path) { - v = self.get(path, null, { noDottedPath: true }); + v = virtuals[path].applyGetters(void 0, self); v = clone(v, options); if (v === void 0) { continue; diff --git a/lib/helpers/schema/idGetter.js b/lib/helpers/schema/idGetter.js index 1fe7cc77ab3..5b576531272 100644 --- a/lib/helpers/schema/idGetter.js +++ b/lib/helpers/schema/idGetter.js @@ -27,7 +27,7 @@ module.exports = function addIdGetter(schema) { function idGetter() { if (this._id != null) { - return String(this._id); + return this._id.toString(); } return null; diff --git a/test/document.unit.test.js b/test/document.unit.test.js index dbae16908ac..d5b84176a35 100644 --- a/test/document.unit.test.js +++ b/test/document.unit.test.js @@ -37,12 +37,11 @@ describe('toObject()', function() { beforeEach(function() { Stub = function() { - const schema = this.$__schema = { + this.$__schema = { options: { toObject: { minimize: false, virtuals: true } }, - virtuals: { virtual: 'test' } + virtuals: { virtual: { applyGetters: () => 'test' } } }; this._doc = { empty: {} }; - this.get = function(path) { return schema.virtuals[path]; }; this.$__ = {}; }; Stub.prototype = Object.create(mongoose.Document.prototype);