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.

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
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
mongoose.Number.cast(v => {
if (typeof v === 'number') { return '30' }
})
let personSchema = new Schema({
name: String,
age: Number
});
let Person = mongoose.model('Person', personSchema);
let person = new Person({
name: 'John Doe',
age: 30
});
console.log('Type of Age is : ', typeof person.age);
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
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let personSchema = new mongoose.Schema({
name: String,
age: {
type: Number,
cast: function castAge(v) {
if (typeof v === 'number') {
return v;
}
if (typeof v === 'string' && !isNaN(v)) {
return +v;
}
if (v instanceof Date) {
return Math.floor((Date.now() - v) /
(1000 * 60 * 60 * 24 * 365));
}
}
}
});
let Person = mongoose.model('Person', personSchema);
let person = new Person({
name: 'John Doe',
age: new Date('2001/01/30')
});
console.log('Type of Age is : ', typeof person.age);
console.log('Age of Person is :', person.age);
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