简体   繁体   English

如何在使用 NodeJs 的 firebase 快照中使用 for 循环?

[英]How to use a for loop with a firebase snapshot using NodeJs?

I want to replicate the.forEach() method using a normal for loop.我想使用普通的 for 循环复制 .forEach() 方法。 The reason is that I need to anidate multiple loops, and the.forEach() method is not giving the expected result.原因是我需要对多个循环进行动画处理,而 .forEach() 方法没有给出预期的结果。

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.例如,如果我想检索我的用户集合,并为每个用户检索他们的帖子,并为每个帖子检索其评论(三个不同的 collections,三个循环动画)然后连接每个帖子的评论,并向每个帖子发送 email用户及其帖子+评论。 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.如果我使用 forEach(),它会给出意想不到的结果,我认为是因为执行不是线性的。

Instead I want to use a for loop.相反,我想使用 for 循环。 But I dont know how to iterate through the snapshot:但我不知道如何遍历快照:

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

The posts is a QuerySnapshot that has a docs property that is an array of all the documents in this QuerySnapshot.这些posts是一个QuerySnapshot ,它有一个docs属性,该属性是这个 QuerySnapshot 中所有文档的数组。 Try refactoring the code as shown below:尝试重构代码,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM