在 AWS Lambda 中使用 Mongoose
AWS Lambda 是一個熱門的服務,用於執行任意函數,而無需管理個別伺服器。在您的 AWS Lambda 函數中使用 Mongoose 很簡單。以下是一個範例函數,它會連線到 MongoDB 實例並尋找單一文檔。
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;
};
連線輔助函式
上面的程式碼在單一 Lambda 函數中運作良好,但是如果您想在多個 Lambda 函數中重複使用相同的連線邏輯呢?您可以匯出以下函式。
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()
您也可以使用 mongoose.connect()
,如此一來您就可以使用 mongoose.model()
來建立模型。
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;
};