首页 > 解决方案 > 使用 Firebase 函数从 Firestore 集合中获取所有文档

问题描述

我试图在我的 Firebase 函数中获取一个名为“repeated_tasks”的集合中的所有文档。

我尝试使用以下代码: Is it possible to get all documents in a Firestore Cloud Function? ,但这似乎对我不起作用。我正在尝试获取信息,以便可以更新集合中的每个文档,将一个字段设置为 false。我有以下代码:

exports.finishedUpdate = functions.pubsub.schedule('0 3 * * *').timeZone('Europe/Amsterdam').onRun((context) => {

//  This is part of the above mentioned stack question
    var citiesRef = database.collection('repeated_tasks');
    const snapshot = citiesRef.get();
    snapshot.forEach(doc => {
      console.log(doc.id, '=>', doc.data());
    });

// A way to update all of the documents in the repeated_tasks collection has to be found

//  This part works, for only the two given document ids
    var list = ['qfrxHTZAJZTJDQpA83fjsM03159438695', 'qfrxHTZAJZQTpM3pA83fjsM0315217389'];

    for (var i = 0; i < list.length; i++) {
        database.doc('repeated_tasks/' + list[i]).update({'finished': false});
    }

    return console.log("Done");
})

非常感谢帮助,因为我似乎无法在任何地方找到任何相关信息,除了堆栈溢出页面,它没有帮助。我正在使用 Node JS (Javascript) 来设置功能。

标签: node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


通过使用从 Firestore 获取信息的语法,我还能够在 Firebase Functions 中更新它,并且可以使用以下代码更新所有信息:

    const reference = database.collection('repeated_tasks/');
    const snapshot = await reference.where('finished', '==', true).get();
    if (snapshot.empty) {
        console.log('no matching documents');
        return;
    }

    snapshot.forEach(doc => {
        database.doc('repeated_tasks/' + doc.id).update({'finished': false});
    });

推荐阅读