DEV Community

Gaute Meek Olsen
Gaute Meek Olsen

Posted on • Originally published at gaute.dev

Firestore, get collection with async/await

Today I Learned how to get all documents in a collection in Firestore with async/await and for...of by using the .docs property.

Firebase documentation has examples with .then to get the result from a Promise.

const logCities = () => {
  let citiesRef = db.collection('cities');
  let allCities = citiesRef.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
      });
    })
}

But it can be written easier with async/await.

const logCities = async () => {
  let citiesRef = db.collection('cities');
  let allCities = await citiesRef.get();
  for(const doc of allCities.docs){
    console.log(doc.id, '=>', doc.data());
  }
}

I think this is more readable, two less lines and .docs allows us to use for of.

Top comments (6)

Collapse
 
bequick profile image
Marcos Donoso • Edited

two lines:

const cities = await db.collection('cities');
const allCities = await (await cities.get()).docs.map(doc => doc.data());
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hcwrohan profile image
Ro

thanks man, came in handy :)

Collapse
 
jfar41 profile image
ricocode

I have some questions regarding async. i have code that looks like this:
queryRooms = async () => {
console.log('line 231');
let recentQuery = await this.chatRooms.where("uidArray", "in",
[this.user.uid+this.state.value.objectID,
this.state.value.objectID+this.user.uid]).get();
for (const qSnap of recentQuery.docs) {
console.log(qSnap.id);
let messagesRef = await this.chatRooms.doc(qSnap.id)

.collection('messages').get();
for (const messages of messagesRef.docs) {
console.log(messages.id, messages.data())
}
}
I call queryRooms in my react app everytime I change the value of the dropdownlist that has teachers students can chat with. However, my problem is that console.log('line 231') is being ran every time that I change the state but then I don't receive the requested information. After a random amount of presses I finally get a weird looking data structure from the queryRooms function. Is there a visible flaw with my async/await structure?

Collapse
 
praveenkalady profile image
praveen

thanks for sharing bro

Collapse
 
chipd profile image
Chris Dermody

helped me a lot with some async problems I was having - and much more readable. thanks for sharing!

Collapse
 
iamsachin619 profile image
iamsachin619

I am not able to console.log(snapshot) after await citiesref.get();