Comprehensive Guide to Google Cloud Firestore Features for Developers

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. It is a NoSQL document database that lets you easily store, sync, and query data for your applications at a global scale.

Getting Started with Google Cloud Firestore

First, let’s initialize your Firebase app and Firestore:

  const firebase = require('firebase');
  require('firebase/firestore');

  const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID"
  };

  firebase.initializeApp(firebaseConfig);
  const db = firebase.firestore();

CRUD Operations with Firestore

Adding Documents

To add a new document to a collection, you can use the add method:

  db.collection("users").add({
    firstName: "Ada",
    lastName: "Lovelace",
    born: 1815
  })
  .then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
  })
  .catch((error) => {
    console.error("Error adding document: ", error);
  });

Retrieving Documents

To retrieve a document from a collection, you can use the get method:

  db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      console.log(`${doc.id} => ${doc.data()}`);
    });
  });

Updating Documents

To update an existing document, you can use the update method:

  db.collection("users").doc("YOUR_DOCUMENT_ID").update({
    lastName: "Byron"
  })
  .then(() => {
    console.log("Document successfully updated!");
  })
  .catch((error) => {
    console.error("Error updating document: ", error);
  });

Deleting Documents

To delete a document, you can use the delete method:

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

Complex Queries in Firestore

Firestore supports complex queries like range queries and compound queries:

Range Queries

  db.collection("users").where("age", ">=", 18).get()
  .then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data());
    });
  })
  .catch((error) => {
    console.log("Error getting documents: ", error);
  });

Compound Queries

  db.collection("users")
    .where("age", ">=", 18)
    .where("city", "==", "San Francisco")
    .get()
    .then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        console.log(doc.id, " => ", doc.data());
      });
    })
    .catch((error) => {
      console.log("Error getting documents: ", error);
    });

Firestore Security Rules

Security rules allow you to define how your data should be structured, how it should be indexed, and when your data can be read from and written to. Here is a simple example:

  service cloud.firestore {
    match /databases/{database}/documents {
      match /users/{userId} {
        allow read, write: if request.auth != null && request.auth.uid == userId;
      }
    }
  }

Firestore in a Server Environment

You can also use Firestore in a server environment using the Firebase Admin SDK. Below is an example:

  const admin = require('firebase-admin');
  admin.initializeApp({
    credential: admin.credential.applicationDefault(),
    databaseURL: 'https://${PROJECT_ID}.firebaseio.com'
  });

  const db = admin.firestore();

  db.collection('users').get()
    .then((snapshot) => {
      if (snapshot.empty) {
        console.log('No matching documents.');
        return;
      }  

      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });

Building a Full Application with Firestore

To demonstrate the utility of Firestore, let’s build a simple note-taking app where users can add, retrieve, update, and delete notes.

Initialize Firebase

  const firebase = require('firebase');
  require('firebase/firestore');

  const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID"
  };

  firebase.initializeApp(firebaseConfig);
  const db = firebase.firestore();

Add a Note

  function addNote() {
    const note = {
      title: "Sample Note",
      content: "This is the content of the sample note.",
      created: firebase.firestore.Timestamp.now()
    };

    db.collection("notes").add(note)
      .then((docRef) => {
        console.log("Note written with ID: ", docRef.id);
      })
      .catch((error) => {
        console.error("Error adding note: ", error);
      });
  }

Retrieve Notes

  function getNotes() {
    db.collection("notes").get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          console.log(`${doc.id} => ${doc.data().title}: ${doc.data().content}`);
        });
      })
      .catch((error) => {
        console.error("Error getting notes: ", error);
      });
  }

Update a Note

  function updateNote(noteId) {
    const updatedContent = {
      content: "Updated content of the sample note."
    };

    db.collection("notes").doc(noteId).update(updatedContent)
      .then(() => {
        console.log("Note successfully updated!");
      })
      .catch((error) => {
        console.error("Error updating note: ", error);
      });
  }

Delete a Note

  function deleteNote(noteId) {
    db.collection("notes").doc(noteId).delete()
      .then(() => {
        console.log("Note successfully deleted!");
      })
      .catch((error) => {
        console.error("Error deleting note: ", error);
      });
  }

Using the above example, you can build a fully functional note-taking app using Google Cloud Firestore.

Hash: 0a11e25f0d48f3e03e694dce6210a8e4346d167b2621ee126981c4c57edf6966

Leave a Reply

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