我有一个 AngularJS 仪表板,用户应该在其中填写表单(提供 ID 和日期),然后将此数据发送到 Express/NodeJS 服务器,该服务器对 mongodb 进行查询。
我的问题是,如果用户填写数据库中不存在的ID,mongodb将返回错误“无法读取未定义的属性计数”,并且express服务器将崩溃。
我尝试使用 try/catch 处理错误,但没有任何变化。
try {
collection
.aggregate(
[{$match: {"content.MemberID_Hash": "xxx", "content.Swipe_DateTime": {$regex:"201602"}}},
{$group: {_id: null, count:{$sum: 1}}}],
function(err,result) {
console.log("User's number of swipes from last month: ", result[0].count);
//findUserRank(result[0].count);
//getNeighbouringValues(result[0].count);
});
} catch (err) {console.log("Wrong query"); console.error(err);}
有没有一种方法可以在保持服务器运行的同时返回错误?
最佳答案
您的代码是异步的,因此 try/catch 不起作用。使用前需验证编程错误。 result[0] 正在尝试访问,即使它不存在
collection.aggregate(
[{$match: {"content.MemberID_Hash": "xxx", "content.Swipe_DateTime": {$regex:"201602"}}},
{$group: {_id: null, count:{$sum: 1}}}],
function(err,result) {
if(err){
throw err ;
}
if(result && result[0]){
console.log("User's number of swipes from last month: ", result[0].count);
//findUserRank(result[0].count);
//getNeighbouringValues(result[0].count);
}
});
关于node.js - MongoDB 在查询后导致 Express 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341920/