![]() |
VOOZH | about |
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:
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.
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:
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:
Reference: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-cast