How to connect to your remote MongoDB Server with Nodejs

If you have MongoDB running on your Linux Server in Amazon EC2, Amazon Lightsail, Vultr or any server, you will see there is no simple tutorial out there explaining how to setup user authentication for Mongo so that you can read and write to your  MongoDB server from your Laptop or from other Backend Server. If so we will show you a way to do that.

If you have not installed mongoDB yet, go to this link

1. Setup your user for your DB

First ssh into your server and enter the mongo shell by typing mongo. For this example, I will set up a user named feedtekuser and give that user read & write access to the yourdb database.

use yourdb

    user: 'feedtekuser',
    pwd: 'secretPassword',
    roles: [{ role: 'readWrite', db:'yourdb'}]

2. Enable auth and open MongoDB access up to all IPs

Edit your MongoDB config file. On Ubuntu:

sudo vim /etc/mongod.conf

  • Look for the bindIp , which is currently limiting MongoDB connections to localhost:
  • Change it to bindIp:
# network interfaces
  port: 27017
  bindIp:  <- change it to
  • Scroll down to the #security: section and add the following line. Make sure to un-comment the security: line.
  authorization: 'enabled'

3. Open port 27017 on your EC2 instance

  • Go to your EC2 dashboard:
  • Go to Instances and scroll down to see your instance’s Security Groups. Eg, it will be something like launch-wizard-4
  • Go to Netword & Security -> Security Groups -> Inbound tab -> Edit button.
  • Make a new Custom TCP on port 27017, Source: Anywhere,

4. Last step: restart mongo daemon (mongod)

sudo service mongod restart

Make sure you can still log in with mongo while ssh’d into the box.

If anything goes wrong, look at the log: tail -f /var/log/mongodb/mongod.log (note: non-Ubuntu machines will keep the log in another directory…)

Logging in using the mongo shell on your laptop

You can close out of ssh and go back to your local console. To enter the remote Mongo database we just set up, you can use the mongo shell:

mongo -u feedtekuser-p secretPassword

Where is your server’s public IP address.

Now you can read and write within the yourdbdatabase from your nodejs projects by using this string connection:

"mongodb://feedtekuser:[email protected]/yourdb"

Leave a Reply

Your email address will not be published. Required fields are marked *