You can't batch-add/bulk-insert documents in the Firebase Web SDK. But you can with the Firebase Admin Node SDK. Like, in a Firebase Cloud Function. Here's an example of how to do that:
const firestore = admin.firestore();
let batch = firestore.batch();
let counter = 0;
let totalCounter = 0;
const promises = [];
for (const thing of MANY_MANY_THINGS) {
counter++;
const docRef = firestore.collection("MY_COLLECTION").doc();
batch.set(docRef, {
foo: thing.foo,
bar: thing.bar,
favNumber: 0,
});
counter++;
if (counter >= 500) {
console.log(`Committing batch of ${counter}`);
promises.push(batch.commit());
totalCounter += counter;
counter = 0;
batch = firestore.batch();
}
}
if (counter) {
console.log(`Committing batch of ${counter}`);
promises.push(batch.commit());
totalCounter += counter;
}
await Promise.all(promises);
console.log(`Committed total of ${totalCounter}`);
I'm using this in a Cloud HTTP function where I can submit a large amount of data and have each one fill up a collection.
Comments
Thank you, Peter; this was helpful and solved my problem.