Firebase Cloud Functions部署报错:functions.firestore.document不是函数
问题描述
我编写了如下Google Cloud Function:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.sendMessageNotification = functions.firestore .document('<path>') .onCreate( async (snapshot, context) => { console.log("onCreate pozvan"); const buildingId = context.params.buildingId; const data = snapshot.data(); const title = String(data.title); const text = String(data.text); console.log("buildingId = " + buildingId); console.log("title = " + title); console.log("text = " + text); const message = { notification: { title: title, body: text, }, topic: buildingId, }; console.log("notification = " + message); try { const response = await admin.messaging().send(message); console.log('❤️:', response); return { success: true, response: response }; } catch (error) { console.error('☠️ Error', error); throw new functions.https.HttpsError('internal', 'Error: ', error); } } );
此前执行firebase deploy部署正常,但现在部署时出现以下错误:
TypeError: functions.firestore.document is not a function at Object.<anonymous> (/Users/me/flutter_projects/ax/functions/index.js:6:6) at Module._compile (node:internal/modules/cjs/loader:1358:14) at Module._extensions..js (node:internal/modules/cjs/loader:1416:10) at Module.load (node:internal/modules/cjs/loader:1208:32) at Module._load (node:internal/modules/cjs/loader:1024:12) at Module.require (node:internal/modules/cjs/loader:1233:19) at require (node:internal/modules/helpers:179:18) at loadModule (/Users/me/flutter_projects/ax/functions/node_modules/firebase-functions/lib/runtime/loader.js:40:16) at loadStack (/Users/me/flutter_projects/ax/functions/node_modules/firebase-functions/lib/runtime/loader.js:157:23) at /Users/me/flutter_projects/ax/functions/node_modules/firebase-functions/lib/bin/firebase-functions.js:56:56
请问该如何解决这个问题?
解决方法
这个错误的核心原因是firebase-functions版本不兼容,或代码写法未匹配当前安装的库版本。以下是具体修复步骤:
1. 检查并锁定firebase-functions版本
之前部署正常,说明是后续依赖版本更新导致API变化。Firebase Functions v10+对触发器写法有调整,也可能是意外升级到了不兼容版本:
- 查看当前安装版本:
npm list firebase-functions - 若版本过高引发兼容问题,可降级到此前能正常部署的版本(比如v9.x):
npm install firebase-functions@9.2.0 --save
2. 确保firebase-admin与firebase-functions版本匹配
两个库版本不匹配会导致API调用异常,安装对应兼容版本:
npm install firebase-admin@10.0.2 --save
(此版本与functions v9.x兼容,可根据实际情况调整)
3. 验证触发器路径格式
确认<path>是正确的Firestore文档路径格式,若需要获取buildingId参数,路径应写为类似buildings/{buildingId}/notifications/{notificationId}的格式,确保context.params.buildingId能正确取值。
4. 重新安装依赖并清理缓存
若依赖安装损坏,执行以下步骤修复:
- 删除
node_modules文件夹和package-lock.json文件 - 重新安装依赖:
npm install - 重新部署函数:
firebase deploy --only functions
5. 更新Firebase CLI版本
旧版CLI可能不兼容新版functions库,更新到最新版本:
npm install -g firebase-tools
内容的提问来源于stack exchange,提问作者Draško
相关产品推荐
相关产品推荐

