MongoDB错误:无法使用limit = 0的可重试写入

gon*_*ezt 7 mongoose mongodb node.js express

我正在使用express,mongodb(atlas cloud)和mongoose工作我的第一个node.js rest api,当我尝试发出.remove请求时,我收到此错误:

{
"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"
}
Run Code Online (Sandbox Code Playgroud)

这是我的要求:

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
        })
    }); ;
});
Run Code Online (Sandbox Code Playgroud)

Ric*_*ves 9

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

更多信息在这里

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

更多信息在这里

如果你使用的是Mongoose 5 ^和MongoDB 3.6,你的代码写得更好:

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
        })
    }); ;
});
Run Code Online (Sandbox Code Playgroud)


the*_*ite 5

我只是将 true 更改为 falseretryWrites=true并且它起作用了。这是一个好方法吗?或者有更好的方法来解决这个问题?