Firebase / Cloud Firestore

Getting Started with Cloud Firestore

This tutorial introduces the basics of Cloud Firestore, including how to set up your project and write, read, update, and delete data.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers real-time database and cloud storage with Cloud Firestore for scalable and secure apps.

Getting Started with Cloud Firestore

1. Introduction

Goal

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.

Learnings

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.

Prerequisites

  • Basic knowledge of JavaScript
  • A Google Firebase project

2. Step-by-Step Guide

Setting up Firestore

Start by navigating to the Firebase console, select your project, then click on "Database" in the sidebar. Choose Firestore and click "Create database".

Basic Operations

Firestore stores data in documents, which are stored in collections. Documents can have sub-collections of their own.

  • Create: To write or create a new document in a collection, use add().
  • Read: To read a document, use doc() and get().
  • Update: To update a document, use update().
  • Delete: To delete a document, use delete().

3. Code Examples

Let's see how these operations work with JavaScript in a Firestore project.

Create

// 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".

Read

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.

Update

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.

Delete

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.

4. Summary

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.

5. Practice Exercises

  1. Exercise 1: Create a collection "users" and add a document with fields "name" and "email".

  2. Exercise 2: Read the document you created in Exercise 1 and log the data.

  3. Exercise 3: Update the "name" field of the document you created in Exercise 1.

Solutions

  1. The solution for Exercise 1 would be similar to the "Create" example above, just replace "cities" with "users" and the fields accordingly.

  2. The solution for Exercise 2 would be similar to the "Read" example above, just replace "cities" with "users" and the document id accordingly.

  3. 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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help