从Mongo Query返回的数据的错误处理

时间:2018-05-27 18:11:50

标签: javascript node.js mongodb mongoose error-handling

仍然是一个相对新手,但我正在使用门户网站,让人们检查一个人是否是俱乐部的成员。我正在使用mongodb和mongoose这样做,但是当输入的数字不在数据库中时会返回错误“TypeError:无法读取未定义的属性'用户名'”公平,但我不知道如何要处理此错误,请参阅下面的代码:我知道有几种方法可以重构和整理我的代码,但这是我想知道的猫鼬错误处理。干杯

app.get('/checkmembership', function(req, res) {

    var jsonResponse = {};
    var returnArray =[];

    var dbArray,
        queryArray,
        resulta,
        resultb,
        resultc,
        resultd,
        resulte,
        resultf;

    console.log("before running compareDetails " + returnArray);

    User.find({username: req.query.memberIdQuery}, function(err, foundData) {

        if(err){
            console.log(err);
        } else {
            dbArray = [foundData[0].username, foundData[0].emailaddress, foundData[0].surname];
            console.log(dbArray);
            dbArray = dbArray.join('|').toLowerCase().split('|');
            console.log(dbArray);
            queryArray = [req.query.memberIdQuery, req.query.emailQuery, req.query.surnameQuery];
            console.log(queryArray);
            queryArray = queryArray.join('|').toLowerCase().split('|');
            console.log(queryArray);
            returnArray = compareDetails(queryArray, dbArray);
            resulta = returnArray[0];
            resultb = returnArray[1];
            resultc = returnArray[2];
            resultd = returnArray[3];
            resulte = returnArray[4];
            resultf = returnArray[5];
        }

        jsonResponse = { 
            set_attributes: 
            {
                resulta : resulta,
                resultb : resultb,
                resultc : resultc,
                resultd : resultd,
                resulte : resulte,
                resultf : resultf
            },
        };

        res.send(jsonResponse);
    });
});

2 个答案:

答案 0 :(得分:0)

您需要检查您获得的数组是否为空:

以下是您可以尝试的内容:

app.get('/checkmembership', function(req, res) {
    var jsonResponse = {};
    var returnArray =[];
    var dbArray,
        queryArray,
        resulta,
        resultb,
        resultc,
        resultd,
        resulte,
        resultf;

    console.log("before running compareDetails " + returnArray);  
        User.find({username:req.query.memberIdQuery}, function(err, foundData){
            if(err){
               console.log(err);
           } else {

            if(foundData && foundData.length) {

            dbArray = [foundData[0].username,foundData[0].emailaddress,foundData[0].surname];
            console.log(dbArray);
            dbArray = dbArray.join('|').toLowerCase().split('|');
            console.log(dbArray);
            queryArray = [req.query.memberIdQuery,req.query.emailQuery,req.query.surnameQuery];
            console.log(queryArray);
            queryArray = queryArray.join('|').toLowerCase().split('|');
            console.log(queryArray);
            returnArray = compareDetails(queryArray, dbArray);
            resulta = returnArray[0];
            resultb = returnArray[1];
            resultc = returnArray[2];
            resultd = returnArray[3];
            resulte = returnArray[4];
            resultf = returnArray[5];


            jsonResponse = { 
                set_attributes: 
                  {
                      resulta : resulta,
                      resultb : resultb,
                      resultc : resultc,
                      resultd : resultd,
                      resulte : resulte,
                      resultf : resultf
                  },
                  };
                 res.send(jsonResponse);
                } else {
                    res.send("Empty result");
                }
           }
       });
});

答案 1 :(得分:0)

  

当输入的数字不在数据库中时,会返回错误" TypeError:无法读取属性' username'未定义"

这是因为,默认情况下,当没有匹配的记录时,foundData将是一个空数组[]。所以, foundData[0],技术上将是undefined

  

执行查询时,结果将是一个文档数组。

来源 mongoose docs

为避免此错误,您可以在访问{0}元素之前检查foundData的大小。

对您的代码进行更改。

app.get('/checkmembership', function (req, res) {

  let {memberIdQuery, emailQuery, surnameQuery} = req.query;

  User.find({
    username: memberIdQuery
  }, function (err, foundData) {

    if (err) {
      console.log(err);
      return res.status(500).send({
        msg: `memberIdQuery = ${memberIdQuery} doesnt exist`
      });
    }

    if (!foundData || foundData.length === 0) {
      return res.status(200).send({
        msg: `No records found for memberIdQuery = ${memberIdQuery}`
      });
    }

    let dbArray = [
      foundData[0].username,
      foundData[0].emailaddress,
      foundData[0].surname
    ];
    dbArray = dbArray.join('|').toLowerCase().split('|');

    let queryArray = [
      memberIdQuery,
      emailQuery,
      surnameQuery
    ];
    queryArray = queryArray.join('|').toLowerCase().split('|');

    let [resulta, resultb, resultc, resultd, resulte, resultf] = compareDetails(queryArray, dbArray);

    return res.send({
      set_attributes: {
        resulta: resulta,
        resultb: resultb,
        resultc: resultc,
        resultd: resultd,
        resulte: resulte,
        resultf: resultf
      },
    });

  });
});