简体   繁体   中英

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

I have a method that deletes products and before it does it check if the user who is trying to delete the product is the user who created it. When i execute it with Insomnia it successfully removes the product but i get an error on the console saying cannot set headers after they are sent to the client.

My method:

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,
      });
    });
};

I'm pretty sure this is happening because I'm chaining a.then() and.catch() after executing it.

I tried to do this but it didn't work because the err parameter that I'm sending to the callback function is 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");
  });
};

When i tried this second approach I always got the 200 status, meanwhile the product didn't delete.

Any idea how to deal with this?

You can try something like this:

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

or: in async / await way

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

By the way, why you are passing userId at the deleteOne method?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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