1

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

const addHistroy = async (items: IHistory[]) => {
    await items.forEach((item) => {
      addDoc(historyCollectionRef, item);
    });
  };
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
LioMir
  • 23
  • 3
  • Can you share your code that you've tried already or what you have right now so we can get some more context on what you are trying to do? – Dharmaraj Sep 07 '22 at 10:34
  • this is what I wrote in order to add a few, I used a loop, but I'm sure there's a better way to do it:const addHistroy = async (items: IHistory[]) => { await items.map((item) => { addDoc(historyCollectionRef, item); }); }; – LioMir Sep 07 '22 at 11:04
  • "doing it one by one with a loop seems like a bad solution" If your concern is performance, have a look at: https://stackoverflow.com/questions/58897274/what-is-the-fastest-way-to-write-a-lot-of-documents-to-firestore – Frank van Puffelen Sep 07 '22 at 13:38

1 Answers1

1

You can add a document using Batched Writes by creating a DocumentReference first as shown below:

const batch = writeBatch(db);

await items.forEach((item) => {
  // Creates a DocRef with random ID
  const docRef = doc(collection(db, "history_collection_name"));

  batch.set(docRef, item)
});

await batch.commit();

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:

const addHistroy = async (items: IHistory[]) => {
  // or alternatively create multiple batched writes of 500
  const promises = items.map((item) => addDoc(historyCollectionRef, item))
  await Promise.all(promises);
  
  console.log("Documents added!")
};
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84