【问题标题】:Firebase specific orderFirebase 特定顺序
【发布时间】:2021-11-16 07:58:33
【问题描述】:

我有一个项目集合,其中包含一个包含“早餐、午餐、晚餐”的类别字段

如何按早餐、午餐和晚餐对这些项目(索引)进行排序?

我目前使用以下代码,按字母顺序简单排序:

.orderBy("Category", "asc")
.orderBy("Name", "asc")

【问题讨论】:

  • 谢谢@FrankvanPuffelen - 我最终使用了你的建议并用数字存储了值

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

data types 上的 Firebase 文档所示,字符串字段按字典顺序排列。没有办法改变这一点。

两个常用选项:

  1. 按照您选择的顺序将用餐类别存储为数值,因此1breakfast2lunch3 为晚餐。
  2. 为餐食类别指定一个数字前缀以确定其顺序,例如1 - breakfast2 - lunch3 - dinner

【讨论】:

    【解决方案2】:

    老实说,我认为 firebase 没有办法创建自定义排序方案。一个解决方案可能是使用云函数。或者你可以这样做(虽然我意识到这不是很优雅):

    let docs = [];
            firebase.firestore().collection('...').where("category","==","breakfast").orderBy("name").get()
            .then((snapshotBreakfast) => {
                snapshotBreakfast.forEach(doc => docs.push(doc.data()));
                firebase.firestore().collection('...').where("category","==","lunch").orderBy("name").get()
                .then((snapshotLunch) => {
                    snapshotLunch.forEach(doc => docs.push(doc.data()));
                    firebase.firestore().collection('...').where("category","==","dinner").orderBy("name").get()
                    .then((snapshotDinner) => {
                        snapshotDinner.forEach(doc => docs.push(doc.data()));
                    })
                })
            })
    

    我还没有测试过,但它应该可以工作。不过我认为这段代码背后的想法很明确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多