Setting Up Firestore in A JavaScript Project
Setting Up Firestore in A JavaScript Project
To get started with Firestore, we'll head to the Firebase console. You can visit
that by going to https://console.firebase.google.com/. You'll need to have a
Google account to sign in.
Once we're signed in, we'll create a new project and give it a name.
This will give us the code we need to integrate Firestore with our JavaScript
project.
// with npm
npm i firebase
// with yarn
yarn add firebase
Firestore can be used either on the client or server. If you are using Firestore
with Node, you'll need to use the CommonJS syntax with require. Otherwise, if
you're using JavaScript in the client, you'll import firebase using ES Modules.
varfirebaseConfig = {
apiKey: "AIzaSyDpLmM79mUqbMDBexFtOQOkSl0glxCW_ds",
authDomain: "lfasdfkjkjlkjl.firebaseapp.com",
databaseURL: "https://lfasdlkjkjlkjl.firebaseio.com",
projectId: "lfasdlkjkjlkjl",
storageBucket: "lfasdlkjkjlkjl.appspot.com",
messagingSenderId: "616270824980",
appId: "1:616270824990:web:40c8b177c6b9729cb5110f",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
You can also include specific Firebase products by adding the following
scripts to the bottom of your <body> tag, but before any Firebase services:
<body>
<!-- Insert these scripts at the bottom of the HTML, but before you use
any Firebase services -->
<!-- Firebase App (the core Firebase SDK) is always required and must be
listed first -->
<script src="https://www.gstatic.com/firebasejs/8.2.4/firebase-
app.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for
Analytics -->
<script src="https://www.gstatic.com/firebasejs/8.2.4/firebase-
analytics.js"></script>
Documents are individual pieces of data in our database. You can think of
documents to be much like simple JavaScript objects. They consist of key-
value pairs, which we refer to as fields. The values of these fields can be
strings, numbers, Booleans, objects, arrays, and even binary data.
Within our Firebase console, go to the 'Cloud Firestore' tab and create your
Firestore database.
Once you've done that, we will start in test mode and enable all reads and
writes to our database. In other words, we will have open access to get and
change data in our database. If we were to add Firebase authentication, we
could restrict access only to authenticated users.
After that, we'll be taken to our database itself, where we can start creating
collections and documents. The root of our database will be a series of
collections, so let's make our first collection.
We can select 'Start collection' and give it an id. Every collection is going to
have an id or a name. For our project, we're going to keep track of our users'
favorite books. We'll give our first collection the id 'books'.
Next, we'll add our first document with our newly-created 'books' collection.
For our first book, we'll make a 'title' field of type 'string', with the value 'The
Great Gatsby', and hit save.
const db = firebase.firestore();
In this cheatsheet, however, I'm going to stick to using the firestore method
each time to be as clear as possible.
To get all of the document data from a collection, we can chain on the
.get() method.
From each document, we can get the id as a separate property, and the rest
of the data using the .data() method.
.firestore()
.collection("books");
booksRef
.get()
.then((snapshot) => {
id: doc.id,
...doc.data(),
}));
});
Subscribing to a collection with .onSnapshot()
The .get() method simply returns all the data within our collection.
Instead of using the .get() method, which is for querying a single time, we
firebase
.firestore()
.collection("books")
.onSnapshot((snapshot) => {
const data = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
console.log("All data in 'books' collection", data);
});
In the code above, we're using what's known as method chaining instead of
creating a separate variable to reference the collection.
What's powerful about using firestore is that we can chain a bunch of methods
one after another, making for more declarative, readable code.
This is important in cases where the user, for example, goes away from a
given page where we're displaying a collection's data. Here's an example,
using the library React were we are calling unsubscribe within the useEffect
hook.
React.useEffect(() => {
.collection("books")
.onSnapshot((snapshot) => {
id: doc.id,
...doc.data(),
}));
setBooks(data);
});
}, []);
After that, however, we use the .doc() method chained on to the collection
method. In order to create a reference, we need to grab this id from the
database if it was auto generated. After that, we can chain on .get() and
resolve the promise.
const bookRef = firebase
.firestore()
.collection("books")
.doc("glMeZvPpTN1Ah31sKcnj");
bookRef.get().then((doc) => {
if (!doc.exists) return;
Once we get the document back, it's essential to check to see whether it
exists.
If we don't, there'll be an error in getting our document data. The way to check
and see if our document exists is by saying, if doc.exists, which returns a
true or false value.
If this expression returns false, we want to return from the function or maybe
throw an error. If doc.exists is true, we can get the data from doc.data.
Adding document to a collection with .add()
Next, let's move on to changing data. The easiest way to add a new document
chain on .add().
need to pass an object to the .add() method and specify all the fields we
want to be on the document.
Let's say we want to add another book, 'Of Mice and Men':
firebase
.firestore()
.collection("books")
.add({
})
.then((ref) => {
});
The .add method returns a promise and from this resolved promise, we get
back a reference to the created document, which gives us information such as
the created id.
The .add() method auto generates an id for us. Note that we can't use this
ref directly to get data. We can however pass the ref to the doc method to
create another query.
Where set differs from add lies in the need to specify our own id upon adding
the data.
This requires chaining on the .doc() method with the id that you want to use.
Also, note how when the promise is resolved from .set(), we don't get a
reference to the created document:
firebase
.firestore()
.collection("books")
.doc("another book")
.set({
title: "War and Peace",
})
.then(() => {
console.log("Document created");
});
Additionally, when we use .set() with an existing document, it will, by
default, overwrite that document.
bookRef
.set({
author: "Lev Nikolaevich Tolstoy"
}, { merge: true })
.then(() => {
console.log("Document merged");
bookRef
.get()
.then(doc => {
console.log("Merged document: ", doc.data());
// Merged document: { title: 'War and Peace',
author: 'Lev Nikolaevich Tolstoy' }
});
});
Updating existing data with .update()
When it comes to updating data we use the update method, like .add() and
When you use .update(), it's important to use some error handling, such as
the .catch() callback in the event that the document doesn't exist.
bookRef
.update({
year: 1869,
})
.then(() => {
})
.catch((error) => {
firebase
.firestore()
.collection("books")
.doc("another book")
.delete()
Note that the official Firestore documentation does not recommend to delete
entire collections, only individual documents.
https://www.freecodecamp.org/news/the-firestore-tutorial-for-2020-learn-by-
example/
https://firebase.google.com/docs/firestore/quickstart