[英]Can you use firebase-admin.firebase.Timestamp instead of FieldValue.serverTimestamp() in Firebase functions?
[英]firebase.firestore.FieldValue.serverTimestamp() doesn't support Timestamp data type
async createUser(uid: string, email: string) {
await this.afs.doc<UserProfileModel>(FirestoreDbConstant.USER_PROFILES + `/${uid}`).set({
email,
createdDate: firebase.firestore.FieldValue.serverTimestamp(),
});
}
这个 model 工作
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):预期类型来自在类型“UserProfileModel”上声明的属性“createdDate”
这里的问题是我需要在模板上使用toDate()
。 但它不适用于createdDate?: firebase.firestore.FieldValue;
<p>{{invitedEvent.startDatetime.toDate() | amDateFormat: 'MMM DD'}}</p>
正如您从serverTimestamp() 的 JavaScript API 文档中看到的那样:
服务器时间戳():字段值
返回与 set() 或 update() 一起使用的标记,以在写入的数据中包含服务器生成的时间戳。
返回字段值
它不返回 Timestamp 类型。 它返回一个 FieldValue,它的值实际上只是一个特殊值的占位符,它告诉服务器生成时间戳。 客户端根本不生成这个时间戳,因为我们不能信任客户端设备的时钟。
这意味着您不能真正使用相同的 model 来读取和写入使用服务器时间戳的记录。 在进入的过程中,它将是一个 FieldValue。 在出路时(当您查询文档时),它将是一个时间戳。
这可能比“任何”或复制模型更好:
lastModified: Timestamp | FieldValue;
另一种选择是定义您自己的接口,该接口部分扩展 Timestamp 和 FieldValue
export interface MyTimestamp extends Partial<FieldValue>, Partial<Timestamp>
{
isEqual: (other: any) => boolean;
valueOf: () => any;
}
然后您可以将时间戳道具设置为:
export interface UserProfileModel {
email: string;
createdDate?: MyTimestamp;
}
然后,您将获得用于写入和读取到 Firestore 的正确类型
一个警告是所有道具和功能现在都是可选的,所以如果你想在 Timestamp 上调用toDate()
例如你需要使用?
user.createdDate?.toDate?.()
写作:
user.createdDate = FieldValue.serverTimestamp();
阅读:
user.createdDate?.toDate?.();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.