第 500 批从 json 文件写入 firestore 循环

Batch 500 writes into firestore loop from json file

使用我从中获得的一些灵感 并回复我试图让我的循环工作,即批量写入 firestore。但是不知何故,即使我可以看到我遍历数组中的不同值,我也只能更新 1 个文档。我将数据加载到数组中并从那里开始工作。

const db = admin.firestore();
const jsonStream = StreamArray.withParser();

let arr = []
jsonStream.on('data', ({ key, value }) => {
    arr.push(value);
});

jsonStream.on('end', () => {

    var counter = 0;
    var commitCounter = 0;
    var batches = [];

    arr.forEach((a, ind) => {
        batches[commitCounter] = db.batch();
        if (counter <= 498) {
            var thisRef = db.collection('Testing').doc(a.id);
            console.log("id")
            console.log(a.id);
            batches[commitCounter].set(thisRef, { ...a });
            counter = counter + 1;
        } else {
            counter = 0;
            commitCounter = commitCounter + 1;
            batches[commitCounter] = db.batch();
        }
    })
    for (var i = 0; i < batches.length; i++) {
        if(i==0)
        {
            console.log(batches[0])
        }
        batches[i].commit().then(function () {
            console.count('wrote batch');
        });
    }
});

const filename = path.join(__dirname, 'mydata.json');
fs.createReadStream(filename).pipe(jsonStream.input);

每次迭代都会执行以下行,这实际上是 "resets" 每一轮的批次:

batches[commitCounter] = db.batch();

因此最后您的每个批次将只包含一个文档写入。