mongoose post remove中间件没有被调用

bkkx9g8r  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(111)

我有这个路由控制器来删除一个项目:

exports.deleteShoppingItem = asyncHandler(async (req, res, next) => {
const shoppingItem = await ShoppingItem.findById(req.params.id);

if (!shoppingItem) {
    return next(
        new ErrorResponse(`shoppingItem not found on id ${req.params.id}`, 404)
);
}

//check if the current user is the owner of the shopping item
if (shoppingItem.user.toString() !== req.user.id) {
return next(
  new ErrorResponse(
    `user with user is not allowed to update this shopping item`,
    401
  )
);
}
await shoppingItem.deleteOne();

这是我的中间件,每当删除一个项目时,我都要执行它:

ShoppingItemSchema.post("remove", async function () {
  console.log("removing")
  await this.constructor.calculateTotalBoughtCost(this.user),
  await this.constructor.calculateTotalCost(this.user);
});

但是这个post remove永远不会被调用,即使这些项目正在被成功删除。
我试着使用remove(),但它说删除不是功能。

kq4fsx7k

kq4fsx7k1#

尝试使用“deleteOne”methodName而不是“remove”。

ShoppingItemSchema.post("deleteOne", async function () {
console.log("removing")
await this.constructor.calculateTotalBoughtCost(this.user),
await this.constructor.calculateTotalCost(this.user);
});

你可以在这里阅读post()钩子中间件文档

相关问题