问题描述:
在AWS Lambda函数内部连接MongoDB Atlas Serverless时,可能会出现无法连接到数据库的问题。
解决方案:
确保你已经在MongoDB Atlas控制台上启用了IP白名单,以允许AWS Lambda函数访问MongoDB Atlas Serverless实例。
使用Node.js AWS SDK中的AWS Secrets Manager服务存储MongoDB Atlas连接凭证,而不是在代码中硬编码。以下是一个示例代码片段,显示如何使用AWS Secrets Manager服务及其Node.js SDK:
const AWS = require('aws-sdk');
const SecretsManager = new AWS.SecretsManager();
exports.handler = async (event, context, callback) => {
try {
const getSecretValue = await SecretsManager.getSecretValue({SecretId: ''}).promise();
const secretJson = JSON.parse(getSecretValue.SecretString);
const uri = secretJson.uri;
// Connect to MongoDB Atlas using MongoDB Node.js driver
const MongoClient = require('mongodb').MongoClient;
const client = await MongoClient.connect(uri, { useNewUrlParser: true });
console.log('Connected to MongoDB Atlas');
// Do something with the database connection
await client.close();
callback(null, 'Success');
} catch (ex) {
console.error(`Failed to connect to MongoDB Atlas: ${ex}`);
callback(ex);
}
};
在上面的代码片段中:
在MongoDB Atlas控制台上,确保您已启用以下 settings.allowConnectionFromPublicIp设置:True。
在AWS Lambda函数的网络配置中,确保您已设置VPC网络,并选择所需的子网和安全组来确保AWS Lambda函数能够与MongoDB Atlas Serverless实例交互。
在以上步骤完成后,您的AWS Lambda函数应该已经能够连接到MongoDB Atlas Serverless并在执行期间使用它。