【问题标题】:How to get the key of a Firebase Object如何获取 Firebase 对象的密钥
【发布时间】:2016-08-11 05:16:08
【问题描述】:

如何在不使用快照的情况下获取 Firebase 对象的密钥?

我已经完成了以下研究。

使用代码:

var ref = new Firebase('https://johnsoncompany.firebaseio.com/people')

var firstPerson = ref.orderByChild("first").limitToFirst(1);

var key = $firebaseObject(firstPerson);

..我得到下面的对象:

{  
   "5":{  
      "first":"Jennifer",
      "last":"Robert",
      "mobile":"121 364 135",
   }
}

Firebase 为我的对象提供了键“5”,因为数据包含在值数组中。这是第 6 个值。

挑战在于,为了获得值“Jennifer”,我必须知道键是“5”。

然后我将使用代码:

var firstPerson = $firebaseObject(ref.child('5'))

var firstName = firstPerson.first; //Returns Jennifer

我知道我可以使用下面的代码来获取密钥“5”:

    ref.orderByChild("first").limitToFirst(1).once("child_added", function(snapshot) {
        alert(snapshot.key());
    }); 

挑战在于它在返回密钥之前存在延迟。这会导致应用出现故障。

有没有办法在没有快照的情况下获得密钥

ref.orderByChild("first").limitToFirst(1).key(); //This doesn't work

【问题讨论】:

  • 如果不异步加载数据,就无法从 Firebase(或任何基于云的数据库)读取密钥。但这一切都取决于您为什么要检索该特定对象。如果不知道它是第 5 项,那么它是否基于另一个属性。例如,如果您想根据用户的号码获取用户,您可以 ref.orderByChild('mobile').equalTo('121 364 135').on(...

标签: arrays json firebase firebase-realtime-database


【解决方案1】:

我知道您现在可能已经找到了解决问题的方法,但这是我用来检索对象键的方法。然后我使用相同的键运行另一个查询(过滤器)。

itemsRef.on('value', (snap) => {
  var items = [];
  snap.forEach((child) => {
    items.push({
      active: child.val().active,
      profile: child.val().profile,
      image: child.val().image,
      description: child.val().description,
      title: child.val().title,
      _key:child.key, //<--------------this is where I get the key
    });
  });
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(items),
  });
});

【讨论】:

    【解决方案2】:

    你也可以使用扩展运算符来赋值:

    itemsRef.on('value', (snap) => {
      var items = [];
      snap.forEach((child) => {
        items.push({
          _key: child.key,
          ...child.val()
        });
      });
    
    });
    

    在向数据添加新属性时更容易,无需维护代码。

    【讨论】:

      【解决方案3】:

      我已经找到了解决方法,你可以看看它是否有帮助

      ArticlesRef.orderByChild('title')
              .equalTo('one2three')
               .once('value')
               .then(function(snapshot){
                  let value = snapshot.val()
                  if(value){
                  let key = Object.keys(value)[0];
                  //since the value is an object you can get the key given by firebase
                  //you can add more code});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-16
        • 2017-09-15
        • 1970-01-01
        • 2019-03-01
        • 2017-12-05
        • 2016-11-08
        相关资源
        最近更新 更多