简体   繁体   中英

Unable to connect mongoDB using nestjs/mongoose

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.

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'
    }),
  ]

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,
   ],

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',
  })
]

Please check the password again.

Sometime users confused with the mongodb account password and user password. You should use user password, not account password.

That was the reason of my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM