Home > Software design >  ReferenceError: err is not defined when connecting mongodb with nodejs express
ReferenceError: err is not defined when connecting mongodb with nodejs express

Time:06-09

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?

CodePudding user response:

You need to catch err in callback.

Your callback should look like this

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

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

CodePudding user response:

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

CodePudding user response:

The first thing is connect method should take a url and callback as parameters. Since you are geeting err is not defined this means you haven't defined it. You should pass err as a parameter in the callback function along with the url like this:

db.connect(url, (err, res) => {
    if(err) //your code
    else //your code
});
  • Related