aws-node-mongodb-atlas
An example app, created in this blog post, showing how to connect AWS Lambda to MongoDB Atlas, which must be configured with a user with read/write privileges and an IP whitelist to allow Lambda to connect to it. See blog post for detailed walkthrough setting up MongoDB Atlas.
The MongoDB connection is cached at module scope so warm Lambda invocations reuse it instead of reconnecting on every request.
Setup
-
Set the
MONGODB_URIenvironment variable inserverless.ymlto your MongoDB Atlas connection string.provider: environment: MONGODB_URI: mongodb+srv://<user>:<password>@<cluster>.mongodb.net/<db>?retryWrites=true -
Install the dependencies and deploy
npm install serverless deploy
Usage
curl https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/hello
{
"insertedPet": { "type": "cat", "name": "Jane Doe" },
"mongoResult": { "acknowledged": true, "insertedId": "..." }
}