首页 > 解决方案 > 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。有谁知道问题是什么以及如何解决?感谢你。

标签: mongodbexpressnestjstypeorm

解决方案


也许您应该尝试使用数据库 URL 连接字符串而不是主机、端口、用户名、密码……

所以而不是使用这个

return {
    type: 'mongodb',
    host,
    port,
    username,
    password,
    database,
    entities: ...
    ...
}

你应该用这个

return {
    type: "mongodb",
    url: configService.get("DATABASE_URL"),
    entities: ...
    ...
}

推荐阅读