如何使用子字符串查询Firebase密钥 [英] How to query firebase keys with a substring
问题描述
我想查询包含输入的Firebase.例如,在下面的数据库结构中,我想查询包含"4140"的所有节点 所以我用这段代码
I want to query Firebase that contains an input. for example in the database structure below, I would like to query all nodes that contains "4140" so I use this code
var catref = Cataloguedatabase.ref("/Listing Search/");
return catref.once('value').then(function(snapshot){
snapshot.forEach(childSnapshot => {
let snapdb = childSnapshot.val();
let key = childSnapshot.key;
//use ES6 includes function
if(key.includes(schname)){
console.log(childSnapshot.val());
var searchresults = childSnapshot.val();
var container = document.getElementById('listing_gallery');
// container.innerHTML = '';
var productCard = `
<div class="col-sm-3">
<div class="card" onclick="gotoproduct(this);" id="${key}">
`
container.innerHTML += productCard;
}
})
})
这是可行的,但问题是它首先查询所有子节点并通过数组排序.这对于没有几个子节点的节点是可以的,但是当涉及到成千上万个子节点时,这是不切实际的.有没有办法我只能查询包含firebase中的值的键,如果没有,我该如何实现呢?
This works but the problem is that it first query all the child and sort through the array.This is ok for node with few children but when it gets to thousands of children, it becomes impractical. is there a away i can only query key the contains the value in firebase and if not how else can i implement this?
推荐答案
正如Doug所说,无法查询包含某个字符串的值.但是您可以查询以开头的某个子字符串的键:
As Doug says, there is no way to query for values that contain a certain string. But you can query for keys that start with a certain substring:
return catref.orderByKey().startAt("4140-").endAt("4140-\uf8ff").once('value').then(function(snapshot){
这只会匹配其键以4140-
开头的子节点.
This will just match the child nodes whose key starts with 4140-
.
这篇关于如何使用子字符串查询Firebase密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!