VOOZH about

URL: https://www.geeksforgeeks.org/mongodb/mongoose-schematype-cast-api/

⇱ Mongoose Schematype.cast() API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mongoose Schematype.cast() API

Last Updated : 28 Apr, 2025

Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose.SchemaType.cast() is a method provided by Mongoose, which is used to cast a value to the appropriate type defined by a Mongoose schema. Let’s understand more about this with some examples.

Syntax:

mongoose.datatype.cast( function(){})

Parameters: 

  • datatype: It is the datatype for which type we want to cast the data. 
  • function: It is a function that uses some logic and returns desired datatype. 

Returns type: It returns the anonymous function which is cast to the datatype.

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 application, Install the required module using the following command:
Advertisement

npm install mongoose

Project Structure: It will look like the following.

πŸ‘ Image
output1

Example 1: In this example, we will use the cast function in the mongoose and type cast the age property of person Schema to string. 

Filename: script.js

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

node script.js

Output:

πŸ‘ Image
 

Example 2: In this example, we will set the cast function inside the age in the property in the schema and typecast the property to Number.

Filename: script2.js

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

node script2.js

Output:

πŸ‘ Image
 

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

Comment
Article Tags:

Explore