[英]MongoDB find doesn't return an error if a record doesn't exist?
I'm using Mongoose:我正在使用猫鼬:
user.find({username: 'xyz'}, function(err, doc){
if(err){
res.render('error', {errorMsg: "Error blah blah"})
}
});
I'm deliberately using a user who doesn't exist xyz and it's not triggering any errors, I thought it was because of Mongoose but then I tried in MongoDB shell and yes MongoDB won't return an error if a record doesn't exist.我故意使用一个不存在 xyz 的用户,它没有触发任何错误,我以为是因为 Mongoose,但后来我在 MongoDB shell 中尝试,是的,如果记录不存在,MongoDB 不会返回错误.
>db.accounts.find({username: 'xyz'})
> // no error, blank line
How do I handle that?我该如何处理? I want the execution of the script stop if a user doesn't exist.
如果用户不存在,我希望脚本停止执行。
Well, if the "username" doesn't exist, that doesn't mean there is an error.好吧,如果“用户名”不存在,这并不意味着有错误。 Instead you should do something like this.
相反,你应该做这样的事情。
user.find({ username: 'xyz' }, function(err, doc){
if(doc.length === 0 || err){
res.render('error', { errorMsg: "Error blah blah" } )
}
});
Or more verbose version:或更详细的版本:
user.find({ username: 'xyz' }, function(err, doc) {
if(err){
res.render('error', { errorMsg: "Error blah blah" } )
} else {
if (doc.length === 0) {
console.log("User doesn't exist");
} else {
//do something
}
}
});
var user = db.accounts.findOne({username: 'xyz'});
if (!user) {
// handle error
alert('fail');
}
Try to check if the doc is null or not first and then you can get on with your function.首先尝试检查文档是否为空,然后您可以继续使用您的功能。
user.find({ username: 'xyz' }, function(err, doc){
if(doc === null || err){
res.render('error', { errorMsg: "Error blah blah" } )
}
else {
do something...
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.