I am using mongoose as database for my node/express js project. I had no problem until I decided to migrate my app to AWS Lambda. There I need to create a persistent connection to avoid my app to connect to mongodb each time a function is invoked.
So, I've checked the mongoose docs but it's unclear to me how to integrate this with my current code :
app.get("/", (req, res) => { res.send("Hello World!") });
app.post("/addMessage", myApp.addMessage);
app.listen(PORT, () => {});
module.exports.handler = serverless(app);
I've tried this, but it did not work
let conn = null;
module.exports.handler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
if (conn == null) {
conn = mongoose.createConnection(URI, {
bufferCommands: false,
bufferMaxEntries: 0
});
await conn;
}
serverless(app)
};
Any suggestion ?