NestJS 中的 TypeORM 无法连接 MongoDB

TypeORM in NestJS can not connect to MongoDB

我在自己的 Ubuntu 服务器上安装了 mongodb 软件,当我在我的 mongo 中输入这个字符串时,我得到了 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: ...
    ...
}

我已经弄清楚是什么问题了,我的mongodb的authSource和数据库保存数据的authSource不是同一个。所以我应该将 authSource 选项设置为 admin,然后它就可以工作了。

return {
      type: 'mongodb',
      host,
      port,
      username,
      password,
      database,
      authSource: 'admin',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    };