Unable to connect to the database. Retrying

Viewed 5029

I'm trying to connect to the database, seems like the set-up is correct, but for some reason, it says that it is not available.

app.module.ts

import { Module } from "@nestjs/common"
import { MongooseModule } from "@nestjs/mongoose";
import { ConfigModule } from "../config";
import { CreatorModule } from "./creator.module";

@Module({
    imports: [
        MongooseModule.forRoot('mongodb://localhost:27017/snaptoon', {
            useCreateIndex: true,
            useUnifiedTopology: true,
            useNewUrlParser: true,
        }),
        CreatorModule,
    ],
    controllers: [],
    providers: []
})

export class AppModule {}

The error is: ERROR [MongooseModule] Unable to connect to the database. Retrying (9)...

I'm using '@nestjs/mongoose': '9.0.2'

4 Answers

I solved by updating manually mongoose version to 6.2.2

 WARN @nestjs/mongoose@9.0.2 requires a peer of mongoose@^6.0.2 but none is installed. You must install peer dependencies yourself.

I realize due to this error on npm install

just use:

 npm install mongoose@6.2.2 --save

Worked for me when I've added "directConnection=true" to the connection string.

"If set to true, the driver will only connect to the host provided in the URI and will not discover other hosts in the cluster. Direct connections are not valid if multiple hosts are specified."

Before:

MongooseModule.forRoot(
  `mongodb://${host}:${post}/${dbName}`,
),

After:

MongooseModule.forRoot(
  `mongodb://${host}:${post}/${dbName}?directConnection=true`,
),

My application was working fine in "@nestjs/mongoose": "^8.0.0" and I faced this error when I changed to "@nestjs/mongoose": "^9.0.0".

Docs: https://www.mongodb.com/docs/drivers/go/current/fundamentals/connection/#connection-options

For those people who cannot solve this problem by the answer above, according to the new specs of nestjs/mongoose.

It might be solved by deleting the line: useNewUrlParser: true.

For me, it works in both ways.

Use mongodb://127.0.0.1:27017/snaptoon instead of mongodb://localhost:27017/snaptoon as connection string. It worked for me.

Related