我使用Firebase如下:
Post--
-Kwc6asRRI1SUqrigYeD <- First input
-> Date: 1:00pm
-> ID: 1
-> Content: Hello!
-Kwc6fXQsN2xIQtHOofZ
-> Date: 2:00pm
-> ID: 2
-> Content: How are you?
-Kwc6fXQsN2xRO39LDPD <-Most recent one
-> Date: 3:00pm
-> ID: 3
-> Content: I am good.
这些是“推送”的,因此会生成一个唯一的密钥,可用于根据"most recent to old"
(或ID:3
到ID:1
)显示它们。
现在,当我需要更新数据时,请说ID:1
帖子的内容从"Hello"
发送到"My name is Steve"
,然后它仍然保持唯一键虽然这是最近的一次。
Post--
-Kwc6asRRI1SUqrigYeD <-Most recent one
-> Date: 4:00pm
-> ID: 1
-> Content: My name is Steve
-Kwc6fXQsN2xIQtHOofZ
-> Date: 2:00pm
-> ID: 2
-> Content: How are you?
-Kwc6fXQsN2xRO39LDPD
-> Date: 3:00pm
-> ID: 3
-> Content: I am good.
我想我可以删除帖子并设置一个新帖子,但这似乎效率低下,特别是如果我有更多关于每个孩子的数据。
有没有办法重新设置密钥以反映时间变化(如下所示)?
Post--
-Kwc6fXQsN2xIQtHOofZ
-> Date: 2:00pm
-> ID: 2
-> Content: How are you?
-Kwc6fXQsN2xRO39LDPD
-> Date: 3:00pm
-> ID: 3
-> Content: I am good.
-Kwc6asRRI1KDodkeixk <-Most recent one
-> Date: 4:00pm
-> ID: 1
-> Content: My name is Steve
答案 0 :(得分:2)
无法更新现有节点的密钥(请参阅1,2,3)。如果需要新密钥,则必须生成具有相同内容的新节点。
但在这种情况下,您似乎更希望保持数据结构不变,而是为每个帖子添加lastUpdated
时间戳:
Post--
-Kwc6asRRI1SUqrigYeD
-> Date: 1:00pm
-> lastUpdated: 1508215054096
-> ID: 1
-> Content: Hello!
-Kwc6fXQsN2xIQtHOofZ
-> Date: 2:00pm
-> lastUpdated: 1507610306270
-> ID: 2
-> Content: How are you?
-Kwc6fXQsN2xRO39LDPD
-> Date: 3:00pm
-> lastUpdated: 1508128668412
-> ID: 3
-> Content: I am good.
使用此结构,您可以使用Firebase查询以您想要的顺序获取结果。在JavaScript中,这看起来像:
var ref = firebase.database().reference("Post");
ref.orderByChild("lastUpdated")
.once("value")
.then(function(snapshot) {
snapshot.forEach(function(post) {
console.log(snapshot.key+": "+snapshot.val().Content);
});
});