2016-12-27 131 views
0

我有一个angularjs仪表板,其中用户应该填写表单(给出一个ID和一个日期),然后这个数据被发送到一个express/nodejs服务器,查询到一个mongodb 。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);} 

有没有一种方法,同时保持服务器运行我可以返回一个错误?

回答

2

你的代码是异步的,所以try/catch将不起作用。编程错误需要在使用前进行验证。结果[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

要避免这个错误,你必须重定向到一个临时收集您的输出,具有触杀$out

如下:

{$out: "temporaryCollection"} 

temporaryCollection将你的数据库上创建

Here你可以找到一个MongoDB文档约$out

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); 
      }); 

试试这个,如果它解决您的错误吧。

+1

try/catch在异步代码中不起作用 – Sumeet

+1

是啊!!!你是对的。我忘了删除它们!你的回答是绝对正确的。去与sumeet! –