简体   繁体   中英

Using Firebase, how can I create a query based on UID?

I created a function that adds a UID to the database along with an item's state:

changestate(item) {

    var postData = {
      state: "listed",
    };

    var user = firebase.auth().currentUser;
    var uid = user.uid;

    var updates = {};
    updates['foods' + '/' + item.$key + '/' + 'state' + '/' + uid] = postData;

    return firebase.database().ref().update(updates);
  }

I want to create a query that only shows the data corresponding to that UID. In a previous query I was using:

getLists(): FirebaseListObservable<any> {
return this.db.list('/foods', {
  query: {
    orderByChild: 'state',
    equalTo: 'listed'
  }
});}

This is the structure of my database:

{
  "foods" : {
    "foodID1" : {
      "category" : "Produce",
      "foodname" : "Apples",
      "state" : {
        "aePQkvozV6gehP7ihjN0OWCltKu2" : {
          "state" : "listed"
        }
      }
    },
    "foodID2" : {
      "category" : "Dairy",
      "foodname" : "Cheese",
      "state" : {
        "aePQkvozV6gehP7ihjN0OWCltKu2" : {
          "state" : "listed"
        }
      }
    }
  }
}

What do I need to do to show the items that correspond to a signed in user's UID?

The orderByChild property can take a path. So the code then simple becomes:

getLists(): FirebaseListObservable<any> {
  return this.db.list('/foods', {
    query: {
      orderByChild: 'state/'+firebase.auth().currentUser.uid+'/state',
      equalTo: 'listed'
    }
  });
}

This requires that the user is signed in of course. To test the query without a signed-in user, you can use a hard-coded value:

getLists(): FirebaseListObservable<any> {
  return this.db.list('/foods', {
    query: {
      orderByChild: 'state/aePQkvozV6gehP7ihjN0OWCltKu2/state',
      equalTo: 'listed'
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM