简体   繁体   English

使用Firebase,如何创建基于UID的查询?

[英]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: 我创建了一个函数,该函数将UID和项的状态一起添加到数据库:

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. 我想创建一个仅显示与该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? 我需要怎么做才能显示与已登录用户的UID相对应的项目?

The orderByChild property can take a path. orderByChild属性可以采用路径。 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'
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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