Performance: Mongoose middleware (pre/post hooks)
This affects server response time and database operation speed by adding extra processing before or after database actions.
Jump into concepts and practice - no test required
schema.pre('save', function(next) { if (this.isModified()) { next(); } else { next(); } });
schema.pre('save', async function() { await heavyComputation(); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous pre-save hook | N/A (server-side) | N/A | N/A | [X] Bad |
| Conditional lightweight pre-save hook | N/A (server-side) | N/A | N/A | [OK] Good |
| Blocking post-save hook with await | N/A (server-side) | N/A | N/A | [X] Bad |
| Asynchronous post-save hook with setImmediate | N/A (server-side) | N/A | N/A | [OK] Good |
pre middleware in Mongoose?pre and post methods for middleware, not before or on.schema.pre('save', function(next) { ... next(); }); to run code before saving.doc.updatedAt after saving?schema.pre('save', function(next) {
this.updatedAt = new Date();
next();
});this.updatedAt to the current date before saving.updatedAt will be updated to the current time.schema.pre('remove', (next) => {
console.log('Removing', this._id);
next();
});this to the document.this, so this will be undefined inside the middleware.this if needed.