为什么我的Mongoose 3.8.7模式获取器和设置器被忽略?

在使用Node.js,Mongoose和MongoDB时,我发现当执行findOne查询时,我的Mongoose模式获取器和设置器不会触发。

我发现了一个旧的线程,表明在版本2.x中有一个getter和setter的问题,但是它表明它已经被解决了,而且我正在使用最新版本的Mongoose(3.8.7)。

这是我的模式的一部分

function testGetter(value) { return value + " test"; } /** * Schema */ var schema = new Schema({ username: { type: String, required: true, unique: true, get: testGetter } }); // I have also tried this. schema.path('username').get(function (value, schemaType) { return value + " test"; }); 

以下是我如何执行查询

 Model .findOne(conditions, fields, options) .populate(population) .exec(function (error, doc) { callback(doc, error); }); 

它回应一个用户名值,缺乏“testing”后修复。 我在这里做错了什么? 任何帮助将不胜感激!

附加信息

这是find的结果:

 { "username": "Radius" } 

这是schema.paths.username.getters在通过上述两种方法之一应用之后的值:

 [ [Function: testGetter] ] 

我在使用Mongoose查询时没有修改返回的文档时遇到同样的问题。 为了使这适用于每个查询,你可以这样做:

 // Enable Mongoose getter functions schema.set('toObject', { getters: true }); schema.set('toJSON', { getters: true }); 

你是否假设虚拟机不工作,因为它们没有显示在你的console.log输出中? 如果是这样,那就是devise。 虚拟是实际文档的外部,所以不要使用console.log默认打印。 要让它们显示,请阅读这些文档: http : //mongoosejs.com/docs/api.html#document_Document-toObject

尝试

 schema.virtual('password').get(function () { return this.username; }); 

作为你的getter函数, this是你的实体实例, value参数在这里没有多大意义。

如果您正在编写setter函数,则必须编写this.username = value