Learn how to get all the documents data from a collection in Firebase version 9 Cloud Firestore Database using the getDocs() method.
- Get All Documents From A Collection → you’re here
- Get Document By ID
The Firestore Database has a cities collection that has four documents in it like the screenshot below.
Import Firestore Database and de-structure three methods that are:
- getFirestore() → Firestore Database
- doc() → It takes references of database and collection that we need to get the data from.
- getDocs() → It gets data from collection based references mentioned in the doc() method.
import { getFirestore, doc, getDocs } from https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js";
The import statement uses the CDN version of the Firebase SDK in this example.
Initialize Firestore Database
const db = getFirestore();
The getDocs() method takes a single argument which is the doc() method.
Two of the arguments of doc() method
- Database → db
- Collection name → cities in this case (see the screenshot above)
Call the doc() method and pass two arguments and assign it to a constant called colRef (short form for collection reference).
const colRef = collection(db, "cities");
Invoke the getDocs() method passing colRef as an argument to it.
The getDocs() method will return a promise, add await keyword in front of it.
Assign it to a constant called docsSnap (short form for documents snapshot).
const docsSnap = await getDocs(colRef);
To see each document from the cities collection, loop through the docsSnap object using the forEach() method.
docsSnap.forEach(doc => {
console.log(doc.data());
})
The forEach() method takes a function as an argument with the parameter called doc.
Note: The parameter doc has nothing to do with the doc() method mentioned above.
The doc parameter will get a document from docsSnap on each iteration.
To get the actual document data, call the data() method on the doc object.
To get the id of a document, access the id property on the doc object.
docsSnap.forEach(doc => {
console.log(doc.id);
})
To catch any client-side error, wrap the await code with try catch block.
try {
const docsSnap = await getDocs(colRef);
docsSnap.forEach(doc => {
console.log(doc.data());
console.log(doc.id);
})
} catch (error) {
console.log(error);
}
One of the ways you can check to see if the we have any document in the collection before going further.
try {
const docsSnap = await getDocs(colRef);
if(docsSnap.docs.length > 0) {
docsSnap.forEach(doc => {
console.log(doc.data());
console.log(doc.id);
})
}
} catch (error) {
console.log(error);
}
Top comments (0)