2 / 6
Nov 2024

I am attempting to learn AWS Lambda functions. I have followed the examples of how to create node.js etc. The first eample of connecting to database works fine. So connection is being established. For the example in returning records i copied the code verbatim and get a null response . According to mongochat this is due to AWS, but there is nothing about AWS configuration in the examples provided. Either the example is incomplete or my advice is incorrect.

{
“StatusCode”: 200,
“body”: “
}

I have also read it could be due to permissions of the collection. I am yet to amend and check if this a possibilty.

const { MongoClient } = require(‘mongodb’);

let cachedClient = null;

exports.handler = async (event) => {
const uri = process.env.MONGODB_URI;
const dbName = process.env.DB_NAME;
const collectionName = process.env.COLLECTION_NAME;

try { if (!cachedClient) { cachedClient = new MongoClient(uri); await cachedClient.connect(); console.log("MongoDB client connected."); } const client = cachedClient; const db = client.db(dbName); const collection = db.collection(collectionName); console.log(`Connected to database: ${dbName}`); console.log(`Using collection: ${collectionName}`); // Perform the query and log the results const data = await collection.find({}).toArray(); console.log("Query result:", JSON.stringify(data, null, 2)); // Check if data is being retrieved correctly if (data && data.length > 0) { console.log(`Data retrieved: ${data.length} documents.`); return { statusCode: 200, body: JSON.stringify({ id: data._id }), }; } else { console.warn("No data found in the collection."); return { statusCode: 404, body: JSON.stringify({ message: "No data found." }), }; } } catch (error) { console.error("Error querying MongoDB:", error); return { statusCode: 500, body: JSON.stringify({ error: "Internal Server Error" }), }; }

};

I have tried to access via VS Code using the connection string and it works. So there is something to do with access via AWS. Connection to the database is successful. What is concerning is the number of open queries. It appears Mongo is not technically supported