0
votes

I am using Serverless framework to deploy my backend to API Gateway and AWS Lambda.

Here is my serverless.yml for this specific lambda function. It is a cron job that runs every hour.

 cron:
     handler: handler.transferHandler
     events:
     - schedule: rate(1 hour)

Now when I test on localhost it works perfectly. But when I deploy to aws I get the following error:

    MongoDB connection error. Please make sure MongoDb is running. { MongoError: failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]
    at Pool.<anonymous> (/var/task/node_modules/mongodb-core/lib/topologies/server.js:336:35)
    at emitOne (events.js:96:13)
    at Pool.emit (events.js:188:7)
    at Connection.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/pool.js:280:12)
    at Connection.g (events.js:292:16)
    at emitTwo (events.js:106:13)
    at Connection.emit (events.js:191:7)
    at Socket.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/connection.js:189:49)
    at Socket.g (events.js:292:16)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at connectErrorNT (net.js:1021:8)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
  name: 'MongoError',
  message: 'failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]' }

Here is my function in my handler.js:

exports.transferHandler = function transferHandler(event, context) {

  context.callbackWaitsForEmptyEventLoop = false;
  mongoose.connect(mongoString, {useMongoClient: true});
  const db = mongoose.connection;

  db.on("error", (err) => {
     console.log("MongoDB connection error. Please make sure MongoDb is running.", err);
     process.exit();
  });

  db.once('open', () => {
      BookingModel
          .find({})
          .then((bookings) => {
            ...
          })
          .catch((err) => {
              console.log(err);
          })
          .finally(() => {
            db.close();
          });
    });
};
1
Is mongod running in your AWS server? Also useMongoClient is deprecated in mongoose 5. - FisNaN
@LeekInPajama I am using mongoose 4.13.9, and I have not seen anything about needing mongod running. Can you explain? - kareem
the mongod service should be running on your server background. To check MongoDB is running or not, simply type mongo in (remote) command line. If you're running MongoDB from AWS. I strongly suggest you always use lastest mongoose. If you google mongoose vulnerabilities, this thing is very vulnerable. - FisNaN
@LeekInPajama i am using mongo atlas for my database and my mongo string is the mongo connection string provided by mongo atlas, only thing i am hosting on aws is my lambda functions and static files on s3. - kareem

1 Answers

1
votes

After 2 weeks of being stuck on this, I learned that I needed to specify my environment variables in my serverless.yml for it to work. My functions were never connecting to the database because my mongo string was never set in lambda. Hope this helps someone.

provider:
  name: aws
  runtime: nodejs6.10
  stage: production
  region: us-west-1
  environment:
    MONGODB_URL: ${env:MONGODB_URL}
    S3_BUCKET: ${env:S3_BUCKET}
    S3_BUCKET_REPORT: ${env:S3_BUCKET_REPORT}
    STRIPE_CLIENT_ID: ${env:STRIPE_CLIENT_ID}
    STRIPE_PUBLIC_KEY: ${env:STRIPE_PUBLIC_KEY}
    STRIPE_SECERET_KEY: ${env:STRIPE_SECERET_KEY}
    JWT_SECRET: ${env:JWT_SECRET}
    SEND_BIRD_TOKEN: ${env:SEND_BIRD_TOKEN}
    SEND_BIRD_APP_ID: ${env:SEND_BIRD_APP_ID}
    MANDRILL_APIKEY: ${env:MANDRILL_APIKEY}