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?
CodePudding user response:
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.
CodePudding user response:
I usually recommend against using await
in a scenario where you are using updateDoc
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 using await
in a forEach
has no impact on the other operations in that same forEach
. For more on this, see: Using async/await with a forEach loop If you were to use a for of
loop though, be sure to remove the await
for improved throughput.