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.

Getters

Suppose you have a User 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.

  1. const userSchema = new Schema({
  2. email: {
  3. type: String,
  4. get: obfuscate
  5. }
  6. });
  7. // Mongoose passes the raw value in MongoDB `email` to the getter
  8. function obfuscate(email) {
  9. const separatorIndex = email.indexOf('@');
  10. if (separatorIndex < 3) {
  11. // 'ab@gmail.com' -> '**@gmail.com'
  12. return email.slice(0, separatorIndex).replace(/./g, '*') +
  13. email.slice(separatorIndex);
  14. }
  15. // 'test42@gmail.com' -> 'te****@gmail.com'
  16. return email.slice(0, 2) +
  17. email.slice(2, separatorIndex).replace(/./g, '*') +
  18. email.slice(separatorIndex);
  19. }
  20. const User = mongoose.model('User', userSchema);
  21. const user = new User({ email: 'ab@gmail.com' });
  22. user.email; // **@gmail.com

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.

By default, Mongoose executes getters when converting a document to JSON, including Express’ res.json() function.

  1. app.get(function(req, res) {
  2. return User.findOne().
  3. // The `email` getter will run here
  4. then(doc => res.json(doc)).
  5. catch(err => res.status(500).json({ message: err.message }));
  6. });

To disable running getters when converting a document to JSON, set the toJSON.getters option to false in your schema as shown below.

  1. const userSchema = new Schema({
  2. email: {
  3. type: String,
  4. get: obfuscate
  5. }
  6. }, { toJSON: { getters: false } });

To skip getters on a one-off basis, use user.get() with the getters option set to false as shown below.

  1. user.get('email', null, { getters: false }); // 'ab@gmail.com'

Setters

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.

  1. const userSchema = new Schema({
  2. email: {
  3. type: String,
  4. set: v => v.toLowerCase()
  5. }
  6. });
  7. const User = mongoose.model('User', userSchema);
  8. const user = new User({ email: 'TEST@gmail.com' });
  9. user.email; // 'test@gmail.com'
  10. // The raw value of `email` is lowercased
  11. user.get('email', null, { getters: false }); // 'test@gmail.com'
  12. user.set({ email: 'NEW@gmail.com' });
  13. user.email; // 'new@gmail.com'

Mongoose also runs setters on update operations, like updateOne(). Mongoose will upsert a document with a lowercased email in the below example.

  1. await User.updateOne({}, { email: 'TEST@gmail.com' }, { upsert: true });
  2. const doc = await User.findOne();
  3. 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.

  1. const userSchema = new Schema({
  2. email: {
  3. type: String,
  4. set: toLower
  5. }
  6. });
  7. function toLower(email) {
  8. // Don't transform `email` if using `updateOne()` or `updateMany()`
  9. if (!(this instanceof mongoose.Document)) {
  10. return email;
  11. }
  12. return email.toLowerCase();
  13. }
  14. const User = mongoose.model('User', userSchema);
  15. await User.updateOne({}, { email: 'TEST@gmail.com' }, { upsert: true });
  16. const doc = await User.findOne();
  17. doc.email; // 'TEST@gmail.com'

Differences vs ES6 Getters/Setters

Mongoose setters are different from ES6 setters 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 _email property or define a corresponding getter for email.

  1. class User {
  2. // This won't convert the email to lowercase! That's because `email`
  3. // is just a setter, the actual `email` property doesn't store any data.
  4. set email(v) {
  5. return v.toLowerCase();
  6. }
  7. }
  8. const user = new User();
  9. user.email = 'TEST@gmail.com';
  10. user.email; // undefined