Connect NodeJS to MongoDB Droplet

青春壹個敷衍的年華 提交于 2021-02-04 08:27:46

问题


So I've decided to set up my project with two droplets, a MongoDB image droplet and a NodeJS image droplet. I did so to make it easier to scale both droplets in the future, and other applications may be connecting to the DB in the future, both on Ubuntu 18.04.

I'm getting the error of:

Could not connect to the database:  { MongooseServerSelectionError: connection timed out
    at new MongooseServerSelectionError (/root/eternal-peace-code/node_modules/mongoose/lib/error/serverSelection.js:22:11)
    at NativeConnection.Connection.openUri (/root/eternal-peace-code/node_modules/mongoose/lib/connection.js:808:32)
    at Mongoose.connect (/root/eternal-peace-code/node_modules/mongoose/lib/index.js:333:15)
    at Timeout.setTimeout [as _onTimeout] (/root/eternal-peace-code/app.js:60:22)
    at ontimeout (timers.js:482:11)
    at tryOnTimeout (timers.js:317:5)
    at Timer.listOnTimeout (timers.js:277:5)
  message: 'connection timed out',
  name: 'MongooseServerSelectionError',
  reason: 
   TopologyDescription {
     type: 'Single',
     setName: null,
     maxSetVersion: null,
     maxElectionId: null,
     servers: Map { 'mongo_droplet_ip:27017' => [Object] },
     stale: false,
     compatible: true,
     compatibilityError: null,
     logicalSessionTimeoutMinutes: null,
     heartbeatFrequencyMS: 10000,
     localThresholdMS: 15,
     commonWireVersion: null },
  [Symbol(mongoErrorContextSymbol)]: {} }

I have set up both servers correctly (so I believe), my MongoDB has two users (both are me but different permissions, I have followed several walkthroughs and so it just happened). My /etc/mongod.conf file has been edited accordingly:

net:
  port: 27017
  bindIp: 127.0.0.1,mongodb_droplet_ip
security:
  authorization: "enabled"

The UFW firewall has HTTPS, SSH and my NodeJS_ip:27017 enabled.

My NodeJS droplet is set up with a domain name pointing to the right IP address, letsencrypt is set up for secure connection at the domain name. The issue I have now is that I can not connect to my Mongo droplet from my NodeJS application, and I would also like to make sure that it is all done securely too. My NodeJS connect code is using Mongoose and a variables environment file, I also have the whole connect in a timeout function as per another suggestion I saw elsewhere:

setTimeout(async () => {
      console.log('Connecting to database...');
      const options = {
        user: process.env.DBUSER,
        pass: process.env.USERPASS,
        keepAlive: true,
        useNewUrlParser: true,
        useFindAndModify: false,
        useCreateIndex: true,
        useUnifiedTopology: true,
        sslCA: cert,
        connectTimeoutMS: 5000,
      }
      await mongoose.connect(process.env.LIVEDB, options)
      .then(() => {
        console.log('We are connected to the database');
      })
      .catch(err => {
        console.log('Could not connect to the database: ', err);
        connectWithTimeout();
        });
    }, 3000);

I have tried a multitude of things through both droplets but I have wasted around 4 days on getting the project to a staging/production stage so it can launch whenever and just be updated as time goes on.

If you need anything else, please do let me know.

All help would be hugely appreciated,

Thanks


回答1:


I don't know the URI format you are using. But I got the same issue initially when I tried to connect my node application with Mongo instance of AWS.

Using the long URI sting with all the cluster name like this

mongoURI = 'mongodb://username:password@mongo-instance-shard-00-00-a4iv8.mongodb.net:27017,mongo-instance-shard-00-01-a4iv8.mongodb.net:27017,mongo-instance-shard-00-02-a4iv8.mongodb.net:27017/test?ssl=true&replicaSet=mongo-instance-shard-0&authSource=admin&retryWrites=true&w=majority'

Instead of something like this: mongodb+srv://server.example.com/

This worked for me. It might help you as well.

Also, found this for digital ocean link and mongo documentation for the connection string



来源:https://stackoverflow.com/questions/60696749/connect-nodejs-to-mongodb-droplet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!