在 Cloud Firestore(NoSQL 数据库)中构建文档的最佳方式?

Best way of structuring documents in Cloud Firestore (NoSQL databases)?

我正在尝试实施 Firestore 云数据库,但我是 NoSQL 数据库的新手。

我想知道将这些集合排列成 collections/documents 的最佳方式是什么:

我有 家餐厅,它们有不同的 食物 预订。将这些数据集构建到 Firestore DB 中的最佳方法是什么?

这是正确的做法吗:

Restaurant1 (Collection)
----> Foods (document) 
----> Reservations (document)

这实际上取决于您要解决的用例,因为您应该针对这些模型的特定查询进行优化。

我建议观看这些视频以获得更好的想法:

我认为将 Foods 和 Reservations 存储为顶级集合最终会在以后为您带来更大的灵活性。

获取 restaurantID 并将其粘贴到这些集合中的每个文档中非常容易,因此我个人认为您不应该将它们嵌套在 Restaurants 集合中。这是使用大量嵌套集合的个人喜好。

我认为最优结构是:

Restaurants (collection)
--- Name: Chipotle
--- ID: restaurant1
--- Foods: [{ Name: foodItem1 }, { Name: foodItem2 }]

Foods (collection)
--- Name: foodItem1
--- Ingredients: abc
--- Nutrition Facts: xyz

Reservations (collection)
--- User: user1
--- Restaurant: { id: restaurant1, name: Chipotle }
--- Time: 3pm

Users (collection)
--- ID: user1

您会注意到有一些冗余信息。这很好,所以如果您请求所有预订,您将获得餐厅的名称和 ID 等您可能想要的东西。你会发现你会想要多次存储数据,这对我来说是一个很好的结构。

有了这个结构,你可以很容易地调用:

All reservations by user XAll foods meeting nutrition limits of Y

而不是调用所有餐厅的预订子集合列表的 collectionGroup 查询。你不会总是想按餐厅查询你的预订,也许你想按用户或时间等来查询。

根据您的评论:

the restaurant´s management should be able to see his reservation together with other reservations from other clients, in a list. And each client should be able to see his history of reservations as well.

我将尝试为您提供一个可以帮助您轻松获取数据的模式。

Firestore-rrot
   |
   --- users (collection)
   |    |
   |    --- uid (document)
   |    |    |
   |    |    --- type: "manager"
   |    |
   |    --- uid (document)
   |         |
   |         --- type: "client"
   |
   --- reservations (collection)
        |
        --- reservationIdOne (document)
        |       |
        |       --- reservedBy: "uid"
        |       |
        |       --- date: September 21, 2019 at 1:15:02 PM UTC+3
        |
        --- reservationIdTwo (document)
                |
                --- reservedBy: "uid"
                |
                --- date: September 21, 2019 at 1:18:42 PM UTC+3

使用此架构,您可以简单地查询数据库以获取所有用户或特定用户(经理或客户)。您还可以通过添加对 reservations 集合的引用来获取所有预订。如果您只想获得单一类型(经理或客户)的预订,您应该使用如下所示的查询:

db.collection("reservations").whereEqual("type", "manager");

如您所见,我还添加了 date 属性 以便您可以轻松地将它们降序排列(最后的预订在前)。