为什么我的Mongoose 3.8.7模式getter和setter被忽略了?

Syn*_*vea 11 getter setter schema mongoose node.js

在使用Node.js,Mongoose和MongoDB时,我发现当我执行findOne查询时,我的Mongoose模式getter和setter不会触发.

我发现一个旧线程表明版本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";
});
Run Code Online (Sandbox Code Playgroud)

这是我执行查询的方式

Model
.findOne(conditions, fields, options)
.populate(population)
.exec(function (error, doc) {
        callback(doc, error);
});
Run Code Online (Sandbox Code Playgroud)

它使用缺少"测试"后修复的用户名值进行响应.我在这里做错了吗?任何帮助将不胜感激!

附加信息

这是找到一个的结果:

{
    "username": "Radius"
}
Run Code Online (Sandbox Code Playgroud)

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

[ [Function: testGetter] ]
Run Code Online (Sandbox Code Playgroud)

小智 37

在使用Mongoose查询时,我遇到了同样的问题,即getters没有修改返回的文档.要使此适用于每个查询,您可以执行以下操作:

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


aar*_*ann 5

您是否认为虚拟机无法正常运行,因为它们未显示在您的console.log输出中?如果是这样,那就是设计.虚拟文件在实际文档的外部,因此默认情况下不会使用console.log打印.要让它们显示,请阅读以下文档:http://mongoosejs.com/docs/api.html#document_Document-toObject