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

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

问题描述

我目前正在使用 express、mongodb(atlas 云)和 mongoose 开发我的第一个 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天全站免登陆