Firebase Firestore collection could not retrieve - react native - javascript

Context: I have a list of doctors on Firebase Firestore and I want to retrieve data related to them.
Problem: App is behaving like collection is empty but it currently contains three doctors. I want to retrieve data in list of objects so I can access them in app. Also, if you have any other idea of retrieving the data let me know, since I haven't found any that works for me.
Here is the problematic part of code:
componentDidMount(){
firebase.firestore().collection('doctors')
.get()
.then((querySnapshot
) => {
querySnapshot.forEach(snapshot => {
const doctors = []
snapshot.forEach(doc => {
const data = doc.data()
data.id = doc.id;
doctors.push(data)
})
this.setState({doctors :doctors})
})})
}
Here is how my Firebase looks like:

I found this snippet which I believe it's your exact use case:
// retrieve a collection
db.collection('documents')
.get()
.then(querySnapshot => {
const documents = querySnapshot.docs.map(doc => doc.data())
// do something with documents
})
You may find this example, and others here. Under each snippet, you can find the original source in case you want more context for each snippet.

Related

how to fetch data of all collections from firebase in react

I am trying to fetch data from the firebase. I have two collections, and I want data from both collections to be printed. When I fetch, only data from one collection is shown
const fetchData = () => {
const arr = []
db.collection('storedata').get().then((querysnapshot) => {
querysnapshot.forEach((element) => {
const dataSet = element.data()
if (email !== '' && password !== '') {
return arr.push(setInfo([dataSet]))
}
})
})
}
You are fetching data from the collection 'storedata', using:
db.collection('storedata').get()
If you want to do the same but with other collection you need to explicitly write the same code for whatever other collection you are trying to fetch!
To achieve what you want to achieve you need to know the name of the other collection and repeat the same process you made for 'storedata' collection
You can't, and should not try to fetch all documents in the Firestore database.
But if you absolutely need for it to happen, then it's better to make it explicit by fetching each collection one by one.

How to join two collections in firebase with array of ids using Angular?

I am new to firebase and I am trying to get data from firebase. In MySQL, this is very easy but I don't know how can we join collections in firebase. Please guide me to solve this small issue.
Below is the data in my firebase.
I want to get match the team ID with the users' collection. Below is my code with where condition but it is not working.
getProjects() {
this.firestore.collection('projects').valueChanges().subscribe(projects => {
// console.log(projects)
// this.projects = projects;
const teamRef = this.firestore.collection('users');
projects.forEach(project => {
teamRef.where('')
})
// console.log(this.projects)
})
}
Any solution Appreciated!

How to use Promise.all with multiple Firestore queries

I know there are similar questions to this on stack overflow but thus far none have been able to help me get my code working.
I have a function that takes an id, and makes a call to firebase firestore to get all the documents in a "feedItems" collection. Each document contains two fields, a timestamp and a post ID. The function returns an array with each post object. This part of the code (getFeedItems below) works as expected.
The problem occurs in the next step. Once I have the array of post ID's, I then loop over the array and make a firestore query for each one, to get the actual post information. I know these queries are asynchronous, so I use Promise.all to wait for each promise to resolve before using the final array of post information.
However, I continue to receive "undefined" as a result of these looped queries. Why?
const useUpdateFeed = (uid) => {
const [feed, setFeed] = useState([]);
useEffect(() => {
// getFeedItems returns an array of postIDs, and works as expected
async function getFeedItems(uid) {
const docRef = firestore
.collection("feeds")
.doc(uid)
.collection("feedItems");
const doc = await docRef.get();
const feedItems = [];
doc.forEach((item) => {
feedItems.push({
...item.data(),
id: item.id,
});
});
return feedItems;
}
// getPosts is meant to take the array of post IDs, and return an array of the post objects
async function getPosts(items) {
console.log(items)
const promises = [];
items.forEach((item) => {
const promise = firestore.collection("posts").doc(item.id).get();
promises.push(promise);
});
const posts = [];
await Promise.all(promises).then((results) => {
results.forEach((result) => {
const post = result.data();
console.log(post); // this continues to log as "undefined". Why?
posts.push(post);
});
});
return posts;
}
(async () => {
if (uid) {
const feedItems = await getFeedItems(uid);
const posts = await getPosts(feedItems);
setFeed(posts);
}
})();
}, []);
return feed; // The final result is an array with a single "undefined" element
};
There are few things I have already verified on my own:
My firestore queries work as expected when done one at a time (so there are not any bugs with the query structures themselves).
This is a custom hook for React. I don't think my use of useState/useEffect is having any issue here, and I have tested the implementation of this hook with mock data.
EDIT: A console.log() of items was requested and has been added to the code snippet. I can confirm that the firestore documents that I am trying to access do exist, and have been successfully retrieved when called in individual queries (not in a loop).
Also, for simplicity the collection on Firestore currently only includes one post (with an ID of "ANkRFz2L7WQzA3ehcpDz", which can be seen in the console log output below.
EDIT TWO: To make the output clearer I have pasted it as an image below.
Turns out, this was human error. Looking at the console log output I realised there is a space in front of the document ID. Removing that on the backend made my code work.

Saving a field from firestore that is an array

I am currently working on a mobile app on React and I am having trouble understanding how to save a field from fire store that is an array.
Since I can't post images my database structure is all strings such as username, first name, etc but I have a field called follow list that is an array.
What I want to do is save the usernames from the following list into an array to later search fire store for the username's in the array, this is basically what I want to do so I can render my app's social Feed. I do know that I can probably create another subcollection and write something familiar to what I did to search for users but that was a QuerySnapShot which was overall documents not a specific one and I also know firebase creates an ID for arrays and it increases as the array gets bigger.
I do not want to end up making two more subcollections one for followers and following which I think not ideal right? My current approach is this
export const fetchUserFollowing = async (username) => {
const ref = firebase.firestore().collection('users').doc(username)
let results = []
ref
.get()
.then( doc => {
let data = doc.data()
results = data
})
.catch((err) => {
return 'an error has occurred ', err
})
}
From what I understand is that a DocumentSnapShot .get() function returns an object but what I want is to store follow list into results and then return that but I am not sure how to manipulate the object return to just give me follow List which is an array
https://rnfirebase.io/docs/v5.x.x/firestore/reference/DocumentSnapshot
link to docs

Get the child object of a limit(1) query on firebase database

I have this data
I do this query
firebase.database().ref(${path}/buy)
.orderByChild('price').limitToFirst(1)
.once('value')
.then(snapshot => console.log(snapshot.val()))
And I get this result
Then the question is
Is there an easy way to access the price attribute of the one object whose key I don't know?
e.g. snapshot.first().price or snapshot.only().price
Simply put, I want to avoid this
var result = snapshot.val()
var key = Object.keys(result)[0]
var price = result[key].price
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
In your callback you need to handle this list by using snapshot.forEach():
firebase.database().ref(${path}/buy)
.orderByChild('price').limitToFirst(1)
.once('value')
.then(snapshot => {
snapshot.forEach(function(child) {
console.log(child.val());
console.log(child.val().price);
})
})

Categories

Resources