Q55 [Scenario]: How do you implement global Soft Deletes in Mongoose so deleted documents are preserved for compliance?

Add an isDeleted: { type: Boolean, default: false } and deletedAt: Date field to the schema. Implement a Mongoose Query Pre-Middleware hook targeting find, findOne, countDocuments, and update regex patterns (/^find/) to append this.where({ isDeleted: false }) automatically.

Global Soft Delete Query Middleware
schema.pre(/^find/, function(next) {
  // Automatically filter out soft-deleted documents from all find queries
  this.where({ isDeleted: { $ne: true } });
  next();
});
💡 Hooks into all find-variant queries to append soft-delete filtering globally.
Key Takeaways
  • Use query middleware regex (/^find/) to append soft-delete filters globally.
  • Ensure compound indexes include { isDeleted: 1 }.
Knowledge Check

Which Mongoose middleware pattern allows applying soft-delete filters across find, findOne, and findById queries simultaneously?