【问题标题】:Batch 500 writes into firestore loop from json file批处理 500 从 json 文件写入 firestore 循环
【发布时间】:2020-06-21 11:55:09
【问题描述】:

使用我从thread 获得的一些灵感并回复我试图让我的循环工作,即批量写入 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);

【问题讨论】:

    标签: node.js firebase google-cloud-firestore firebase-admin


    【解决方案1】:

    在每次迭代时都会执行以下行,这基本上会在每一轮中“重置”您的批次:

    batches[commitCounter] = db.batch();
    

    所以最后你的每个批次将只包含一个文档写入。

    【讨论】:

    • 非常感谢!我已经太盲目了。改代码后我明天接受你的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 2023-03-23
    • 2023-04-08
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多