Why are my Mongoose 3.8.7 schema getters and setters being ignored?

廉价感情. 提交于 2019-12-09 14:59:42

问题


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.

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).

Here's part of my schema

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";
});

Here's how I execute the query

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!

Additional information

This is the result of the find one:

{
    "username": "Radius"
}

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

[ [Function: testGetter] ]

回答1:


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 });



回答2:


Are you assuming virtuals are not working because they don't show up in your console.log output? If so, that is by design. Virtuals are external to your actual document so do not get printed with console.log by default. To get them to display, read these docs: http://mongoosejs.com/docs/api.html#document_Document-toObject




回答3:


Try

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

as your getter function, this is your entity instance and the value parameter doesn't mean much here.

If you were writing a setter function, you would have to write this.username = value.



来源:https://stackoverflow.com/questions/21832088/why-are-my-mongoose-3-8-7-schema-getters-and-setters-being-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!