MongoDB无法删除数据+启用retryWrites仍报limit=0错误求助
Hey there, let's tackle this error and your delete problem step by step. The Cannot use (or request) retryable writes with limit=0 error usually stems from mismatched MongoDB connection settings or deprecated Mongoose methods. Here's how to resolve both issues:
1. Update Your MongoDB Connection String
You already added retryWrites=true, but retryable writes require a write concern of majority to work properly. Your current string is missing this parameter.
Modified Connection String:
mongoose.connect('mongodb+srv://admin:admin@rest-shop-e3hfo.mongodb.net/test?retryWrites=true&w=majority') .then(() => console.log("Successfully connected to MongoDB!")) .catch(err => console.error("MongoDB connection failed:", err));
- Added
&w=majorityto enforce the required write concern - Added connection success/error logging to verify if your DB connection works as expected
2. Replace Deprecated remove() Method
Mongoose's remove() method is deprecated and can cause unexpected behavior (like your delete failure). Use deleteOne() instead, which is the modern, supported method for single-document deletion.
Modified Delete Route in Orders Module:
router.delete('/:orderId', (req, res, next) => { Order.deleteOne({_id: req.params.orderId}) .then(result => { if (result.deletedCount === 0) { return res.status(404).json({ message: "Order not found" }); } res.status(200).json({ message: 'Order deleted' }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); });
- Swapped
Order.remove()withOrder.deleteOne() - Added a check for
deletedCountto return a 404 if no order was found (improves error handling)
3. Verify Mongoose Version
Outdated Mongoose versions may have compatibility issues with MongoDB's retryable writes feature. Update to the latest stable version to rule this out:
npm install mongoose@latest
4. Quick Check: Ensure Your Database User Has Delete Permissions
Double-check that your MongoDB Atlas user (admin in this case) has the necessary permissions to perform delete operations on the test database. You can verify this in the MongoDB Atlas dashboard under "Database Access".
After making these changes, restart your server and test the delete endpoint again—both the retryable writes error and deletion failure should be resolved.
内容的提问来源于stack exchange,提问作者Oleksandr Tatarinov

