Mongoose deleteMany in pre-hook, how to access all documents that will be deleted?

Viewed 1237

I have this code:

postSchema.pre('deleteMany', async function (next: NextFunction) {
  try {
    console.log(this);
    return next(); // normal save
  } catch (error) {
    return next(error);
  }
});

console.log is giving a query object. Are documents available somewhere in the query?

1 Answers

query in deletemany Located at _conditions key of this,so you can do like this in Post Model for example :

postSchema.pre('deleteMany', async function (next: NextFunction) {
  try {
   let deletedData =await Post.find(this._conditions).lean()
    console.log(deletedData );
    return next(); // normal save
  } catch (error) {
    return next(error);
  }
});

let Post= mongoose.model("Post", userSchema);
module.exports = Post
Related