2.3 A beginner's guide to Firebase V9 - Firestore CRUD command templates for Web Version 9
Last Reviewed: April 2022
Introduction
Google's online documentation for Firestore CRUD (create, read, update, delete) instructions is very full but may be a bit verbose for everyday use. Here's are templates for the most important variants. If you find these useful, my suggestion is that you cut and paste them as is and then replace the word "my" in variable names by some suitable contraction of the name of the collection ("myCollection") that you're applying them to.
Creating documents
To create a document containing a myDocData object with an automatically-generated id:
const myCollRef = collection(db, "myCollection");
const myDocRef = doc(myCollRef);
await setDoc(myDocRef, myDocData);
Note that if you find you need to find the value that's be assigned to your automatically-generated id, this is available as myDocRef.id
(see Postscript below for further information on this point)
To create a document with a data item as its identifier:
const myDocRef = doc(db, "myCollection", myDocId);
await setDoc(myDocRef, myDocData);
Reading documents
To retrieve an individual document using its document id:
const myDocRef = doc(db, "myCollection", myDocId);
const myDoc = await getDoc(myDocRef);
if (myDoc.exists()) {
console.log("Document data:", myDoc.data());
}
To retrieve a selection of documents with selection and ordering criteria (example):
const myCollRef = collection(db, "myCollection");
const myQuery = query(myCollRef, where("field1", "==", "X"), orderBy("field2", "asc"));
const mySnapshot = await getDocs(myQuery);
mySnapshot.forEach((myDoc) => {
console.log(myDoc.id, " => ", myDoc.data());
});
Note that:
- If you don't specify an
orderBy
field, documents will be returned in ascending order of docId. Note also that if you specify more than onewhere
field, you will need to create a (compound) index. Individual fields are indexed automatically in a Firestore database. Within a Snapshot'sforEach
, the data for a document is available asmyDoc.data()
, its docRef asmyDoc.ref
its docId asmyDoc.id
. - When debugging queries it's often useful to remember that the number of items returned is available as myQuery.size
To retrieve all of the documents in a collection:
const myCollRef = collection(db, "myCollection");
const myQuery = query(myCollRef);
const mySnapshot = await getDocs(myQuery);
mySnapshot.forEach((myDoc) => {
console.log(myDoc.id, " => ", myDoc.data());
});
Updating a document
Example - to change the value of the field1 property in a document's myDocData content
const myDocRef = doc(db, 'myCollection', myDocId);
await setDoc(myDocRef, {field1: "new value"}, { merge: true });
Example - to replace the entire content of document myDocId with a new object containing only a field1 property
const myDocRef = doc(db, 'myCollection', myDocId);
await setDoc(myDocRef, {field1: "new value"}, { merge: false });
Deleting a document
const myDocRef = doc(db, 'myCollection', myDocId);
await deleteDoc(myDocRef);
CRUD operations within transactions
Inside a transaction, the patterns introduced above remain unchanged but the precise form of the setDoc commands are amended as follows:
Within the runTransaction(db, async (transaction) => {
/ }).catch();
function:
- getDoc is replaced by transaction.get()
- setDoc is replaced by transaction.set()
- deleteDoc is replaced by transaction.delete()
### Postscript ###
If you're curious about how Firestore manages to supply a unique automatically-generated id without vising your collection (we know this because there's no await
on the doc(myCollRef)
call that creates it), you might like to check out the discussion at StackOverflow.
As an alternative to universal use of setDoc(), as proposed above, Google provides addDoc() and updateDoc() functions to explicitly address document creation and update operations. But addDoc() can only be used for the creation of documents with auto ids and there's no transaction.add() function to provide the equivalent of an addDoc statement within a transaction . You may find that it's simpler, in practice, just to use setDoc everywhere.
If you have found this post interesting, you might find it useful to check out the index to this series
Google documentation references
Add data to Cloud Firestore : https://firebase.google.com/docs/firestore/manage-data/add-data
Get data with Cloud Firestore : https://firebase.google.com/docs/firestore/query-data/get-data
Delete data from Cloud Firestore : https://firebase.google.com/docs/firestore/manage-data/delete-data
SDK documentation can be found at: