How to add multiple docs to a collection in firebase?
Solution 1
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()
Solution 2
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 () {
// ...
});
Solution 3
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();
Kolby Watson
Updated on June 07, 2022Comments
-
Kolby Watson almost 2 years
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?