Mongoose SchemaType.prototype.transform() API
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose SchemaType transform is a SchemaType method that allows us to transform or manipulate a path when converting a document into JSON. Mongoose uses the current value of the path as a parameter for the method. 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
touch main.js
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 transform function that will give us the year of the data stored in a path.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err) :
console.log( 'Connected to database' ));
const personSchema = new mongoose.Schema({
date: {
type: Date,
transform: v => v.getFullYear()
}
});
const Person = mongoose.model( 'Person' , personSchema);
const person = new Person({ date: new Date() });
console.log(person.toJSON().date);
|
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 transform function that will give us the full name of a person from an Array of first names and Last names.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log( 'Connected to database' ));
const personSchema = new mongoose.Schema({
name: {
type: Array,
transform: v => v.join( ' ' )
}
});
const Person = mongoose.model( 'Person' , personSchema);
const person = new Person({ name: [ 'John' , 'Doe' ] });
console.log(person.toJSON().name);
|
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/schematype.html#schematype_SchemaType-transform
Last Updated :
02 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...