Hello all, we are using MongoDB Serverless and connecting to it from AWS Lambda. I realized that after a while (a few minutes) of idle, subsequent database queries returns this error:
MongoNetworkError: connection 1 to *IP*:27017 closed
at Connection.onClose (.../node_modules/mongodb/lib/cmap/connection.js:134:19)
at TLSSocket.<anonymous> (.../node_modules/mongodb/lib/cmap/connection.js:62:46)
at TLSSocket.emit (node:events:513:28)
at TLSSocket.emit (node:domain:489:12)
at TCP.done (node:_tls_wrap:588:7)
The next few requests will continue to fail as each connection within the pool fails and reconnects. At one point the failures will subside, until I leave it idle for X minutes, and the problem will surface again.
For each of my Lambda function, I have this set:
request.context.callbackWaitsForEmptyEventLoop = false;
with the mongodb client instance outside of the handler function, as suggested by the mongodb for lambda guide.
I can also confirm it is not a network access issue as it currently has 0.0.0.0 allowed and it works consistently at fresh start.
Any suggestions or help will be much appreciated! Thanks
@Danny_Yang it might have something to do with whitelisted ip addresses…
@Danny_Yang – Did you find a solution? Running into the same problem in Vercel API routes.
Please did you get a solution to this. I’m using nextjs and running into the same error
Maybe it’s because your current ip address and ip address in mongodb atlas are not the same.
you need to add your current address to network access in mongodb atlas project that are you working on or add 0.0.0.0/0 to ip address list and this will make any Someone who can log in has a connection to the database (I recommend the first method)
the second option is really an easy alternative to do with. can you specifying the first option, please? Like we need to adding extra option script inside our code or something.
because it will throw some error when you just adding a character. you need to add your currenet IP address over and over after you make changes.
Through Network access option , Whitelist your current IP address or simply allow access from everywhere, i.e. 0.0.0.0/0 (includes your current IP address), also ensure that you have good internet connection.
This worked in my case. Hoping same for others.
I have whitelisted my ip, but I still have this issue. Does anyone have another solution?