Using Mongoose With AWS Lambda

Sponsor #native_company# — #native_desc#

AWS Lambda is a popular service for running arbitrary functions without managing individual servers. Using Mongoose in your AWS Lambda functions is easy. Here’s a sample function that connects to a MongoDB instance and finds a single document:

  1. const mongoose = require('mongoose');
  2. let conn = null;
  3. const uri = 'YOUR CONNECTION STRING HERE';
  4. exports.handler = async function(event, context) {
  5. // Make sure to add this so you can re-use `conn` between function calls.
  6. // See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
  7. context.callbackWaitsForEmptyEventLoop = false;
  8. // Because `conn` is in the global scope, Lambda may retain it between
  9. // function calls thanks to `callbackWaitsForEmptyEventLoop`.
  10. // This means your Lambda function doesn't have to go through the
  11. // potentially expensive process of connecting to MongoDB every time.
  12. if (conn == null) {
  13. conn = mongoose.createConnection(uri, {
  14. // Buffering means mongoose will queue up operations if it gets
  15. // disconnected from MongoDB and send them when it reconnects.
  16. // With serverless, better to fail fast if not connected.
  17. bufferCommands: false, // Disable mongoose buffering
  18. bufferMaxEntries: 0 // and MongoDB driver buffering
  19. });
  20. // `await`ing connection after assigning to the `conn` variable
  21. // to avoid multiple function calls creating new connections
  22. await conn;
  23. conn.model('Test', new mongoose.Schema({ name: String }));
  24. }
  25. const M = conn.model('Test');
  26. const doc = await M.findOne();
  27. console.log(doc);
  28. return doc;
  29. };

To import this function into Lambda, go the AWS Lambda console and click “Create Function”.

AWS Lambda - 图1

Create a function called “mongoose-test” with the below settings:

AWS Lambda - 图2

Copy the source code into a file called lambda.js. Then run npm install mongoose co. Finally, run zip -r mongoose-test.zip node_modules/ lambda.js to create a zip that you can upload to Lambda using the “Upload a Zip File” option under “Function code”. Make sure you also change the “Handler” input to lambda.handler to match the lambda.js file’s handler function.

AWS Lambda - 图3

Next, click the “Save” button and then the “Test” button. The “Test” button will ask you to create a new test event, just create one because your inputs don’t matter for this example. Then, hit “Test” again to actually run your function:

AWS Lambda - 图4

If your MongoDB database goes down in between function calls, you may see the below error message:

  1. cannot find account after reload: could not find config for <hostname>

Lambda’s JavaScript framework recently added support for async/await as long as you’re using Node 8.x, so make sure you’re not using Node.js 6.x.

Want to learn how to check whether your favorite JavaScript frameworks, like Express or React, work with async/await? Spoiler alert: neither Express nor React support async/await. Chapter 4 of Mastering Async/Await explains the basic principles for determining whether a framework supports async/await. Get your copy!

AWS Lambda - 图5