在Firebase中未知父键时检索子记录

时间:2015-11-27 10:37:04

标签: javascript firebase

我有这样的数据:

"customers": {
    "aHh4OTQ2NTlAa2xvYXAuY29t": {
        "customerId": "xxx",
        "name": "yyy",
        "subscription": "zzz"
    }
}

我需要通过customerId审核客户。由于路径限制,父密钥只是B64编码的邮件地址。通常我通过这个电子邮件地址查询数据,但有几次我只知道customerId。我试过这个:

getCustomersRef()
   .orderByChild('customerId')
   .equalTo(customerId)
   .limitToFirst(1)
   .once('child_added', cb);

如果客户真的存在,这很有效。在相反的情况下,永远不会调用回调。

我尝试了value这个有效的事件,但这给了我整个树,从编码的电子邮件地址开始,所以我无法达到里面的实际数据。或者我可以吗?

我找到了这个答案Test if a data exist in Firebase,但这又假设你知道所有路径元素。

getCustomersRef().once('value', (snapshot) => {
    snapshot.hasChild(`customerId/${customerId}`);
});

我还能在这做什么?

更新

我认为我找到了解决方案,但感觉不对。

let found = null;
snapshot.forEach((childSnapshot) => {
    found = childSnapshot.val();
});
return found;

1 个答案:

答案 0 :(得分:1)

<强>旧;误解了这个问题:

  

如果你知道“endcodedB64Email”,就可以了。:

var endcodedB64Email = B64_encoded_mail_address;

firebase.database().ref(`customers/${endcodedB64Email}`).once("value").then(snapshot => {
       // this is getting your customerId/uid. Remember to set your rules up for your database for security! Check out tutorials on YouTube/Firebase's channel.
       var uid = snapshot.val().customerId;
       console.log(uid) // would return 'xxx' from looking at your database

// you want to check with '.hasChild()'? If you type in e.g. 'snapshot.hasChild(`customerId`)' then this would return true, because 'customerId' exists in your database if I am not wrong ...
});
  

更新(更正):

     

我们必须至少知道一把钥匙。所以如果你在某些情况下   只知道 customer-uid-key ,然后我会这样做。:

// this is the customer-uid-key that is know. 
var uid = firebase.auth().currentUser.uid; // this fetches the user-id, referring to the current user logged in with the firebase-login-function
// this is the "B64EmailKey" that we will find if there is a match in the firebase-database
var B64EmailUserKey = undefined;

// "take a picture" of alle the values under the key "customers" in the Firebase database-JSON-object
firebase.database().ref("customers").once("value").then(snapshot => {
     // this counter-variable is used to know when the last key in the "customers"-object is passed
     var i = 0;
     // run a loop on all values under "customers". "B64EmailKey" is a parameter. This parameter stores data; in this case the value for the current "snapshot"-value getting caught
     snapshot.forEach(B64EmailKey => {
          // increase the counter by 1 every time a new key is run
          i++;
          // this variable defines the value (an object in this case)
          var B64EmailKey_value = B64EmailKey.val();
          // if there is a match for "customerId" under any of the "B64EmailKey"-keys, then we have found the corresponding correct email linked to that uid
          if (B64EmailKey_value.customerId === uid) {
               // save the "B64EmailKey"-value/key and quit the function
               B64EmailUserKey = B64EmailKey_value.customerId;

               return B64UserKeyAction(B64EmailUserKey)
          }

          // if no linked "B64EmailUserKey" was found to the "uid"
          if (i === Object.keys(snapshot).length) {
               // the last key (B64EmailKey) under "customers" was returned. e.g. no "B64EmailUserKey" linkage to the "uid" was found
               return console.log("Could not find an email linked to your account.")
          }
     });
});

 // run your corresponding actions here
 function B64UserKeyAction (emailEncrypted) {
      return console.log(`The email-key for user: ${auth.currentUser.uid} is ${emailEncrypted}`)
 }
  

我建议将其放在函数或类中,这样您就可以轻松地调用它并以有条理的方式重用代码。

我还想要补充说明必须定义firebase的规则以确保一切安全。如果必须计算敏感数据(例如价格),那么在Firebase的服务器端执行此操作!使用云功能。这是Firebase 2017的新功能。