简体   繁体   English

将 NodeJS 连接到 MongoDB Droplet

[英]Connect NodeJS to MongoDB Droplet

So I've decided to set up my project with two droplets, a MongoDB image droplet and a NodeJS image droplet.所以我决定用两个 Droplet 来设置我的项目,一个 MongoDB 图像 Droplet 和一个 NodeJS 图像 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.我这样做是为了在将来更容易扩展这两个 droplet,并且将来其他应用程序可能会连接到数据库,两者都在 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).我已经正确设置了两台服务器(所以我相信),我的 MongoDB 有两个用户(都是我,但权限不同,我遵循了几次演练,所以它刚刚发生)。 My /etc/mongod.conf file has been edited accordingly:我的 /etc/mongod.conf 文件已相应编辑:

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. UFW 防火墙启用了 HTTPS、SSH 和我的 NodeJS_ip:27017。

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.我的 NodeJS droplet 设置了一个指向正确 IP 地址的域名,letsencrypt 设置为在域名上进行安全连接。 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.我现在遇到的问题是我无法从我的 NodeJS 应用程序连接到我的 Mongo droplet,我还想确保这一切都安全完成。 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:我的 NodeJS 连接代码正在使用 Mongoose 和一个变量环境文件,根据我在别处看到的另一个建议,我还在超时函数中进行了整个连接:

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.我已经通过这两个 droplets 尝试了很多东西,但是我浪费了大约 4 天的时间来让项目进入暂存/生产阶段,这样它就可以随时启动并且随着时间的推移而更新。

If you need anything else, please do let me know.如果您需要其他任何东西,请告诉我。

All help would be hugely appreciated,所有帮助将不胜感激,

Thanks谢谢

I don't know the URI format you are using.我不知道您使用的 URI 格式。 But I got the same issue initially when I tried to connect my node application with Mongo instance of AWS.但是当我尝试将我的节点应用程序与 AWS 的 Mongo 实例连接时,我最初遇到了同样的问题。

Using the long URI sting with all the cluster name like this像这样使用带有所有集群名称的长 URI 字符串

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/而不是这样的: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另外,在数字海洋链接连接字符串的mongo 文档中找到了这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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