gpt4 book ai didi

node.js - MongoDB 错误 : Cannot use retryable writes with limit=0

转载 作者:IT老高 更新时间:2023-10-28 13:18:35 27 4
gpt4 key购买 nike

我目前正在使用 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"
}

这是我的要求:

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 将在连接时尝试执行函数。

更多信息here

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

更多信息 here

如果你使用的是 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
})
}); ;
});

关于node.js - MongoDB 错误 : Cannot use retryable writes with limit=0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50283081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com