【问题标题】:How to add Timestamp in firebase cloud functions如何在 Firebase 云功能中添加时间戳
【发布时间】:2019-06-26 13:45:16
【问题描述】:

我正在尝试在 Firebase Cloud 功能的 Firestore 文档中添加 Timestamp

我试过firestore.Timestamp.fromDate(new Date()),但它不起作用。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firestore = admin.firestore();
const createdAt = firestore.Timestamp.fromDate(new Date());
console.log(createdAt);

createdAt 的值应该返回服务器时间戳,但它的抛出错误。

【问题讨论】:

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


    【解决方案1】:

    而不是这个:

    const firestore = admin.firestore();
    const createdAt = firestore.Timestamp.fromDate(new Date());
    

    试试这个:

    const firestore = admin.firestore;
    const createdAt = firestore.Timestamp.fromDate(new Date());
    

    可能很难发现差异。所以这里是解释: 您正在调用对象“admin”的函数“firestore()”,而不是访问具有您正在寻找的属性“Timestamp”的对象“admin”的属性“firestore”。

    【讨论】:

      【解决方案2】:

      这行代码有语法错误。它不是有效的 JavaScript:

      const createdAt: firestore.Timestamp.fromDate(new Date());
      

      看来你是要写这个的:

      const createdAt = firestore.Timestamp.fromDate(new Date());
      

      【讨论】:

      • 对不起,我尝试了const createdAt = firestore.Timestamp.fromDate(new Date());,但它仍然无法正常工作。
      【解决方案3】:

      我个人使用const timestamp = new Date().getTime(); 然后将其保存到 firstore 文档中,它就可以工作了。

      【讨论】:

        【解决方案4】:

        当专门使用云函数挂钩functions.auth.user().onCreate((user) => {}) 时,我使用user.metadata.creationTime 来获取确切的创建时间,而不必考虑时区和日期/时间问题。

        【讨论】:

          猜你喜欢
          • 2020-03-09
          • 2018-01-14
          • 1970-01-01
          • 2018-12-29
          • 2021-04-26
          • 2017-06-21
          • 2020-12-01
          • 2018-05-17
          • 2019-10-09
          相关资源
          最近更新 更多