Their documentation only shows how to set multiple documents with batch, but I need to add new docs and doing it one by one with a loop seems like a bad solution
JavaScript
x
6
1
const addHistroy = async (items: IHistory[]) => {
2
await items.forEach((item) => {
3
addDoc(historyCollectionRef, item);
4
});
5
};
6
Advertisement
Answer
You can add a document using Batched Writes by creating a DocumentReference
first as shown below:
JavaScript
1
11
11
1
const batch = writeBatch(db);
2
3
await items.forEach((item) => {
4
// Creates a DocRef with random ID
5
const docRef = doc(collection(db, "history_collection_name"));
6
7
batch.set(docRef, item)
8
});
9
10
await batch.commit();
11
If you don’t want to use Batched Writes and use a loop (which you might have to if you want to add more than 500 documents at once). Try the following:
The map()
does not return a Promise but addDoc()
does. So you must await
the addDoc()
instead. You cannot use async-await
with a forEach
loop so you can either use for-of
loop or use Promise.all()
as shown below:
JavaScript
1
8
1
const addHistroy = async (items: IHistory[]) => {
2
// or alternatively create multiple batched writes of 500
3
const promises = items.map((item) => addDoc(historyCollectionRef, item))
4
await Promise.all(promises);
5
6
console.log("Documents added!")
7
};
8