Getters/Setters in Mongoose
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.
Keep in mind that getters do not impact the underlying data stored in MongoDB. If you save user
, the email
property will be ‘ab@gmail.com’ in the database.
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 as shown below.
To skip getters on a one-off basis, use user.get()
with the option set to false
as shown below.
user.get('email', null, { getters: false }); // 'ab@gmail.com'
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'
In a setter function, this
can be either the document being set or the query being run. If you don’t want your setter to run when you call updateOne()
, you add an if statement that checks if this
is a Mongoose document as shown below.
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