Open In App

Mongoose SchemaTypes Getters

Last Updated : 07 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is a popular Object Data Modeling (ODM) library for MongoDB in Node.js and MongoDB. Mongoose can define custom getters and setters for schema fields using SchemaTypes. Getters allow you to define a function that transforms the raw value of a schema field before it is returned from the database. This can be useful for formatting, parsing, or encrypting data stored in MongoDB.

Parameters: The getter function defined for a SchemaType should accept one argument and the value of the field that is being transformed. The function can return any value that should be used as the transformed value for the field. If the function returns undefined, the original value of the field will be used instead.

Syntax:

const mySchema = new mongoose.Schema({
    field: {
        type: String,
        get: function(value) {
            // Transform and return value here
            return transformedValue;
        }
    }
});

Example 1: Here we use the javascript inbuilt function toUpperCase. When the user inputs any value either in lowercase or in uppercase it is automatically converted into uppercase before it gets to MongoDB.

Javascript




// Import the mongoose
const mongoose = require('mongoose');
  
// User Schema
// Define the schema for the "Geek" object
const geekSchema = new mongoose.Schema({
    name: {
  
        // The "name" field is of type "String"
        type: String,
          
        // A getter function that returns the 
        // value of the "name" field in uppercase
        get: (name) => name.toUpperCase()
    }
});
  
// User model
// Create a model for the "Geek" object
// using the "geekSchema" schema
const Geek = mongoose.model('Geek', geekSchema);
  
// Create a new "Geek" object with the "name" 
// field set to "geeksforgeeks"
const geek = new Geek({ name: 'geeksforgeeks' });
  
// Log the value of the "name" field on the console
console.log(geek.name); // Output: "GEEKSFORGEEKS"


Output:

Output

Example 2: Here we make a schema of email and password, where we try to mask the email and encrypt the password. To mask the email we will bulid our own function and, we use md5 hashing. First we must install md5 in the app using the command in command prompt.

npm i md5

Javascript




// Import required dependencies
// Import Mongoose for defining the 
// schema and model
const mongoose = require('mongoose');
  
// Import MD5 for encrypting the password
const md5 = require('md5');
  
// Define the user schema
const userSchema = new mongoose.Schema({
    email: {
  
        // Set the data type to string
        type: String,
          
        // Define a getter function for email field
        get: (email) => {
  
            // Initialize a variable for storing
            // the masked email
            let masked = "";
  
            // Get the actual email value
            let mailId = email;
              
            // Get the prefix part of email
            let prefix = mailId.substring(0, 
                mailId.lastIndexOf("@"));
              
            // Get the postfix part of email
            let postfix = mailId.substring(
                mailId.lastIndexOf("@"));
  
            // Loop through each character of prefix
            for (let i = 0; i < prefix.length; i++) {
  
                // Keep first and last characters unmasked
                if (i == 0 || i == prefix.length - 1) {
  
                    // Append the unmasked character
                    // to masked string 
                    masked = masked + prefix[i].toString();
                }
                else {
                    // Mask all other characters with '*'
                    masked = masked + "*";
                }
            }
  
            // Add the postfix to masked string
            masked = masked + postfix;
            return masked; // Return the masked email
        }
    },
    password: {
  
        // Set the data type to string
        type: String,
  
        // Define a getter function for password 
        // field to encrypt the value using MD5
        get: (type) => md5(type)
    }
});
  
// Create a user model from the schema
const User = mongoose.model('User', userSchema);
  
// Create a new user instance with email and password
const user = new User({ 
    email: 'abc1452@gmail.com'
    password: '1234' 
});
  
// Log the masked email and encrypted
// password of the user
  
// Output: a******@gmail.com
console.log(user.email);
  
// Output: 81dc9bdb52d04dc20036dbd8313ed055
console.log(user.password);


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads