Table of contents
Code on gitlab: https://gitlab.com/test-projects47/firestore-import-json
Creating a Firestore database
Register for a firebase account and go to Firebase Console (console.firebase.google.com)
Add Project
Click Continue when the project is ready, which takes you back to the console
Add a new app (Web app in this case) to the project
Copy firebaseConfig in the next screen for later use.
Continue to console
Click into Cloud Firestore and create a database
Pick a mode and select a region and "Enable"
Setup a service account
We will authenticate the app using a service account key.
Read more about Google Authentication here - Authentication at Google (Principal)
Go to the Service account page ( Project Overview -> settings -> users and permissions ->service accounts)
"Generate new private key", which will save a JSON file to your computer
The Code
https://gitlab.com/test-projects47/firestore-import-json
- start a new node.js project
yarn init
2. Add dependencies
yarn add firebase-admin
yarn add dotenv
Include the following files in the folder
data.json
- your data in json format*-firebase-adminsdk-*.json
- google service account private key json file.env
- environment variablesIn the .env file, put the path of the service account private key in the variable
GOOGLE_APPLICATION_CREDENTIALS
GOOGLE_APPLICATION_CREDENTIALS="./*-firebase-adminsdk-*.json"
(Optional) Firebase config variables in
.env
FIREBASE_PUBLIC_API_KEY="" FIREBASE_AUTH_DOMAIN="" FIREBASE_PROJECT_ID="" FIREBASE_APP_ID="" FIREBASE_MESSAGING_SENDER_ID="" FIREBASE_STORAGE_BUCKET=""
Here (index.js) we insert the data in
data.json
into a collection called "users", with an automatically generated document id.db.collection('users').doc();
// index.js const { initializeApp } = require('firebase-admin/app'); const { getFirestore } = require('firebase-admin/firestore'); require('dotenv').config(); const data = require('./data.json'); const firebaseConfig = { apiKey: process.env.FIREBASE_PUBLIC_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: process.env.FIREBASE_PROJECT_ID, storageBucket: process.env.FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID, appId: process.env.FIREBASE_APP_ID, }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); const importJSON = async () => { for await (const user of data) { db.collection('users').doc().set(user); } }; importJSON();
data.json looks like this
[ {"id":1,"first_name":"Maudie","last_name":"Ivakin","email":"mivakin0@npr.org"}, {"id":2,"first_name":"Boonie","last_name":"Navarro","email":"bnavarro1@tamu.edu"}, {"id":3,"first_name":"Elden","last_name":"MacCafferky","email":"emaccafferky2@mashable.com"} ]
run the code
node index.js