Mongoose SchemaTypes Getters
Last Updated :
07 May, 2023
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
const mongoose = require( 'mongoose' );
const geekSchema = new mongoose.Schema({
name: {
type: String,
get: (name) => name.toUpperCase()
}
});
const Geek = mongoose.model( 'Geek' , geekSchema);
const geek = new Geek({ name: 'geeksforgeeks' });
console.log(geek.name);
|
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
const mongoose = require( 'mongoose' );
const md5 = require( 'md5' );
const userSchema = new mongoose.Schema({
email: {
type: String,
get: (email) => {
let masked = "" ;
let mailId = email;
let prefix = mailId.substring(0,
mailId.lastIndexOf( "@" ));
let postfix = mailId.substring(
mailId.lastIndexOf( "@" ));
for (let i = 0; i < prefix.length; i++) {
if (i == 0 || i == prefix.length - 1) {
masked = masked + prefix[i].toString();
}
else {
masked = masked + "*" ;
}
}
masked = masked + postfix;
return masked;
}
},
password: {
type: String,
get: (type) => md5(type)
}
});
const User = mongoose.model( 'User' , userSchema);
const user = new User({
email: 'abc1452@gmail.com' ,
password: '1234'
});
console.log(user.email);
console.log(user.password);
|
Output:
Share your thoughts in the comments
Please Login to comment...