I want to create a new collection and add thousands of documents sized ~ 1-2K to it. I already have data in json so I thought this would be easy.
I understand that b
You're creating a single batch for all writes at the top level of your program. It's getting reused for all the calls to batch.set()
that you make for all your batch writes.
var batch = db.batch();
Instead, you should create a new batch for each set of writes. You can do that at the top of your while loop:
while(lc<=tc) {
var batch = db.batch();
// use the new batch here
}
This works for me:
function loadJson(){
var ref = firebase.firestore().collection("my-parent-collection-name");
getJSON("https://my-target-domain.com/my-500-plus-objects-file.json").then(function (data) {
var counter = 0;
var commitCounter = 0;
var batches = [];
batches[commitCounter] = db.batch();
Object.keys(data).forEach(function(k, i) {
if(counter <= 498){
var thisRef = ref.doc(k);
batches[commitCounter].set(thisRef, data[k]);
counter = counter + 1;
} else {
counter = 0;
commitCounter = commitCounter + 1;
batches[commitCounter] = db.batch();
}
});
for (var i = 0; i < batches.length; i++) {
batches[i].commit().then(function () {
console.count('wrote batch');
});
}
}, function (status) {
console.log('failed');
});
}
loadJson();