gonzarodriguezt
gonzarodriguezt

Reputation: 191

MongoDB Error: Cannot use retryable writes with limit=0

I'm currently working on my first node.js rest api with express, mongodb (atlas cloud) and mongoose, when i try to make a .remove request i get this error:

{
"error": {
    "name": "MongoError",
    "message": "Cannot use (or request) retryable writes with limit=0",
    "driver": true,
    "index": 0,
    "code": 72,
    "errmsg": "Cannot use (or request) retryable writes with limit=0"
}

This is my request:

router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
    .exec()
    .then(result => {
        res.status(200).json(result);
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        })
    }); ;
});

Upvotes: 9

Views: 9279

Answers (3)

Ricardo Alves
Ricardo Alves

Reputation: 561

The findOneAndRemove() function would work more accordingly since its specific to the filtering method passed in the function .findOneAndRemove(filter, options) to remove the filtered object. Still, if the remove process is interrupted by the connection the retryRewrites=true will attempt the execution of the function when connected.

More information here

When using retryRewrites set to true tells the MongoDB to retry the same process again which in fact can help prevent failed connections to the database and operate correctly, so having it turn on is recommended.

More info here

If you are using Mongoose 5^ and MongoDB 3.6 your code is better written like:

mongoose.connect('mongodb.....mongodb.net/test?retryWrites=true', (err) => {
if(err){
    console.log("Could not connect to MongoDB (DATA CENTER) ");
    }else{
        console.log("DATA CENTER - Connected")
    }
});// CONNECTING TO MONGODB v. 3.6

router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.findOneAndRemove({ _id: id })//updated function from .remove()
    .exec()
    .then(result => {
        res.status(200).json({
       message: "Product Removed Successfuly"
     });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        })
    }); ;
});

Upvotes: 10

drojas
drojas

Reputation: 373

retryWrites=true is a good thing, a workaround for this incompatibility is to use findOneAndRemove instead of remove (looks like you're using mongoose)

Upvotes: 3

thegreathypocrite
thegreathypocrite

Reputation: 2363

I just changed the true to false in retryWrites=true and it worked. Is that a good approach? Or there is a better way to solve this problem?

Upvotes: 6

Related Questions