Using Mongoose With AWS Lambda

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. // and tell the MongoDB driver to not wait more than 5 seconds
  15. // before erroring out if it isn't connected
  16. serverSelectionTimeoutMS: 5000
  17. });
  18. // `await`ing connection after assigning to the `conn` variable
  19. // to avoid multiple function calls creating new connections
  20. await conn;
  21. conn.model('Test', new mongoose.Schema({ name: String }));
  22. }
  23. const M = conn.model('Test');
  24. const doc = await M.findOne();
  25. console.log(doc);
  26. return doc;
  27. };

Connection Helper

The above code works fine for a single Lambda function, but what if you want to reuse the same connection logic in multiple Lambda functions? You can export the below function.

  1. 'use strict';
  2. const mongoose = require('mongoose');
  3. let conn = null;
  4. const uri = 'YOUR CONNECTION STRING HERE';
  5. exports.connect = async function() {
  6. if (conn == null) {
  7. conn = mongoose.createConnection(uri, {
  8. serverSelectionTimeoutMS: 5000
  9. });
  10. // `await`ing connection after assigning to the `conn` variable
  11. // to avoid multiple function calls creating new connections
  12. await conn;
  13. }
  14. return conn;
  15. };

Using mongoose.connect()

You can also use mongoose.connect(), so you can use mongoose.model() to create models.

  1. 'use strict';
  2. const mongoose = require('mongoose');
  3. let conn = null;
  4. const uri = 'YOUR CONNECTION STRING HERE';
  5. exports.connect = async function() {
  6. if (conn == null) {
  7. conn = mongoose.connect(uri, {
  8. serverSelectionTimeoutMS: 5000
  9. }).then(() => mongoose);
  10. // `await`ing connection after assigning to the `conn` variable
  11. // to avoid multiple function calls creating new connections
  12. await conn;
  13. }
  14. return conn;
  15. };

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 - 图1