In my lambda function, I tried to close the mongo connection as soon as I send a callback. But it has a problem.
db.close()
things work perfectly.I think lambda re-use the connection for all the functions because I open the connection in the top of the handler:
// Connect to database
mongoose.connect(process.env.DATABASE_URL);
const handleCreateUser = async (event, context, callback) => {
// eslint-disable-next-line no-param-reassign
context.callbackWaitsForEmptyEventLoop = false;
const data = JSON.parse(event.body);
const { user, userProfile } = data;
await createUser({ callback, user, userProfile });
};
Any idea what how to fix this? Do we really have to close the connection at this point?
Either move the mongoose.connect
code inside the handler, or stop calling db.close()
. You currently have a single database connection being reused by multiple invocations of your Lambda function, but you are closing it after the first invocation completes.