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?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
3 answers

Please replace droplet_ip with ip first.

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?

Make sure that your mongodb is running.
Check docker ls result, you should see both your app and mongo at up status. if your mongo is missing or down, that is the problem

Submit an Answer