Jon Sud
Jon Sud

Reputation: 11641

How and when should I connect to database with serverless?

I new to aws lambda and serverless.

Serverless provides me one file called handler.js.

How can I use the mongo database in this file?

In regular nodejs application I was connect to the mongo database then after the connection is good I was continue the application and launch the server. something like this:

(async() => {
   await mongoose.connect(...);
   const app = import('./app');
   app.listen(....);
})();

But when I use serverless the application already launched. when to make the connection to db should be?

Upvotes: 1

Views: 883

Answers (1)

Sarika Bartakke
Sarika Bartakke

Reputation: 21

Create sperate mongoconnection.js to maintain mongo db connection and import it in handler.js

mongoconnection.js

"use strict";
// Import dependency.
const { MongoClient } = require('mongodb');
// Connection string to the database
const uri = process.env.MONGODB_URI;
// Validate that the database connection string has been configured.
if (!uri) {
  throw new Error(
    'The MONGODB_URI environment variable must be configured with the connection string ' +
      'to the database.'
  );
}
// Cached connection promise
let cachedPromise = null;
// Function for connecting to MongoDB, returning a new or cached database connection
module.exports.connectToDatabase = async function connectToDatabase() {
  if (!cachedPromise) {
    // If no connection promise is cached, create a new one. We cache the promise instead
    // of the connection itself to prevent race conditions where connect is called more than
    // once. The promise will resolve only once.
    // Node.js driver docs can be found at http://mongodb.github.io/node-mongodb-native/.
    cachedPromise =
      MongoClient.connect(uri, { useNewUrlParser: true,  useUnifiedTopology: true });
  }
  // await on the promise. This resolves only once.
  const client = await cachedPromise;
  return client;
}

handler.js

// Import dependency.
const { connectToDatabase } = require('./connect-to-mongodb');
// Handler
module.exports.handler = async function(event, context) {
  // Get a MongoClient.
  const client = await connectToDatabase();
  // Use the connection to return the name of the connected database.
  return client.db().databaseName;
}

Please refer below link for more details https://docs.atlas.mongodb.com/best-practices-connecting-to-aws-lambda/

Upvotes: 2

Related Questions