0

As part of a lambda function I would like to reuse the connection from a previous context. The way our functions are written currently is using connect so I would like to run a few options by you.

I am currently using the second and the connection is not being picked up, so I was wondering if this is possible.

1: Choosing when to use connect

if (!mongoose.connection.readyState) {
   log(`Connecting to ${DB_URI}.`);
   mongoose.connect(DB_URI, options);
   log('Connected to the database.');
}
  1. Reusing a variable and assigning that to connection
let conn;
if (!conn) {
  log(`Connecting to ${DB_URI}.`);
  conn = mongoose.createConnection(DB_URI, options);
  mongoose.connection = conn;
  log('Connected to the database.');
} else {
  log(`Using old connection to ${DB_URI}.`);
  mongoose.connection = conn;
  log('Connected to the database.');
}

And my connection options are:

const options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
  useFindAndModify: false,
  autoIndex: false,
  poolSize: 50,
  serverSelectionTimeoutMS: 10000,
  socketTimeoutMS: 30000,
  family: 4,
};

With context.callbackWaitsForEmptyEventLoop = false;

Thank you.

JK023v1
  • 27
  • 3
  • https://dev.to/scalegrid/how-to-use-mongodb-connection-pooling-on-aws-lambda-43h6 & https://duckduckgo.com/?t=palemoon&q=mongodb+lambda+reuse+connection&ia=web – D. SM Jun 30 '20 at 11:27
  • related question is https://stackoverflow.com/questions/56435634/is-there-a-good-way-to-close-mongo-connections-when-a-lambda-container-expires – NIKHIL C M Jul 01 '20 at 08:46
  • as per above link, if you increase socketTimeoutMS to a value above than the timeout of a warm container. say 20000. Another similar question can be found here : https://stackoverflow.com/questions/54226024/aws-lambda-node-js-v-8-10-mongoose-mongonetworkerror-connection-to-db-tim – NIKHIL C M Jul 01 '20 at 08:49

0 Answers0