Firebase第二代云函数报错:TypeError: Cannot read properties of undefined (reading 'value')
从Firebase第一代云函数切换到第二代时出现报错,相关代码、错误信息及package.json配置如下:
原代码
const {onDocumentCreated} = require("firebase-functions/v2/firestore"); exports.totalGroup = onDocumentCreated( {region: "asia-southeast2"}, "tallyscan/{id}", async (event)=>{ console.log("get event data"); const snapshot = event.data(); const id = event.params.id; console.log(snapshot); console.log(id); });
报错信息
TypeError: Cannot read properties of undefined (reading 'value')
at func (/workspace/node_modules/firebase-functions/lib/v2/providers/firestore.js:297:115)
at /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/function_wrappers.js:113:25
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
package.json配置
{ "name": "functions", "description": "Cloud Functions for Firebase", "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "shell": "firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "18" }, "main": "index.js", "dependencies": { "exceljs": "^4.4.0", "firebase-admin": "^12.1.0", "firebase-functions": "^5.0.1" }, "devDependencies": { "eslint": "^8.15.0", "eslint-config-google": "^0.14.0", "firebase-functions-test": "^3.1.0" }, "private": true }
解决方案
报错原因是第二代Firestore触发器的参数格式错误:第二代API要求将区域配置和文档路径合并到同一个配置对象中,而非分开传递。
修正后的代码:
const {onDocumentCreated} = require("firebase-functions/v2/firestore"); exports.totalGroup = onDocumentCreated( { region: "asia-southeast2", document: "tallyscan/{id}" }, async (event)=>{ console.log("get event data"); const snapshot = event.data(); const id = event.params.id; console.log(snapshot); console.log(id); });
说明:第二代云函数的onDocumentCreated仅接受两个参数——包含所有配置项的对象,以及触发时执行的回调函数。文档路径需要放在配置对象的document字段中,之前分开传递参数的写法会导致触发器内部无法正确解析路径,从而抛出Cannot read properties of undefined (reading 'value')错误。
内容的提问来源于stack exchange,提问作者marendra

