Connecting MongoDB from AWS Lambda and Node JS

Code With Travel
2 min readFeb 27, 2021

--

Node.js can be used in database applications. One of the most popular NoSQL databases is MongoDB.

MongoDB

To be able to experiment with the code examples, you will need access to a MongoDB database.

You can download a free MongoDB database at https://www.mongodb.com.

Or get started right away with a MongoDB cloud service at https://www.mongodb.com/cloud/atlas.

Let us try to access a MongoDB database with Node.js.

To download and install the official MongoDB driver, open the Command Terminal and execute the following:

npm install mongodb

Node.js can use this module to manipulate MongoDB databases:
To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct IP address and the name of the database you want to create.

MongoDB will create the database if it does not exist, and make a connection to it.

var url = "mongodb://localhost:27017/lambdatest";

MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

Now create lambda and paste the following code into it.

"use strict";
const MongoClient = require('mongodb').MongoClient;
const MONGODB_URI = process.env.MONGODB_URI; // or Atlas connection string
let cachedDb = null;function connectToDatabase (uri) {
console.log('=> connect to database');
if (cachedDb) {
console.log('=> using cached database instance');
return Promise.resolve(cachedDb);
}
return MongoClient.connect(uri)
.then(db => {
cachedDb = db;
return cachedDb;
});
}
function queryDatabase (db) {
console.log('=> query database');
return db.collection('items').find({}).toArray()
.then(() => { return { statusCode: 200, body: 'success' }; })
.catch(err => {
console.log('=> an error occurred: ', err);
return { statusCode: 500, body: 'error' };
});
}
module.exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
console.log('event: ', event);connectToDatabase(MONGODB_URI)
.then(db => queryDatabase(db))
.then(result => {
console.log('=> returning result: ', result);
callback(null, result);
})
.catch(err => {
console.log('=> an error occurred: ', err);
callback(err);
});
};

Deploy your lambda function and give a try.

--

--

No responses yet