Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
Kolby Watson Avatar asked Jan 23 '19 07:01

Kolby Watson


People also ask

How many documents can be in a collection firebase?

20 for multi-document reads, transactions, and batched writes. The previous limit of 10 also applies to each operation.

How do I add files to firestore collection?

Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.

What is the difference between collection and document in firebase?

Documents within the same collection can all contain different fields or store different types of data in those fields. However, it's a good idea to use the same fields and data types across multiple documents, so that you can query the documents more easily. A collection contains documents and nothing else.


2 Answers

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() 
like image 195
Dominik Šimoník Avatar answered Oct 14 '22 23:10

Dominik Šimoník


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 () {
    // ...
});
like image 23
HakanC Avatar answered Oct 14 '22 23:10

HakanC