Connection Timeout MongoDB, AWS lambda and Nodejs

I am facing a weird issue. I have MongoDB installed and working on a project on an EC2 instance. I tried to access the DB from local it is working fine. But, when I try to execute my AWS lambda function I get a timeout error. So increased the lambda function timeout to 50seconds. I am running a simple query to find one record of 10 records. And I am getting the following error. Can anyone help me with this?

MongoNetworkError: failed to connect to server [EC2_PUBLIC_IP:PORT_NUMBER] on first connect [MongoNetworkError: connection 0 to EC2_PUBLIC_IP:PORT_NUMBER timed out]

I am using MONGODB-NATIVE with Nodejs.

const MongoClient = require('mongodb').MongoClient;

MongoClient.connect(DB_URL, (err, conn) => {
  if(err) return console.error(err);

  let db = conn.db('DB_NAME');

  db.collection('COLLECTION_NAME').findOne({ value: 1232131 }, (error,results) => {
    if(error) return console.error(error);

    conn.close();
    return console.log(results);
  });
});

1 answer

  • answered 2018-02-13 02:26 Ridham Tarpara

    I don't think this is an issue with your code. This is an off-topic question as it's a problem with your firewall settings.

    In the EC2 security groups please add MongoDB port in inbound ports that default to 27017 and then try to access the db.