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 store, sync, and query data for your mobile and web apps at a global scale.

Key Concepts

  1. NoSQL Database

  • Document-Oriented: Unlike traditional SQL databases, Firestore stores data in documents, which are organized into collections.
  • Schema-less: Each document can contain different fields and data types, making it highly flexible.

  1. Real-time Updates

  • Real-time Listeners: Firestore can notify your app of data changes in real-time, allowing for dynamic and responsive applications.

  1. Offline Support

  • Local Cache: Firestore caches data locally, enabling your app to read, write, and listen to data even when the device is offline.

  1. Scalability

  • Horizontal Scaling: Firestore automatically scales to handle the load from your app, whether you have a few users or millions.

Firestore Data Model

Documents

  • Structure: A document is a lightweight record that contains fields, which map to values. Each document is identified by a unique ID.
  • Example:
    {
      "name": "John Doe",
      "age": 30,
      "email": "[email protected]"
    }
    

Collections

  • Structure: Collections are containers for documents. Each collection can contain multiple documents, and each document can contain sub-collections.
  • Example:
    users (collection)
      |
      |-- userID1 (document)
      |     |-- name: "John Doe"
      |     |-- age: 30
      |     |-- email: "[email protected]"
      |
      |-- userID2 (document)
            |-- name: "Jane Smith"
            |-- age: 25
            |-- email: "[email protected]"
    

Sub-Collections

  • Structure: Documents can contain nested collections, allowing for complex data structures.
  • Example:
    users (collection)
      |
      |-- userID1 (document)
            |
            |-- orders (sub-collection)
                  |
                  |-- orderID1 (document)
                        |-- product: "Laptop"
                        |-- price: 1200
                  |
                  |-- orderID2 (document)
                        |-- product: "Phone"
                        |-- price: 800
    

Practical Example

Setting Up Firestore in Your Project

  1. Add Firestore to Your Project:

    • Go to the Firebase Console.
    • Select your project.
    • Click on "Firestore Database" in the left-hand menu.
    • Click "Create Database" and follow the setup instructions.
  2. Initialize Firestore in Your App:

    • Add the Firebase SDK to your project.
    • Initialize Firestore in your app code.
    // Import the Firebase modules
    import firebase from 'firebase/app';
    import 'firebase/firestore';
    
    // Initialize Firebase
    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);
    
    // Initialize Firestore
    const db = firebase.firestore();
    

Adding Data to Firestore

// Reference to the 'users' collection
const usersRef = db.collection('users');

// Add a new document with a generated ID
usersRef.add({
  name: "John Doe",
  age: 30,
  email: "[email protected]"
})
.then((docRef) => {
  console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
  console.error("Error adding document: ", error);
});

Reading Data from Firestore

// Reference to the 'users' collection
const usersRef = db.collection('users');

// Get all documents in the 'users' collection
usersRef.get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
  });
});

Exercises

Exercise 1: Add a New User

  1. Add a new user to the users collection with the following details:

Solution:

usersRef.add({
  name: "Alice Johnson",
  age: 28,
  email: "[email protected]"
})
.then((docRef) => {
  console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
  console.error("Error adding document: ", error);
});

Exercise 2: Retrieve All Users

  1. Retrieve and log all users from the users collection.

Solution:

usersRef.get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
  });
});

Common Mistakes and Tips

  • Mistake: Forgetting to initialize Firestore.

    • Tip: Ensure you have called firebase.initializeApp(firebaseConfig) and firebase.firestore() before attempting to interact with Firestore.
  • Mistake: Incorrectly structuring data.

    • Tip: Plan your data structure ahead of time to make sure it fits your app's needs and is easy to query.

Conclusion

In this section, you learned the basics of Cloud Firestore, including its data model, real-time capabilities, and how to perform basic read and write operations. With this foundation, you are now ready to dive deeper into more advanced Firestore features and operations.

© Copyright 2024. All rights reserved