so my firebase document looks like this:
So it is a list with name, imgUrl etc inside of the list. My problem right now with firebase cloud firestore, is that I just want to extract all the "name:" stuff so that I can count how many times a particular name appears.
I am retrieving the data from the document like so:
const matchLikes = async () => {
await fire.firestore()
.collection("eventLikes")
.doc(eventID).onSnapshot((querySnapshot) => {
//console.log("print indi event heree " querySnapshot.data().eventID)
setLikes(querySnapshot.data().ActivityLikes)
})
and I have the array in a hook to use, but i just cant figure out how to access just the "name:" stuff inside the array I have tried even doing querySnapshot.data().ActivityLikes.name
but it fails. Does anyone know where I am going wrong?
CodePudding user response:
Firestore doesn't support projecting specific fields and aggregating the data. You'll have to fetch the document and then manually find count of each name. Also there you don't need an await
before onSnapshot
. Try refactoring the code as shown below:
const matchLikes = () => {
fire.firestore()
.collection("eventLikes")
.doc(eventID).onSnapshot((docSnapshot) => {
const nameCounts = docSnapshot.data().ActivityLikes.reduce((acc, cur) => {
acc[cur.name] = (acc[cur.name] || 0) 1;
return acc;
}, {});
// setLikes(querySnapshot.data().ActivityLikes)
})
}