本文介绍了从检索Firebase中排除某些子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望检索某个集合中除一个特定子项之外的所有子项。我有由多个用户ID组成的数据库&USERS";。
"users"
|- "userId1"
|- "userId2"
|- "userId3"
等等。 我现在只想检索";userId1";和";userId3";,并排除";userId2";。我已经知道如何只获取userId2,因为我还将其存储在另一个数据库中。该数据库由用户ID组成,构建如下:
"blocked-users"
|- "userId1"
|- "userId2"
这就是我要从检索用户中排除userId2的原因。假设userId1是CurrentUser,并且已经阻止了userId2,我想阻止userId1找到userId2。我该怎么做?
这就是我获取userId2的ID的方式:
guard let currentUid = Auth.auth().currentUser?.uid else { return }
BLOCKED_USERS.child(currentUid).observe(.childAdded) { (snapshot) in
print("this is the user, that should not be shown: ", snapshot.key)
现在如何才能在此函数中排除Snapshot.key?:
var userCurrentKey: String?
USER_REF.queryLimited(toLast: 10).observeSingleEvent(of: .value) { (snapshot) in
guard let first = snapshot.children.allObjects.first as? DataSnapshot else { return }
guard let allObjects = snapshot.children.allObjects as? [DataSnapshot] else { return }
allObjects.forEach({ (snapshot) in
let uid = snapshot.key
Database.fetchUser(with: uid, completion: { (user) in
self.users.append(user)
self.tableView.reloadData()
})
})
self.userCurrentKey = first.key
}
这里是我为获取所有用户而调用的整个函数:
func fetchUsers() {
guard let currentUid = Auth.auth().currentUser?.uid else { return }
if userCurrentKey == nil {
BLOCKED_USERS.child(currentUid).observe(.childAdded) { (snapshot) in
print("these are the users that have blocked this user: ", snapshot.key)
var dontShowThisUser = snapshot.key
USER_REF.queryLimited(toLast: 10).observeSingleEvent(of: .value) { (snapshot) in
guard let first = snapshot.children.allObjects.first as? DataSnapshot else { return }
guard let allObjects = snapshot.children.allObjects as? [DataSnapshot] else { return }
allObjects.forEach({ (snapshot) in
let uid = snapshot.key
Database.fetchUser(with: uid, completion: { (user) in
self.users.append(user)
self.tableView.reloadData()
})
})
self.userCurrentKey = first.key
}
}
} else {
USER_REF.queryOrderedByKey().queryEnding(atValue: userCurrentKey).queryLimited(toLast: 5).observeSingleEvent(of: .value, with: { (snapshot) in
guard let first = snapshot.children.allObjects.first as? DataSnapshot else { return }
guard var allObjects = snapshot.children.allObjects as? [DataSnapshot] else { return }
allObjects.removeAll(where: { $0.key == self.userCurrentKey })
allObjects.forEach({ (snapshot) in
let uid = snapshot.key
if uid != self.userCurrentKey {
Database.fetchUser(with: uid, completion: { (user) in
self.users.append(user)
if self.users.count == allObjects.count {
self.tableView.reloadData()
}
})
}
})
self.userCurrentKey = first.key
})
}
}
推荐答案
我找到了一种方法。在Firebase规则中,我是这样解决这个问题的:
"$users": {
"$uid": {
".read": "auth != null && !(root.child('blocked-users').child(auth.uid).hasChild($uid))",
".write": "auth != null"
}
}
内容如下:如果auth不为空,并且用户不在其要查找的用户的阻止用户集合中,则允许该用户读取该用户的数据。
这篇关于从检索Firebase中排除某些子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!