【问题标题】:Cloud Function doesn't work - Query and update firestoreCloud Function 不起作用 - 查询和更新 firestore
【发布时间】:2021-08-11 21:19:33
【问题描述】:

以下函数应该从某些文档的字段中接收数据。然后在另一个集合中查询时使用该数据。查询后它应该更新文档。该代码在编辑器中没有给出任何错误,但它不起作用。

export const dailyTaskFunction2 = functions.pubsub
.schedule("0 0 * * *")
.timeZone("Europe/Istanbul")
.onRun(async () => {
  const users = await db
      .collection("users")
      .where("location", "==", "GMT+3")
      .get();
  const taskPromises = users.docs.map((doc) => {
    return db
        .collection("tasks")
        .where("dailyTasks", "==", true)
        .where("completed", "==", true)
        .where("userID", "==", doc.get("userID"))
        .get();
  });
  const taskDocs = await Promise.all(taskPromises);
  const actionsPromises = taskDocs.map((snapshots) => {
    return snapshots.docs.map((snapshot) => {
      return db
          .collection("tasks")
          .doc(snapshot.id)
          .set({completed: false}, {merge: true});
    });
  });
  await Promise.all(actionsPromises);
  return null;
});

【问题讨论】:

    标签: typescript google-cloud-firestore google-cloud-functions


    【解决方案1】:

    我认为问题出在您的语法上。这个想法很明确,但您的实施不正确。

    特别是:

    const taskPromises = users.docs.map((doc) => {
        return db
            .collection("tasks")
            .where("dailyTasks", "==", true)
            .where("completed", "==", true)
            .where("userID", "==", doc.get("userID"))
            .get();
      });
    

    您正在返回多个承诺,这些承诺将返回不同的查询快照,您假装将它们连接到单个数组上。

    为什么不先尝试将 Promise 存储在数组中。也尝试使用.catch() 来处理可能的异常。

     export const dailyTaskFunction2 = functions.pubsub.schedule("0 0 * * *").timeZone("Europe/Istanbul").onRun(async () => {
      const users = await db
          .collection("users")
          .where("location", "==", "GMT+3")
          .get();
    
    
      var taskPromises = []
      var taskDocs = []
    
      users.docs.map((doc) => {
        taskPromises.push(db
            .collection("tasks")
            .where("dailyTasks", "==", true)
            .where("completed", "==", true)
            .where("userID", "==", doc.get("userID"))
            .get().then((snapShot)=>{
                taskDocs = snapShot.concat(snapShot.docs);
                return;
            }))
      });
    
      await Promise.all(taskPromises).catch((e)=>{
        console.log(e)
      });
    
      const actionsPromises = []
      
      taskDocs.map((snapshot) => {
        actionsPromises.push(db
            .collection("tasks")
            .doc(snapshot.id)
            .set({completed: false}, {merge: true}))
      });
    
      return Promise.all(actionsPromises).catch((e)=>{
          console.log(e)
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-03-18
      • 2020-05-28
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      相关资源
      最近更新 更多