Search code examples
node.jsmongodbmongoose

mongoose: middleware pre deleteOne options not working


documentation of mongoose says:

Mongoose - Schema-pre

Schema.prototype.pre():
Parameters:
The «String|RegExp» method name or regular expression to match method name
[options] «Object»
[options.document] «Boolean» If name is a hook for both document and query middleware, set to true to run on document middleware.
[options.query] «Boolean» If name is a hook for both document and query middleware, set to true to run on query middleware.
callback «Function»

And also about pre hook "deleteOne":
Mongoose - middleware

Document middleware is supported for the following document functions. In document middleware functions, this refers to the document:
...deleteOne

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

So, deleteOne is in Document and Query hook, now let's try to use this:

mySchema.pre('deleteOne', { document: true }, function(next) {
  console.log(this)
  next()
})

Result: this refers to Query, not to Document. Why?


Solution

  • Oh, it is not clear from docs, that 'this' refers to document only in document#deleteOne.

    So, the correct usage of 'deleteOne' hook is:
    In model:

    DocSchema.pre('deleteOne', { document: true }, function(next) {
      console.log(this)
      next()
    })
    

    later in code (in controller, etc):

    const doc = await DocModel.findOne({ name: 'myDoc' })
    await doc.deleteOne()
    

    Now 'this' refers to the document 🎉