首页 > 解决方案 > 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 );

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


这里的问题是坐标有一个嵌套集合,每次执行操作时都会创建一个新文档

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);

推荐阅读