Intro to Firestore and how to use it in your web app

Intro to Firestore and how to use it in your web app

This is part one of a three blog series on Firebase basics. In this one, we will read about firestore. I have tried my best to make this beginner-friendly.

What is Firebase?

It is a Backend-as-a-Service (Baas). It provides various tools and services to help programmers develop high-quality apps, enhance their user base, and generate revenue. It is constructed using Google's infrastructure. Firebase is a No-SQL database program that stores data in JSON-like documents.


Create a database in Cloud Firestore.

  • Create a Firebase project if you haven't already. Click Add project in the Firebase console, then follows the on-screen steps to build or add Firebase services to an existing GCP project.
  • Open the Firebase console and go to the Cloud Firestore section. Select an existing Firebase project when requested. Follow the steps for creating a database.
  • For your Cloud Firestore Security Rules, choose a starting mode from Test mode or Locked mode

References to Collections and Documents

Every document in Cloud Firestore has a unique identifier based on its database location. Assume an "apple" document is in the "fruits" collection. A reference is supposed to be created to refer to this particular location in your code.

Creating refs of a Document

  • using commas
import { doc, getFirestore  } from "firebase/firestore";

const db = getFirestore()
const appleDocumentRef = doc(db, 'fruits', 'apple');
  • using slash
import { doc, getFirestore   } from "firebase/firestore"; 

const db = getFirestore()
const appleDocumentRef = doc(db, 'fruits/apple');

Notice the number of arguments of the doc method in both the approach above

Creating refs of a Collection

  • using commas
import { collection, getFirestore } from "firebase/firestore";

const db = getFirestore()
const fruitsCollectionRef = collection(db, 'fruits');

Adding data to Cloud Firestore

You can write data to Cloud Firestore in a variety of ways:

  • Set the data of a document in a collection by specifying a document identification explicitly.
  • A new document can be added to a collection. Cloud Firestore creates the document identification for you automatically in this situation.
  • Make a blank document with an automatically generated identification and fill it with data afterward.
  • step 1: Set a document

import { doc, setDoc, getFirestore } from "firebase/firestore"; 

const db = getFirestore()
// Add a new document in collection "fruits"
await setDoc(doc(db, "fruits", "mango"), {
  name: "mango",
  color: "yellow"
});

If the document does not already exist, it will be generated. If the document already exists, the newly provided data will be overwritten unless you specify that the data should be merged into it, as follows:

import { doc, setDoc, getFirestore } from "firebase/firestore"; 

const db = getFirestore()
const fruitRef = doc(db, 'fruits', 'apple');
setDoc(fruitRef , { color: "green"}, { merge: true });
  • step 2: Add a document

    When using setDoc() for creating a document, you must provide an ID for the document. However, there are situations when there isn't a relevant ID for the document, and it's easier to let Cloud Firestore create one for you. addDoc() method can be used to accomplish this:
import { collection, addDoc, getFirestore } from "firebase/firestore"; 

const db = getFirestore()
// Add a new document with a generated id.
const docRef = await addDoc(collection(db, "fruits"), {
  name: "pear",
  color: "green"
});
console.log("Document written with ID: ", docRef.id);

In some circumstances, creating a document reference with an auto-generated ID and then using the reference afterward can be advantageous. You can use doc() for this purpose:

import { collection, doc, setDoc, getFirestore } from "firebase/firestore"; 

const db = getFirestore()
// Add a new document with a generated id
const newFruitRef = doc(collection(db, "fruits"));

// later...
await setDoc(newFruitRef, {
  name: "banana",
  color: "yellow"
});
  • step 3: Update a document

    Use the 'updateDoc()' method to update specific fields of a document without rewriting the entire document:
import { doc, updateDoc, getFirestore } from "firebase/firestore";

const db = getFirestore()
const watermelonRef = doc(db, "fruits", "melon");

// Set the "color" field of the fruit 'melon'
await updateDoc(watermelonRef, {
  color: "green"
});

Reading Data from firestore

There are two methods for retrieving data from Cloud Firestore. These methods can be used with individual documents, collections of documents, or query results.

  • Call a method to get the data.
  • Set a listener to receive data-change events.

When you create a listener, Cloud Firestore sends your listener an initial snapshot of the data, followed by a new snapshot every time the document updates.

We are not going to read about listeners today. To learn more about them visit here

  • Get a document

    The following example explains how to use 'getDoc()' to fetch the data of a single document.
import { doc, getDoc, getFirestore } from "firebase/firestore";

const db = getFirestore()
const docRef = doc(db, "fruits", "mango");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  console.log("No such document!");
}
  • Get multiple documents from a collection

    You can also query documents in a collection to obtain several documents with a single request. For example, you can use where() to find all documents that satisfy a given condition, then getDocs() to get the results.
import { collection, query, where, getDocs, getFirestore } from "firebase/firestore";

const db = getFirestore()
const q = query(collection(db, "fruits"), where("color", "==", "green"));

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});
  • Get all documents in a collection

    Furthermore, by skipping the where() filter entirely, you can retrieve all documents in a collection.
import { collection, getDocs, getFirestore } from "firebase/firestore";

const db = getFirestore()
const querySnapshot = await getDocs(collection(db, "fruits"));
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

In this blog, I've attempted to cover nearly every significant aspect concerning firestore; as a total beginner, this should be more than enough to get started with web development. Nonetheless, if you want to learn more about firestore in-depth, click here.

In the next blog, we will be reading about cloud storage which is another very essential part of firebase.