firebase.firestore.FieldValue.serverTimestamp()不支持Timestamp数据类型

时间:2019-11-02 17:39:53

标签: angular typescript firebase google-cloud-firestore

 async createUser(uid: string, email: string) {
    await this.afs.doc<UserProfileModel>(FirestoreDbConstant.USER_PROFILES + `/${uid}`).set({
      email,
      createdDate: firebase.firestore.FieldValue.serverTimestamp(),
    });
  }

此模型有效

export interface UserProfileModel {
    email: string;
    createdDate?: firebase.firestore.FieldValue;
}

但是为什么我不能像这样在这里使用Timestamp

import { Timestamp } from '@firebase/firestore-types';

export interface UserProfileModel {
    email: string;
    createdDate?: Timestamp;
}

然后给出此错误:

  

(属性)UserProfileModel.createdDate ?:时间戳记类型“ FieldValue”   缺少“时间戳”类型的以下属性:秒,   纳秒,toDate,toMillists(2739)user-profile.model.ts(11,5):   预期的类型来自声明的属性“ createdDate”   在这里输入'UserProfileModel'

这里的问题是我需要在模板上使用toDate()。但这不适用于createdDate?: firebase.firestore.FieldValue;

<p>{{invitedEvent.startDatetime.toDate() | amDateFormat: 'MMM DD'}}</p>

2 个答案:

答案 0 :(得分:2)

这可能比“任何”或复制模型更好:

lastModified: Timestamp | FieldValue;

答案 1 :(得分:1)

JavaScript API documentation for serverTimestamp()中可以看到:

  

serverTimestamp():FieldValue

     

返回与set()或update()一起使用的哨兵,以包括   服务器在写入的数据中生成的时间戳。

     

返回字段值

它不返回时间戳类型。它返回一个FieldValue,其值实际上只是一个特殊值的占位符,该值告诉服务器生成时间戳。客户端根本不会生成此时间戳,因为我们无法信任客户端设备的时钟。

这意味着您不能真正使用相同的模型来读取和写入使用服务器时间戳记的记录。在即将到来的时候,它将是一个FieldValue。在出门时(当您查询文档时),它将是时间戳记。