Reading Data from Cloud Firestore
Method 1: Using get() Method
- The get() method in Cloud Firestore retrieves data once from a specific document or collection.
- It’s suitable for scenarios where we only need to fetch data once.
Example: Using get() Method
firestore.collection('users').doc('user1').get()
.then(function(doc) {
if (doc.exists) {
var data = doc.data();
console.log(data);
} else {
console.log("No such document!");
}
})
.catch(function(error) {
console.error("Error fetching data: ", error);
});
Output
{ name: 'John Doe', age: 25, email: 'john@example.com' }
Executing the above code will retrieve data once from the document with the ID ‘user1‘ in the ‘users‘ collection in Cloud Firestore.
Method 2: Using Real-time Listeners
- Similar to Realtime Database, Cloud Firestore also provides real-time listeners to listen for changes to the data.
Example: Using Real-time Listeners
firestore.collection('users').doc('user1').onSnapshot(function(doc) {
var data = doc.data();
console.log(data);
});
Output
Continuously listens for changes to the data in the document with the ID ‘user1’ and logs the data whenever it changes.
Reading Data in Firebase
Firebase a comprehensive platform for building mobile and web applications, provides powerful tools for reading and managing data. Understanding how to read data from Firebase databases is essential for developers working with Firebase.
In this article, we will explore the concepts, methods, and examples of reading data from Firebase databases, including the Realtime Database and Cloud Firestore and so on.