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
Step 2
Install the SDK of Cloud Firestore, you can download it using the npm package:
Step 3
Add firebase and firestore libraries to your web application.
- <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>
- <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
- const firebase = require("firebase");
- require("firebase/firestore");
Step 5
Initialize an instance of Cloud Firestore
- firebase.initializeApp({
- apiKey: '## FIREBASE API KEY ##',
- authDomain: '## FIREBASE AUTH DOMAIN ##',
- projectId: '## CLOUD FIRESTORE PROJECT ID ##'
- });
-
- 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.
-
- FireBaseContext().collection("Students")
- .get()
- .then(collectionData => {
-
- console.log('data collection : ', collectionData);
- }).catch(err => {
-
- console.log('error', err.response);
- });
Simple queries - with one conditional parameter
- db.collection("Students").where("name", "==", true);
- db.collection("Students").where("country", "==", "IN");
- db.collection("Students").where("age", "<", 100000);
- db.collection("Students").where("age", ">=", "30");
Complex queries - with one or more conditional parameters
- db.collection("Students").where("age", ">=", "20").where("age", "<=", "35");
- 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.
- db.collection("Students").doc("Ankit")
- .get()
- .then(function(doc) {
- if (doc.exists) {
-
- console.log("Student detail:", doc.data());
- } else {
-
- console.log("No such document!");
- }
- }).catch(function(error) {
- console.log("Error getting document:", error);
- });
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.
-
- FireBaseContext().collection("Students")
- .doc(obj.Id)
- .set(obj)
- .then(function () {
-
- console.log('Student details successfully added!');
- })
- .catch(function (error) {
-
- console.error("Error writing document: ", error);
- });
-
- db.collection("Students").add({
- name: "abc",
- country: "india"
- });
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.
-
- FireBaseContext().collection("Students")
- .doc('
3Pq6VJx5p8K0DAyYx
')
- .set(obj)
- .then(function () {
-
- console.log('Student details successfully added!');
- })
- .catch(function (error) {
-
- console.error("Error writing document: ", error);
- });
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.
-
- FireBaseContext().collection("Students")
- .doc('
3Pq6VJx5p8K0DAyYx
')
- .update({ name: 'Ankit Kanojia' })
- .then(function () {
-
- console.log('Student details successfully added!');
- })
- .catch(function (error) {
-
- console.error("Error writing document: ", error);
- });
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.
-
- FireBaseContext().collection("Students")
- .doc('
3Pq6VJx5p8K0DAyYx
')
- .delete()
- .then(function () {
-
- console.log("Student details successfully deleted!");
- }).catch(
- function (error) {
-
- console.error("Error removing document: ", error);
- });
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.