Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - 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
        })
    }); ;
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...