我想从我的实时数据库中获取最后一个密钥(最新消息),但不确定如何实现。 我从这个链接 i need to get Last child of my firebase databse 看到我可以使用 orderByKey().limitToLast(1) 来获得它,但看起来我需要指定完整的 ref 才能实现这一点。那是对的吗?或者是否可以在 val() 上 orderByKey().limitToLast(1) ?或者有另一种方法可以实现这一目标吗? 这是我在数据库中的消息结构:
我在每个键下都有一个时间戳子项,如上所示,我以为我可以查询以提取最新的键,但我真的不知道该怎么做。有人可以帮忙吗?以下是我目前的代码:
database().ref(`messages/`).once(`value`,snapshot => {
if(snapshot.exists()) {
snapshot.forEach(function (childsnapshot) {
if(childsnapshot.key.includes(auth().currentUser.uid)) {
console.log("show me the key: "+childsnapshot.key)
//not working
console.log("show last message: "+ JSON.stringify(childsnapshot.val().orderbyKey().limitToLast(1)))
}
})
}
})
console.log(JSON.stringify(messages)) => [{"-MfqYBzbusp1Cljgxpan":{"unreadMessage":true,"user":{"name":"Mike","avatar":"xxxxxx","_id":"tFhmw5oQoPhk8nF2sx5rE5BFqw93"},"timestamp":1627634061437,"senderId":"tFhmw5oQoPhk8nF2sx5rE5BFqw93",""Project","image:"{yUrHe","image:"{ ./assets/xxxxx.png"},"text":"嘿"}}]
console.log(JSON.stringify(unreadMsgs)) => []