Mastering Firebase with Google Cloud Firestore Ultimate Guide with Code Examples

Introduction to Google Cloud Firestore

Google Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. By enabling straightforward syncing of real-time data, developers can create rich and dynamic applications with ease.

Getting Started with Firestore

To start using Firestore, you need to set up a Firebase project and integrate the Firestore SDK into your application.

Below are key code snippets to get you up and running with Firestore:

Initializing Firestore

  const firebase = require("firebase/app");
  require("firebase/firestore");

  // Initialize Cloud Firestore through Firebase
  firebase.initializeApp({
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID"
  });

  var db = firebase.firestore();

Adding Data

To add data to Firestore, use the set() method:

  db.collection("users").doc("alovelace").set({
    first: "Ada",
    last: "Lovelace",
    born: 1815
  })
  .then(() => {
    console.log("Document successfully written!");
  })
  .catch((error) => {
    console.error("Error writing document: ", error);
  });

Retrieving Data

To retrieve data, use the get() method:

  var docRef = db.collection("users").doc("alovelace");

  docRef.get().then((doc) => {
    if (doc.exists) {
      console.log("Document data:", doc.data());
    } else {
      console.log("No such document!");
    }
  }).catch((error) => {
    console.log("Error getting document:", error);
  });

Updating Data

To update data, use the update() method:

  var userRef = db.collection("users").doc("alovelace");

  userRef.update({
    born: 1820
  })
  .then(() => {
    console.log("Document successfully updated!");
  })
  .catch((error) => {
    console.error("Error updating document: ", error);
  });

Deleting Data

To delete a document, use the delete() method:

  db.collection("users").doc("alovelace").delete().then(() => {
    console.log("Document successfully deleted!");
  }).catch((error) => {
    console.error("Error removing document: ", error);
  });

Listening for Real-time Updates

Firestore provides real-time updates with the onSnapshot() method:

  var docRef = db.collection("users").doc("alovelace");

  var unsubscribe = docRef.onSnapshot((doc) => {
    console.log("Current data: ", doc.data());
  });

Building a Simple Firestore Application

Let’s create a simple web app to manage a list of users:

  <!DOCTYPE html>
  <html>
  <head>
    <title>Firestore Example</title>
    <script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-firestore.js"></script>
  </head>
  <body>
    <h1>Firestore User Management</h1>
    <div id="users"></div>

    <script>
      var firebaseConfig = {
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
        projectId: "YOUR_PROJECT_ID"
      };
      firebase.initializeApp(firebaseConfig);

      var db = firebase.firestore();

      function getUsers() {
        db.collection("users").onSnapshot((snapshot) => {
          var usersDiv = document.getElementById("users");
          usersDiv.innerHTML = "";
          snapshot.forEach((doc) => {
            var user = doc.data();
            usersDiv.innerHTML += "<p>" + user.first + " " + user.last + "</p>";
          });
        });
      }

      getUsers();
    </script>
  </body>
  </html>

With Firestore, you can quickly implement powerful features into your applications. The examples above show how to set up Firestore, add and manage data, and implement real-time listeners, making it easier to build dynamic and responsive apps.

Hash: 0a11e25f0d48f3e03e694dce6210a8e4346d167b2621ee126981c4c57edf6966

Leave a Reply

Your email address will not be published. Required fields are marked *