Open In App

Mongoose SchemaTypes Getters

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
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.

What Are Mongoose Getters?

In Mongoose, getters are functions that are used to transform or manipulate the raw value of a schema field before it is returned from the database. This can be helpful for various purposes like formatting, parsing, or encrypting data. We can define a getter on any field in your Mongoose schema by using the get property within the field's definition.

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.

Why Use Mongoose Getters?

  1. Data Transformation: Getters allow you to return data in a desired format, such as transforming dates into human-readable formats or changing strings to uppercase.
  2. Security: You can use getters to encrypt sensitive data (e.g., passwords) or mask fields like emails for privacy.
  3. Data Formatting: Getters can be used to format or clean data before sending it to the client.

How to Define Getters in Mongoose Schema

To define a getter in Mongoose, use the get property within your schema definition. The getter function takes the field's raw value as an argument and returns the transformed value.

Syntax:

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

Parameters:

  • The getter function takes one argument: the value of the field being transformed.
  • The function should return the desired transformed value. If the function returns undefined, the original value is used.

Example 1: Convert Text to Uppercase Using a Getter

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.

// 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

Explanation: In this example, the name field is automatically converted to uppercase when fetched from the database.

Example 2: Masking Emails and Encrypting Passwords Using Getters

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
// 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: '[email protected]',
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:

Explanation:

  • The email is masked such that only the first and last characters are visible, and the rest are replaced with *.
  • The password is encrypted using the MD5 hashing algorithm.

How to Apply Getters for Field Transformation in Mongoose

1. Formatting Dates: You might want to format dates to a more readable format before sending them to the client.

const schema = new mongoose.Schema({
createdAt: {
type: Date,
get: (date) => date.toLocaleDateString() // Format date into a readable string
}
});

2. Handling Arrays or Complex Data Types: You can also use getters to format or process arrays or objects before they are returned.

const schema = new mongoose.Schema({
tags: {
type: [String],
get: (tags) => tags.join(', ') // Convert array to a string
}
});

What is __v in Mongoose?

In Mongoose, the __v field is used to track the version of a document. This field is automatically added to every document in a collection by Mongoose. It's used to implement versioning for documents, which helps in handling concurrency and ensuring the integrity of document updates.

You can disable the __v field by setting versionKey: false in your schema options:

const schema = new mongoose.Schema({
name: String
}, { versionKey: false });

How to Join Two Schemas in Mongoose?

We can join two schemas in Mongoose using population. Population allows you to reference documents from one schema in another. For example, if you have a Post schema and a User schema, you can populate the user field in the post document with the user’s data.

const postSchema = new mongoose.Schema({
title: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

const userSchema = new mongoose.Schema({
name: String,
email: String
});

const Post = mongoose.model('Post', postSchema);
const User = mongoose.model('User', userSchema);

// Fetch a post and populate its author details
Post.findOne({ title: 'Mongoose Guide' })
.populate('author')
.exec((err, post) => {
console.log(post.author.name); // Access user details from the post
});

What is the Type of _id in Mongoose?

In Mongoose, the _id field is automatically created for each document in a collection. By default, _id is of type ObjectId, which is a unique identifier generated by MongoDB for each document. You can customize the _id field by specifying a different type, but typically it remains as an ObjectId.

const schema = new mongoose.Schema({
name: String
});

// The _id field will be of type ObjectId by default
const Model = mongoose.model('Model', schema);

Conclusion

Mongoose getters offer a powerful way to manipulate data before it’s retrieved from the database. Whether you need to format strings, mask sensitive data, or handle complex data structures, getters give you the flexibility to ensure the data is presented in the best way. Understanding getters in Mongoose can significantly improve how you work with MongoDB data in your Node.js applications. By following this article, you can make the most of Mongoose’s getter functionality and enhance your MongoDB workflows.


Next Article

Similar Reads