Home > Back-end >  How to use a for loop with a firebase snapshot using NodeJs?
How to use a for loop with a firebase snapshot using NodeJs?

Time:09-16

I want to replicate the .forEach() method using a normal for loop. The reason is that I need to anidate multiple loops, and the .forEach() method is not giving the expected result.

For exmple, if I want to retrieve my user collection, and for each user retrieve their posts, and for each post retrieve its coments (three diferent collections, with three loops anidated) then concatenate coments for each post, and send an email to each user with their posts comments. For this I did something like:

const users = await usersRef.get().then(users => {
  users.forEach(user => {  
      const userDocRef = firestore.collection('users').doc(user.id);
        postsRef.where('user', '==', userDocRef).get().then(posts => {
        posts.forEach(user => { 
        
        ...

If I use a forEach(), it gives unexpected results, I think because the exection is not linear.

Instead I want to use a for loop. But I dont know how to iterate through the snapshot:

const users = await usersRef.get();  
  for(let user of users.getChildren()) { 

...

CodePudding user response:

The posts is a QuerySnapshot that has a docs property that is an array of all the documents in this QuerySnapshot. Try refactoring the code as shown below:

for (const post of posts.docs) {
   console.log(post.data())
}
  • Related