Firebase Database query list for not equal to

2019-09-16 07:06发布

问题:

I am using Firebase in my Angular 4 app using AngularFire2. I have my database structure something like this.

{
  "users": {
    "-Kr6HDbj9tMxmxsQ8UnM": {
      "name": "abc",
      "email": "xyz@example.com",
      "uid": "XLTPwGtFYcX6xVHbJGerHxGayT2"
    },
    "-Kr6JBzN_9PZAMctYwt-": {
      "name": "pqr",
      "email": "pqr@example.com"
      "uid": "cdIj8YOncYYiUIEJrb65ynfFcl2"
    },
    ............
  }
}

I want to retrieve the last two entries of this data structure but exclude the data where uid is not equal to auth.uid.

回答1:

I think it would be easier if you changed the datastructure so the key of each user is their uid, like this.

{
"users": {
    "XLTPwGtFYcX6xVHbJGerHxGayT2": {
      "...": ".........",
      "...": "........."
    },
    "cdIj8YOncYYiUIEJrb65ynfFcl2": {
      "...": ".........",
      "...": "........."
    }
}

Then you could easily access the specific users properties With the https://firebase.google.com/docs/reference/js/firebase.database.Reference#once

Example

var ref = firebase.database().ref("users/"+auth.uid);
ref.once('value')
    .then(function(dataSnapshot) {
    // handle read data.
});