简体   繁体   中英

Unable to connect nodejs to mongodb

I just created a mongo database on DigitalOcean 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?

It seems you might not enabled the mongo port to access from Remote location .

First run the following commands on your droplet

sudo ufw enable

sudo ufw allow OpenSSH

sudo ufw allow 27017

Now open the mongo config file and add append your droplet ip in bindIp section.

file path:

sudo nano /etc/mongod.conf

Add the below code, edit droplet_ip with your server ip :

 . . .
net:
  port: 27017
  bindIp: 127.0.0.1, droplet_ip
 . . .

Now restart mongo by below command:

sudo systemctl restart mongod

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM