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

Firestore无法正确追加数据:React Native每周调查数据存储问题

解决Firestore嵌套对象更新时的覆盖问题

问题核心:你当前用update(surveyData)的方式,会把整个weeklySurvey字段直接替换成新的嵌套对象,导致之前存储的年月调查数据被全部覆盖。Firestore的update方法如果传入嵌套对象,默认会替换整个上层字段,而非追加子节点。

解决方法:使用点符号路径指定需要更新的具体深层字段,这样只会修改指定的年月日节点,不会影响其他已有的数据。

修改后的代码:

const addWeeklySurveyDataOnFirestore = (email) => {
    const dateObj = new Date();
    const year = dateObj.getFullYear();
    const day = dateObj.getDate();
    const month = dateObj.getMonth() + 1;
    // 构造带点路径的更新对象,仅指向当前年月日的节点
    const surveyData = {
        [`weeklySurvey.${year}.${month}.${day}`]: {
            "Exhause Rate": exhaustLevel,
            "Pain Rate": painRate,
            'Practice Sessions': practiceSessions,
            "Sleep Rate": sleepRate,
        }
    };

    firestore()
        .collection('users')
        .doc(email)
        .update(surveyData)
        .then(() => {
            console.log('用户调查数据已提交!');
        })
        .catch(() => {
            Alert.alert('提交失败,请重试');
        });
};

关键说明:

  • 用模板字符串生成路径weeklySurvey.${year}.${month}.${day},直接定位到要更新的具体日期节点
  • Firestore会识别这种点路径,仅更新该路径对应的字段,不会替换整个weeklySurvey对象
  • 如果目标年月节点不存在,Firestore会自动创建;若已存在,只会新增/替换当天的调查数据,不会影响其他日期的数据

这种方案既保留了你想要的嵌套对象结构,又彻底解决了覆盖问题,完全不需要使用嵌套集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:31:05