node.js - MongoDB 在查询后导致 Express 崩溃

标签 node.js mongodb

我有一个 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/

相关文章:

javascript - 如何使用 Node.js 和 Promise 编写同步 while 循环

mongodb - 获取一个 Collection Mongodb 中的文档数

mongodb - mongodb 中商店和产品类数据库的最佳结构是什么?

perl - MongoDB 不同的值

node.js - RabbitMQ 与 nodejs

node.js - 一个包含 node.js 和 mongodb 的整个网站?

java - 以编程方式设置 MongoDb 转换器

node.js - 如何在Connect中间件中异步调用mongoDB?

node.js websocket 模块已安装但在脚本中不起作用

javascript - Discord.JS - 使用角色将 Discord 中的用户移动到您的 VC