【问题标题】:Cloud function -> comparing timestamps云函数 -> 比较时间戳
【发布时间】:2019-02-26 12:44:37
【问题描述】:

我正在尝试创建一个云函数,其中该函数删除“eindTijd”(结束时间)时间戳比现在旧的“链接”集合中的每个项目。

该函数在每次数据库写入时都会执行,并且根本没有给我任何错误,但只是没有做我打算做的事情。快把我逼疯了!

我怀疑错误出在 oldItemsQuery 中,但无法找出问题所在。任何帮助将不胜感激!

“eindTijd”字段是使用 Date 函数生成的,并且在 Firestore 中被识别为有效的时间戳。

  'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const firestore = admin.firestore();
const settings = {timestampsInSnapshots: true};
firestore.settings(settings);

exports.verwijderOudeNodes = functions.firestore
.document('/links/{pushId}')
.onWrite(() => {
  const now = Date.now();
  let oldItemsQuery = firestore.collection('links').where('eindTijd', '<=', now);
  return oldItemsQuery.get().then((snapshot) => {
    // create a map with all children that need to be removed
    let batch = firestore.batch();
    snapshot.forEach(child => {
      batch.delete(child.ref);
    });
    // execute all updates in one go and return the result to end the function
    return batch.commit();
  });
});

【问题讨论】:

  • 您是否尝试使用 return oldItemsQuery.get().then((snapshot) =&gt; {console.log(snapshot.size); .... 记录 QuerySnapshot 的大小?
  • 当您遇到此类问题时,请始终首先尝试在独立节点脚本中重现该问题。如果你能重现同样的问题,你就知道它与 Cloud Functions 无关。如果您无法独立复制它,您知道它与 Cloud Functions 相关。

标签: javascript firebase google-cloud-firestore firebase-admin


【解决方案1】:

我不确定您传递now 的方式是否正确。基于Firebase documentation on writing its various data types,我希望:

const now = admin.firestore.Timestamp.fromDate(new Date())

【讨论】:

  • 就是这样做的!非常感谢您,先生。
  • 或者你可以直接传递new Date(),它会自动转换为时间戳。
  • @Doug:我想知道这一点,但后来看到文档包含这个更复杂的示例。听起来我们应该在那里添加更多样本。 :)
猜你喜欢
  • 2021-07-11
  • 2012-07-09
  • 1970-01-01
  • 2016-07-26
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
相关资源
最近更新 更多