【问题标题】:how to update all my document every day in firestore using cloud function如何使用云功能每天在 Firestore 中更新我的所有文档
【发布时间】:2020-01-24 20:05:22
【问题描述】:

我在 android studio 中构建了一个待办事项列表应用程序,将任务保存在 firestore 中,我给每个人列出了截止日期,我想每天早上检查是否达到最后期限,我试图用云来做,问题是我找不到如何获取特定路径中的所有文档并进行一些检查和重写更改

我下载了node.js并初始化了firebase,我也尝试在控制台中这样做,但它没有这个选项

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();
// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions

 exports.scheduledFunctionCrontab = functions.pubsub.schedule('0 0 6 * *')
//  .timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
  .onRun((context) => {

const overdueSnap = admin.firestore().collection('tasks')
  .where('overdue','==',false)
  .where('due_time', '=<', new Date()).getTime();

await Promise.all(overdueSnap.docs.map((doc) => doc.ref.update({color: true}));

console.log('This will be run every day at 6 AM Eastern!');
return null;

});

【问题讨论】:

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


    【解决方案1】:

    您的问题有点含糊,但听起来您想要做的是查询所有过期的文档并更新它们。我假设您将到期日期存储为Timestamps 在due_time 字段中,并且您希望在任务过期时将overdue 字段标记为true。你可以这样做:

    exports.scheduledFunctionCrontab = functions.pubsub
      .schedule('0 0 6 * *')
      .onRun(async (context) => {
         const overdueSnap = await admin.firestore().collection('tasks')
           .where('overdue','==',false)
           .where('due_time' '<=', new Date()).get();
    
         await Promise.all(overdueSnap.docs.map((doc) => doc.ref.update({overdue: true}));
      });
    

    此代码执行以下操作:

    1. 查找过去带有due_time 且尚未将overdue 标记为true 的所有文档。
    2. 并行更新每个文档,将 overdue 设置为 true。

    您的具体情况可能有所不同,但这是解决您所描述问题类型的一般方法。

    【讨论】:

    • 是的,这正是我想要的,但它给了我一个错误的错误:Unexpected token Promise,我更新了我的代码
    • 你需要确保函数是async——我更新了我上面的代码以获得更多的上下文。
    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2021-02-13
    • 2018-05-19
    • 2020-02-08
    • 2020-02-01
    相关资源
    最近更新 更多