I don't think if mongoose has this feature built-in.
(我不认为猫鼬是否内置此功能。)
The best you can do is to create a remove middleware as described here :
(你能做的最好的是创建一个删除中间件作为描述在这里 :)
By the way, to make your existing code shorter, you can use findByIdAndDelete
.
(顺便说一句,为了使现有代码更短,可以使用findByIdAndDelete
。)
It returns the deleted document, so with the following code 2 database hits make the job:(它返回已删除的文档,因此使用以下代码2命中数据库即可完成工作:)
const parentDel = await Parent.findByIdAndDelete(id);
const childDel = await Child.deleteOne({_id: parentDel.child});
console.log(parentDel, childDel);
parentDel will look like this:
(parentDel将如下所示:)
{
"_id": "5de0114ad068f335b480925a",
"name": "Parent 1",
"child": "5de01144d068f335b4809259",
"__v": 0
}
And childDel will look like this:
(而且childDel将如下所示:)
{
"n": 1,
"ok": 1,
"deletedCount": 1
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…