Get All Records From Collection With All Refrences In Firestore
Hi I'm currently blocked because I can't get all records from a collection with references values. I would like to get all records from collection events (it works) but when I wann
Solution 1:
When you use CollectionReference#get
, it returns a Promise
containing a QuerySnapshot
object. The forEach
method on this class is not Promise
/async
-compatible which is why your code stops working as you expect.
What you can do, is use QuerySnapshot#docs
to get an array of the documents in the collection, then create a Promise
-returning function that processes each document and then use it with Promise.all
to return the array of processed documents.
In it's simplest form, it would look like this:
async function getDocuments() {
const querySnapshot = await firebase.firestore()
.collection("someCollection")
.get();
const promiseArray = querySnapshot.docs
.map(async (doc) => {
/* do some async work */return doc.data();
});
return Promise.all(promiseArray);
}
Applying it to your code gives:
export const getEventsRequest = async () => {
const querySnapshot = await firebase.firestore()
.collection('events')
.get();
const dataPromiseArray = querySnapshot.docs
.map(async (doc) => {
const {
name,
address,
city,
duration,
level,
startDate,
maxPeople,
categoryId,
} = doc.data();
const { name: categoryName, color } = (
await firebase.firestore().collection('categories').doc(categoryId).get()
).data();
return {
name,
address,
city,
duration,
level,
startDate,
maxPeople,
category: { name: categoryName, color },
};
});
// wait for each promise to complete, returning the output data arrayreturn Promise.all(dataPromiseArray);
};
Post a Comment for "Get All Records From Collection With All Refrences In Firestore"