Unable to connect to the database. Retrying
Asked Answered
P

11

9

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'

Phosphorous answered 16/1, 2022 at 13:32 Comment(4)
Have you been able to connect to the database from CLI?Bobbie
Considered using forRootAsync: MongooseModule.forRootAsync({ useFactory: () => ({ uri: 'mongodb://localhost:27017/snaptoon', }), }),Shelley
There are 10 retries that the connection goes through by default. After the tenth, the full error is printed out. Most likely, your version of mongo does not support one or more of the options you are passingVomit
In my case, I removed useCreateIndex:true and it connected.Algid
N
5

I solved by updating manually mongoose version to 6.2.2

 WARN @nestjs/[email protected] 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 [email protected] --save
Nard answered 17/2, 2022 at 16:26 Comment(0)
L
40

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

Lifeanddeath answered 30/8, 2022 at 4:51 Comment(1)
For whoever curious, this is due to Node is now prefer IPv6 which translates localhost to ::1 instead of 127.0.0.1Waggery
N
9

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}:${port}/${dbName}`,
),

After:

MongooseModule.forRoot(
  `mongodb://${host}:${port}/${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

Nosegay answered 29/6, 2022 at 23:1 Comment(1)
That this change has not been promoted more heavily in the documentation, is beyond me. Thanks for saving us some time here, buddy.Ningpo
N
5

I solved by updating manually mongoose version to 6.2.2

 WARN @nestjs/[email protected] 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 [email protected] --save
Nard answered 17/2, 2022 at 16:26 Comment(0)
U
3

I'm trying to connect with remote database. I've solved this problem with this adding this 2 query parameter

?authSource=admin&directConnection=true

Full URI

mongodb://username:password@host:port/dbname?authSource=admin&directConnection=true

And if you get this error

MongoParseError: Password contains unescaped characters

wrap your password with encodeURIComponent function.

mongodb://username:${encodeURIComponent(password)}@host:port/dbname?authSource=admin&directConnection=true

Unfrock answered 21/10, 2022 at 17:56 Comment(0)
W
3

Are you using Node 17 or above? Node now prefers IPv6 over IPv4 from Node 17 so localhost will translate to ::1: and not 127.0.0.1 - related issue. Your local MongoDB server is probably running on 127.0.0.1 and thus your application is unable to connect. Try connecting to mongodb://127.0.0.1:27017/snaptoon as this answer suggested.

Weightless answered 4/12, 2022 at 15:38 Comment(0)
P
2

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.

Phosphorous answered 25/3, 2022 at 9:12 Comment(1)
Mongose 6 are no longer to support the options: useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex. Cause useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. mongoosejs.com/docs/… credits to @Alex GEmpiricism
A
0

I changed useCreateIndex: true to useCreateIndex: undefined in MongooseModule.forRoot() config parameter object.

Admit answered 19/11, 2022 at 19:27 Comment(0)
A
0

had an issue with MongoDB docker image version, solved problem with 3.6 version

Abolition answered 27/11, 2022 at 20:31 Comment(0)
P
0
  1. Database Deployments /Cluster connect : Example: mongodb+srv://<DataBaseName>:<password>@<clusterName>.gsr9ucc.mongodb.net/?retryWrites=true&w=majority
  2. Turn off all vpn and proxy. In browser and window. Anywhere.
  3. Go to mongodb/Network Access set current ip. Check several times to make sure.
Potboiler answered 6/2, 2023 at 10:22 Comment(0)
S
0

I am using latest version (current date is 04/05/2023) and solved this issue. Some of this step is optional but good to try!

  1. Open terminal and make sure MongoDB is running net start MongoDB

  2. Make sure your connection is success by test connection in MongoDB Compass

note: this code below will generate database (or just make new collection, if the db is already exist) automatically in your mongoDB.

Nest Js code

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { CatModule } from './cat/cat.module';

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://127.0.0.1:27017/nest', {
      useNewUrlParser: true, useUnifiedTopology: true
    }),
    CatModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

cat.module.ts

import { Module } from '@nestjs/common';
import { CatController } from './cat.controller';
import { CatService } from './cat.service';
import { MongooseModule } from '@nestjs/mongoose';
import { Cat, CatSchema } from './cat.model';

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: Cat.name, schema: CatSchema },
    ])
  ],
  controllers: [CatController],
  providers: [CatService]
})
export class CatModule { }

cat.service.ts

import { Injectable } from '@nestjs/common';
import { InjectConnection, InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './cat.model';
import { Connection, Model } from 'mongoose';
import { CreateCatDto } from './dto/create-cat.dto';

@Injectable()
export class CatService {
    constructor(
        @InjectModel(Cat.name) private catModel: Model<CatDocument>) { }
}

cat.model.ts

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document } from 'mongoose';

export type CatDocument = Cat & Document;

@Schema()
export class Cat {
    @Prop()
    id: number;

    @Prop()
    name: string;

    @Prop()
    health: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);
Stumer answered 4/5, 2023 at 16:54 Comment(1)
update & note: 1. I solved the issue after adding useNewUrlParser: true, useUnifiedTopology: true, and my nestJs could connect to mongodb 2. after that i tried removing useNewUrlParser: true, useUnifiedTopology: true, but still working i didnt know what just happened, but it solved the issue. please correct my answer or comment If you have better explanation.Stumer
Z
0

5

I solved by updating manually mongoose version to 6.2.2

WARN @nestjs/[email protected] 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 [email protected] --save
Zoology answered 28/5 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.