You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mongoose调用remove方法报错:Cannot use retryable writes with limit=0

Fixing "MongoError: Cannot use (or request) retryable writes with limit=0"

Hey there, that error you're hitting happens because the remove() method you're using doesn't play nice with MongoDB Atlas's default retryable writes feature. When you call remove() without specifying a limit, it defaults to limit=0—and retryable writes don't support that configuration.

On top of that, Mongoose has actually marked remove() as deprecated, so it's a good idea to switch to the newer, recommended methods anyway. Here are two solid solutions for you:

Option 1: Use deleteOne()

This method is purpose-built for deleting a single document, and it's fully compatible with retryable writes:

router.delete('/:productId', (req, res, next) => {
  const id = req.params.productId;
  Product.deleteOne({ _id: id })
    .exec()
    .then(result => {
      if (result.deletedCount === 0) {
        return res.status(404).json({ message: "Product not found" });
      }
      res.status(200).json({ message: "Product deleted successfully", result });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({ error: err });
    });
});

Option 2: Use findByIdAndDelete()

If you're deleting by _id, this method is even more straightforward—no need to build a query object manually:

router.delete('/:productId', (req, res, next) => {
  const id = req.params.productId;
  Product.findByIdAndDelete(id)
    .exec()
    .then(deletedProduct => {
      if (!deletedProduct) {
        return res.status(404).json({ message: "Product not found" });
      }
      res.status(200).json({ message: "Product deleted successfully", deletedProduct });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({ error: err });
    });
});

Why do these work?

  • Both deleteOne() and findByIdAndDelete() are official MongoDB-recommended methods for single-document deletion. Their default configurations are compatible with retryable writes, so you won't hit that limit=0 error anymore.
  • They also make it easier to handle edge cases, like when the product doesn't exist—you can return a 404 status code instead of just a generic success response, which makes your API more robust.

Going forward, I'd suggest avoiding deprecated methods like remove() and findOneAndRemove() entirely. Sticking with deleteOne(), deleteMany(), and findByIdAndDelete() will keep your code aligned with modern MongoDB best practices and reduce compatibility issues down the line.

内容的提问来源于stack exchange,提问作者gonzarodriguezt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:08:25