Firebase - 使用 'Node-Id' 检索节点
Firebase - Retrieving Node using 'Node-Id'
我很难理解在检索完整节点时如何使用 where。如果我有这样的结构:
- users
-user_id1
- key1:value1
- key2:value2
-user_id2
- key1:value3
- key2:value4
...
如果我知道“user_id1”,我怎样才能得到整个节点;所以我可以使用 snapshot.key
获取 user_id,并使用 snapshot.value
获取 [key:value]
?
-user_id1
- key1:value1
- key2:value2
这是我到目前为止尝试过的...
let key = "user_id1" // static for test
let usersRef = Firebase(url: secret + "/users")
usersRef.queryEqualToValue(key).observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot)
// print(snapshot.key) // id
// print(snapshot.value) // [key:value]
})
这是返回:
Snap (users) <null>
Snap (users) <null>
尝试添加 queryOrderedByKey()
例如
let ref = root.child("users")
ref.queryOrderedByKey().queryEqualToValue("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in
// could get many items in snapshot hence the loop
for item in snapshot.children {
print(item)
}
})
它比您尝试的要简单得多:
ref.child("users").child("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in
print(item.key)
print(item.value)
})
这不仅更简单,而且对数据库来说也更便宜,因为它不必执行(可能很昂贵的)查询。
例如,请参阅 documentation on reading child value with Swift 的这一部分。
我很难理解在检索完整节点时如何使用 where。如果我有这样的结构:
- users
-user_id1
- key1:value1
- key2:value2
-user_id2
- key1:value3
- key2:value4
...
如果我知道“user_id1”,我怎样才能得到整个节点;所以我可以使用 snapshot.key
获取 user_id,并使用 snapshot.value
获取 [key:value]
?
-user_id1
- key1:value1
- key2:value2
这是我到目前为止尝试过的...
let key = "user_id1" // static for test
let usersRef = Firebase(url: secret + "/users")
usersRef.queryEqualToValue(key).observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot)
// print(snapshot.key) // id
// print(snapshot.value) // [key:value]
})
这是返回:
Snap (users) <null>
Snap (users) <null>
尝试添加 queryOrderedByKey()
例如
let ref = root.child("users")
ref.queryOrderedByKey().queryEqualToValue("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in
// could get many items in snapshot hence the loop
for item in snapshot.children {
print(item)
}
})
它比您尝试的要简单得多:
ref.child("users").child("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in
print(item.key)
print(item.value)
})
这不仅更简单,而且对数据库来说也更便宜,因为它不必执行(可能很昂贵的)查询。
例如,请参阅 documentation on reading child value with Swift 的这一部分。