In this section, we will cover the fundamental CRUD (Create, Read, Update, Delete) operations in Cloud Firestore. These operations are essential for interacting with your Firestore database and managing your data effectively.

  1. Introduction to CRUD Operations

CRUD operations are the basic operations you can perform on a database. They stand for:

  • Create: Adding new data to the database.
  • Read: Retrieving data from the database.
  • Update: Modifying existing data in the database.
  • Delete: Removing data from the database.

  1. Setting Up Firestore

Before we dive into CRUD operations, ensure you have set up Firestore in your Firebase project. If you haven't, follow these steps:

  1. Go to the Firebase Console.
  2. Select your project.
  3. Navigate to Firestore Database.
  4. Click on "Create Database" and follow the prompts to set up Firestore.

  1. Create Operation

To add new data to Firestore, you use the set() or add() methods.

Using set()

The set() method is used to create or overwrite a document with a specified ID.

// Initialize Firestore
const db = firebase.firestore();

// Reference to a document
const docRef = db.collection('users').doc('user_id');

// Set data
docRef.set({
    name: 'John Doe',
    email: '[email protected]',
    age: 30
})
.then(() => {
    console.log('Document successfully written!');
})
.catch((error) => {
    console.error('Error writing document: ', error);
});

Using add()

The add() method is used to add a new document with an auto-generated ID.

// Initialize Firestore
const db = firebase.firestore();

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

// Add data
usersRef.add({
    name: 'Jane Doe',
    email: '[email protected]',
    age: 25
})
.then((docRef) => {
    console.log('Document written with ID: ', docRef.id);
})
.catch((error) => {
    console.error('Error adding document: ', error);
});

  1. Read Operation

To retrieve data from Firestore, you use the get() method.

Reading a Single Document

// Initialize Firestore
const db = firebase.firestore();

// Reference to a document
const docRef = db.collection('users').doc('user_id');

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

Reading Multiple Documents

// Initialize Firestore
const db = firebase.firestore();

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

// Get all documents
usersRef.get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
}).catch((error) => {
    console.error('Error getting documents: ', error);
});

  1. Update Operation

To update existing data, you use the update() method.

// Initialize Firestore
const db = firebase.firestore();

// Reference to a document
const docRef = db.collection('users').doc('user_id');

// Update data
docRef.update({
    age: 31
})
.then(() => {
    console.log('Document successfully updated!');
})
.catch((error) => {
    console.error('Error updating document: ', error);
});

  1. Delete Operation

To delete data, you use the delete() method.

// Initialize Firestore
const db = firebase.firestore();

// Reference to a document
const docRef = db.collection('users').doc('user_id');

// Delete document
docRef.delete()
.then(() => {
    console.log('Document successfully deleted!');
})
.catch((error) => {
    console.error('Error deleting document: ', error);
});

  1. Practical Exercise

Exercise: Implement CRUD Operations

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

  2. Read: Retrieve and log all users from the users collection.

  3. Update: Update Alice Smith's age to 29.

  4. Delete: Delete the user with the name "Alice Smith".

Solution

// Initialize Firestore
const db = firebase.firestore();

// 1. Create
db.collection('users').add({
    name: 'Alice Smith',
    email: '[email protected]',
    age: 28
})
.then((docRef) => {
    console.log('Document written with ID: ', docRef.id);

    // 2. Read
    return db.collection('users').get();
})
.then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });

    // 3. Update
    const aliceRef = querySnapshot.docs.find(doc => doc.data().name === 'Alice Smith').ref;
    return aliceRef.update({ age: 29 });
})
.then(() => {
    console.log('Document successfully updated!');

    // 4. Delete
    const aliceRef = db.collection('users').where('name', '==', 'Alice Smith');
    return aliceRef.get();
})
.then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        doc.ref.delete().then(() => {
            console.log('Document successfully deleted!');
        });
    });
})
.catch((error) => {
    console.error('Error: ', error);
});

  1. Conclusion

In this section, we covered the basic CRUD operations in Cloud Firestore. You learned how to create, read, update, and delete documents in your Firestore database. These operations are fundamental for managing your data and will be used frequently in your applications. In the next section, we will explore advanced queries in Firestore to help you retrieve data more efficiently.

© Copyright 2024. All rights reserved