首页 > 解决方案 > 使用管理 SDK 保存 firebase 时间戳值

问题描述

我想将日期保存为 firebase 时间戳格式。我正在使用管理 SDK 在 cloudFunctions 中执行此操作。

这是我正在尝试的:

deactivationDate: moment().toDate(),
deactivationDate1:  new Date(),
deactivationDate2 : admin.firestore.Timestamp.fromDate(new Date()),

当我在客户端检索此记录时,我得到:

deactivationDate: {_seconds: 1597421671, _nanoseconds: 993000000}
deactivationDate1: {_seconds: 1597421671, _nanoseconds: 993000000}
deactivationDate2: {_seconds: 1597421671, _nanoseconds: 993000000}

我想知道为什么它会发送给我_seconds and _nanoseconds(带下划线)

由于_我认为,我无法将此值转换为日期。

标签: firebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


我能够以毫秒的形式获得正确的时间戳值。

问题是我在从我的云函数中检索时没有将其转换为 Millis()。

我有一个云功能检索这样的用户:

    admin
              .firestore()
              .collection("users")
              .where(query)
              .get();    
    const propertyIdUsers: FirebaseFirestore.DocumentData[] = [];
                propertyIdUsersSnapshot.forEach((p) => {
                  const userDoc = p.data();
                  propertyIdUsers.push({
                    ...userDoc,
                    createdAt: userDoc.createdAt?.toMillis(),
                    updatedAt: userDoc.updatedAt?.toMillis(),
                    deactivationDate: userDoc.deactivationDate?.toMillis(), // I needed to convert toMillis() right here before going to client. 
// This way client receives milliseconds that will work with moment js. 
                  });
                });

感谢@Frank van Puffelen 将我重定向到该解决方案的评论。


推荐阅读