Not so long ago Firebase team announced new document database called Firestore. A new database has many improvements and new abilities. Even now in beta, it has almost the same limitation like the old brother Firebase Realtime Database (100 000 concurrent connections). From obvious advantages:
- multi-region support
- document-oriented data-structure!
- easy querying
- offline support (even for web)
During this tutorial, I will call Firebase Realtime Database as RTDB.
How to import data?
The first question you might ask yourself is how to push data to the new database. Old RTDB was great with the features of export/import database as the single JSON file.
For the new Cloud Firestore, we need to implement a mechanism by yourself. Let’s assume you are trying to migrate from RTDB to Firestore, so you need to export your current database snapshot. If you don’t have RDBM instance you can just use any JSON data to test this approach.
Script to load data
Why Firebase admin SDK instead of Firebase SDK?
At the current point, there are still problems with pushing nested arrays to firebase using Firebase SDK (tested in 4.6.1). If you try to set nested arrays using Firebase SDK you will get something like this:
Function DocumentReference.set() called with invalid data. Nested arrays are not supported.
To authorize our application we need to export service key.
In the Firebase Console click on the settings wheel next to the Overview section and choose Users and permissions option.
You’ll be landed on permissions page. Choose Service accounts tab and fill it with data as shown in the screenshot above. Fill checkbox Furnish a new private key, so you will be able to download your key and use it in the script. After creation, you will be asked for the location to save the key. Let’s save it as
const admin = require('./node_modules/firebase-admin');
const serviceAccount = require("./service-key.json");
credentials — property will be filled by just created service account key
databaseURL — is the name of your Database instance + firebaseio.com
Rest of the script
As long as Arrays are also objects this script is fully ready to use.
$ node json-to-firestore.js
Keep in mind that script relies on few files:
firebase-admin — npm module, you can install it locally to the folder of the script
service-key.json — file we’ve generated in the Authentication section
data.json — actually the data we want to push to our Firestore
Cloud Firestore looks very promising. And even despite that fact that it’s still in beta doesn’t mean you should not get your hands on it. Already well known Firebase product called Cloud Functions (still in beta) have already been used by thousands of projects.
In this article, I’ve covered an easy way to submit JSON data to Cloud Firestore. If you are interested in configuring Firebase hosting with the Angular Framework Learn How Get to From Zero to Production with Angular, Firebase, and GitLab CI.