You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级firebase-admin@11后firestore.Timestamp未定义,data()调用报错求助

firebase-admin@11 中 firestore.Timestamp 未定义导致 instanceof 报错的解决方法

升级至firebase-admin@11后,在自定义FirestoreDataConverter中使用lastLoggedAtData instanceof firestore.Timestamp时抛出TypeError: Right-hand side of 'instanceof' is not an object,原因是v11调整了Firestore API的导出结构,firestore.Timestamp不再指向可用的构造函数实例,需要调整导入和类型检查方式。

两种有效解决方案

方案1:直接导入Timestamp类型

从firebase-admin中单独导入Timestamp,替代通过firestore对象访问的方式:

// 修改导入语句
import { firestore, Timestamp } from "firebase-admin";

然后在类型检查时直接使用Timestamp:

if (lastLoggedAtData && lastLoggedAtData instanceof Timestamp) {
  userEntity.lastLoggedAt = DateTime.fromMillis(lastLoggedAtData.toMillis());
}

方案2:使用Timestamp.isTimestamp()静态方法

Firebase提供了静态方法isTimestamp来判断对象是否为Timestamp类型,无需依赖构造函数:

if (lastLoggedAtData && firestore.Timestamp.isTimestamp(lastLoggedAtData)) {
  userEntity.lastLoggedAt = DateTime.fromMillis(lastLoggedAtData.toMillis());
}

修正后的完整Converter代码

同时修正原代码中的笔误(如未实例化UserEntity、变量名错误、取值错误):

import { firestore, Timestamp } from "firebase-admin";
import { DateTime } from "luxon";
import { UserEntity } from "../entities";

export class UserEntityConverter implements firestore.FirestoreDataConverter<UserEntity> {
  toFirestore(modelObject: UserEntity): firestore.DocumentData;
  toFirestore(modelObject: Partial<UserEntity>, options: firestore.SetOptions): firestore.DocumentData;
  toFirestore(modelObject: UserEntity | Partial<UserEntity>, options?: firestore.SetOptions): firestore.DocumentData {
    return {
      balance: modelObject.balance,
      lastLoggedAt: modelObject.lastLoggedAt?.toJSDate() || null,
    };
  }

  fromFirestore(snapshot: firestore.QueryDocumentSnapshot<firestore.DocumentData>): UserEntity {
    const data = snapshot.data();
    const userEntity = new UserEntity();

    userEntity.balance = data.balance;

    const lastLoggedAtData = data.lastLoggedAt;
    if (lastLoggedAtData && lastLoggedAtData instanceof Timestamp) {
      userEntity.lastLoggedAt = DateTime.fromMillis(lastLoggedAtData.toMillis());
    }

    return userEntity;
  }
}

内容的提问来源于stack exchange,提问作者Maksym B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:45:49