MongoDB在查询后崩溃了Express

时间:2016-12-27 08:52:23

标签: node.js mongodb

我有一个angularjs仪表板,用户应填写表格(给出ID和日期),然后将此数据发送到对mongodb进行查询的express / nodejs服务器。

我的问题是,如果用户填写数据库中不存在的ID,mongodb将返回错误“无法读取未定义的属性数”,快递服务器将崩溃。

我尝试使用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);}

有没有办法可以在保持服务器运行的同时返回错误?

3 个答案:

答案 0 :(得分:2)

您的代码是异步的,因此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);
                      }

                  });

答案 1 :(得分:1)

要防止出现此错误,您必须将输出重定向到临时集合中,标记为$out

如下:

{$out: "temporaryCollection"}

将在您的数据库上创建temporaryCollection

Here您可以找到有关MongoDB

$out文档

答案 2 :(得分:1)

        collection
        .aggregate(
          [{$match: {"content.MemberID_Hash": "xxx", "content.Swipe_DateTime": {$regex:"201602"}}},
          {$group: {_id: null, count:{$sum: 1}}}],
          function(err,result) {
              if(err){
                 console.log(err);
                 return;
               }
              else{
              console.log("User's number of swipes from last month: ", result[0].count);
             }
              //findUserRank(result[0].count);
              //getNeighbouringValues(result[0].count);
          });

如果它能解决您的错误,请尝试此操作。