Open In App

Mongoose Schematype.set() API

Last Updated : 03 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is a MongoDB object modeling and handling for a node.js environment.

Mongoose SchemaType setters are SchemaType methods that allow us to transform or manipulate data before it gets stored in MongoDB or before a query is executed. Let’s understand more about this with some examples.

Creating node application And Installing Mongoose:

Step 1: Create a node application using the following command:

mkdir folder_name
cd folder_name
npm init -y

Step 2: After creating the ReactJS application, Install the required module using the following command:

npm install mongoose

Project Structure: It will look like the following.

 

Example 1: In this example, we will create a setter that will allow us to convert a name into uppercase before it gets stored in DB.

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : console.log
    ('Connected to database'));
  
function toUpper(v) {
    return v.toUpperCase();
}
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
        set: toUpper
    }
});
  
const Person = mongoose.model('Person', personSchema);
const person = new Person({ name: 'John' });
console.log(person.name);


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Example 2: In this example, we will create a setter that will allow us to convert an age into a number before it gets stored in DB.

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : 
    console.log('Connected to database'));
  
function helper(val) {
    if (typeof val === 'string') {
        val = Number(val)
    }
    return val;
}
  
const personSchema = new mongoose.Schema({
    age: {
        type: Number,
        set: helper,
    }
});
  
const Person = mongoose.model('Person', personSchema);
const person = new Person({ age: '21' });
console.log(person.age);


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Reference: https://mongoosejs.com/docs/api.html#schematype_SchemaType-set



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads