【问题标题】:Get timestamp field from snapshot as Timestamp inside Cloud Function Triggers从快照中获取时间戳字段作为 Cloud Function Triggers 中的时间戳
【发布时间】:2019-06-28 12:10:23
【问题描述】:

在打字稿中,我可以使用 Cloud Functions Triggers 中的 change.after.updateTime 或 snap.createTime 来创建包含 createdAt、updatedAt 等字段的文档。

但在 onUpdate 等其他触发器中,假设存储时间戳的字段 change.after.data().updatedAt 给了我一个对象。

如果我不能将它们作为时间戳值,我该如何比较它们?我怎样才能将字段作为时间戳值?谢谢

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


export const setCreatedAt = functions.firestore.document('path')
    .onCreate(async (snap, context) => {

        return snap.ref.update({
            createdAt: snap.createTime, // Type Timestamp
            updatedAt: snap.createTime // Type Timestamp
        });

    });

export const setUpdatedAt = functions.firestore.document('path')
    .onUpdate(async (change, context) => {

        let beforeTimestamp = change.before.data().updatedAt; // Type object, not Timestamp
        let afterTimestamp = change.after.data().updatedAt; // Type object, not Timestamp

        console.log('beforeTimestamp', beforeTimestamp);
        console.log('afterTimestamp', afterTimestamp);

        if (change.before.data().updatedAt === change.after.data().updatedAt) {
            change.after.ref.update({
                updatedAt: change.after.updateTime, // Type Timestamp
            });
        }
    });

下图显示了更新时的日志。

看起来{ timestampsInSnapshots: true } 设置无效,因为我在控制台内仍然有警告。但为什么呢?

存储在 Firestore 中的 Date 对象的行为将会改变 并且您的应用程序可能会中断

【问题讨论】:

  • 请注意,在 v0.20.0 之后,googleapis/nodejs-firestore timestampsInSnapshots 设置默认为 true。所以你不需要再显式设置它了。

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


【解决方案1】:

需要将返回的 Timestamp 对象转换为 Date 对象:

beforeTimestamp.toDate()

然后您可以将 Date 对象与< and > 运算符进行比较。如果您需要比较是否相等,则需要先将日期转换为数字:beforeTimestamp.toDate().getTime()

【讨论】:

  • 这正是我的问题,.toDate 不是函数,因为变量是Type object, not Timestamp
  • 您需要注意 change.before 和 change.after 都是可选属性(它们可能未定义)。 createTime 属性也是如此。
  • 这里它们不是未定义的,当我使用 typeof change.before.data().updatedAt 时,它返回object。它应该是时间戳...
  • 是的,因为就 javascript 而言,它只是 object。试试这个:class Foo {}; a = new Foo(); typeof(a); 它将返回 object。
  • 是的,我想我同意你的看法。但它必须是 Timestamp 类型才能具有 .toDate() 函数参考:firebase.google.com/docs/reference/android/com/google/firebase/…。我认为问题在于 timestampsInSnapshot 在这里不起作用。 (例如在我的代码中snap.createTime 的类型是时间戳。)
猜你喜欢
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多