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

Firebase数据保存避免覆盖问题求助(Kotlin/Android Studio)

解决Firestore签到记录被覆盖的问题

你当前的问题出在使用update方法直接替换entrada字段的值——每次调用都会把旧的时间字符串换成新的,自然留不住历史记录。下面给你两种可行的解决思路:

方案一:将entrada改为数组类型,追加记录

Firestore提供了arrayUnion方法,可以在数组字段中追加新元素(不会重复添加相同值)。修改后的代码如下:

import com.google.firebase.firestore.FieldValue

val dateStringEntrada = "${now.year}-${now.monthValue}-${now.dayOfMonth} ${now.hour}:${now.minute}:${now.second}"

db.collection("entradas").document(mail.toString())
    .update("entrada", FieldValue.arrayUnion(dateStringEntrada))

注意:第一次执行时,如果用户文档里还没有entrada字段,Firestore会自动创建这个数组并添加第一个元素;之后每次调用都会把新的时间追加到数组末尾。

方案二:用子集合存储每条独立记录

如果后续需要对单条签到记录做更多操作(比如修改、删除单条记录),更推荐把每条签到记录作为独立的子文档存储。示例代码:

val dateStringEntrada = "${now.year}-${now.monthValue}-${now.dayOfMonth} ${now.hour}:${now.minute}:${now.second}"
// 可以用时间戳作为子文档ID,保证唯一
val recordId = now.toEpochSecond(ZoneOffset.UTC).toString()

db.collection("entradas").document(mail.toString())
    .collection("records").document(recordId)
    .set(mapOf("entrada" to dateStringEntrada))

这种方式每条记录都是独立文档,后续查询历史记录、统计签到次数都会更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:27:17