簡體   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