Using MongoDB in a Serverless app
If you have been developing an API in Node setting up a connection to a MongoDB database is relatively straight forward. Check out my previous post if you need a refresher.
When considering serverless we can't think about a server running constantly which has a persistent connection to the database. Serverless apps run as functions which are destroyed at the end of the invocation. So we'll have to create a new connection (or reuse an old one) every time the serverless function is called.
Setting up the Database connection
Since we cannot use a persistent database connection, we'll have to create a function to create the connection when needed.
Start by installing mongoose.
Then let's start defining a function to create the database connection. First import the mongoose dependencies.
After that let's create a variable to cache the connection so that we can try to cut down on the number of connection we make to the database.
Next get the MongoDB connection URI.
You can use packages like dotenv and dotenv-webpack to load environment variables from a .env file into
process.env. If you use the Now CLI this is done automatically. Remember to not commit the .env file!
Then we'll declare and export the function to create the database connection.
All we're doing in the function is checking if there is a cached connection. If there is a cached connection the function returns it. If there isn't one, a new connection is created, cached and returned.
Defining a Model
For this example, let's create a Note model.
First import the dependencies.
Then declare an interface for Note type.
After that define the schema for the Note model.
To define the model we need the database connection. Since the connection has to created for each serverless function invocation, we'll also need to create the model for each invocation as well. So just like we declared a function to create the database connection, we'll declare and export a function to create the model as well.
Using the Model
To create the connection just call the
Then to create the Note model just pass the connection to the function used to create the model.
After that the model can be used as normal, for example to find a Note by its id.
I hope you found this post useful. Please be sure to share if you did! 😊