Normal
Normal

Reputation: 3716

execute Middleware function for all query middlewares

According to Mongoose documentation about the Middlewares here:

Query middleware is supported for the following Model and Query functions. In query middleware functions, this refers to the query.

  • count
  • countDocuments
  • deleteMany
  • deleteOne
  • estimatedDocumentCount
  • find
  • findOne
  • findOneAndDelete
  • findOneAndRemove
  • findOneAndReplace
  • findOneAndUpdate
  • remove
  • replaceOne
  • update
  • updateOne
  • updateMany

This means that I can write a middleware like the following one and it's going to execute whenever a findOneAndUpdate method gets called:

mySchema.pre('findOneAndUpdate', function(next){
const query = this
console.log("called the pre-findOneAndUpdate middleware and hello");
})

Now, If I wanted to make the console.log above print its output on pre('count'), pre('replaceOne'), pre('findOneAndRemove')...etc , I will have to write too much.

is there a way to perform this by doing something like:

mySchema.pre('*', function(next){
const query = this
console.log("called the pre-* middleware and hello");
})

where * means any of the methods listed above in the long list in the quote

??

Upvotes: 1

Views: 516

Answers (1)

traynor
traynor

Reputation: 8717

looks like there is no such possibility

you might construct it dynamically

you could grab a list of methods here: https://github.com/Automattic/mongoose/blob/c5893fa9f6d652d2bed08a52ad58f0f875e34bb4/lib/helpers/query/validOps.js

(I couldn't find them on the library)

and then pass that array, or construct each method with a loop:

// https://github.com/Automattic/mongoose/blob/c5893fa9f6d652d2bed08a52ad58f0f875e34bb4/lib/helpers/query/validOps.js
const validOps = [
    // Read
    'count',
    'countDocuments',
    'distinct',
    'estimatedDocumentCount',
    'find',
    'findOne',
    // Update
    'findOneAndReplace',
    'findOneAndUpdate',
    'replaceOne',
    'update',
    'updateMany',
    'updateOne',
    // Delete
    'deleteMany',
    'deleteOne',
    'findOneAndDelete',
    'findOneAndRemove',
    'remove'
]

mySchema.pre(validOps, function(next) {
    //...
})

// or        
for (const method of validOps) {
    mySchema.pre(method, function(next) {
        const query = this;
        console.log(`called the pre-${method} middleware and hello`);
    })
}

Upvotes: 1

Related Questions