【问题标题】:Adding a Timestamp to a nested object in Cloud Firestore向 Cloud Firestore 中的嵌套对象添加时间戳
【发布时间】:2020-04-03 18:44:42
【问题描述】:

我正在尝试将嵌套元素上的时间戳字段设置为当前时间:

docRef.update({
   arrayOfStuff: {
        id: 123,
        dateAdded: admin.firestore.FieldValue.serverTimestamp()
   }
})

我得到错误:

FieldValue.serverTimestamp() cannot be used inside of an array

使用 Date.now() 得到一个 int 值,而不是时间戳。

尝试Firestore.Timestamp.fromDate() 会产生错误:

TypeError: date.getTime is not a function
    at Function.fromDate (/srv/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/timestamp.js:108:42)
    at firestoreDB.doc.get.then.site (/srv/index.js:32:45)

index.js 的第 32 行是:

let now = admin.firestore.Timestamp.fromDate(Date.now());

想法?

【问题讨论】:

  • 所以我决定继续使用:let now = admin.firestore.Timestamp.now() 它在 Firestore 中产生一个“时间戳”值。我怀疑不同之处在于我得到的时间戳来自代码运行时,而不是 serverTimestamp() 我认为是数据实际存储在 Firestore 中的时间(两次之间可能存在延迟)。

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


【解决方案1】:

正如here 解释的那样,“如果不对 Firestore 的工作方式进行重大改革,就无法在阵列内部支持FieldValue.serverTimestamp”。所以这种行为是意料之中的。

再搜索一下,我找到了 Renaud Tarnec 的 workaround。尽管他提到您可能需要更改数据模型。

我希望这会有所帮助。

【讨论】:

  • 查看here 一种可能的解决方法,使用云函数和包含时间戳的文档(不是数组)中的字段。
猜你喜欢
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2013-11-07
相关资源
最近更新 更多