【问题标题】:firestore timestamp in nodejs admin SDKnodejs admin SDK中的firestore时间戳
【发布时间】:2019-11-26 08:22:12
【问题描述】:

我正在尝试将时间戳从 Firestore 转换为 NodeJS 管理 SDK 中的 Date 对象。但我总是收到 toDate() 不是函数的错误。为什么?如何在管理 SDK 中将时间戳转换为 Date 对象?

这是我尝试过的代码。

this.getService.sample()
  .then(doc => {
    const callable = this.fns.httpsCallable('myTestFn');
    const data$ = callable({ text: 'google', arraySize: 10, date: doc.data().date });
    data$.toPromise()
      .then(e1 => {
        console.log(e1);
      }).catch(err => {
        console.log(err);
      })
  });

onCall 函数:

const original = data.text;
    const arraySize: number = data.arraySize;
    if (arraySize > 100) {
        // Throwing an HttpsError so that the client gets the error details.
        throw new functions.https.HttpsError('unknown', 'invalid request,input is above the permistted range!');
    }
    const date = data.date.toDate();
    console.log('--- This is the date---', date);
    const numberArray = [];
    for (let i = 1; i <= arraySize; i++) {
        await numberArray.push(i);
    }
    const sum = await numberArray.reduce((acc, curr) => acc + curr, 0);
    console.log('-----------sum-------------', sum)
    const writeResult = await admin.firestore().collection('messages').add({ original: original,sum, createdAt: admin.firestore.FieldValue.serverTimestamp() });
    return { wish: 'A wish from function', original, writeResult: writeResult.id, numberArray, sum };

【问题讨论】:

    标签: typescript google-cloud-firestore firebase-admin


    【解决方案1】:

    在将值从客户端传递到服务器时,可调用函数不保留数据类型。当您将date: doc.data().date 传递给函数时,您可能会在客户端传递一个 Timestamp 类型的对象,但它不会在函数中显示为 Timestamp 类型的对象。它可能显示为时间戳的序列化版本,它只是一个具有两个属性的对象,秒和纳秒。如果您想将此对象视为时间戳,则必须手动将该对象转换为时间戳。

    【讨论】:

    • 是的,它显示了一个具有秒和纳秒两个属性的对象。但是我可以使用 admin.firestore.Timestamp.fromMilli(milliseconds) 从服务器端创建新的时间戳;
    猜你喜欢
    • 2018-06-10
    • 1970-01-01
    • 2019-05-16
    • 2020-11-17
    • 2021-02-24
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多