Home > Mobile >  How to stop endAt when it tries to search again from the end?
How to stop endAt when it tries to search again from the end?

Time:10-04

I am stuck when using endAt() in Firebase RealtimeDatabase.Some incorrect values appear in my results. Here is my code:

  resuftObj = await messagesRef
          .child("test")
          .orderByChild("country")
          .endAt("ja", "9")
          .limitToLast(4)
          .once("value");

Here my example data or view:
|-test:
|---1:{ "country" : "us", "id" : 1 },
|---2:{ "country" : "ja", "id" : 2 },
|---3:{ "country" : "ca", "id" : 3 },
|---4:{ "country" : "uk", "id" : 4 },
|---5:{ "country" : "us", "id" : 5 },
|---6:{ "country" : "ca", "id" : 6 },
|---7:{ "country" : "uk", "id" : 7 },
|---8:{ "country" : "ja", "id" : 8 },
|---9:{ "country" : "us", "id" : 9 }

image

I would expect returned objects with "country" = "ja." But I see two values 3 and 6 ("country" = "ca"). My thinking is that when it reaches id= 2, my Query finds no more results so re-search from the end (id=9). How to prevent this?
Result:

{
    "2": {
        "country": "ja",
        "id": 2
    },
    "3": {
        "country": "ca",
        "id": 3
    },
    "6": {
        "country": "ca",
        "id": 6
    },
    "8": {
        "country": "ja",
        "id": 8
    }
}

CodePudding user response:

To further limit the results to only those with country equal to ja, you must also specify startAt("ja"):

ref.orderByChild("country")
          .startAt("ja")
          .endAt("ja", "9")
          .limitToLast(4)

Also see my repro here: https://jsbin.com/fajegol/edit?js,console

  • Related