我的Firebase数据库中有以下结构
-- user-posts
---- -KeKDik4k3k5Wjnc
------ title: "Batman is the Greatest Hero"
------ body: "There is basically no other hero to compare here..."
---- -K34idfgKlksdCxq
------ title: "Superman is Weak"
------ body: "Let's talk about a shoddy, overrated alien for a m..."
假设我想查询/user-posts
节点中的所有对象,但将-KeKDik4k3k5Wjnc
设置/排序为第一个元素。这可以在Firebase中完成吗?如果是这样,它是否也可以与limitToFirst
结合使用?我没有在文档中看到这个确切的功能,但我可能忽略了。
如果我可以提供帮助,我希望避免自己操纵数组。
赞赏任何意见?
答案 0 :(得分:0)
假设您的数据库中有一个usersRef节点,并且项目中有一个带有id,title和body的Post对象,您可以将queryOrderedByKey和queryLimited结合起来,如下所示:
func userPostObserver(_ completion: @escaping () -> ()) {
guard let currentUserId = Auth.auth().currentUser?.uid else {
return
}
usersRef.child(currentUserId).child("posts").queryOrderedByKey.queryLimited(toLast: 10).observe(.childAdded, with: { [weak self] (snapshot) in
guard let title = snapshot.childSnapshot(forPath: "title").value as? String,
let body = snapshot.childSnapshot(forPath: "body").value as? String,
else {
return
}
self?.posts.append(Post(id: snapshot.key, title: title, body: body))
completion()
})
}
这将检索按键排序的特定用户的最后10个帖子(Firebase唯一推送ID是从创建数据的数据生成的),因此您将获得有序列表!
注意:queryLimited(toLast:10)将获取此节点中添加的最后10个帖子,这意味着它将获取最多最近帖子。对于添加到此节点的每个新帖子,它也会被触发。