I was recently working on a serverless api that uses serverless offline, express.js and mongodb.
We were running out of mongodb database connections when we were running it locally and connecting to the hosted database.
We onboarded a larger group of developers for a few months to help on a few bugs and started getting emails from MongoDB Atlas telling us that we ran out of connections.
I thought this was really strange because I thought serverless offline was working the same way as AWS Lambda does – it only starts the index.js the first run but that isn’t correct.
Every function run causes all of the code to run again which means you could be quickly running through connections if you aren’t cleaning up at the end.
To fix this, you need to disconnect mongodb if it’s connected in the response and make sure that you connect to it prior to the request being sent off to express.
This solution should work fine for you if you are using any version of serverless 2 – process.env.IS_OFFLINE is deprecated in version.
This solution should also work if you are using the following libraries:
Also published on Medium.