Firebase 数据结构思想

Firebase data structure ideas

我在 POS 系统中工作,我在后端使用 Firebase。我需要做的报告之一是 "most/less sold products".

我有这样的结构/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
}

和/products/:

{
    "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
    }
}

因此,如果我现在必须获得 "most sold products",我必须在每次找到产品时遍历所有销售额并添加数量,然后订购结果并获得销量最高的产品,然后糟透了。

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

  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(...