let’s say that i wanna update a serie of documents, i’m doing it using forEach like this.
students.forEach(async (name) => {
const docRef = doc(db, "students", name);
await updateDoc(docRef, {
school: "Some School",
});
});
And it’s working fine, but i was wondering if that’s bad for sending too many requests or something. Is there another better/smarter way to do it?
2
Answers
There’s nothing particularly "bad" about this given what you’ve shared, unless you are also observing some behavior that you don’t like.
If your intent is to update all of the documents atomically (up to a limit of 500 in a batch), so that any failures or interruptions won’t leave the set of documents in an inconsistent state, you are better off using a batch write instead. But that won’t necessarily give you any better performance or other improved runtime behavior.
I usually recommend against using
await
in a scenario where you are usingupdateDoc
on a sequence of documents, as it’s actually faster to let the updates run in parallel. For more on this, see What is the fastest way to write a lot of documents to Firestore?But the
await
here is harmless, since usingawait
in aforEach
has no impact on the other operations in that sameforEach
. For more on this, see: Using async/await with a forEach loop If you were to use afor of
loop though, be sure to remove theawait
for improved throughput.