4

I have been using MLab MongoDB and mongoose library to create a db connection inside a serverless (Lambda) handler. It works smoothly on local machine. But sometimes it doesn't work after deployment.The request returns an Internal server error. The weird thing is sometimes it works. But If I remove the database connection code, the handler works. The serverless log just says Process exited before completing request. No real errors so no idea what to do.

The db connection looks like this: handler.js

// Connect to database
mongoose.connect(process.env.DATABASE_URL, {
  useMongoClient: false
}).then((ee) => {
  console.log('------------------------invoke db ', ee);
})
  .catch(err => console.error('-----------error db ', err));

No error in here too. Any idea what's happening?

THpubs
  • 7,804
  • 16
  • 68
  • 143

2 Answers2

3

When you get Process exited before completing request, it means that the node process has crashed before Lambda was able to call callback. If you go to Cloudwatch logs, there would be an error and stack trace of what happened.

You should connect to the MongoDB instance inside your handler and before you call callback(), disconnect first.

It would be like this...

exports.handler = (event, context, callback) => {
  let response;

  return mongoose.connect(process.env.DATABASE_URL, {
    useMongoClient: false
  }).then((ee) => {
    // prepare your response
    response = { hello: 'world' }
  }).then(() => {
    mongoose.disconnect()
  }).then(() => {
    // Success
    callback(null, response)
  }).catch((err) => {
    console.error(err);

    callback(err);
  })
};
Noel Llevares
  • 15,018
  • 3
  • 57
  • 81
1

Here is an article explaining with details how lambda work with node and an example of how to implement DB connection. Differently of @dashmug suggested, you should NOT disconnect your DB since connecting every time will decrease your performance.

Cleriston
  • 750
  • 5
  • 11