简体   繁体   English

从firebase列表中获取单个项目

[英]Obtaining a single item from firebase list

Firebase allows you to query for a single value in a list if you know it's key. 如果您知道密钥,Firebase允许您查询列表中的单个值。 However it seems tricky to obtain a single value in a list if you don't have the key. 但是,如果没有密钥,在列表中获取单个值似乎很棘手。

I've been able to retrieve the desired item, however the solution seems verbose and a bit hacky. 我已经能够检索到所需的项目,但解决方案似乎冗长而且有点hacky。

Heres my function: (fbutil is my firebase url reference base) 继承我的功能:( fbutil是我的firebase网址参考基础)

function getCopy(number){
      var defer = $q.defer();
      var ref = fbutil.ref('copies').orderByChild("number").equalTo(number);
      ref.once("value",function(copySnap){
        if(!copySnap.exists()){
          defer.reject(null);
        }else{
          var listObj = copySnap.val();
          var list = Object.keys(listObj).map(function(copy){
              return listObj[copy]});
          defer.resolve(list[0]);
        }
      })
      return defer.promise;
    }

This code does work however I wonder if there is a better way to obtain the item. 这段代码确实有用,但我想知道是否有更好的方法来获取该项目。 Is there a firebase function that I am missing? 我缺少一个firebase功能吗? Or a cleaner way to extract the item? 或者更简洁的方式来提取物品?

Your function could be made a little simpler. 您的功能可以更简单一些。

With the Firebase 3 API: 使用Firebase 3 API:

The once function returns a promise, so you don't need to create your own. once函数返回一个promise,因此您不需要创建自己的promise。 And you could use the snapshot's forEach function to enumerate the children - returning true to short-circuit the enumeration after the first child: 并且您可以使用快照的forEach函数来枚举子项 - 返回true以在第一个子项之后使枚举短路:

function getCopy (number) {
  var ref = fbutil.ref('copies').orderByChild("number").equalTo(number);
  return ref.once("value").then(function (copiesSnap) {
    var result = null;
    copiesSnap.forEach(function (copySnap) {
      result = copySnap.val();
      return true;
    });
    return result;
  });
}

With the Firebase 2 API: 使用Firebase 2 API:

once does not return a promise, but you could still use the snapshot's forEach function to enumerate the children - returning true to short-circuit the enumeration after the first child: once没有返回一个承诺,但你仍然可以使用快照的forEach函数枚举子forEach - 返回true以在第一个子进程后短路枚举:

function getCopy (number) {
  var defer = $q.defer();
  var ref = fbutil.ref('copies').orderByChild("number").equalTo(number);
  ref.once("value", function (copiesSnap) {
    var result = null;
    copiesSnap.forEach(function (copySnap) {
      result = copySnap.val();
      return true;
    });
    defer.resolve(result);
  });
  return defer.promise;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM