Roshith
Roshith

Reputation: 35

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?

Upvotes: 1

Views: 863

Answers (3)

Mohammad Abdul Alim
Mohammad Abdul Alim

Reputation: 488

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

Upvotes: 0

Dima Goldin
Dima Goldin

Reputation: 499

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

Upvotes: 1

Megha Hegde
Megha Hegde

Reputation: 11

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

Upvotes: 1

Related Questions