Firebase Cloud Function无法获取userId与tweetId问题求助
问题排查:Firestore onCreate触发器中context.params参数为undefined
核心原因
onCreate触发器的参数签名错误,导致无法正确获取上下文参数。onCreate的第一个参数是新增文档的快照(snapshot),而非change(change是onUpdate/onWrite触发器的专属参数)。你当前把第一个参数写为change,导致第二个参数context并非正确的上下文对象,因此context.params返回undefined。
修复方案
修正触发器参数签名
将onCreate的第一个参数改为snapshot,保留第二个参数context:const admin = require('firebase-admin') admin.initializeApp() const db = admin.firestore() const functions = require("firebase-functions"); functions.logger.log("START OF FUNCTION"); exports.myFunction = functions.firestore .document('timelines/{userId}/tweets/{tweetId}') .onCreate((snapshot, context) => { // 替换change为snapshot const userId = context.params.userId const tweetId = context.params.tweetId functions.logger.log(userId); functions.logger.log(tweetId); return db.doc(`/timelines/${userId}/tweets/${tweetId}`).update({likeCount: 200}) })补充异步操作返回值
Cloud Functions需要通过返回Promise来确认异步操作完成,否则函数可能在数据库更新前被强制终止。上述代码中直接返回update方法的Promise(update本身会返回Promise),确保操作完整执行。
额外验证
确认iPhone应用新增的Tweet确实写入到timelines/{实际用户ID}/tweets/{实际推文ID}路径下,路径结构必须与触发器定义的完全一致,否则即使参数签名正确,context.params也无法正确提取值。
内容的提问来源于stack exchange,提问作者john doe
相关产品推荐
相关产品推荐

