Search code examples
typescriptfirebaseionic-frameworkfirebase-realtime-databaseionic5

Retrieve another user UID using the a child node data


I am creating a referral code function for my ionic web-app. Currently when a referral code is being submitted and it exists in the firebase real time database, 50 points will be added to current user account. However I am trying to also add points to the other user whose referral code is being used.

So far I am trying to call the UID of the other user then i will call that UID and create the update function. But I am not able to get the UID, is there a way I can do this? I have added my firebase structure and the code I have tried. this is my database structure

var ref = firebase.database().ref('users/').startAt(this.checking.referralCode).endAt(this.checking.referralCode);
ref.once("child_added", function(snapp) {
    console.log(snapp.key); 
});

UPDATE: I have tried this code, however it brings out all of the UID, is there a way I can specify which UID I want using the data from referral code?

 var ref = firebase.database().ref("users");

ref.orderByKey().endAt("referralCode").on("child_added", function(snapp) {
  var key = snapp.key;
  console.log(key)

Thank you !


Solution

  • It sound like you're trying to order/filter on the referralCode child value, which you can do with:

    var query = ref.orderByChild("referralCode").equalTo("56483579").limitToFirst(1);
    query.once("child_added").then(function(snapshot) {
      console.log(snapshot.key); // "jHl9Srh..."
    })
    

    If there may be multiple child nodes with the same value, you'd do:

    var query = ref.orderByChild("referralCode").equalTo("56483579");
    query.once("value").then(function(results) {
      results.forEach(function(snapshot) {
        console.log(snapshot.key); // "jHl9Srh..."
      })
    })