I\'m new in nodeJS, started learning by following a trailer on youtube, everything goes well until I added the connect function if mongodb,
mongo.connect(\"m
If the mongoDB server is already installed and if you are unable to connect from a remote host then follow the below steps,
Login to your machine, open mongodb configuration file located at /etc/mongod.conf
and change the bindIp
field to specific ip / 0.0.0.0
, after that restart mongodb server.
sudo vi /etc/mongod.conf
The file should contain the following kind of content:
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
journal:
enabled: true
processManagement:
fork: true
net:
bindIp: 127.0.0.1 // change here to 0.0.0.0
port: 27017
setParameter:
enableLocalhostAuthBypass: false
Once you change the bindIp
, then you have to restart the mongodb, using the following command
sudo service mongod restart
Now you'll be able to connect to the mongodb server, from remote server.
mongoose.connect('mongodb://localhost:27017/').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
Better just connect to the localhost Mongoose Database only and create your own collections. Don't forget to mention the port number. (Default: 27017)
For the best view, download Mongoose-compass for MongoDB UI.
just install MongoDB on your system. That's it.
My problem was the wrong port number for mongoDB
server.
I had:
DATABASE_URL= "mongodb://localhost:3000/node-express-mongodb-server"
in my .env
file (my environmental variables), but I had written it before running mongoDB server
. So when I ran the mongoDB server
, it wrote a different port number and I had to change it. I changed it to the right port number (which was written on my cmd window by mongoDB
):
DATABASE_URL= "mongodb://localhost:27017/node-express-mongodb-server"
and now it works fine.
This had occurred to me and I have found out that it was because of faulty internet connection. If I use the public wifi at my place, which blocks various websites for security reasons, Mongo refuses to connect. But if I were to use my own mobile data, I can connect to the database.
You can check detail of error by running this command
sudo service mongod status
if error is something like this
simply running this will resolve your issue
rm /tmp/mongodb-27017.sock