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

在Cloud Functions中用TypeScript获取Firebase Firestore文档单个字段

解答
  • 场景1:仅需要使用触发当前函数的新建订单文档的指定字段
    你不需要额外调用get()方法主动拉取数据,触发器触发时传入的snapshot参数已经包含了当前文档的全部数据,直接调用get()方法传入目标字段名即可取值:
export const onNewOrder = functions.firestore.document("/orders/{orderId}").onCreate(async (snapshot, context) => {
  // 直接从触发快照中取指定字段,示例中要取的字段为totalPrice
  const targetFieldValue = snapshot.get('totalPrice');
  console.log(targetFieldValue);
});
  • 场景2:需要主动拉取任意文档的指定字段
    Firestore Admin SDK提供了select()方法用来指定需要返回的字段,多个字段用逗号分隔即可,仅返回你指定的字段内容,不会拉取文档的其他数据,调用位置放在get()之前即可:
export const onNewOrder = functions.firestore.document("/orders/{orderId}").onCreate(async (snapshot, context) => {
  const orderId = context.params.orderId;

  // select参数为你要拉取的目标字段,可传入多个
  const snap = await admin.firestore().collection("orders").doc(orderId).select('totalPrice', 'userId').get();
  // 取值同样用get方法传入字段名
  const totalPrice = snap.get('totalPrice');
  console.log(totalPrice);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 03:00:03