【问题标题】:How to stop endAt when it tries to search again from the end?endAt 尝试从末尾再次搜索时如何停止?
【发布时间】:2021-11-24 05:59:15
【问题描述】:

我在 Firebase RealtimeDatabase 中使用 endAt() 时卡住了。我的结果中出现了一些不正确的值。这是我的代码:

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

这是我的示例数据或视图:
|-测试:
|---1:{ “国家”:“我们”, “身份证”:1 },
|---2:{ “国家”:“ja”, “身份证”:2 },
|---3:{ “国家”:“ca”, “身份证”:3 },
|---4:{ “国家”:“英国”, “身份证”:4 },
|---5:{ “国家”:“我们”, “身份证”:5 },
|---6:{ “国家”:“ca”, “身份证”:6 },
|---7:{ “国家”:“英国”, “身份证”:7 },
|---8:{ “国家”:“ja”, “身份证”:8 },
|---9:{ “国家”:“我们”, “身份证”:9 }

我希望返回带有“country”=“ja”的对象。但我看到两个值 3 和 6(“country”=“ca”)。我的想法是,当它达到 id=2 时,我的 Query 找不到更多结果,所以从最后(id=9)重新搜索。如何预防?
结果:

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

【问题讨论】:

    标签: node.js firebase firebase-realtime-database


    【解决方案1】:

    要进一步将结果限制为仅country 等于ja 的结果,您还必须指定startAt("ja")

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

    也可以在这里查看我的复制:https://jsbin.com/fajegol/edit?js,console

    更新:更容易理解为什么会得到 ca 结果,因为你以正确的顺序打印结果(我最初没有这样做):

    ref.orderByChild("country")
              .endAt("ja", "8")
              .limitToLast(4)
    .once("value", function(snapshot) {
      snapshot.forEach(function(child) {
        console.log(child.val());
      })
    });
    

    给出这个输出:

    { "国家" : "ca", "id" : 3 }

    { "国家" : "ca", "id" : 6 }

    { "国家" : "ja", "id" : 2 }

    { "国家" : "ja", "id" : 8 }

    这样就更有意义了:子节点按country 排序,这是您告诉endAt() 之前的最后4 个节点。

    您的问题中的输出来自记录 snapshot.val(),它为您提供了没有您请求的顺序的结果(因为 JSON 中的键根据定义是无序的)。

    【讨论】:

    • 谢谢。您轻松且正确地做到了这一点!
    猜你喜欢
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2021-09-15
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 2014-09-23
    相关资源
    最近更新 更多