【发布时间】: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