Mongoose Connection outside NestJS for Lambda Mongoose Connection outside NestJS for Lambda mongoose mongoose

Mongoose Connection outside NestJS for Lambda


My first impression is to explicitly close connections, or set a timeout. However, I cannot seem to find anything approaching official documentation for nest.js for either of these options.

So: You have a database that doesn't automatically close idle connections, and a middleware that never closes connections, so your system is getting plugged. You could try putting something between them, to wait for idle and break the connection (even some firewalls may be talked into doing that). However, considering how impossible and/or undocumented proper connection handling is with these products, I suggest you rethink your choice of technologies.


You must call app.close() after your function is executed to close mongoose connection.

example for AWS Cognito Lambda trigger:

    import { INestApplicationContext } from '@nestjs/common';    let cachedApp: INestApplicationContext;    async function bootstrap() {      if (!cachedApp) {        cachedApp = await NestFactory.createApplicationContext(          PreTokenGenerationModule        );      }      return cachedApp;    }    export async function handler(       event: CognitoUserPoolTriggerEvent,       context: Context,       callback: Callback    ) {       const app = await bootstrap();       const preTokenGenerationService = app.get(PreTokenGenerationService);       await preTokenGenerationService.execute(event, context, callback);       app.close();    }