Intermediate LevelMongoDB & Mongoose
How do you create custom SchemaTypes in Mongoose?
❓ Interview Prompt: Explain extending mongoose.SchemaType, implementing cast(), validate(), and serialize() for custom data types.
Extending 'mongoose.SchemaType' allows creating custom data types (e.g. 'Int32', 'EncryptedString', 'EmailType') with custom casting and validation logic:
Code Implementation Example
typescript
import mongoose from 'mongoose';
class Int32Type extends mongoose.SchemaType {
cast(val: any) {
const num = Number(val);
if (isNaN(num) || !Number.isInteger(num)) {
throw new Error('Int32Type: ${val} is not an integer');
}
return num;
}
}
mongoose.Schema.Types.Int32Type = Int32Type;💡Extending Mongoose SchemaType to build custom data casting rules.
🎯 Interview Key Takeaway
Create custom Mongoose SchemaTypes to encapsulate domain-specific data parsing and validation rules.
#SchemaTypes#Mongoose#Custom Types#Intermediate
Back to all MongoDB & Mongoose Questions→