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.
- 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.
 
- 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:
- Go to the Firebase Console.
 - Select your project.
 - Navigate to Firestore Database.
 - Click on "Create Database" and follow the prompts to set up Firestore.
 
- 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);
});
- 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);
});
- 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);
});
- 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);
});
- Practical Exercise
 
Exercise: Implement CRUD Operations
- 
Create: Add a new user to the
userscollection with the following data:- Name: Alice Smith
 - Email: [email protected]
 - Age: 28
 
 - 
Read: Retrieve and log all users from the
userscollection. - 
Update: Update Alice Smith's age to 29.
 - 
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);
});
- 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.
Firebase Course
Module 1: Introduction to Firebase
Module 2: Firebase Authentication
- Introduction to Firebase Authentication
 - Email and Password Authentication
 - Social Media Authentication
 - Managing Users
 
Module 3: Firebase Realtime Database
- Introduction to Realtime Database
 - Reading and Writing Data
 - Data Structure and Security Rules
 - Offline Capabilities
 
Module 4: Cloud Firestore
- Introduction to Cloud Firestore
 - Firestore Data Model
 - CRUD Operations
 - Advanced Queries
 - Security Rules
 
Module 5: Firebase Storage
Module 6: Firebase Cloud Messaging
- Introduction to Cloud Messaging
 - Sending Notifications
 - Handling Notifications
 - Advanced Messaging Features
 
