Instantly share code, notes, and snippets.

Embed
What would you like to do?
MongoDB-Lambda-Example
'use strict'
const AWS = require('aws-sdk');
var MongoClient = require('mongodb').MongoClient;
let atlas_connection_uri;
exports.handler = (event, context, callback) => {
var uri = process.env['MONGODB_ATLAS_CLUSTER_URI'];
if (atlas_connection_uri != null) {
processEvent(event, context, callback);
}
else {
const kms = new AWS.KMS();
kms.decrypt({ CiphertextBlob: new Buffer(uri, 'base64') }, (err, data) => {
if (err) {
console.log('Decrypt error:', err);
return callback(err);
}
atlas_connection_uri = data.Plaintext.toString('ascii');
processEvent(event, context, callback);
});
}
};
function processEvent(event, context, callback) {
console.log('Calling MongoDB Atlas from AWS Lambda with event: ' + JSON.stringify(event));
var jsonContents = JSON.parse(JSON.stringify(event));
//date conversion for grades array
if(jsonContents.grades != null) {
for(var i = 0, len=jsonContents.grades.length; i < len; i++) {
//use the following line if you want to preserve the original dates
//jsonContents.grades[i].date = new Date(jsonContents.grades[i].date);
//the following line assigns the current date so we can more easily differentiate between similar records
jsonContents.grades[i].date = new Date();
}
}
try
{
MongoClient.connect(atlas_connection_uri, function(err, db)
{
createDoc(db, jsonContents, callback);
});
}
catch(err)
{
console.error('an error occurred', err);
}
}
function createDoc (db, json, callback) {
db.collection('restaurants').insertOne( json, function(err, result) {
if(err!=null) {
console.error("an error occurred in createDoc", err);
callback(null, JSON.stringify(err));
}
else {
console.log("Kudos! You just created an entry into the restaurants collection with id: " + result.insertedId);
callback(null, "SUCCESS");
}
db.close();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment