mongodb - NestJS中的TypeORM无法连接到MongoDB
问题描述
我在我自己的 Ubuntu 服务器上安装了 mongodb 软件,我得到了这样的 mongo 字符串mongodb://xxx:pass@42.212.159.109:27017
,当我在本地终端中输入这个字符串并使用mongosh mongodb://xxx:pass@42.212.159.109:27017
时,它工作正常并且连接成功。但是当我在我的nestjs项目中使用这个mongodb字符串时,当我运行时npm run start
,终端输出MongoServerError: Authentication failed.
app.module.ts
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
const username = configService.get('MONGO_USER');
const password = configService.get('MONGO_PASS');
const database = configService.get('MONGO_DATABASE');
const host = configService.get('MONGO_HOST');
const port = configService.get('MONGO_PORT');
return {
type: 'mongodb',
host,
port,
username,
password,
database,
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
};
},
mongodb版本是4.1.3,TypeOrm版本是0.2.38。有谁知道问题是什么以及如何解决?感谢你。
解决方案
也许您应该尝试使用数据库 URL 连接字符串而不是主机、端口、用户名、密码……
所以而不是使用这个
return {
type: 'mongodb',
host,
port,
username,
password,
database,
entities: ...
...
}
你应该用这个
return {
type: "mongodb",
url: configService.get("DATABASE_URL"),
entities: ...
...
}
推荐阅读
- typescript - 如何定义特定类型的常量?
- scala - 需要使用数据框 API 而不是 RDD 来转换数据框
- r - 在 mac 上安装 ProStar
- python - Python:pysftp 异常处理
- javascript - 带视频的 iframe(youtube 和 vimeo)在 safari 中有奇怪的行为
- flutter - Flutter-web:浏览器刷新时提供者状态丢失
- opencv - 在失真的图像上绘制极线
- angular - Angular 2 Reactive Form - 仅在表单脏时显示重置按钮
- docker - 为什么我们需要在 DockerFile 中为 Asp.net 核心提供多个复制指令
- angular - 实现了两个 HTTP 拦截器,但只调用了一个