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?
3
Answers
You need to catch err in callback.
Your callback should look like this
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:
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
The first thing is
connect
method should take aurl
andcallback
as parameters. Since you are geetingerr 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: