2016-12-27 130 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! –