How to connect Node.js to a MongoDB droplet

February 16, 2018 1k views
Node.js MongoDB DigitalOcean Ubuntu 16.04
valip
By:
valip

Hello, I just created a MongoDB database following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-mongodb-on-ubuntu-16-04 and everything works fine when I'm accessing a database from the mongo shell but I can't connect to the database using node.js

This is my code:

import mongoose from 'mongoose';
mongoose.connect('mongodb://user:pass@droplet_ip:27017/my_database', (err, res) => {
  if(err) {
    console.log(err);
  }
  else {
    console.log('connected');
  }
})

And this is the error:

{ MongoError: failed to connect to server [droplet_ip:27017] on first connect [MongoError: connection 0 to droplet_ip:27017 timed out]
    at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:336:35)
    at emitOne (events.js:96:13)
    at Pool.emit (events.js:189:7)
    at Connection.<anonymous> (/node_modules/mongodb-core/lib/connection/pool.js:280:12)
    at Object.onceWrapper (events.js:291:19)
    at emitTwo (events.js:106:13)
    at Connection.emit (events.js:192:7)
    at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:197:10)
    at Object.onceWrapper (events.js:291:19)
    at emitNone (events.js:86:13)
    at Socket.emit (events.js:186:7)
    at Socket._onTimeout (net.js:342:8)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)
  name: 'MongoError',
  message: 'failed to connect to server [droplet_ip:27017] on first connect [MongoError: connection 0 to droplet_ip:27017 timed out]' }

What am I doing wrong?

2 Answers

Please replace droplet_ip with ip first.

  • I'm using the ip when I'm trying to connect to the MongoDB database. I simply replaced it here with "droplet_ip".

If you followed Part Three: Configuring Remote Access (Optional) of the "Install and Secure Mongodb" article, make sure you've didn't accidentally firewall off the droplet running the express app from connecting to the mongodb droplet.

Are you able to connect to monodb from the mongo shell ON the droplet that is running the express app?

message: 'failed to connect to server [dropletip:27017] on first connect [MongoError: connection 0 to dropletip:27017 timed out]' }

Maint take away from the error message is it "Timed Out", so I'm thinking its unable to connect, or something is blocking it from connecting.

Does the express app droplet have any outgoing firewall rules?

Have another answer? Share your knowledge.