Keeping lambdas warm breaks DB connection

I’m having issues connecting to mongodb when I am using a cloud watch event rule to trigger lambdas to keep them warm and also the same issue when I tried using serverless-plugin-warmup. Anyone have and ideas as to why this would be happening? Also I whitelist IP’s for my database and use an Elastic IP for my lambda functions. Could the cloud watch event rules be causing the lambdas to use a different IP?

{"error":{"name":"MongoError","message":"no connection available"}}

I wrap my functions with the following to make sure the database is connected before running code

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;
let cachedDB = null;

module.exports = fn => (...args) => {
  const [, context] = args;

  context.callbackWaitsForEmptyEventLoop = false;

  if (cachedDB && cachedDB.readyState != 0 && cachedDB.readyState != 3) {
    fn(...args);
  } else {
    mongoose.connect(process.env.MONGO_URI);

    mongoose.connection.on('error', err => {
      console.log('Connection Error');
      console.log(err);
    });

    mongoose.connection.once('open', () => {
      cachedDB = mongoose.connection;
      fn(...args);
    });
  }
};
1 Like

Did you disable reconnect in the mongo driver? This error seems to be thrown only if reconnect is disabled.