【问题标题】:Get all documents from Firestore Collection using Firebase Functions使用 Firebase 函数从 Firestore 集合中获取所有文档
【发布时间】:2020-11-02 01:20:24
【问题描述】:

我试图在我的 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.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    通过使用从 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});
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 2021-05-09
      • 2020-08-08
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 2021-03-27
      • 2021-07-29
      相关资源
      最近更新 更多