Home > database >  How do I add multiple documents in firebase 9 with javascript?
How do I add multiple documents in firebase 9 with javascript?

Time:09-08

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);
    });
  };

CodePudding user response:

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!")
};
  • Related