Firebase实时数据库按子值查找节点

时间:2018-08-20 14:18:32

标签: firebase firebase-realtime-database find

我具有以下结构:

root
  -LKMsdf2_Qxbwtv4238D
     details
       uid: john

  -YKMWrmj_QxbwtvSBM5A
     details
       uid: tony

  -R45Wrmj_Qxbf321BMd4
     details
       uid: karina

如何通过uid在'root'下找到ref键:

例如:通过uid:karina,我需要获取参考密钥-R45Wrmj_Qxbf321BMd4

有没有办法使用/ root / {recordid} / details / uid之类的通配符?

========谢谢您的提示! ====这是我的最终解决方案================

findEntry = function(targetUid) {
var entriesRef = db.ref('root');
return entriesRef.once('value')
    .then((snapshot)=>{
        var id = []; // found id

        snapshot.forEach((childSnapshot)=>{
            var childKey = childSnapshot.key;
            var childData = childSnapshot.val();
            var found = (childData.uid === targetUid);
            if (found) {
                console.log('Found for uid:' + targetUid  + ': ' + childKey);
                id = childKey;
            }
            return found; // true - breaks the forEach, false - continue
        });
    if (!id) {
        console.log('Not Found for uid:' + targetUid);
    }
    return id;
  });

}

1 个答案:

答案 0 :(得分:1)

不,最好的办法是子(键)搜索和相等性(请参见此处的示例https://firebase.google.com/docs/reference/js/firebase.database.Query#equalTo

// Find all dinosaurs whose height is exactly 25 meters.
var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
  console.log(snapshot.key);
});

没有比这更深入的查询了。

您可能具有用于反向查找的其他结构,可以整理数据或以其他方式解决数据。