[英]How to get deleted documents from DeleteMany middleware in Mongoose?
I have an application in which I manage categories
and subcategories
.我有一个管理categories
和subcategories
的应用程序。
So each time I delete a category
, I have a mongoose middleware that deletes all the subcategories
who belong to it.所以每次我删除一个category
时,我都有一个 mongoose 中间件删除属于它的所有subcategories
。
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?当我只删除一个category
时效果很好,当我删除多个时会发生什么?
I tried registering a deleteMany
middleware like so:我尝试像这样注册一个deleteMany
中间件:
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).但是deleteMany
中间件只是向我的回调发送查询结果(花费的时间、已删除文档的数量和一些内部 mongoose/mongodb 属性)。
Is there anyway I can get the deleted documents or their ids inside a mongoose middleware?无论如何我可以在 mongoose 中间件中获取已删除的文档或其 ID?
If not what are my other options here?如果不是,我在这里的其他选择是什么?
The deleteMany
method returns an object with three fields: deleteMany
方法返回一个包含三个字段的 object:
n
– number of matched documents n
- 匹配文档的数量ok
– 1
if the operation was successful, else 0 ok
– 如果操作成功则为1
,否则为 0deletedCount
– number of deleted documents deletedCount
– 已删除文档的数量This is the same behaviour of the mongodb db.collection.deleteMany
method.这与 mongodb db.collection.deleteMany
方法的行为相同。
I suggest you to add a static method to your model:我建议您在 model 中添加一个static 方法:
// 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)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.