当您需要花哨的查询时,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
希望对你有帮助