简体   繁体   English

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

[英]Error handling for data returned from Mongo Query

Still a relative newbie, but I'm using a portal to allow people to check if a person is a member of a club. 仍然是相对的新手,但是我正在使用门户网站让人们检查某个人是否是俱乐部的成员。 I'm using mongodb and mongoose to do this, however when a number is entered that isn't in the database an error is returned "TypeError: Cannot read property 'username' of undefined" fair enough,but i'm not sure how to handle this error, please see my code below: I know there are a few ways I can refactor and tidy up my code, but it's the mongoose error handling i would like to know about. 我正在使用mongodb和mongoose来执行此操作,但是当输入的数字不在数据库中时,将返回错误“ TypeError:无法读取未定义的属性'username'”,但我不确定要处理此错误,请参见下面的代码:我知道有几种方法可以重构和整理代码,但这是我想知道的猫鼬错误处理方法。 Cheers 👍 干杯👍

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

You need to check if the array you getting is not empty: 您需要检查获取的数组是否不为空:

Here's what you can try: 您可以尝试以下方法:

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

when a number is entered that isn't in the database an error is returned "TypeError: Cannot read property 'username' of undefined" 输入不在数据库中的数字时,将返回错误“ TypeError:无法读取未定义的属性'username'”

This is because, by default, when there are no matching records foundData will be an empty array [] . 这是因为,默认情况下,当没有匹配记录时, foundData将为空数组[] So, foundData[0] , technically will be an undefined . 因此, foundData[0]技术上讲将是undefined

When the query is executed, the result will be an array of documents. 执行查询时,结果将是一个文档数组。

Source mongoose docs 原始 猫鼬文档

To avoid this error, you can check for the size of the foundData before accessing it's 0th element. 为避免此错误,您可以在访问它的第0个元素之前检查foundData的大小。

Making those changes to your code. 对您的代码进行更改。

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

  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM