Cloud Firestore APIs With Firebase Database

Introduction

 
Firebase database is handled using Firestore APIs. Firestore also offers seamless integration with Google Cloud products and other Firebase functions, including cloud functions. 
 

Quick Configuration of Firebase Environment


Step 1
 
Configure your firebase account and follow the instructions mentioned in Introduction and Configuration of a Firebase Account.

Step 2
 
Install the SDK of Cloud Firestore, you can download it using the npm package:
  1. npm install [email protected] or yarn add [email protected]   
Step 3
 
Add firebase and firestore libraries to your web application.
  1. <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>  
  2. <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-firestore.js"></script>  
Step 4
 
Import or include both Firebase and Cloud Firestore libraries
  1. const firebase = require("firebase");  
  2. require("firebase/firestore");  
Step 5
 
Initialize an instance of Cloud Firestore
  1. firebase.initializeApp({  
  2.   apiKey: '## FIREBASE API KEY ##',  
  3.   authDomain: '## FIREBASE AUTH DOMAIN ##',  
  4.   projectId: '## CLOUD FIRESTORE PROJECT ID ##'  
  5. });  
  6.   
  7. var db = firebase.firestore(); 
You can find the value of 'initializeApp' object from your Firebase web app configuration.
  • Go to your Settings option or click on the setting icon (Click Here) Project settings in the Firebase console.
  • Click on Your apps card, select the app in which you need a config object.
  • Click on Config section in the Firebase SDK snippet pane.
  • Copy the config object, you can paste it directly into your web app

Getting Started with Firestore APIs

 
Read Data - Fetch of documents from a collection
 
There are two different ways to fetch data stored in Cloud Firestore. These methods are used with collections of documents, documents, or the results of queries.
  • Call a method to fetch the data
  • Set a listener event to receive on data change event. (When you set a listener event, Cloud Firestore sends your listener initial collections or snapshots of data, and then other data collection on each time documents get changes)
Here is the example, to retrieve all the data or collection of Students from the Students Table using the get() method. 
  1. // GET method or Fetch data API call from firestore database  
  2. FireBaseContext().collection("Students")  
  3.       .get()  
  4.       .then(collectionData => {  
  5.         // you will get student data collection in collectionData object  
  6.         console.log('data collection : ', collectionData);  
  7.       }).catch(err => {  
  8.         // Error or Exception occure  
  9.         console.log('error', err.response);  
  10.       }); 
Simple queries - with one conditional parameter
  1. db.collection("Students").where("name""=="true);  
  2. db.collection("Students").where("country""==""IN");  
  3. db.collection("Students").where("age""<", 100000);  
  4. db.collection("Students").where("age"">=""30"); 
Complex queries - with one or more conditional parameters
  1. db.collection("Students").where("age"">=""20").where("age""<=""35");  
  2. db.collection("Students").where("age"">""20").where("country""==""IN"); 

Fetch Detail - Get a specific document based on field

 
By default, get call will fetch all the documents from the database collection. Sometimes we are required to fetch a specific snapshot or details of data from a collection. Using the doc option, we can retrieve a snapshot of a specific item. You can pass field value as a parameter in the doc function as shown below.
 
Here, we want to fetch details of student whose name is 'Ankit', then we can pass 'Ankit' as an argument to fetch details from the Students collection.
  1. db.collection("Students").doc("Ankit")  
  2.   .get()  
  3.   .then(function(doc) {  
  4.     if (doc.exists) {  
  5.       // Student details based on filtered value  
  6.       console.log("Student detail:", doc.data());  
  7.     } else {  
  8.       // doc.data() will be undefined in this case  
  9.       console.log("No such document!");  
  10.     }  
  11.   }).catch(function(error) {  
  12.     console.log("Error getting document:", error);  
  13.   }); 

Add API - Add new document

 
Cloud Firestore API stores data in Documents, which are stored in Cloud Collections. Cloud Firestore creates new collections and documents implicitly the first time you add data to the document. For that, you do not need to explicitly create collections or documents.

Create a new document and collection using the following code example.
  1. // Add document using set option from firestore database  
  2.  FireBaseContext().collection("Students")  
  3.       .doc(obj.Id)  
  4.       .set(obj)  
  5.       .then(function () {  
  6.         // Student details addedd in firebase database    
  7.         console.log('Student details successfully added!');  
  8.       })  
  9.       .catch(function (error) {  
  10.         // Error or Exception occure  
  11.         console.error("Error writing document: ", error);  
  12.       }); 
  1. // Add a new document with a auto-generated id.  
  2. db.collection("Students").add({  
  3.     name: "abc",  
  4.     country: "india"  
  5. }); 
Note
  •  Cloud Firestore will auto-generate an ID.
  • .add(...) and .doc().set(...) are completely equivalent, you can choose either one of the option

Update API - Update existing document

 
There are two ways to update existing data.
 
set()
 
In case you want to update specific detail in a snapshot, you need to retrieve data based on an auto-generated ID and pass it as an argument in the doc method. Afterwards, in the set method, you can pass your updated object as an argument which will override the existing object using document ID.         
  1. // Update document using set option from firestore database    
  2. FireBaseContext().collection("Students")    
  3.       .doc('3Pq6VJx5p8K0DAyYx')    
  4.       .set(obj)    
  5.       .then(function () {    
  6.         // Student details addedd in firebase database      
  7.         console.log('Student details successfully added!');    
  8.       })    
  9.       .catch(function (error) {    
  10.         // Error or Exception occure    
  11.         console.error("Error writing document: ", error);    
  12.       });   
update()
 
Eventually, both methods are similar, but the only difference is document ID or document which you specifically want to update, should available in the database, otherwise it will throw an error. Using the set() method, in case of a document is not available then it will automatically create a new document in the database but an error will not be thrown.
  1. // Update document using set option from firestore database  
  2. FireBaseContext().collection("Students")  
  3.       .doc('3Pq6VJx5p8K0DAyYx')  
  4.       .update({ name: 'Ankit Kanojia' })  
  5.       .then(function () {  
  6.         // Student details addedd in firebase database    
  7.         console.log('Student details successfully added!');  
  8.       })  
  9.       .catch(function (error) {  
  10.         // Error or Exception occure  
  11.         console.error("Error writing document: ", error);  
  12.       }); 

Delete API - Delete document

 
To delete a snapshot or document, the delete() method is used, you need to pass auto-generated ID which is document ID in the delete method as an argument.
  1. // Delete an existing document from the list    
  2. FireBaseContext().collection("Students")    
  3.       .doc('3Pq6VJx5p8K0DAyYx') // Obj.Id
  4.       .delete()    
  5.       .then(function () {    
  6.         // Student details deleted from firebase database      
  7.         console.log("Student details successfully deleted!");    
  8.       }).catch(    
  9.         function (error) {    
  10.           // Error or Exception occure    
  11.           console.error("Error removing document: ", error);    
  12.         });   

Summary

 
Cloud Firestore is the Realtime Database with a new, more intuitive data model that provides database iteration using the Firebase database. It provides rich features, faster queries, and scales further than the Realtime Database. Please refer to the Firestore Pricing for more details.


Similar Articles