Amazon DocumentDB(TLSが無効)にLambda(node.js v20)から接続する
TLSが無効なDocumentDBにLambdaから接続します。同一VPCの同一プライベートサブネット上にあるとします。
セキュリティグループはポート27017を開放済みとします。
Lambda(node.js v20)
import { MongoClient } from 'mongodb';
// DocumentDBの接続URI
const uri = 'mongodb://<ユーザ名>:<パスワード>@<クラスターエンドポイント>:27017/?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
// Lambda関数のエントリポイント
export const handler = async (event) => {
const client = new MongoClient(uri, {});
try {
await client.connect();// DocumentDBに接続
const database = client.db('sample-db');// データベース作成
const collection = database.collection('emp');// コレクション作成
const result = await collection.insertOne({ name: 'takahashi', age: 20 });// サンプルデータ作成
console.log(result.insertedId);
const query = { _id: result.insertedId };
const document = await collection.findOne(query); // サンプルデータ取得
console.log(document);
return {
statusCode: 200,
body: JSON.stringify('Success.'),
};
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify('Error.'),
};
} finally {
await client.close();
}
};
開発者ガイド
プログラムによる Amazon DocumentDB への接続 - Amazon DocumentDB
このセクションでは、複数の言語を使用して Amazon DocumentDB (MongoDB 互換)に接続する方法を示すコード例を紹介します。コード例は、Transport Layer Security (TLS) が有効または無効になっ...

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^
