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

更新Firebase Admin SDK后serverTimestamp()未定义问题求助

问题描述

配置了一个Firebase可调用云函数,使用Node.js版Admin SDK向Firestore写入数据,代码如下:

const admin = require('firebase-admin');
const functions = require("firebase-functions");

exports.myFunction = functions.https.onCall(async (data, context) => {
    await admin.firestore().doc("/test").create({
        timestamp: admin.firestore.FieldValue.serverTimestamp()
    });
})

当前依赖包版本:

"firebase-admin": "^11.2.1",
"firebase-functions": "^4.0.2",
"firebase-tools": "11.16.0"

使用模拟器测试时,日志出现错误:

TypeError: Cannot read properties of undefined (reading 'serverTimestamp')

该问题在更新Admin SDK和firebase-tools至上述版本后出现,已尝试重新安装但未解决。

排查与解决方法
  • 显式初始化Admin SDK:新版本Admin SDK在云函数模拟器环境中可能需要显式初始化,否则admin.firestore()相关API可能未正确加载。修改代码添加初始化逻辑:

    const admin = require('firebase-admin');
    const functions = require("firebase-functions");
    
    // 避免重复初始化
    if (!admin.apps.length) {
      admin.initializeApp();
    }
    
    exports.myFunction = functions.https.onCall(async (data, context) => {
        await admin.firestore().doc("/test").create({
            timestamp: admin.firestore.FieldValue.serverTimestamp()
        });
    })
    
  • 调整FieldValue引用方式:尝试直接从firestore模块导入FieldValue,避免路径引用问题:

    const admin = require('firebase-admin');
    const { FieldValue } = require('firebase-admin/firestore');
    const functions = require("firebase-functions");
    
    if (!admin.apps.length) {
      admin.initializeApp();
    }
    
    exports.myFunction = functions.https.onCall(async (data, context) => {
        await admin.firestore().doc("/test").create({
            timestamp: FieldValue.serverTimestamp()
        });
    })
    
  • 彻底清理并重装依赖:删除旧的依赖缓存和锁文件,重新安装确保依赖完整:

    rm -rf node_modules package-lock.json
    npm install
    
  • 升级firebase-tools版本:当前使用的firebase-tools@11.16.0可能与firebase-admin@11.2.1存在兼容性问题,升级到最新稳定版:

    npm install -g firebase-tools@latest
    
  • 重启Firebase模拟器:模拟器可能存在缓存或启动异常,停止后重新启动:

    firebase emulators:stop
    firebase emulators:start
    

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:05:20