简体   繁体   中英

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. 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"

This is because, by default, when there are no matching records foundData will be an empty array [] . So, foundData[0] , technically will be an 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.

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

  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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