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?
20 for multi-document reads, transactions, and batched writes. The previous limit of 10 also applies to each operation.
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.
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.
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()
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 () {
// ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With