Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Firestore Tutorial

Introduction

Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. Firestore is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps - at global scale.

Setting Up Firestore

To use Firestore, you need to set up a Firebase project and configure Firestore in your app. Follow these steps:

  1. Go to the Firebase Console.
  2. Create a new project or select an existing one.
  3. Navigate to the Firestore Database section and click "Create Database".
  4. Choose a starting mode for security rules, then click "Enable".

Connecting Your App to Firestore

To connect your app to Firestore, you need to add Firebase SDK to your project. Here is an example for a web app:

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>

<script>
// Your web app's Firebase configuration
var 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"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Initialize Firestore
var db = firebase.firestore();
</script>
                

Adding Data

Firestore stores data in documents, which are organized into collections. Here's how you can add data to Firestore:

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

Reading Data

Reading data from Firestore is straightforward. Here’s how you can read a single document:

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

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

Updating documents in Firestore can be done using the update() method. Here’s an example:

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

// Set the "born" field of the document
return userRef.update({
    born: 1816
})
.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("Ada").delete().then(() => {
    console.log("Document successfully deleted!");
}).catch((error) => {
    console.error("Error removing document: ", error);
});
                

Querying Data

Firestore provides powerful querying capabilities. Here’s an example of how to query documents:

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

Conclusion

Firestore is a powerful, flexible, and scalable NoSQL database that can be used for a variety of applications. This tutorial covered the basics of setting up Firestore, adding, reading, updating, deleting, and querying data. For more detailed information, refer to the official Firestore documentation.