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.

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

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

    To skip getters on a one-off basis, use as shown below.

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

    Mongoose also runs setters on update operations, like updateOne(). Mongoose will 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. 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. return v.toLowerCase();
    5. }
    6. }
    7. const user = new User();
    8. user.email = 'TEST@gmail.com';
    9. user.email; // undefined