Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] ]
like image 784
Synzvato Chavea Avatar asked Feb 17 '14 14:02

Synzvato Chavea


People also ask

Which schema types are not supported by Mongoose?

Mongoose does not natively support long and double datatypes for example, although MongoDB does.

What is getters and setters in Mongoose?

Mongoose getters and setters allow you to execute custom logic when getting or setting a property on a Mongoose document. Getters let you transform data in MongoDB into a more user friendly form, and setters let you transform user data before it gets to MongoDB.

Does Mongoose need schema?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.


2 Answers

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 });
like image 187
Jamie S Avatar answered Sep 30 '22 10:09

Jamie S


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

like image 44
aaronheckmann Avatar answered Sep 30 '22 10:09

aaronheckmann