How to connect MongoDB with a handler in Express.js (node.js) app using Firebase Functions

--

Hi! So, after a full day of searching for answers for the related topic, I found this problem a little bit difficult (I spent a full day writing 3 lines of code, damn).

What was the idea? I wanted to use Firebase Functions (Google Cloud Functions) as my backend and to able to make requests to my MongoDB database. Also, to have wrapped it inside Express.js app.

Problem… PROBLEMS.
First: Firebase Functions are not a complete serverless platform for backend, they have to be called to be initiated.
Second: no mongoose, only the native MongoDB node.js pack, only hardcore.
Third: server structure, I want to have my DB handler outside of my index.js to make DB requests from routes and other staff.

So, let’s create a new db.js file, where we will export an async function.

After that, we just import somewhere in our app getClient function and call it, using the returned promise of our client, like this:

That’s all. When we call our firebase function after deploy for the first time, we create only one connection of our client, and then, every next call will use the same connected client. Pretty simple and reusable.

If you don’t know how to export your Express.js App as Firebase Functions, this is the magic line:

// index.js 
const functions = require("firebase-functions");
...
const api = functions.https.onRequest(app); // app is Express app.
module.exports = {api};

Now we have only one function that covers all the backend.
URL is https://your-function.cloudfunctions.net/api

Thank for reading. By the way, this is my first post on Medium 😋.

--

--