1

I am trying to connect to local mongoDB in the AppModule by doing the following but it won't connect:

imports: [
    MongooseModule.forRootAsync({
      useFactory: async () => {
        return {
          uri: 'mongodb://localhost:27017/client',
          useNewUrlParser: true,
          useCreateIndex: true,
        };
      },
    }),
  ],

Error from NestJS: [MongooseModule] Unable to connect to the database. Retrying (1)...

The MongoDB is running fine. I can connect to it through MongoDB Compass with the same uri.

What is done wrong causing the connection not being established?

jackielpy
  • 72
  • 1
  • 11

2 Answers2

0

useNewUrlParser , useUnifiedTopology , useFindAndModify , and useCreateIndex are no longer supported options,İf you remove that option everything will works.From the Mongoose 6.0 docs:

MongooseModule.forRootAsync({
      useFactory: async () => ({
        uri: 'mongodb://localhost:27017/client',
      }),
    }),
0

This works with async and logging options

MongooseModule.forRootAsync({
      useFactory: async () => {
        const connection = await ConnectToMongodb.getConnectionString();
        return {
          connectionFactory: (connection) => {
            if (connection.readyState === 1) {
              console.log('Database Connected successfully');
            }
            connection.on('disconnected', () => {
              console.log('Database disconnected');
            });
            connection.on('error', (error) => {
              console.log('Database connection failed! for error: ', error);
            });

            return connection;
          },
          uri: connection,
        };
      },
    })
Gvs Akhil
  • 2,165
  • 2
  • 16
  • 33