Kolby Watson
Kolby Watson

Reputation: 573

How to add multiple docs to a collection in firebase?

Im working with React native and react-native-firebase

My objective is to add multiple docs(objects) to a collection at once. Currently, I have this:

const array = [
  {
     name: 'a'
  },{
    name: 'b'
  }
]
array.forEach((doc) => {
  firebase.firestore().collection('col').add(doc);
}

This triggers an update on other devices for each update made to the collection. How can I batch these docs together for ONE update?

Upvotes: 51

Views: 37408

Answers (5)

Hypermona
Hypermona

Reputation: 147

A batched write can contain up to 500 operations. Each operation in the batch counts separately towards your Cloud Firestore usage.

Note: For bulk data entry, use a server client library with parallelized individual writes. Batched writes perform better than serialized writes but not better than parallel writes. You should use a server client library for bulk data operations and not a mobile/web SDK.

Upvotes: 0

Gareth
Gareth

Reputation: 321

Version 9 of Web API is slightly different, the docs include this example:

import { writeBatch, doc } from "firebase/firestore"; 

// Get a new write batch
const batch = writeBatch(db);

// Set the value of 'NYC'
const nycRef = doc(db, "cities", "NYC");
batch.set(nycRef, {name: "New York City"});

// Update the population of 'SF'
const sfRef = doc(db, "cities", "SF");
batch.update(sfRef, {"population": 1000000});

// Delete the city 'LA'
const laRef = doc(db, "cities", "LA");
batch.delete(laRef);

// Commit the batch
await batch.commit();

Upvotes: 8

Lavi Moolchandani
Lavi Moolchandani

Reputation: 51

The batch from database also has a create function that adds a new document in a collection and throws an error if there is already a document. we just need the reference to the document. Please note that this function exists in admin sdk of firebase.

const batch = db.batch();
await users.map(async (item)=> {
    const collectionRef = await db.collection(COLLECTION_NAME).doc();
    batch.create(collectionRef, item);
  });

const result = await batch.commit();

Upvotes: 5

Cappittall
Cappittall

Reputation: 3441

You can execute multiple write operations as a single batch that contains any combination of set(), update(), or delete() operations. A batch of writes completes atomically and can write to multiple documents.

var db = firebase.firestore();
var batch = db.batch();

array.forEach((doc) => {

  batch.set(db.collection('col').doc(), doc);
}
// Commit the batch
batch.commit().then(function () {
    // ...
});

Upvotes: 23

Dominik Šimoník
Dominik Šimoník

Reputation: 1602

You can create batch write like

var db = firebase.firestore();
var batch = db.batch()

in you array add updates

array.forEach((doc) => {
  var docRef = db.collection("col").doc(); //automatically generate unique id
  batch.set(docRef, doc);
});

finally you have to commit that

batch.commit()

Upvotes: 101

Related Questions