如何用Node.js Cloud Function将复杂JSON Webhook内容写入Cloud Firestore
解决方案
你要提取嵌套JSON的字段,直接通过JavaScript对象的点语法链式访问即可,Cloud Functions的Express运行时已经自动将Webhook POST的JSON payload解析到req.body对象中,无需额外手动解析。
调整步骤
- 首先补充缺失的payload获取逻辑,你现有代码中的
data变量未定义,需要从req.body获取请求数据 - 访问嵌套字段直接使用
[父字段].[子字段]的格式即可,你示例中people下的id字段取值写法为req.body.people.id - 建议添加请求方法校验、可选链、异常捕获逻辑,避免字段缺失或请求类型错误导致函数报错
完整可运行示例代码
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.webhook = functions.https.onRequest(async (req, res) => { // 只允许POST请求 if (req.method !== 'POST') { return res.status(405).send('Method Not Allowed'); } try { const payload = req.body; // 提取字段示例 await admin.firestore().collection("testCollection").doc().set({ rootId: payload.id, // 根层级的id字段 peopleId: payload.people?.id, // 嵌套在people下的id字段,可选链避免people不存在时报错 // 如果要直接保存整个people嵌套对象,直接写下面这行即可,Firestore会自动存为Map类型 // people: payload.people }); return res.status(200).send('Data saved successfully'); } catch (error) { console.error('Error saving data:', error); return res.status(500).send('Internal Server Error'); } });
更深层级嵌套的取值示例
如果你的JSON结构为多层嵌套,比如:
{ "id": "1", "people": { "id": "1", "contact": { "phone": "13xxxxxxxxx", "email": "test@example.com" } } }
要获取邮箱字段的写法为payload.people.contact.email。
内容的提问来源于stack exchange,提问作者Stephen Stilwell
相关产品推荐
相关产品推荐

