1

I have a nest.js node server and I am trying to connect mongoDB data base in the app.module, when the connection string doesn't contains the DB name - the connection to default DB "test" success, but when I specify the DB name- always getting "Authentication failed" error.

app.module.ts:

This works:

  imports: [
    MongooseModule.forRoot('mongodb://admin:admin@localhost:30000'),
  ]

But this specifying the DB name failed with Authentication error:

  imports: [
    MongooseModule.forRoot('mongodb://admin:admin@localhost:30000/test'),
  ]

or:

  imports: [
    MongooseModule.forRoot('mongodb://admin:admin@localhost:30000/data'),
  ]

Using MongoClient directly (without nestjs) connecting successfully:

const client = new MongoClient('mongodb://admin:admin@localhost:30000');
await client.connect();
db = client.db('data');

Any idea what is my problem and what should I do in order to solve this problem?

Thanks.

user2436448
  • 335
  • 6
  • 17

3 Answers3

10

Specify the DB name as a connection option - not as a part of the connection string solved the problem:

imports: [
    MongooseModule.forRoot({
       uri: 'mongodb://admin:admin@localhost:30000',
       dbName: 'data'
    }),
  ]
user2436448
  • 335
  • 6
  • 17
5

This actually is not supported on newest version of @nestjs/mongoose, for instance in version ^7.2.4 it receives an string as first parameter and an object as second parameter, so what worked for me was:

   imports: [
      MongooseModule.forRoot(
      'mongodb://user:password@localhost:27017/nestjs-tutorial?authSource=admin&readPreference=primary',
    ),
    customModule,
   ],
Erick Garcia
  • 440
  • 4
  • 8
4

according to NestJS official document, forRoot() method accepts the same configuration object as mongoose.connect() from the Mongoose package.

you may define the db name in this way:

imports: [
  MongooseModule.forRoot('mongodb://admin:admin@localhost:30000', {
    dbName: 'custom_db_name',
  })
]