In this tutorial, we will learn how to build a CRUD (Create, Read, Update, Delete) web application using Firestore, a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.
By the end of this tutorial, you will:
You should have basic knowledge of HTML, CSS, and JavaScript. Familiarity with Firebase is helpful, but not necessary.
First, create a Firebase account and a new project in Firebase. Navigate to the Firestore Database section and create a new Firestore database.
In your HTML file, include the Firebase JavaScript library by adding these scripts in your HTML file:
<script src="https://www.gstatic.com/firebasejs/7.24.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.24.0/firebase-firestore.js"></script>
Then, initialize Firebase in your JavaScript file:
const firebaseConfig = {
apiKey: "your-api-key",
authDomain: "your-auth-domain",
projectId: "your-project-id"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
To add a document to Firestore, use the .add()
method with your data as an object:
db.collection('users').add({
firstName: 'John',
lastName: 'Doe',
age: 30
});
To get all documents in a collection, use the .get()
method:
db.collection('users').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
console.log(doc.data());
});
});
To update a document, use the .update()
method:
db.collection('users').doc('document-id').update({
age: 31
});
To delete a document, use the .delete()
method:
db.collection('users').doc('document-id').delete();
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
// Add a new document
db.collection('users').add({
firstName: 'John',
lastName: 'Doe',
age: 30
});
// Get all documents
db.collection('users').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
console.log(doc.data());
});
});
// Update a document
db.collection('users').doc('document-id').update({
age: 31
});
// Delete a document
db.collection('users').doc('document-id').delete();
This example shows how to connect to Firestore and perform CRUD operations. Make sure to replace 'document-id'
with the actual ID of the document you want to update or delete.
In this tutorial, we've learned how to connect to Firestore and perform CRUD operations. You have now a grasp on how to create, read, update, and delete documents in Firestore.
Exercise 1: Create a new collection and add 5 documents to it, each with three different fields.
Exercise 2: Read all documents from the collection you created and log them to the console.
Exercise 3: Update one of the documents you created in Exercise 1.
Exercise 4: Delete one of the documents you created in Exercise 1.