Beginner's guide to Firestore

Beginner's guide to Firestore

Firestore is a database service that allows you to store and manage data in the cloud. It is a NoSQL database, which means that it does not use a traditional SQL relational database structure. Instead, it stores data as documents, which are JSON-like objects with key-value pairs. In this blog, we will look at how to set up Firestore(web version 9) and perform the basic operations of creating, reading, updating, and deleting(CRUD) data in the database.

So, let's begin

Setting up Firestore

Before you can start using Firestore, you need to set up a Firebase project and enable the Firestore service. Here's how:

  1. Go to the Firebase website and click on the "Get Started" button.

  2. Sign in with your Google account, or create a new one if you don't have one.

  3. Click on the "Add project" button and give your project a name.

  4. Choose the default account and click on the "Create project" button.

  5. Once the project has been created, click on the "</>" icon to get your Firebase configuration details.

  6. Give the web app a nickname and click on “Register app” button.

  7. You will see some Javascript code with your Firebase configuration details. Copy these details, as you will need them later.

  8. Click on “Continue to Console” button.

Now that you have set up your Firebase project, you need to enable the Firestore service. Here's how:

  1. Click on the "Firestore Database" button in the left-hand menu.

  2. Click on the "Create database" button in the Cloud Firestore section.

  3. Select the "Start in test mode" option and click on the "Next" button.

  4. Select the location for your database and click on the "Enable" button.

Now, you will see this kind of interface:

Your Firestore database is now set up and ready to use.

How Firestore stores Data

Before moving forward we will take a look at how firestore stores data so that it's easy for us to do CRUD operations. So, firestore stores data in documents that are stored in a collection. Each document can contain multiple fields(key-value pairs) and each collection can contain multiple documents. Each document have a unique ID that can be used to reference and retrieve the data.

Adding Firestore to Javascript

  1. Install Firebase using npm:
$ npm install firebase
  1. Past this code on the top of your JavaScript file to Initialize Firebase in your app:
import { initializeApp } from 'firebase/app';
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
//Paste the Firebase configuration details that you copied earlier
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

Create a Document

There are two methods to create a document:

  1. setDoc() method

With this method you can create or overwrite a single document. If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data. In this method you have to specify the ID of the document like in the code below “adalovelace” is the ID of the document.

import { doc, setDoc } from "firebase/firestore";
// Add a new document in collection "users"
const createDoc = async () => {
await setDoc(doc(db, "users", "adalovelace"), {
first: "Ada",
last: "Lovelace",
born: 1815,
});
};
createDoc();

After you run the above code, your dashboard will like this:

2. addDoc() method

You can use this method to create a document. In this method, you don’t need to specify the ID of the document as Firebase will automatically generate a unique ID for you.

import { collection, addDoc } from "firebase/firestore";
// Add a new document in colletion "users"
const createDoc = async () => {
const docRef = await addDoc(collection(db, "users"), {
first: "Ada",
last: "Lovelace",
born: 1815,
});
console.log("Document written with ID: ", docRef.id);
};
createDoc();

After you run the above code, your dashboard will look like this:

💡 Make sure that you set the type attribute to module <script type="module">

⚠️ If you are getting an error like this Uncaught TypeError: Failed to resolve module specifier "firebase/app". Relative references must start with either "/", "./", or "../". You can resolve this error by replacing all your importlines to import { } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-SERVICE.js' (where SERVICE is an SDK name such as firebase-firestore) or by using a module bundler

Read Documents

There are two ways by which you can retrieve data from a collection:

  1. Retrieve a single document from a collection

  2. Retrieve all the documents from a collection

getDoc() method

To retrieve a single document from a collection you can use this method. In this method, you need to specify the ID of the collection(which in our case is “users”) and the ID of the document(which in our case is “adaloveloace”).

import { doc, getDoc } from "firebase/firestore";
// Retrieve "adalovelace" document in the "users" collection
const readDocuments = async () => {
const docRef = doc(db, "users", "adalovelace");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log(docSnap.data());
} else {
console.log("No such document Found!");
}
};
readDocuments();

getDocs() method

To retrieve all the documents from a collection you can use the getDocs() method. The code below will return all the documents that are located in the “users” collection.

import { collection, getDocs } from "firebase/firestore";
// Retrieve the entire collection
const readDoc = async () => {
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(doc.data());

});
};
readDoc()

Update a Document

You can update a document by updateDoc() method. With this method, you can change some fields of a document without overwriting the entire document. To update a document you have to specify the ID of the collection and the ID of that document.

import { doc, updateDoc } from "firebase/firestore";
const updateDocument = async () => {
const docRef = doc(db, "users", "adalovelace");
// Set the "born" field of the city '1915'
await updateDoc(docRef, {
born: 1915,
});
};
updateDocument();

Delete a Document

To delete a document, you can use the delete() method. Here you also have to specify the name of the collection and the id of the document that you want to delete.

import { doc, deleteDoc } from "firebase/firestore";
// Delect the document "adalovelace" in collection "users"
const deleteDocument = async () => {
await deleteDoc(doc(db, "users", "adalovelace"));
};
deleteDocument();

Conclusion

Firestore is a database service that allows you to store and manage data in the cloud. In firestore, you can create a document by setDoc() or addDoc() method. You can retrieve documents/document from a collection by getDoc() or getDocs() method. You can update a document by updatedDoc() method. And delete a document by deleteDoc() method.