【问题标题】:MongoDB crashes Express after query查询后 MongoDB Express 崩溃
【发布时间】:2016-12-27 17:41:21
【问题描述】:

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

我的问题是如果用户填写了数据库中不存在的ID,mongodb会返回错误"cannot read property count of undefined",快递服务器会崩溃。

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

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

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      如下:

      {$out: "temporaryCollection"}
      

      temporaryCollection 将在您的数据库中创建

      Here 你可以找到关于$out 的MongoDB 文档

      【讨论】:

        【解决方案3】:
                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);
                  });
        

        如果它解决了你的错误,试试这个。

        【讨论】:

        • 是啊!!!你是对的。我忘记删除它们了!!!你的回答是绝对正确的。和 sumeet 一起去!!!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-16
        • 2014-02-27
        • 1970-01-01
        • 2013-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多