The main goal of this tutorial is to compare two of Firebase's powerful database options: Firestore and Realtime Database. We will explore the key differences, advantages, disadvantages, and ideal use cases for each.
By the end of this tutorial, you will understand:
- The core concepts of Firestore and Realtime Database
- When to use Firestore or Realtime Database
- How to interact with both databases using code examples
A basic understanding of Firebase, JavaScript and databases will be helpful for this tutorial.
Firestore is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps at a global scale. It organizes data as collections of documents, and can even have nested sub-collections.
Realtime Database is Firebase's original database. It's a NoSQL database that stores data as JSON and synchronizes it in realtime to every connected client.
// Initialize Firestore
const db = firebase.firestore();
// Add a new document
db.collection("users").add({
first: "Alan",
last: "Turing",
born: 1912
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
// Get a reference to the database service
const database = firebase.database();
// Write new post
function writeNewPost(uid, username, picture, title, body) {
const postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
const newPostKey = firebase.database().ref().child('posts').push().key;
const updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
In this tutorial, we compared Firestore and Realtime Database. Firestore is more scalable and provides more robust querying, but Realtime Database can be more straightforward for simple data needs.
Next steps for learning could include diving deeper into the Firebase platform and exploring other services it offers, like authentication and cloud functions.
Remember, practice is the key to mastering any skill. Continue experimenting with Firestore and Realtime Database to understand their potential. Happy coding!