gpt4 book ai didi

node.js - 在 JavaScript(Node.js) 中更新 MongoDB 集合时如何处理错误

转载 作者:可可西里 更新时间:2023-11-01 10:04:13 25 4
gpt4 key购买 nike

我一直在尝试在运行错误代码时出错。以下代码尝试更新 _id 值为 5 的记录。实际上没有这样的记录,但我无法使用以下函数捕获任何错误消息。

我该怎么办?

collection.update(
{ _id : "5" },
// { _id : req.session.User._id },
{ $set: { password : req.param('password') } },
{ writeConcern: { w: "majority", wtimeout: 3000 } },
function(err, result) {
if (err) { console.log(err); return err; }

res.send("/user/show");
}
);

最佳答案

update() 的回调有 2 个参数,err 和 result。更新项目时,结果设置为 true,否则设置为 false。所以当因为找不到item而没有更新item时,不认为是错误,所以err为null。 if (err) 不会是真的。您需要以这种方式测试更新:

collection.update(
{ _id : "5" },
// { _id : req.session.User._id },
{ $set: { password : req.param('password') } },
{ writeConcern: { w: "majority", wtimeout: 3000 } },
function(err, result) {
if (err) { console.log(err); res.send(err); return;}
if (result) {
res.send("/user/show");
} else {
res.send("/user/notshow");
}
);

关于node.js - 在 JavaScript(Node.js) 中更新 MongoDB 集合时如何处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24853114/

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