This tutorial aims to guide you through the basics of Cloud Firestore, a flexible, scalable NoSQL cloud database from Google Firebase to store and sync data for client and server-side development.
By the end of this tutorial, you will be able to set up a Firestore database, and perform basic operations such as creating, reading, updating, and deleting data.
Start by navigating to the Firebase console, select your project, then click on "Database" in the sidebar. Choose Firestore and click "Create database".
Firestore stores data in documents, which are stored in collections. Documents can have sub-collections of their own.
add()
.doc()
and get()
.update()
.delete()
.Let's see how these operations work with JavaScript in a Firestore project.
// Get a reference to the Firestore service
var db = firebase.firestore();
// Add a new document in collection "cities"
db.collection("cities").add({
name: "Los Angeles",
state: "CA",
country: "USA"
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
In this code snippet, we're adding a document to the "cities" collection. The document contains the fields "name", "state", and "country".
var cityRef = db.collection('cities').doc('LA');
var getDoc = cityRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
This code snippet reads the document with the id 'LA' from the 'cities' collection.
var cityRef = db.collection('cities').doc('LA');
var updateSingle = cityRef.update({ capital: true });
This code snippet updates the document with the id 'LA' from the 'cities' collection, setting the "capital" field to true
.
var cityRef = db.collection('cities').doc('LA');
var deleteDoc = cityRef.delete();
This code snippet deletes the document with the id 'LA' from the 'cities' collection.
In this tutorial, we've learned how to set up a Firestore database and perform basic operations: creating, reading, updating and deleting data.
For further learning, you should explore Firestore's advanced features such as transactions, compound queries, and security rules.
Exercise 1: Create a collection "users" and add a document with fields "name" and "email".
Exercise 2: Read the document you created in Exercise 1 and log the data.
Exercise 3: Update the "name" field of the document you created in Exercise 1.
Solutions
The solution for Exercise 1 would be similar to the "Create" example above, just replace "cities" with "users" and the fields accordingly.
The solution for Exercise 2 would be similar to the "Read" example above, just replace "cities" with "users" and the document id accordingly.
The solution for Exercise 3 would be similar to the "Update" example above, just replace "cities" with "users", the document id, and field name accordingly.