简体   繁体   中英

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. 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. 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. Anyone idea how to solve this?

If you want to read the files in sequence, you cannot use forEach indeed. Just use a modern for … of loop instead, in which await will work as expected:

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.

Thank you @DougStevenson for pointing me in right direction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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