【问题标题】:Checking nested object value from firebase realtime db?从firebase实时数据库检查嵌套对象值?
【发布时间】:2021-05-04 22:04:40
【问题描述】:

这是我的目标,

 const data = {
   7Wkdijxaa001: {
        2bMjRYcaJL4tMxr1k8vE:{
             amount: 750,
             date: 1617120845312,
             startDate: "March 31,2021",
             status: "cancelled"
       },
       DSEnhMvi2lc4OL9bnUsw:{
             amount: 50,
             date: 1617371574679,
             startDate: ""April 30,2021"",
             status: "cancelled"
       },
  },
  Dkiah11mmjcjnajk: {
        zc9vUzYlqM3DxEW6tk86:{
             amount: 750,
             date: 1617120845312,
             startDate: "March 31,2021",
             status: "cancelled"
       },
       DSEnhMvi2lc4OL9bnUsw:{
             ....
             .....
             .......
       },
  }
}

实际上,这是用户下的订单列表,我在实时数据库中有 20k 条记录。现在我需要阅读 startDate 并过滤数据以显示在管理面板的“今天的订单”下。例如,如果今天的日期是 3 月 31 日,我需要查看所有 20k 记录并获取开始日期为 3 月 31 日的对象并将其显示在管理面板上?

如何做到这一点,我可以成功获取所有数据,但可以理解这些嵌套对象。正在使用和尝试 lodash

请指导如何执行此操作,我尝试了映射 - 那么如何根据嵌套对象键进行过滤?在这种情况下,我需要根据“startDate”进行过滤

_.map(data)

但我觉得它的方法不对,我是新手请帮忙!

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    我怀疑是否有直接的方法可以这样做,因为路径中涉及通配符(用户 UID)。对于这个用例,Firestore 会更理想。但是,您可以获取所有订单,然后在前端过滤数据:

    const data = {
        "7Wkdijxaa001": {
            "2bMjRYcaJL4tMxr1k8vE": {
                amount: 750,
                date: 1617120845312,
                startDate: "March 31,2021",
                status: "cancelled"
            },
            "DSEnhMvi2lc4OL9bnUsw": {
                amount: 50,
                date: 1617371574679,
                startDate: "April 30,2021",
                status: "cancelled"
            },
        },
        "Dkiah11mmjcjnajk": {
            "zc9vUzYlqM3DxEW6tk86": {
                amount: 750,
                date: 1617120845312,
                startDate: "March 31,2021",
                status: "cancelled"
            }
        }
    }
    
    const today = "March 31,2021"
    const todaysOrders = []
    
    Object.entries(data).forEach((user) => {
        Object.entries(data[user[0]]).forEach((order) => {
            if (order[1]["startDate"] === today) {
                todaysOrders.push({orderId: order[0], ...order[1]})
            }
        })
    })
    
    
    console.log(todaysOrders);
    

    我在您的示例 JSON 上运行了代码,输出如下:

    【讨论】:

    • 谢谢,会检查这个!
    • @christine11sure。如果可行,您可以通过单击对勾图标接受答案,以便其他人知道问题已解决,否则请随时回答更多问题。
    • 这是一种有效的方法吗?它在数千条记录下的表现如何?
    • @christine11 不,我建议继续使用 Firestore 或更改此处的结构。在 Firestore 中,查询会更容易。
    • 但是比较实时数据库会不会很昂贵?
    猜你喜欢
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多