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

如何在Google Cloud Firestore触发器中获取JSON格式的事件值?

问题描述

我正在使用Google Cloud Firestore Triggers,当Firestore中创建文档时会触发云函数,功能运行正常,但找不到获取无类型定义的常规JSON格式负载的方法。

我的云函数代码如下:

/* Triggered when a comment is created, updated or deleted.
* Trigger resource is: 
* 'projects/myproj/databases/(default)/documents/books/{bookId}'
*/
exports.bookAdded = async (event, context) => {
    let data = event.value;
    console.log(data);
}

打印出的data结构如下:

{
    createTime: '2023-02-22T07:17:31.413935Z',
    fields: {
        title: { stringValue: 'The Breaker' },
        author: { stringValue: 'Don Gold' },
    },
    name: 'projects/myproj/databases/(default)/documents/books/38',
    updateTime: '2023-02-22T07:17:31.413935Z'
}

这里的常规JSON指不含类型信息、仅保留键值对的格式,比如期望得到:{ title: 'The Breaker', author: 'Don Gold' }。

我原本以为Firestore Events文档里的data()方法可用,但实际不行。文档示例中是这样获取数据的:

exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => {
  // Get an object representing the document
  // e.g. {'name': 'Marie', 'age': 66}
  const newValue = snap.data();
  ... 

我需要和这个data()方法等效的实现方式。

解决方案

你当前使用的是Cloud Event 格式的触发器(直接通过event.value获取数据),而文档里的snap.data()是Firebase Functions SDK提供的便捷方法。要实现等效功能,有两种方式:

方式一:使用Firebase Functions SDK重构触发器

如果可以切换到Firebase Functions SDK,直接用官方提供的onCreate等触发器,就能直接调用snap.data()获取无类型的JSON:

const functions = require('firebase-functions');

exports.bookAdded = functions.firestore
  .document('books/{bookId}')
  .onCreate((snap, context) => {
    const regularJson = snap.data(); // 直接得到{ title: 'The Breaker', author: 'Don Gold' }
    console.log(regularJson);
    // 后续逻辑
  });

方式二:手动解析Cloud Event的fields字段

如果必须保留当前的Cloud Event格式触发器,可以手动遍历fields,提取对应的值。针对常见的Firestore数据类型(stringValue、integerValue、booleanValue等),可以写一个解析函数:

exports.bookAdded = async (event, context) => {
    const fields = event.value.fields;
    // 解析函数:提取每个字段的实际值
    const parseFirestoreFields = (fieldsObj) => {
        const result = {};
        for (const key in fieldsObj) {
            const field = fieldsObj[key];
            // 遍历字段的属性,找到带Value后缀的键(比如stringValue)
            const valueKey = Object.keys(field).find(k => k.endsWith('Value'));
            result[key] = field[valueKey];
        }
        return result;
    };

    const regularJson = parseFirestoreFields(fields);
    console.log(regularJson); // 输出{ title: 'The Breaker', author: 'Don Gold' }
};

这个解析函数可以处理大多数基础数据类型,如果需要支持嵌套对象或数组,可以扩展逻辑(比如处理mapValue或arrayValue)。


内容的提问来源于stack exchange,提问作者jola

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:45:38