繁体   English   中英

使用 mongoose.removeOne 后,Node JS throwing 在发送到客户端后无法设置标头

[英]Node JS throwing cannot set headers after they are sent to the client, after using mongoose.removeOne

我有一种删除产品的方法,在它执行之前检查尝试删除产品的用户是否是创建它的用户。 当我使用 Insomnia 执行它时,它成功删除了产品,但我在控制台上收到错误消息,提示无法在将标头发送到客户端后设置标头。

我的方法:

exports.deleteProduct = (req, res) => {
  const id = req.params.productId;
  Product.deleteOne({ _id: id, userId: req.user._id }, () => {
    return res.status(401).json("Not authorized");
  })
    .then(() => {
      return res.status(200).json("Product deleted");
    })
    .catch((err) => {
      return res.status(500).json({
        error: err,
      });
    });
};

我很确定这正在发生,因为我在执行它之后链接了 a.then() 和 .catch() 。

我尝试这样做,但没有成功,因为我发送给回调 function 的 err 参数是 null。:

exports.deleteProduct = (req, res) => {
  const id = req.params.productId;
  Product.deleteOne({ _id: id, userId: req.user._id }, (err) => {
    if (err) {
      return res.status(401).json("Not authorized");
    }
    return res.status(200).json("Product deleted");
  });
};

当我尝试第二种方法时,我总是得到 200 状态,同时产品没有删除。

知道如何处理这个问题吗?

你可以尝试这样的事情:

Product.deleteOne({ _id: id, userId: req.user._id }, (err, result) => {
   if(err) {
      return "something"
   }
   return "something else"
});

或:以异步/等待方式

try {
  await Product.deleteOne({ _id: id, userId: req.user._id });
} catch (err) {
  // handle error here
}

顺便说一句,为什么你在deleteOne方法中传递userId

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM