如何将Firebase的ServerValue.TIMESTAMP用作子项并为其设置值 [英] How to use Firebase's ServerValue.TIMESTAMP as a child and set a value to it
问题描述
我想创建一个类似
"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
但是当我尝试时:
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
我知道此错误是因为该方法期望使用Map<String, Object>
映射而不是时间戳映射.
I know that this error is because the method expects a Map<String, Object>
map instead of Map of timestamp.
但是我该如何以这种方式存储ServerValue并为其设置一个值?
But how could I store the ServerValue this way and set a value to it?
推荐答案
这不是ServerValue.TIMESTAMP
的使用本意.
child()
接受一个String,其中包含您要访问的孩子的名字.这是数据库中节点的名称.即使将其格式化为数字,也只能将其引用为字符串.
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
是一个特殊的(映射)值,可用于在节点内添加或更新子数据时插入服务器当前时间的位置. 它不能用作节点本身的名称.
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.
如果要基于某个时间创建数据库的位置,则需要在开始访问数据库之前知道该时间. ServerValue.TIMESTAMP
不会帮助您,因为它是服务器上唯一生成的.
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.
如果要按时间添加数据,则应该将push()数据推入数据库中.推送ID基于时间,但这是客户端的时间感,而不是服务器的时间感.
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.
这篇关于如何将Firebase的ServerValue.TIMESTAMP用作子项并为其设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!