Firestore is a simple sophisticated database which helps to store our data in document format in cloud. It provides very easy to use API for performing all CRUD (Create, Read, Update, Delete) operations. But during initial phase of project we may wish to upload some master or setup data in bulk. Currently there is no direct data upload option provided in Firestore database, so we need to do bit of coding to achieve that. Lets start.
- Step 1: Prepare your data in JSON format. You may use excel worksheet to prepare your basic data like this —
Kindly note whatever name you are using as column header will be used as name of the fields, except 1st column “dockey”. “dockey” column values will be used as key of the documents in Firestore database.
Now export this file as CSV and save it somewhere.
You can use any online tool to convert your CSV data into JSON format, but I found https://www.csvjson.com/csv2json more suitable for our job. Open that website. Select your CSV file. Make sure you have selected Hash as Output option. Press Convert button below, now you will able to see your JSON data, download the file.
- Step 2: Download service key from your Firebase project. Open your Firebase project > click on settings icon > select “Users and permissions”
Inside Settings click on “Service accounts”. From left-hand side tab-bar select “Firebase Admin SDK”, and then press on “Generate Private Key” button at the bottom of the page, it will download your service account key JSON file. Please take note of “databaseURL” link mentioned in configuration code snippet. We will use that value in our upload program.
Our data and service account key is ready so lets prepare the upload program.
- Step 3: Setup a node.js project to upload your JSON data file to Firestore database. Create a project folder at your preferred location. Open terminal or command prompt and navigate inside that folder and run command npm init
After running above command you can see one “package.json” file is created inside your project folder. Place “data.json” & “serviceAccountKey.json” files inside your project folder. Open your project folder in any of your favourite IDE editor ( my favourite is Visual Studio Code ), and create “index.js” file.
We need to write our upload program inside this “index.js” file. Before we proceed we need to install “firebase-admin” library. Install it by using below command from terminal, you must run the command from your project’s root folder.
npm install firebase-admin
After installation you can see one “node_modules” folder created inside your project folder, and one dependency (firebase-admin) added inside your package.json file.
Now copy below code and paste inside your index.js file. Please remember to replace collectionKey (name of the collection) and databaseURL (which you noted down during service account key download) values with your own.
const admin = require('./node_modules/firebase-admin');const serviceAccount = require("./serviceAccountKey.json");const data = require("./data.json");const collectionKey = "entities"; //name of the collectionadmin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://your-database.firebaseio.com"});const firestore = admin.firestore();const settings = {timestampsInSnapshots: true};firestore.settings(settings);if (data && (typeof data === "object")) {Object.keys(data).forEach(docKey => { firestore.collection(collectionKey).doc(docKey).set(data[docKey]).then((res) => { console.log("Document " + docKey + " successfully written!");}).catch((error) => { console.error("Error writing document: ", error);});});}
Code Explanation
Line 1: Importing firebase-admin library
Line 2: Importing service account key information
Line 4: Importing JSON data file
Line 5: Setting up collection name. please modify this line and setup your own collection name
Line 7–10: Initialising admin sdk
Line 12–14: Setting up Firestore property
Line 16: Checking if any data exists in data file and if it is object type
Line 17: Loop on data object
Line 18: Calling Firestore API to store each document
Line 19: Setting collection name
Line 20: Setting document name/key. Please do not provide document key if you want auto generated document key.
Line 21: Setting document data
Line 23: Success message, after document successfully stored in Firestore database
Line 26: Error message if fail
- Step 4: Execute your program. In terminal go one level up from your project folder , and run below command to execute your upload program —
node <Your_Project_Folder_Name>
If everything is fine you should see an output like below, after running your program.
Thats all, we are done.
happy coding …