javascript - Firebase数据结构思想

标签 javascript firebase firebase-realtime-database nosql

我正在使用 POS 系统,并使用 Firebase 作为后端。我需要制作的报告之一是“销售最多/销售较少的产品”。

我的结构如下 /sales/:

"1234": {
    "date": 1234567890, // timestamp
    "products": {
        "coca-cola-clasica-355-ml": {
            "quantity": 3,
            "salesPrice": 500,
            "costPrice": 400
        },
        "coca-cola-clasica-600-ml": {
            "quantity": 6,
            "salesPrice": 900,
            "costPrice": 700
        }
    },
    "subtotal": 6400,
    "total": 6400
},
"5678": {
    "date": 1234567890, // timestamp
    "products": {
        "taqueritos-chile-picante": {
            "quantity": 2,
            "salesPrice": 100,
            "costPrice": 80
        },
        "coca-cola-clasica-600-ml": {
            "quantity": 4,
            "salesPrice": 900,
            "costPrice": 700
        }
    },
    "subtotal": 200,
    "total": 200
}

和/产品/:

{
    "coca-cola-clasica-355-ml": {
        "costPrice": 350,
        "name": "Coca Cola Clasica 355 ml",
        "salesPrice": 500,
        "stock": 99,
        "supplier": "femsa-coca-cola",
        "tax": false,
    },
    "coca-cola-clasica-600-ml": {
        "costPrice": 700,
        "name": "Coca Cola Clasica 600 ml",
        "salesPrice": 900,
        "stock": 99,
        "supplier": "femsa-coca-cola",
        "tax": false,
    },
    "taqueritos-chile-picante": {
        "costPrice": 80,
        "name": "Taqueritos Chile Picante",
        "salesPrice": 100,
        "stock": 500,
        "supplier": "dinant",
        "tax": true
    }
}

因此,如果我现在必须获得“最畅销的产品”,我必须迭代所有销售并在每次找到产品时添加数量,然后排序结果并获得最畅销的产品,这很糟糕。

我有两个想法来解决这个问题:

  1. /products/ 添加一个属性,例如“soldTimes”,并在每次产品售出时添加数量。
  2. 创建第三个实体调用,例如 soldProducts,并在客户每次购买产品时计算每件产品的已售出数量。

这两种方法有效吗?我在 Firebase 中遗漏了一些东西吗?

感谢您的帮助。

最佳答案

在 NoSQL 中,您通常最终会按照应用程序想要使用数据的方式对数据进行建模。因此,如果您的应用需要拥有最畅销产品的列表,您应该考虑将该列表存储在数据库中。

productLeaderboard: {
    coca-cola-clasica-355-ml: {
        totalQuantity: 3,
        totalSalesPrice: 500,
        totalCost: 400,
        totalProfit: 100
    },
    ...
}

现在要查找最畅销的产品,您只需执行以下操作:

ref.child('productLeaderboard').orderByChild('totalQuantity').limitToFirst(3).on(...

关于javascript - Firebase数据结构思想,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829755/

相关文章:

javascript - React Native & TextInput : How to get what the use type one by one for Android?

javascript - 使用 Google 脚本将变量推送到 HTML 中

javascript - 在javascript中反序列化xml

javascript - Google Sheets Node.js 快速入门指南 : How to return the rows array returned from API into a variable

firebase - 如何优雅地处理 Firebase 权限被拒绝异常

android - 来自 Firebase 消息服务的 SQLite 后台插入

javascript - 在网页上显示完整的firebase json数据

ios - 在 Firebase 中对大量数据进行分页的最有效方法

java - Android Studio 中的 Firebase 增值

java - 在 firebase 实时数据库中保存子类