获取单项 firebase

Get single item firebase

我刚开始在 Firebase 数据库中进行查询,希望能获得更多见解。

此查询用于从 firebase 数据库中检索单个项目。我的内联理解。

  var ref = DatabaseRef; // root of my fbase db
  var codeRef = ref.child('codes'); // at root/codes/ now

  codeRef
    .child($stateParams.codeId) // a param comes in
    // grab value one-time 
    // https://www.firebase.com/docs/web/guide/retrieving-data.html#section-reading-once
    .once('value', function(snap) {
      console.log(snap.val());
    })

以上作品。但是下面没有,为什么?我的内联理解。

// same ref from above
codeRef
  // traverse the /codes/ url, and find all items that match
  // the specified param
  .equalTo($stateParams.codeId)
    .once('value', function(snap) {
      console.log(snap.val()); // returns `null`
    })

相反,我希望显示与该 ID 匹配的所有项目。在这种情况下,id 是唯一的,因此,我希望取回单个项目。但是,返回 null

来自docs

The equalTo() method allows us to filter based on exact matches. As is the case with the other range queries, it will fire for each matching child node.

所以,也许我看错了整个 Firebase 查询。会喜欢开悟。

equalTo() 是一种过滤方法。您需要与它一起使用订购方法。查看 latest docs。所以也许是这样的:

  codeRef.orderByKey().
  .equalTo($stateParams.codeId)
    .once('value', function(snap) {
      console.log(snap.val()); // returns `null`
    })

我猜你的数据结构如下:

"codes" : {
        "codeId": {
            ....: ....
            }
        }

并且您正在查询 "codeId"。

我建议在"codeId"对象下添加codeId(key/value)进行查询,如下:

"codes" : {
        "-yabba_dabba_doo": { // codeId 
            codeId : "-yabba_dabba_doo"
            }
        }

现在您可以这样做了:

ref.child('codes').orderByChild('codeId').equalTo('-yabba_dabba_doo')

如果我没有正确猜出您的数据层次结构,请分享您的 firebase 数据层次结构以帮助您。