为什么我的Mongoose 3.8.7模式获取器和设置器被忽略? [英] Why are my Mongoose 3.8.7 schema getters and setters being ignored?

查看:66
本文介绍了为什么我的Mongoose 3.8.7模式获取器和设置器被忽略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While working with Node.js, Mongoose and MongoDB, I have found that my Mongoose schema getters and setters do not fire when I perform a findOne query.

我发现一个旧线程表明版本2.x中的getter和setter存在问题,但它指出此问题已得到解决,并且我使用的是最新版本的Mongoose(3.8.7)

I have found an old thread that suggests there was an issue with getters and setters in version 2.x, but it states that it has since been resolved and I'm using the very latest version of 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);
});

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

It responds with a username value that lacks the " test" post-fix. Am I doing something wrong here? Any help would be greatly appreciated!

其他信息

这是找到一个的结果:

{
    "username": "Radius"
}

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

This is the value of schema.paths.username.getters after applying one through one of the two ways described above:

[ [Function: testGetter] ]

推荐答案

我遇到了同样的问题,即用Mongoose查询时,吸气剂没有修改返回的文档.要将其应用于每个查询,您可以执行以下操作:

I was having the same problem with getters not modifying the returned documents when querying with Mongoose. To make this apply to every query, you can do this:

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

这篇关于为什么我的Mongoose 3.8.7模式获取器和设置器被忽略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆