【发布时间】:2020-03-15 19:25:39
【问题描述】:
所以我决定用两个小滴设置我的项目,一个 MongoDB 图像小滴和一个 NodeJS 图像小滴。我这样做是为了在将来更容易扩展这两个 Droplet,并且其他应用程序将来可能会连接到数据库,两者都在 Ubuntu 18.04 上。
我收到以下错误:
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)]: {} }
我已经正确设置了两台服务器(所以我相信),我的 MongoDB 有两个用户(都是我,但权限不同,我已经遵循了几个演练,所以它就发生了)。我的 /etc/mongod.conf 文件已被相应地编辑:
net:
port: 27017
bindIp: 127.0.0.1,mongodb_droplet_ip
security:
authorization: "enabled"
UFW 防火墙启用了 HTTPS、SSH 和我的 NodeJS_ip:27017。
我的 NodeJS droplet 设置了一个指向正确 IP 地址的域名,letsencrypt 设置为在该域名处进行安全连接。我现在遇到的问题是我无法从我的 NodeJS 应用程序连接到我的 Mongo droplet,我还想确保这一切都安全地完成了。 我的 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);
我已经通过这两个 Droplet 尝试了很多东西,但是我浪费了大约 4 天的时间来让项目进入暂存/生产阶段,以便它可以随时启动并随着时间的推移进行更新。
如果你还需要什么,请告诉我。
所有帮助将不胜感激,
谢谢
【问题讨论】:
标签: node.js mongodb digital-ocean