I want to automatically add a query option for all queries related for a specific mongoose model without affecting other models
I saw this answer where Mongoose.Query is patched and that will affect all mongoose models.
I was able to do this for my soft deleted items. Haven't tested it extensively yet though.
function findNotDeletedMiddleware(next) {
this.where('deleted').equals(false);
next();
}
MySchema.pre('find', findNotDeletedMiddleware);
MySchema.pre('findOne', findNotDeletedMiddleware);
MySchema.pre('findOneAndUpdate', findNotDeletedMiddleware);
MySchema.pre('count', findNotDeletedMiddleware);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With