Wednesday 17 May 2017

aws-serverless-express connecting to mongo and get mongo document

I am trying to make a Lambda proxy with express using the aws-serverless-express node module. However I keep getting the error 'Error: socket hang up' and I don't know why.

Here is my lambda code:

 const app = require('./app');
 const awsServerlessExpress = require('aws-serverless-express');
 const server = awsServerlessExpress.createServer(app);

 exports.handler = (event, context, callback) => {
  console.log('EVENT: ' + JSON.stringify(event));
  awsServerlessExpress.proxy(server, event, context);
}

and here is my express code:

MongoClient.connect("mongodb:/mongoUriGoesHere", function(err, db) {
if(err) { return console.dir(err); }

let collection = db.collection('collection');

app.get('/hello', (req, res) => {
 collection.find().toArray()
  .then((documents) => /* Handle success (console.log) */)
  .catch((err) => /* Handle error */)
 })
});

module.exports = app;

This is my response from the lambda

https://i.stack.imgur.com/Y0ybB.png

I know lambda functions are supposed to be stateless when creating a connection to a db, but I don't know how to get this to work. I've also tried using mongoose and no luck. I can get it to work when there is no code that attemps to connect to the db, but this is my problem at the moment. Any answers would be greatly appreaciated. Been at this for a while and still can't figure it out!



via Rohan Hadnum

No comments:

Post a Comment