【发布时间】:2022-03-11 19:44:21
【问题描述】:
问题
我正在尝试使用 nestjs(^8.2.3) 和 typeorm(^0.2.28) 连接到 mongodb 在测试环境中,连接到 mongodb 独立服务器正在工作。供您参考,node mongodb 库版本为 ^3.6.2。
生产示例代码(nestjs 服务器)
我提到了typeorm code 来编写 mongodb 选项
import { TypeOrmModule } from '@nestjs/typeorm';
import { MongoConnectionOptions } from 'typeorm/driver/mongodb/MongoConnectionOptions';
export const configForOrmModule = TypeOrmModule.forRootAsync({
imports: [],
useFactory: async () => {
const mongodbConfig: MongoConnectionOptions = {
type: 'mongodb',
username,
// for replicaSet (production)
hostReplicaSet: 'server1.example.com:20723,server2.example.com:20723,server.example.com:20723',
replicaSet: 'replicaSetName'
port: Number(port),
password: encodeURIComponent(password),
database,
authSource,
synchronize: true,
useUnifiedTopology: true,
entities: [Something],
};
return mongodbConfig;
},
inject: [],
});
但是在生产环境中,当nestjs服务器尝试连接mongodb副本集时,服务器一遍又一遍地得到这个服务器选择循环错误消息,如下所示。有趣的是服务器尝试连接的域与replicaSet主机不同(例如another-hostname不包括在server1.example.com:20723,server2.example.com:20723,server.example.com:20723中)。 (+ 编辑:另一个主机名是由 dns(server.example.com) 指示的实际物理服务器)
[39m01/28/2022, 2:39:16 AM [31m ERROR[39m [38;5;3m[TypeOrmModule] [39m[31mUnable to connect to the database. Retrying (3)...[39m
MongoServerSelectionError: getaddrinfo ENOTFOUND <another-hostname>
at Timeout._onTimeout (/home/node/app/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
我试过了,但这些都不起作用
- 删除
useUnifiedTopology: true选项 - 将
mongodb库版本降级到 3.5.11(我在 mongodb 社区读到 3.6 版本之后的拓扑存在一些错误) - 使用主机选项而不是 hostReplicaSet
如果您需要更多信息,请告诉我。谢谢你的帮助。
【问题讨论】: