【问题标题】:How to update timeStamp field in a firestore document from cloud function?如何从云功能更新 Firestore 文档中的时间戳字段?
【发布时间】:2020-02-08 23:41:38
【问题描述】:

我使用以下代码从云函数更新 Firestore 文档中的 timeStamp 字段:

  exports.updateDateWhenPhotoAdded = functions.firestore
  .document('posts/{postId}')
  .onCreate((snap, context) =>
  {
      const userId = snap.data().userId;

      return db.collection('following').doc(`${userId}`).update({ latestPostTimeStamp: `${snap.data().timeStamp.toDate()}` });

  });

timeStamp 字段的数据类型为 timestamp。但是,执行上述代码后,字段自动转换为字符串数据类型,并且timeStamp updated 不是默认时间戳格式('MMMM dd,yyyy 'at' HH:mm:ss a z' )。如何预防?

【问题讨论】:

    标签: android google-cloud-firestore google-cloud-functions


    【解决方案1】:

    该字段在数据库中显示为字符串,因为您正在传递一个字符串。这就是 JavaScript 中反引号的作用——构建一个字符串。

    如果您想将时间戳从一个文档复制到另一个文档,只需传递原始字段值而不将其转换为字符串。

    return db.collection('following').doc(userId).update({
        latestPostTimeStamp: snap.data().timeStamp
    });
    

    【讨论】:

      【解决方案2】:

      你可以使用这个admin.firestore.FieldValue.serverTimestamp()

      【讨论】:

      • 怎么做?有没有办法将snap.data().timeStamp 传递给该函数?
      • 我认为你不需要传递这个,它已经为你的 firestoreDB 生成了一个服务器时间戳对象,你可以在这里找到更多信息:firebase.google.com/docs/reference/js/…
      猜你喜欢
      • 1970-01-01
      • 2019-08-07
      • 2020-01-09
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 2021-03-27
      相关资源
      最近更新 更多