【问题标题】:TypeORM in NestJS can not connect to MongoDBNestJS中的TypeORM无法连接到MongoDB
【发布时间】:2021-12-03 11:28:40
【问题描述】:

我在自己的 Ubuntu 服务器上安装了 mongodb 软件,我得到了像 mongodb://xxx:pass@42.212.159.109:27017 这样的 mongo 字符串,当我在本地终端中输入这个字符串并使用 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。 有谁知道问题是什么以及如何解决?谢谢你。

【问题讨论】:

    标签: mongodb express nestjs typeorm


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      所以不要使用这个

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

      你应该使用这个

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

      【讨论】:

        猜你喜欢
        • 2019-08-13
        • 2019-08-02
        • 2020-01-25
        • 2021-10-19
        • 2021-05-25
        • 2023-01-05
        • 2021-05-26
        • 1970-01-01
        • 2021-02-17
        相关资源
        最近更新 更多