Aquasar
  • Home
  • Portfolio
  • Articles
  • Pricing
  • About
  • Contact
WEB DEVELOPMENT |SEO |DIGITAL ADS

Query Middleware in Mongoose

Oct 8th, 2019

Alex Quasar

mongoquery middleware

Using the `pre find ` hook allows us to query documents and the this keyword is pointing to the document or instance of the model, rather than the model itself. We can use methods like find, findById, aggregate, to filter or aggregate the data to our liking.

Why should you use the a `pre find` hook?

It can be used to filter out documents that are sensitive and you don't want to show in your results. This hook gets executed each time before find gets called in the API.

For example:

TourSchema.pre('find', function(next) {
  this.find({ secretTour:{ $ne: true } })
  next();
})  

There is one potential downside. This will only get called for find, and not for findById, or findByIdAndUpdate. This is because findById and findByIdAndUpdate use findOne behind the scenes.

So we could potentially fetch a secret document when we use those commands. To ensure that does not happen, replace `find` with a regular expression.