javascript - Overwriting document in firebase
问题描述
I am trying to save user location in Firebase by storing the results from getLocation from google location service.
When I use the following code:
Lat_Coordinate = location.getLatitude();
Lon_Coordinate = location.getLongitude();
Map<String, Object> user_location = new HashMap<>();
user_location.put( "Lat", Lat_Coordinate );
user_location.put( "Lon", Lon_Coordinate );
db.collection( "Users" ).document( auth.getUid() ).collection( "Location" ).add( user_location );
It keeps adding documents to Location collection. However, my goal is always to keep only one document of location which will be the last information.
Is there a way to overwrite the document that already exists instead of adding a new one?
I'm sure there is a way to delete collection then create a new one but I think its too many operations.
Thank you
SOLUTION:
What I eventually did was to create again a document with known ID by using auth.getUID and store in it the location. Since the ID is always the same, it overwrites the document:
db.collection( "Users" ).document( auth.getUid() ).collection( "Location" ).document(auth.getUid()).set( user_location );
解决方案
这里的问题是坐标有一个嵌套集合,每次执行操作时都会创建一个新文档
users/uid/location/map
第一个选项是将位置作为文档属性添加到用户文档
db.collection( "Users" ).document( uid ).update("location", map);
在嵌套集合中添加位置可能是有原因的,例如查询。为此,您可以通过定义静态文档键来做到这一点:
db.collection( "Users" ).document( uid ).collection("location").document("static_key").update("location", map);
推荐阅读
- javascript - 如何找到我不知道确切字符串的子字符串的结束索引
- java - Nimbus Look and Feel 是否适用于所有平台(即使 jar 被转换为 exe)?
- javascript - Image .onerror — 区分服务器响应 400 和 200,但 Content-Type 不是图像?
- python - 导入 python 日志记录时遇到问题
- css - div标签内按钮的CSS选择器
- html - 在页面重新加载时停止 python 函数调用
- javascript - 出于数学目的使用 React 将日期/时间转换为秒
- firebase - Firebase 错误:没有要更新的文档(带有 Firebase 应用的 Vue 3)。但是如果等待 1 分钟然后重新加载它是可更新的
- c++ - 如何正确使用 warpPerspective?
- javascript - 在reactjs中使用refs绑定输入类型