Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS: How to get instance of mongoose for health check?

I am using the @nestjs/mongoose package to connect to Mongo DB. I have this in app.module.ts:

imports: [
   MongooseModule.forRoot(process.env.MONGODB_URI, {
      useNewUrlParser: true,
      bufferCommands: false,
      bufferMaxEntries: 0,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true
})]

Now, the NestJS service is running in a Kubernetes cluster with proper health, liveness and readiness checks. Whenever the readiness or health end-point is invoked on the service, i need to check if the hosted Atlas Mongo DB connection is available or if there is an outage. As of now, the following code is executed for readiness and health end-points:

this.mongoDbConnection = await mongoose.connect(process.env.MONGODB_URI, options);
return (this.mongoDbConnection.connection.readyState === 1);

But this creates a new connection with the mongo DB server. What i want is to retrieve the readyState of the existing connection that NestJS makes through MongooseModule.forRoot in app.module.ts.

I am not sure how to retrieve the existing mongoose connection object in the health check service code. Any help would be much appreciated.

like image 721
Ramandeep Singh Avatar asked Oct 15 '25 07:10

Ramandeep Singh


2 Answers

I'd suggest using @nestjs/terminus module, see the documentation and/or repository to integrate the module in application.

and your health controller can look something like this

import { Controller, Get } from "@nestjs/common";
import {
  HealthCheck,
  HealthCheckResult,
  HealthCheckService,
  MongooseHealthIndicator,
} from "@nestjs/terminus";

@Controller("health")
export class HealthController {

  constructor(
    private healthCheck: HealthCheckService,
    private mongooseHealth: MongooseHealthIndicator,
  ) {
  }

  @Get()
  @HealthCheck()
  async check(): Promise<HealthCheckResult> {
    return this.healthCheck.check(
      [
        () => this.mongooseHealth.pingCheck("mongoDB"),
      ],
    );
  }

}

like image 173
kaznovac Avatar answered Oct 17 '25 02:10

kaznovac


Try remove this line

useUnifiedTopology: true

UPDATE:

I apologize for my answer. My project create health check route for K8s like this

import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';

@Controller()
export class HealthzController {
  constructor (@InjectConnection() private readonly connection: Connection) { }

  @Get('/_status/healthz')
  healthCheck (@Res() res: Response) {
    if (this.connection.readyState === 1) {
      res.status(HttpStatus.OK).json({ db: { status: 'up' } });
    } else {
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ db: { status: 'down' } });
    }
  }
}

Hope that helps you.

like image 35
TrwKc Avatar answered Oct 17 '25 03:10

TrwKc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!