MongoDB错误:无法使用limit = 0进行可重试的写入 [英] MongoDB Error: Cannot use retryable writes with limit=0

查看:260
本文介绍了MongoDB错误:无法使用limit = 0进行可重试的写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用express,mongodb(阿特拉斯云)和猫鼬开发我的第一个node.js rest api,当我尝试提出.remove请求时出现此错误:

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"
}

这是我的要求:

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

推荐答案

findOneAndRemove()函数的作用更大,因为它特定于函数.findOneAndRemove(filter,options)中传递的用于过滤对象的过滤方法.但是,如果删除过程被连接中断,则 retryRewrites = true 将在连接时尝试执行该功能.

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.

更多信息此处

使用retryRewrites设置为true时,将告诉MongoDB重试相同的过程,实际上这可以帮助防止与数据库的连接失败并正确运行,因此建议将其打开.

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.

更多信息此处

如果您使用的是Mongoose 5 ^和MongoDB 3.6,则您的代码最好像这样编写:

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

这篇关于MongoDB错误:无法使用limit = 0进行可重试的写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆