【问题标题】:Sorting in descending order in Firebase database [duplicate]在Firebase数据库中按降序排序[重复]
【发布时间】:2023-03-03 11:00:01
【问题描述】:

Firebase 实时数据库中有以下图书列表:

[
  {
    title: "Don't Make Me Think",
    upvotes: 110
  },
  {
    title: "The Mythical Man Month",
    upvotes: 111
  },
  {
    title: "Code Complete 2",
    upvotes: 112
  }
]

默认情况下,以下查询按 ASC 顺序返回此列表:

firebase.database().ref('books').orderByChild('upvotes')

如何改用upvotes DESC 查询和排序?

【问题讨论】:

  • 如果我是正确的,上面链接中建议的解决方案建议我将upvote 属性存储为负数。然后,在渲染时,应该再次将其转换为正整数。如果是这样,这似乎有点骇人听闻,因为我数据库中的数据并不能真正反映书籍的赞成票。
  • 我理解这种担忧。然而,它是一个数字——无论是正数还是负数,你都知道它代表什么。或者,您可以将数字的负数版本存储在另一个可用于排序的子节点中。您也可以随时对代码进行排序。
  • 使用 Collections.reverse(thearray);关于结果
  • 一旦您从 firebase 获得响应,您可以使用 Array.unshift(obj) 将所有对象取消移动到本地变量。这将使您的对象反转订单。例如:- var yourVariableName =[]; firebase.database().ref('books').orderByChild('upvotes').on("child_added", (snapshopt) => { yourVariableName .unshift(snapshopt.val()); });
  • 你不能从 firebase 得到它,但是你可以在获取它们并在 swift 中应用排序函数后以任何顺序拥有它们

标签: firebase firebase-realtime-database


【解决方案1】:

不幸的是,firebase 不允许按降序返回。我通常只是颠倒了客户端返回结果的顺序。

如果您的数据查询太大而无法对客户端进行排序,您可以这样做

firebase.database().ref('books').orderByChild('ups').limitToLast(2)

然后从那里反转结果。文档可见here

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 2019-05-01
    • 2020-03-24
    • 2018-05-23
    • 2018-08-14
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多