How to connect Node.js to a MongoDB droplet
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?