Search code examples
node.jsmongodbexpressexpress-handlebarsexpress-generator

ReferenceError: err is not defined when connecting mongodb with nodejs express


I was following an ecommerce website tutorial on Nodejs express (handlebars template). When try to connect to mongo dB (installed on system i.e., port 27017) it shows

if(err) console.log ("connection Error"+ err)

^

ReferenceError: err is not defined

  var db=require('./config/connection');

db.connect(()=>{
  if(err) console.log("connection Error"+ err);
  else console.log("Database Connected to port 27017");
})

i tried installing npm module using command : "npm install mongodb" and fixing npm errors using command :npm audit fix --force

how to solve this error?


Solution

  • db.connect receives a callback function in the form of a lambda. the callback you passed is in the form of ()=> {}, which is a function that receives nothing and does something.

    err isnt referenced inside that lambda.

    the callback should receive the err variable to be able to do something with it.

    it should look something like this:

    db.connect((err)=>{
      if(err) console.log("connection Error"+ err);
      else console.log("Database Connected to port 27017");
    })
    

    this way it receives a callback which has 1 argument named "err" and now you can reference it inside of the callbacks logic as you did