Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding mongoose query for a specific model

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.

like image 202
eyadof Avatar asked Dec 19 '22 11:12

eyadof


1 Answers

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);
like image 165
Alex Avatar answered Jan 13 '23 20:01

Alex