将 Mongoose 与 AWS Lambda 结合使用

¥Using Mongoose With AWS Lambda

AWS Lambda 是一种流行的服务,用于运行任意功能而无需管理单独的服务器。在 AWS Lambda 函数中使用 Mongoose 非常简单。以下是连接到 MongoDB 实例并查找单个文档的示例函数:

¥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:

const mongoose = require('mongoose');

let conn = null;

const uri = 'YOUR CONNECTION STRING HERE';

exports.handler = async function(event, context) {
  // Make sure to add this so you can re-use `conn` between function calls.
  // See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
  context.callbackWaitsForEmptyEventLoop = false;

  // Because `conn` is in the global scope, Lambda may retain it between
  // function calls thanks to `callbackWaitsForEmptyEventLoop`.
  // This means your Lambda function doesn't have to go through the
  // potentially expensive process of connecting to MongoDB every time.
  if (conn == null) {
    conn = mongoose.createConnection(uri, {
      // and tell the MongoDB driver to not wait more than 5 seconds
      // before erroring out if it isn't connected
      serverSelectionTimeoutMS: 5000
    });

    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn.asPromise();
    conn.model('Test', new mongoose.Schema({ name: String }));
  }

  const M = conn.model('Test');

  const doc = await M.findOne();
  console.log(doc);

  return doc;
};

连接助手

¥Connection Helper

上面的代码对于单个 Lambda 函数来说效果很好,但是如果你想在多个 Lambda 函数中重用相同的连接逻辑怎么办?你可以导出以下函数。

¥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.

const mongoose = require('mongoose');

let conn = null;

const uri = 'YOUR CONNECTION STRING HERE';

exports.connect = async function() {
  if (conn == null) {
    conn = mongoose.createConnection(uri, {
      serverSelectionTimeoutMS: 5000
    });

    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn.asPromise();
  }

  return conn;
};

使用 mongoose.connect()

¥Using mongoose.connect()

你还可以使用 mongoose.connect(),因此你可以使用 mongoose.model() 来创建模型。

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

const mongoose = require('mongoose');

let conn = null;

const uri = 'YOUR CONNECTION STRING HERE';

exports.connect = async function() {
  if (conn == null) {
    conn = mongoose.connect(uri, {
      serverSelectionTimeoutMS: 5000
    }).then(() => mongoose);

    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn;
  }

  return conn;
};