How to use Firebase's ServerValue.TIMESTAMP as a child and set a value to it

我只是一个虾纸丫 提交于 2019-12-24 09:14:51

问题


I want to create a structure like

"child1/1510612788766/": key: "quantity", value: 10
"child1/1510612788767/": key: "quantity", value: 4
"child1/1510612788768/": key: "quantity", value: 1
"child2/1510612788710/": key: "quantity", value: 6
"child2/1510612788756/": key: "quantity", value: 8

but when I try:

ref.child("child1").child(ServerValue.TIMESTAMP);

there is a compilation error on the second child call:

Error:(59, 52) error: incompatible types: Map<String,String> cannot be converted to String

I know that this error is because the method expects a Map<String, Object> map instead of Map of timestamp.

But how could I store the ServerValue this way and set a value to it?


回答1:


This isn't how ServerValue.TIMESTAMP is meant to be used.

child() takes a String with the name of the child you want to access. This is the name of a node in the database. It can only be referenced as a string, even if it's formatted as a number.

ServerValue.TIMESTAMP is a special (Map) value that you can use where you want to insert the server's sense of current time when adding or updating child data inside a node. It can't be used for the name of the node itself.

If you want to create a location of the database that's based on some time, you need to know what that time is before you start accessing it. ServerValue.TIMESTAMP won't help you with that, since it's a only generated on the server.

If you want to add data ordered by time, you should instead push() data into the database. The push id is based on time, but it is the client's sense of time, not the server.

If you REALLY need to use the server's sense of time in the name of a node, you should instead be using Cloud Functions for Firebase to measure time on Google servers and generate the path that you want to write.



来源:https://stackoverflow.com/questions/47274974/how-to-use-firebases-servervalue-timestamp-as-a-child-and-set-a-value-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!