Firebase snapshot.key 不返回实际密钥? [英] Firebase snapshot.key not returning actual key?

查看:19
本文介绍了Firebase snapshot.key 不返回实际密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个根据用户 ID 搜索用户的查询.

I have a query that searches for a user based on user ID.

usersRef.queryOrderedByChild("email").queryEqualToValue(email).observeEventType(.Value, withBlock: { snapshot in
    if snapshot.exists() {
        print("user exists")
        print(snapshot.key)

查询返回正确的用户,但行 print(snapshot.key) 字面上返回单词users",而不是实际的用户 ID.print(snapshot) 返回以下用户:

The query returns the correct user, but the line print(snapshot.key) literally returns the word "users", and not an actual user ID. print(snapshot) returns the following user:

Snap (users) {
   DELyncz9ZmTtBIKfbNYXtbhUADD2 =     {
       email = "test3@gmail.com";
       "first_name" = test;
       "last_name" = test;
   };

我如何获得DELyncz9ZmTtBIKfbNYXtbhUADD2?我可以使用 let email = child.value["email"] 获取电子邮件,但我无法获取密钥,因为它不是命名属性.

How can I get DELyncz9ZmTtBIKfbNYXtbhUADD2? I can get the email by using let email = child.value["email"] but I can't get the key because it's not a named attribute.

谢谢!!

感谢弗兰克的回答,更新了代码.获取key的歧义使用

Updated code thanks to Frank's answer. Getting ambiguous use of key

query.observeEventType(.Value, withBlock: { snapshot in
            print(snapshot.key)

            if snapshot.exists() {
                print("user exists")

                for child in snapshot.children {
                    print(child.key)

推荐答案

当您在某个位置运行查询时,结果将是匹配子项的列表.即使只有一个匹配项,结果也会是一个包含一个子项的列表.

When you run a query at a location, the result will be a list of the matching children. Even if there is only a single matching item, the result will be a list of one child.

您正在打印所有结果子项的密钥.由于没有单一结果,SDK 会打印您查询的位置/集合的键:users.

You're printing the key of all resulting children. Since there is no single result, the SDK prints the key of the location/collection that you queried: users.

您可能要查找的是遍历匹配的子项并打印它们的键:

What you're likely looking for is to loop over the matching children and print their keys:

let query = usersRef.queryOrderedByChild("email").queryEqualToValue(email)
query.observeEventType(.Value, withBlock: { snapshot in
    for child in snapshot.children {
        print(child.key)
    }
})

这篇关于Firebase snapshot.key 不返回实际密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆