Batch write to firebase cloud firestore

后端 未结 2 1676
野的像风
野的像风 2020-12-06 07:18

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

2条回答
  •  再見小時候
    2020-12-06 07:51

    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();
    

提交回复
热议问题