2

I'm trying to connect to AWS documentDB from Lambda function but, not able to connect.

MongoClient.connect never calls the callback function connected.

TLS is off on documentDB Cluster. I'm able to connect via mongo shell.

Lambda & documentDB are in same VPC & Security group.

'use strict';

module.exports.search = async (event, context, callback) => {

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://xxx:xxxx@xxx-db.cluster-xxx.us-east-2.docdb.amazonaws.com:27017";

console.log("Starting");

MongoClient.connect(url, 
    { 
        useNewUrlParser: true
    },
    function(err, client) {
        if(err)
            throw err;

        console.log("Connected");

        db = client.db('mydb');

        col = db.collection('mycollection');

        col.find({}).toArray().then(result => {
            console.log(result);
            return { statusCode: 200, body: result };
        }).catch(err => {
            console.log('=> an error occurred: ', err);
            return { statusCode: 500, body: 'error' };
        });

    });

};

Output only prints starting which was consoled before calling Mongo.Connect. How to identify or debug the issue ?

Atul Sharma
  • 9,397
  • 10
  • 38
  • 65

1 Answers1

3

Just from looking at the current code I am pretty sure your function exit before it is able to complete. Therefore, your callback is not executed

Because MongoClient.connect runs asynchronously

Try to take a look at some resource around async/await/promise and Lambda

https://medium.com/tensult/async-await-on-aws-lambda-function-for-nodejs-2783febbccd9

How to wait for async actions inside AWS Lambda?

qkhanhpro
  • 4,371
  • 2
  • 33
  • 45
  • yes, when i added await, the request keeps getting timeout. Seems like not able to get the documentDb connection. Is their any way we can get the trace of error ? – Atul Sharma Jun 26 '19 at 09:17
  • Now this would suffice to go through another question or else it will get complicated here For me the best thing you could do to trace is that : 1/ Create a public mongoDB on the internet 2/ Connect to that DB through your Lambda ( Make sure you have a nat instance to give your lambda inside VPC internet access ) 3/ Then you can make sure your code running normally. 4/ After that, look back at the connectivity between Lambda and DocumentDB – qkhanhpro Jun 26 '19 at 10:47
  • Solved ! seems like there is some issue with AWS documentDB connection. Even if `TLS is disabled` on cluster, you still need to provide `sslCA` to connect which is strange. – Atul Sharma Jun 27 '19 at 05:54
  • 1
    @AtulSharma, this is not expected. When you disabled TLS, did you reboot the instanced in your cluster? If you change the parameter to disable TLS, it only takes hold after a reboot. For more information: https://docs.aws.amazon.com/documentdb/latest/developerguide/security.encryption.ssl.html – Joseph Idziorek Jul 12 '19 at 12:52