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

Firebase Functions使用v2 Firestore触发器时出现TypeError: Cannot read properties of undefined (reading 'document')错误求助

Firebase Functions使用v2 Firestore触发器时出现TypeError: Cannot read properties of undefined (reading 'document')错误求助

我在部署Firebase Cloud Functions时,一直碰到TypeError: Cannot read properties of undefined (reading 'document')这个错误,虽然我的导入语句和代码看起来都没问题。这个错误是在我尝试用functions.firestore.v2.document(...)定义Firestore触发器的时候出现的。

我的代码

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const axios = require("axios");
const { FieldValue } = require('firebase-admin/firestore');

admin.initializeApp();
const db = admin.firestore();

exports.rahh = functions.firestore.v2.document("user/{userId}").onCreate(async (event) => {
    // ... (这里是我的函数逻辑 - 从Google People API获取数据) ...
});

错误信息

TypeError: Cannot read properties of undefined (reading 'document')
at Object. (C:\path\to\my\functions\index.js:9:39)
... (堆栈跟踪的其余部分) ...

问题核心

尽管我已经正确导入了const functions = require("firebase-functions");,也完成了Firebase Admin SDK的初始化 (admin.initializeApp();),但functions对象上的firestore属性居然是undefined,这直接导致了这个错误。

我已经尝试过的解决方法

  • 重置模拟器:依次执行firebase emulators:stop、firebase emulators:clear、firebase emulators:start --only functions
  • 切换Node版本:用nvm把Node版本切换到了18
  • 模拟器测试:在本地模拟器上运行函数时完全正常,没有报错
  • 重装依赖包:删除了package-lock.json和node_modules文件夹,然后重新执行npm install
  • 更新全局Firebase CLI:执行npm install -g firebase-tools更新了CLI版本
  • 简化代码测试:写了一个只包含简单HTTPS函数的极简index.js,这个版本可以正常部署和运行
  • 检查package.json配置:确认main字段已经正确设置为"index.js"
  • 排查拼写错误:反复检查了导入语句和函数调用的拼写,没有发现问题
  • 排除IDE影响:用记事本编辑index.js,避免IDE的缓存或配置问题干扰

我的package.json配置

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": { /* ... */ },
  "engines": { "node": "18" },
  "main": "index.js",
  "dependencies": {
    "axios": "^1.7.9",
    "firebase": "^11.2.0", // Firebase客户端SDK(可能在functions中不需要)
    "firebase-admin": "^13.0.2",
    "firebase-functions": "^6.3.1"
  },
  "devDependencies": { /* ... */ },
  "private": true
}

环境信息

  • Firebase CLI版本:13.29.3

新建的空白项目使用同样的代码可以正常工作,说明应该是当前项目的配置出了问题,但我实在找不到问题点在哪里。想请教一下,到底是什么原因会导致这个"undefined"错误,我已经尝试了上面所有的排查步骤还是解决不了,求指点!

备注:内容来源于stack exchange,提问作者squarewatermeln

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:53:02