简体   繁体   English

for 循环中的 Firestore 批处理仅存储最后一个文档

[英]Firestore batch in for loop stores only last document

I am trying to update user data in multiple tasks collection.我正在尝试更新多个任务集合中的用户数据。 So I have multiple id's of tasks, where I use forEach loop reading each of task.所以我有多个 id 的任务,我使用 forEach 循环读取每个任务。 In each task I have multiple users where I want to update only one specific user.在每项任务中,我都有多个用户,我只想更新一个特定的用户。

I am using firestore and batch for writing data.我正在使用 firestore 和 batch 来写入数据。 The problem is that only last task is updated.问题是只更新了最后一个任务。 This is my code这是我的代码

tasksIds.forEach(async function(taskId) {
 
                
                const batch = db.batch()

                try {
                    taskRef =  db.collection("tasks")
                        .doc(taskId)
                    const projectDataTemp = await taskRef.get()
                    projectData=  projectDataTemp.data()
                    allClients = projectData.users
                } catch (error) {
                    console.log(error)
                
                await allClients.map(async (oneClient) => {
                    if(oneClient.id === id) {
                        oneClient.name = name
                    }

                })

                    
                    await batch.update(taskRef, { users: allClients})
                
                // Commit the batch
                 await batch.commit().then(() => console.log("success",allClients))
        
            })
        }

So everything is good except that only last task is updated, I suppose that the problem is of synchronisation that batch.commit isn't finished and another task is started.所以一切都很好,除了只有最后一个任务被更新,我想问题是同步问题 batch.commit 没有完成并且另一个任务开始了。 Anyone idea how to solve this?有人知道如何解决这个问题吗?

If you want to read the files in sequence, you cannot use forEach indeed.如果要按顺序读取文件,确实不能使用 forEach。 Just use a modern for … of loop instead, in which await will work as expected:只需使用现代的 for … of 循环代替,其中 await 将按预期工作:

async function printFiles () {
  const files = await getFilePaths();

  for (const file of files) {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }
}

Changing forEach loop for standard one, solved problem.将 forEach 循环更改为标准循环,问题已解决。

Thank you @DougStevenson for pointing me in right direction谢谢@DougStevenson 为我指明了正确的方向

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

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