Jagadeesh
Jagadeesh

Reputation: 2097

Correct way to get a value from mongodb?

I am using mongodb and mysql with my nodejs.

employee.find({status:1}, function(error,response) {
                for(i=0;i<=response.length;i++){
                  var fileid = response[i]._id;
                  var sql = "SELECT * FROM EMPLOYEE WHERE `id` = '"+fileid+"'";
                  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Result: " + result);
  });
                  }
                })

The above code gives me the exact record and result but in my logger file i am getting the below error everytime,But i have no problem in getting my output.I am using winston to record my service logs. The main reason why i am worrying about this error is my node js APi's are going down more or less after every 8 hours and my databases are not going idle(using forever npm module to run my service forever) and so i am believing that this might be the reason for killing my node processess. Below is my error.Any help?

"stack":["TypeError: Cannot read property '_id' of undefined"(var fileid = response[i]._id;)]

Upvotes: 0

Views: 38

Answers (1)

Ved
Ved

Reputation: 12103

Because i should be less than response.length. array length is always greater than the last index. For example,

var arr = [1,2]; //length is 2 and last index value is 1

Change you code like this: for(i=0;i<response.length;i++)

 employee.find({status:1}, function(error,response) {
                    for(i=0;i<response.length;i++){
                      var fileid = response[i]._id;
                      var sql = "SELECT * FROM EMPLOYEE WHERE `id` = '"+fileid+"'";
                      con.query(sql, function (err, result) {
                         if (err) throw err;
                           console.log("Result: " + result);
                        });
                      }
                    })

Upvotes: 2

Related Questions