Integrate MongoDB with Firebase

3,368
  1. Firebase Hosting is a CDN for hosting static websites. So it is not possible to host an application like MongoDB server. You can't host MongoDB on any Firebase services. You have to deploy it somewhere else. There are several options. You can either get a VPS and install MongoDB server on it. But you will have to manage your own DB which can be difficult and can take quite some time. Another option is to use a Cloud Database like MongoDB Atlas. This is a faster and more secure solution. However, pricing can be high. So you have to decide depending on your needs.

  2. Once you have a running MongoDB server, you need to write an API for client apps to communicate securely. Client apps should never talk with a DB instance directly. In this case you can use Firebase Cloud Functions to create an api.

  3. You can use Firebase Auth service with Firebase Cloud Functions. You should have a look at the Firebase Callable Functions which can pass auth context to the function body. Here you can just ensure the user is authenticated or perform some access control logic depending on your authorization needs.

Overall, you are going to add an another layer to your architecture. It is possible but will take your time to set things up and you will loose some firestore benefits like offline persistency.

Share:
3,368
atefsawaed
Author by

atefsawaed

Updated on December 24, 2022

Comments

  • atefsawaed
    atefsawaed over 1 year

    I have a Flutter app (still in development) that currently uses Firebase for the backend. More specifically, I use Firebase Authentication, Storage, Cloud Functions, Firestore and in the future I am willing to use Remote Config, Dynamic Links, Cloud Messaging and more of Firebase's features.

    I got to a point where Firestore is not enough anymore for my purposes: Full-text search, geographical querying and advanced queries in general. I know that I can use 3rd party services like Algolia for this but It's too expensive and I wanted something already integrated with my database.

    I was thinking of start using MongoDB as my database (while keeping all other Firebase services) but before I do that I need to understand what is the best way to do it.

    1. Can I host MongoDB on Firebase Hosting (I don't know if this possible at all?) or just use MongoDB Atlas and access it directly (See my next question) from my application?
    2. What is the best way to connect my application to MongoDB? From the app directly (using Rest API) or using Firebase Cloud Functions (so I won't expose my database)?
    3. Can I use Firebase Authentication tokens to access MongoDB or do I have to use MongoDB's authentication service?

    If there is more things I need to consider before I start switching to MongoDB please point it to me.