Answer a question

I have an application in which I manage categories and subcategories.
So each time I delete a category, I have a mongoose middleware that deletes all the subcategories who belong to it.

schema.post('findOneAndDelete',
    (category: CategoryDocument) => subcategoryModel.deleteMany({ category: category.id }))

That works fine when I delete just one category, what happens when I delete multiple?
I tried registering a deleteMany middleware like so:

schema.post('deleteMany',
            (deletedQueryResult: any) => {})

But the deleteMany middleware just sends to my callback the result of the query (the time it took, number of deleted documents and some internal mongoose/mongodb properties).

Is there anyway I can get the deleted documents or their ids inside a mongoose middleware?
If not what are my other options here?

Answers

The deleteMany method returns an object with three fields:

  • n – number of matched documents
  • ok1 if the operation was successful, else 0
  • deletedCount – number of deleted documents

This is the same behaviour of the mongodb db.collection.deleteMany method.

I suggest you to add a static method to your model:

// Assign a function to the "statics" object of our schema
categorySchema.statics.deleteManyWithSubs = async function(catIds) {
  const deleteQuery = /*your delete query using catIDs*/
  const delRes = await this.deleteMany(deleteQuery);
  catIds.forEach(id => {
     await subcategoryModel.deleteMany({ category: id })
  });
  return true;
};

// Usage
categoryModel.deleteManyWithSubs(ids)...
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐