1

Is it possible to create a mongoose plugin that in every query it will add a standard filter?

I want every time a make a User.find() or User.findOne() or User.update() or User.delete() etc... to include everytime this filter { activated: true }

Michalis
  • 6,686
  • 13
  • 52
  • 78

1 Answers1

0

The way we do it in our team is we have a UsersManager class which implements methods like find or fineOne, and those methods call mongoose's methods while adding the base filters. For example:

class UsersManager {
    find(filter) {
        return userModel.find()
            .where('activated', true)
            .where(filter)
            .exec();
    }
}

No other class will ever call userModel.find directly.

If you need to add the same filter on every method, you should consider using a utility method.

OzW
  • 848
  • 1
  • 11
  • 24