按子项值

时间:2017-12-20 07:06:47

标签: firebase react-native firebase-realtime-database

{
 "users" : {
  "1320104182" : {
   "datas" : {
    "bio" : "some_data",
    "picture" : "some_data",
    "username" : "some_data",
    "website" : "some_data",
    "followers" : 14,
   }
  },
  "3271376571" : {
   "datas" : {
    "bio" : "some_data",
    "picture" : "some_data",
    "username" : "some_data",
    "website" : "some_data",
    "followers" : 10,
   }
  }
 }
}

我是Firebase的新手,我想在这里做多次思考,但到目前为止没有任何成功。

如何在不知道密钥的情况下通过“用户名”检索用户?

或者我如何通过粉丝订购用户?

我试着在文档中找到了几个小时,我很绝望。

2 个答案:

答案 0 :(得分:4)

这看起来相当简单:

<ContentPresenter x:Name="ContentElement" Grid.Column="1" Grid.Row="1" 
                  AutomationProperties.AccessibilityView="Raw" 
                  Margin="{TemplateBinding BorderThickness}" 
                  Padding="{TemplateBinding Padding}" 
                  VerticalContentAlignment="Center"/>

答案 1 :(得分:1)

当您需要花哨的查询时,Firebase不是很好。您必须处理客户端(JavaScript)中的所有内容,这不是处理大数据时的最佳方法。在这种情况下,我建议你这样:

const nameToSearch = 'John';
firebase.ref('users').once('value') //get all content from your node ref, it will return a promise
.then(snapshot => { // then get the snapshot which contains an array of objects
  snapshot.val().filter(user => user.name === nameToSearch) // use ES6 filter method to return your array containing the values that match with the condition
})

要按照关注者订购,您也可以应用sort()(参见示例1)或任何firebase默认方法orderByChild()(参见示例2),orderByKey(参见示例3) ,或orderByValue(见例4)

示例1:

firebase.database().ref("users").once('value')
.then(snapshot => {
  const sortedUsers = snapshot.sort((userA, userB) => {
    if (userA.name < userB.name) {
      return -1;
    }
    if (userA.name > userB.name) {
      return 1;
    }
    return 0;
  })
})

示例2:

var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("height").on("child_added", function(snapshot) {
  console.log(snapshot.key + " was " + snapshot.val().height + " m tall");
});

示例3:

var ref = firebase.database().ref("dinosaurs");
ref.orderByKey().on("child_added", function(snapshot) {
  console.log(snapshot.key);
});

示例4:

var scoresRef = firebase.database().ref("scores");
scoresRef.orderByValue().limitToLast(3).on("value", function(snapshot) {
  snapshot.forEach(function(data) {
    console.log("The " + data.key + " score is " + data.val());
  });
});

注意:示例中可能存在拼写错误,我写的只是为了向您展示概念的概念。

查看以下文档以获取更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://firebase.google.com/docs/reference/js/firebase.database.Query#orderByChild

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

希望有所帮助