Getters/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.
Suppose you have a collection and you want to obfuscate user emails to protect your users’ privacy. Below is a basic userSchema
that obfuscates the user’s email address.
By default, Mongoose executes getters when converting a document to JSON, including .
app.get(function(req, res) {
return User.findOne().
// The `email` getter will run here
then(doc => res.json(doc)).
catch(err => res.status(500).json({ message: err.message }));
To disable running getters when converting a document to JSON, set the toJSON.getters
option to false
in your schema as shown below.
user.get('email', null, { getters: false }); // 'ab@gmail.com'
Suppose you want to make sure all user emails in your database are lowercased to make it easy to search without worrying about case. Below is an example userSchema
that ensures emails are lowercased.
Mongoose also runs setters on update operations, like . Mongoose will upsert a document with a lowercased email
in the below example.
await User.updateOne({}, { email: 'TEST@gmail.com' }, { upsert: true });
const doc = await User.findOne();
doc.email; // 'test@gmail.com'
Mongoose setters are different from because they allow you to transform the value being set. With ES6 setters, you would need to store an internal _email
property to use a setter. With Mongoose, you do not need to define an internal property or define a corresponding getter for email
.
class User {
// This won't convert the email to lowercase! That's because `email`
// is just a setter, the actual `email` property doesn't store any data.
return v.toLowerCase();
}
}
const user = new User();
user.email = 'TEST@gmail.com';
user.email; // undefined