Here I wrote a simple class that will enable one to take a JSON file and upload its content to the Firebase Firestore database. The code is quite explanatory for itself.
All you need is a firebase project. Get the credential from your project settings to give authorization for one to be able to write data to firebase.
constfirebase=require("firebase");// Required for side-effectsrequire("firebase/firestore");constfs=require('fs');const{resolve}=require('path');// Initialize Firebase// Get your firebase credentials from // the firebase console for your projectfirebase.initializeApp({apiKey:[YOUR_FIREBASE_APIKEY],authDomain:[YOUR_FIREBASE_AUTHDOMAIN],projectId:[YOUR_FIREBASE_PROJECTID]});/** * Tutorial on how to upload json data to firestore * Using JavaScript * RUN: node json-to-firestore/populateJsonFirestore.js [RELATIVE PATH TO FILE] [FIRESTORE METHOD] [COLLECTION NAME] */classPopulateJsonFireStore{// class constructorconstructor(){console.time("Time taken");this.db=firebase.firestore();// Obtain the relative path, method type, collection name arguments provided throughconst[,,filepath,type,collectionname]=process.argv;// Obtain the absolute path for the given relativethis.absolutepath=resolve(process.cwd(),filepath);// Obtain the firestore method typethis.type=type;// Obtain the firestore method typethis.collectionname=collectionname;// Lets make sure the right firestore method is used.if(this.type!=='set'&&this.type!=='add'){console.error(`Wrongmethodtype${this.type}`)console.log('Acceptedmethodsare:setoradd');this.exit(1);}// If file path is missingif(this.absolutepath==null||this.absolutepath.length<1){console.error(`Makesureyouhavefilepathassigned${this.absolutepath}`)this.exit(1);}// If collection name not setif(this.collectionname==null||this.collectionname.length<1){console.error(`Makesuretospecifyfirestorecollection${this.collectionname}`)this.exit(1);}console.log(`ABS:FILEPATH${this.absolutepath}`);console.log(`Type:methodis${this.type}`);}// The populate function// uploads the json data to firestoreasyncpopulate(){// initialize our data arrayletdata=[];// Get data from json file using fstry{data=JSON.parse(fs.readFileSync(this.absolutepath,{}),'utf8');}catch(e){console.error(e.message);}//data.forEach((item) => console.log(item));// loop through the data// Populate Firestore on each run// Make sure file has atleast one item.if(data.length<1){console.error('Makesurefilecontainsitems.');}vari=0;for(varitemofdata){console.log(item);try{this.type==='set'?awaitthis.set(item):awaitthis.add(item);}catch(e){console.log(e.message)this.exit(1);}// Successfully got to end of data;// print success messageif(data.length-1===i){console.log(`**************************\n****SUCCESSUPLOAD*****\n**************************`);console.timeEnd("Time taken");this.exit(0);}i++;}}// Sets data to firestore database// Firestore auto generated IDSadd(item){console.log(`Addingitemwithid${item.id}`);returnthis.db.collection(this.collectionname).add(Object.assign({},item)).then(()=>true).catch((e)=>console.error(e.message));}// Set data with specified ID// Custom Generated IDSset(item){console.log(`settingitemwithid${item.id}`);returnthis.db.doc(`${this.collectionname}/${item.id}`).set(Object.assign({},item)).then(()=>true).catch((e)=>console.error(e.message));}// Exit nodejs consoleexit(code){returnprocess.exit(code);}}// create instance of class// Run populate functionconstpopulateFireStore=newPopulateJsonFireStore();populateFireStore.populate();
Code: https://github.com/ericel/tutoring/tree/main/javascript/json-to-firestore
In this class, you have two alternative methods(add or set) to add your data to Firestore. The set method gives you the option of using custom ids for your content, while with the add method, firebase auto generates document ids for your content.
Ericel1231 week, 2 days ago
no comments yet