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

查询Firestore得到文档对象后无法访问其中字段数据该如何解决

问题核心原因

你的代码存在三个关键错误,导致无法正常拿到字段值:

  • Firestore 的 get() 是异步方法,返回值为 Promise 而非直接的查询结果,你没有等待异步请求完成就直接访问属性,拿到的只是未完成的 Promise 对象,自然不存在你要的字段。
  • where() 条件查询返回的是 QuerySnapshot 集合快照,哪怕只有一条匹配结果,也需要先从 docs 数组中取出对应文档对象,才能调用 data() 读取字段。
  • 查询逻辑硬编码了 user 字段的匹配值,没有使用传入的 helperId 参数,参数传递完全无效。

修正后的代码

1. 调整查询函数

// 函数添加async标识,支持await异步等待
async function getHelperToken(helperId) {
    const tokensRef = db.collection('tokens');
    // 等待异步查询返回,同时使用传入的helperId作为查询条件
    const querySnapshot = await tokensRef.where('user', '==', helperId).get();
    if (querySnapshot.empty) {
        functions.logger.log('helper_token EMPTY');
        return null;
    }
    // 取第一条匹配文档,读取字段值
    const targetDoc = querySnapshot.docs[0];
    const deviceToken = targetDoc.data().device_token;
    functions.logger.log('helper_token=' + deviceToken);
    return deviceToken;
};

2. 调整触发器逻辑

调用异步函数时需要添加 await 等待返回结果,同时触发器回调函数要添加 async 标识:

exports.sendHelperInvitation = functions.database.ref('/HelpersInvitations/{helper_invitation_id}')
    // 回调函数添加async标识
    .onCreate(async (snapshot, context) => {
        const helperId = snapshot.val().helperId;
        const title = snapshot.val().title;
        const body = snapshot.val().body;
        
        functions.logger.log('HelperID=' + helperId);
        // 等待异步查询返回结果
        const helper_token2 = await getHelperToken(helperId);
        functions.logger.log('getHelperToken=' + helper_token2);

        // 无有效token直接终止流程
        if (!helper_token2) {
            functions.logger.log('无有效设备token,取消推送');
            return null;
        }
        
        const payload = {
            notification: {
                title: title,
                body: body,
                icon: 'default',
                click_action: 'com.skillblaster.app.helperinvitationnotification' 
            }
        }
        
        functions.logger.log('helper_token [BEFORE sendToDevice]=' + helper_token2);
        return admin.messaging().sendToDevice(helper_token2, payload);
    });

补充说明

如果业务中同一个用户可能对应多条 token 记录,你可以遍历 querySnapshot.docs 数组批量获取所有 token,再调用推送接口批量发送。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:54:05