QA
Beginner LevelMongoDB & Mongoose

How do toJSON and toObject transforms work in Mongoose schemas?

❓ Interview Prompt: Explain schema options (toJSON, toObject), custom transform functions, stripping sensitive properties, and mapping _id to id.

When serializing Mongoose Document instances to JSON (e.g. 'res.json(user)'), Mongoose invokes 'toJSON()' transforms:

Common Transforms:

•
Remove sensitive internal fields ('password', '__v').
•
Rename '_id' to standard 'id' string representations.

Code Implementation Example

typescript
import { Schema } from 'mongoose';

const userSchema = new Schema({
  name: String,
  passwordHash: String
}, {
  toJSON: {
    transform: (doc, ret) => {
      ret.id = ret._id.toHexString();
      delete ret._id;
      delete ret.__v;
      delete ret.passwordHash; // Protect sensitive data
      return ret;
    }
  }
});
💡Customizing Mongoose JSON serialization transforms to scrub sensitive fields.
🎯 Interview Key Takeaway

Use toJSON transforms to scrub internal passwords and map _id to id during API response serialization.

#toJSON#Transforms#Serialization#Mongoose#Beginner
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?