Connection Nodejs to Mongodb in Droplet

August 7, 2017 1k views
Node.js MongoDB Ubuntu 16.04

I created two droplets, deployed my Nodejs backed in first one, installed Mongodb in the second one. I also secured the MongoDB with database admin user, and a SSH key login to the MongoDB Droplet. Now I am stuck, I don't know how to connect my Nodejs app to MongoDB Database. How will I connect to the database? Using a Connection String? or by attaching and sending an object with all port values, ssh key etc? I am not sure how to get it done, any help will be highly appreciated. Thank you.

1 Answer

By default, the MongoDB listens on the local interface. In order to allow your Node application to access the MongoDB instance, modify the value of bindIp in /etc/mongod.conf If you do so, you are highly advised to first review the security checklist from the MongoDB documentation.

The relevant section of the config file should look like:

# [ ... ]
net:
  port: 27017
  bindIp: 127.0.0.1,ip_of_mongo_droplet
# [ ... ]

In addition to enabling one of the forms of authentication supported by MongoDB, you should set up a firewall to limit access to the MongoDB instance. You can do this with a DigitalOcean firewall or UFW which comes pre-installed on Ubuntu Droplets.

If you go with UFW, this command will allow access from the Node app's IP address and nowhere else:

  • sudo ufw allow from node_ip_address to any port 27017

Now that MongoDB is listening for connections from the outside and has been secured with a firewall, you can connect to it from Node using the MongoDB Node.JS driver

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://mongo_ip_address:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

In order to make your app more portable, consider making the value of url in the above example configurable using an environment variable.

UFW is a firewall configuration tool for iptables that is included with Ubuntu by default. This cheat sheet-style guide provides a quick reference to UFW commands that will create iptables firewall rules are useful in common, everyday scenarios. This includes UFW examples of allowing and blocking various services by port, network interface, and source IP address.
Have another answer? Share your knowledge.