Intermediate LevelMongoDB & Mongoose
How do custom Mongoose Plugins extend schema functionality across models?
❓ Interview Prompt: Explain Mongoose Plugin architecture, reusable schema functions (schema.plugin()), injecting global hooks, and static methods.
Mongoose Plugins wrap schema hooks, virtuals, and custom static methods into reusable functions that can be applied across multiple schemas via 'schema.plugin(customPlugin)':
Use Cases:
•
Centralizing soft-delete behavior, audit logging, and automated tenant scoping across all application models.
Code Implementation Example
typescript
import { Schema } from 'mongoose';
// Reusable soft-delete plugin
function softDeletePlugin(schema: Schema) {
schema.add({ isDeleted: { type: Boolean, default: false } });
schema.pre('find', function () {
this.where({ isDeleted: false }); // Automatically filter soft-deleted docs!
});
}
// Apply to schema
const userSchema = new Schema({ name: String });
userSchema.plugin(softDeletePlugin);💡Creating a reusable Mongoose soft-delete schema plugin.
🎯 Interview Key Takeaway
Use Mongoose plugins to DRY up schema lifecycle hooks, soft-deletes, and audit fields across models.
#Mongoose Plugin#schema.plugin#Reusability#Intermediate
Back to all MongoDB & Mongoose Questions→