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

Kotlin上传数据到Firebase Firestore时生成嵌套Map的原因是什么?

问题原因

你调用update方法时传入了两个参数:第一个参数是LocalDateTime.now().toString()作为字段名,第二个参数是你组装好的stepMap作为该字段的值,所以Firestore会将整个stepMap作为嵌套对象存储在这个以当前时间命名的字段下,也就出现了你看到的嵌套Map结构。

修复方案

如果你的需求是把stepMap中所有「日期:步数」的键值对直接作为用户文档的顶级字段存储,直接将stepMap作为update方法的入参即可:

val stepMap = HashMap<String, String>()
for (dp in dataSet.dataPoints) {
    Log.i(TAG,"Data point:")
    Log.i(TAG,"	Type: ${dp.dataType.name}")
    Log.i(TAG,"	Start: ${dp.getStartTimeString()}")
    Log.i(TAG,"	End: ${dp.getEndTimeString()}")
    for (field in dp.dataType.fields) {
        Log.i(TAG,"	Field: ${field.name.toString()} Value: ${dp.getValue(field)}")
        stepMap.put("${dp.getStartTimeString()}", "${dp.getValue(field)}")
    }
}

db.collection("users")
    .document(""+GoogleSignIn.getLastSignedInAccount(this).email)
    .update(stepMap as Map<String, Any>)

补充说明

  • 如果你的日期键存在重复的情况,后面遍历到的步数会直接覆盖之前写入的同日期步数,符合按日期更新步数的需求
  • 如果你需要先清空文档下原有步数数据再写入新数据,可以把update替换为set(stepMap, SetOptions.merge()),避免覆盖文档内其他非步数相关的字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:45:03