-1

i have this code, i try to create new field in my collection with bacth, i want to verify with this condition ((index + 1) % 500 === 0) to use the commit, what is the wrong?

const myFunction = async () => {
  try {
    let batch = db.batch()
    const batchCommits = []
    
    await schoolList.forEach(async (school, index) => {
      await ref
        .doc(school.id)
        .collection('mycollection')
        .where('visual', '==', 'none')
        .get()
        .then(async (querySnapshot) => {
          if (querySnapshot.empty) {
            const curses = await ref
              .doc(school.id)
              .collection('curses')
              .doc()
            batch.set(curses, common)
            if ((index + 1) % 500 === 0) {
              batchCommits.push(batch.commit())
              batch = db.batch()
            }
          }
        })
    })
    batchCommits.push(batch.commit())
    return Promise.all(batchCommits)
  } 
}

i am getting this error: Error: Cannot modify a WriteBatch that has been committed.

  • 1
    `await` does not work the way you expect inside a forEach loop. It's not blocking each iteration through, and forEach does not return another promise to await. https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Doug Stevenson Nov 03 '20 at 16:39
  • Try: `await Promise.all(schoolList.map(...))` – Titus Nov 03 '20 at 16:39
  • @DougStevenson i deleted the await, but the error is continuing –  Nov 03 '20 at 17:03

1 Answers1

1

The way I understand it is you could work through the results using a for of loop i.e. for(const school of Schools). This is pretty rough but maybe something like the below? Not too sure about combining the batches into a promise.all

If you've already solved this please post your solution.

    let batch = db.batch()
        
    for( const school of schoolList) {
        const myCollectionDoc =  await ref.collection('mycollection')
            .doc(school.id)
            .get()

        if(myCollectionDoc.empty) {
            const curses = await ref.doc(school.id).collection('curses').doc()
            batch.set(curses, common)
         }

        if (batch._writes.length === 500) {
            await batch.commit()
            batch = db.batch()
        }
    }
        
    if (batch._writes.length != 0) {
        await batch.commit()
    }
Cleanbeans
  • 655
  • 4
  • 12