This repository demonstrates how to use MongoDB Change Streams as a trigger to an AWS Lambda function.
This is the Lambda function used to send an email from a MongoDB Change Stream notification
- In AWS, create an S3 bucket, create a
Templatesfolder and upload the ChangeStreamInfo.html file into it. - In AWS, configure SES with (at least) 2 verified email addresses (one will be used to send the email, the other to receive the email)
- In
sam.yaml, customize- the
S3_BUCKETenvironment variable with the value of your S3 bucket - the
FROM_ADDRESSenvironment variable with the value of the first SES-verified email address
- the
- In config.js set the
toEmailproperty to your other SES-verified email address
- Install SAM Local on your machine
- In the email-lambda folder, run
npm installto install the required Node dependencies - Run
sh invoke.shfrom Terminal to test your Lambda function local
- Run
sh package.shfrom Terminal to package your SAM package - Run
sh deploy.shfrom Terminal to deploy your SAM package to AWS - Once the script has completed (without errors), sign in into the AWS Console
- Navigate to the IAM service, edit the
ChangeStream-SendEmail-SendEmailRole-[random]role - Add 2 inline policies
- For Amazon S3, add the
GetObjectpolicy on the*ARN - For Amazon SES, add the
SendEmailpolicy
- For Amazon S3, add the
- Test that the
SendEmaillambda function works correctly (you can use theevent.jsonfile as a test event). - Navigate to the API Gateway console and select API Keys. Create an API Key and copy the value to the
awsApiGWKeyproperty of the trigger/config.js file. - Select the ChangeStream-SendEmail API and in the Actions menu, select Deploy API for the Stage deployment stage.
- In the ChangeStream-SendEmail/Stages menu, select the Stage stage and copy the Invoke URL value. Copy it to the
awsApiGWUrlproperty of the trigger/config.js file.
You must configure a replica set for change streams to work. Follow the instructions below:
- Make sure the latest version of mtools is installed on your machine
- In the trigger folder, edit setup.sh and update the MONGO_LOCATION variable to point to your local MongoDB 3.6 installation root
- Run
sh setup.shto set up your MongoDB 3.6 replica set using mlaunch - Run
sh run.shto start your MongoDB 3.6 replica
- In the trigger folder, run
npm installto install the required Node dependencies - Run
node trigger.jsto start listening to change streams coming from the devices collection of the demo database. - In a separate Terminal window, run
node addDoc.js- this will add a document to thedevicescollection of thedemodatabase. - Look at the window running
trigger.jsand if everything was properly configured you should get a Change Stream output log message, followed by a message confirming that the email was successfully sent. - Check your email inbox and you should find an email titled MongoDB 3.6 Change Stream notification for ecobee_1234.