QA
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→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?