提问者:小点点

Firebase,Cloud函数,根据日期更改值


我有与值‘日期’与时间戳格式的协商集合(10月21号凌晨1:00:00 UTC+1)。我有的另一个值是“status”(true/false)

每个时间戳都有相同的时间,它都是UTC+1凌晨1:00:00。

我想设置“状态”为假,如果日期是明天或它已经走了。

下面是我尝试自己做的云功能:

exports.scheduledFunction = functions.pubsub
  .schedule("* 1 * * *")
  .timeZone("Europe/Prague")
  .onRun(async () => {
    const tommorow = new Date().getTime() + 24*60*60;

    await firebase.firestore
      .collection("consultations")
      .where("date" '==' tommorow)
      .set((status: false), { merge: true });
  });


共2个答案

匿名用户

您可以使用JS的本机date对象来查询timestams。

async function updateListingsByDate(operator, date) {
  await firebase.firestore
    .collection("consultations")
    .where('date', operator, date)
    .set((status: false), { merge: true });
}

因此,您可以使用以下方法更新明天发生的列表:

async function updateTomorrow() {
  const tomorrow = new Date();
  const tmp = tomorrow.getDate() + 1;
  tomorrow.setDate(tmp);

  return updateListingsByDate('==', tomorrow);
}

并以类似方式更新今天之前发生的列表:

async function updatePastDates() {
  return updateListingsByDate('<', new Date());
}

匿名用户

您正在将Firestore时间戳存储在数据库中。

您共享的代码有两个问题:

>

  • 您的ToMorow变量是一个数字(自纪元以来的毫秒数)。由于您将日期/时间存储在Firestore中,所以您试图将一个数字与日期/时间进行比较,这将永远不会匹配。

    由于存储的是日期/时间,因此获取一天的文档是一个范围操作。您想要日期/时间A和日期/时间B之间的所有文档。

    null

    const nowTimestamp = Date.now();
    const now = new Date(nowTimestamp);
    const tommorow = new Date(nowTimestamp + 24*60*60*1000);
    
    firebase.firestore
      .collection("consultations")
      .where("date", '>=', now)
      .where("date", '<', tomorrow)
    

    null

    1. 执行查询以获取与其匹配的文档。
    2. 循环遍历代码中的文档。
    3. 依次更新每个文档。

    有关这方面的更多信息,我建议查看:How to use where and update