我可以向 Cloud Firestore 服务器时间戳添加天数吗?

jqu*_*rtz 5 firebase react-native google-cloud-firestore

我正在编写一个 React Native 应用程序,为具有创建日期字段以及 Firestore 中过期日期的用户创建优惠券。过期日期是创建日期加上一些天数(例如 7)

理想情况下,我想在我的 firebase 函数中使用 firestore.FieldValue.serverTimestamp() 来创建日期,并为此添加 7 天作为到期时间,以避免用户生成日期。

有办法做到这一点吗?

Cri*_*zúa 5

遇到了同样的问题,下面的代码似乎可以工作。

 const expiresIn = 7200
 const createdAt = admin.firestore.Timestamp.now().toDate()
 createdAt.setSeconds(createdAt.getSeconds() + expiresIn);
 admin.firestore.Timestamp.fromDate(createdAt)
Run Code Online (Sandbox Code Playgroud)


Fra*_*len 1

当您告诉 Firestore 写入服务器时间戳时,它会执行以下操作:写入服务器的时间戳。无法为此操作指定偏移量。

这意味着您有两种选择:

  1. 将偏移量写入同一文档中的单独字段。因此,您最终会在文档中得到两个字段:createdAtexpiresInDays
  2. 读回服务器时间戳并更新它。这通常是您在创建文档时在 Cloud Functions 中执行的操作functions.firestore.document('users/{userId}').onCreate((snap, context)