【问题标题】:Storing data by 'week' in Firebase / Firestore在 Firebase / Firestore 中按“周”存储数据
【发布时间】:2018-08-10 14:42:26
【问题描述】:

我正在尝试设计我的商店数据结构来存储我们设置为特定周的购物清单。

这是我最初的方法:

// api/users

{
    user: 'Karl Taylor',
    userId: 43
    shoppingListId: 1
}

那我就查询api/shopping_lists/1

我打算将周条目设置为一周的第一天。例如 2018 年 3 月 19 日星期一,这将包括从 19 日星期一到 25 日星期日的所有内容。

// api/shopping_lists/1

{
    userId: 43
    weeks: {
        19-03-2018: ['Eggs', 'Milk'] // week 1
        26-03-2018: ['Pasta', 'Cheese'] // week 2
    }
}

任何关于这种数据结构的好资源都会很棒。

【问题讨论】:

  • 当我评论彼得的回答时,我建议使用ISO 8601 格式。例如:YYYY-Www,例如: 2018-W1.
  • @FrankvanPuffelen 感谢弗兰克的建议,我会将其整合到这个新流程中。

标签: firebase database-design nosql google-cloud-firestore data-modeling


【解决方案1】:

你可以这样做:

Users
  useruid
    name:userx
    email:userx@gmail.com
  useruid
    name:usery
    email:usery@gmail.com

Daysoftheweek
     randomid
        date: 2018-03-19
        item1:eggs
        item2:popcorn
        username: userx
      randomid
         date:2018-03-26
         item1:pizza
         item2: pepsi
         username:userx

然后你可以查询orderByChild("date").equalTo(2018-03-19),你会得到当周的物品清单

【讨论】:

  • 此查询不会获取所有用户在特定日期的所有购物清单吗?我只想为特定一周的 1 个用户获取特定的购物清单
  • 是的,这个查询只是一个例子orderByChild("date").equalTo(19-03-2018) 它会给你上面评论中所说的内容。但是要获取特定用户,您只需获取当前用户并对其进行查询
  • 请不要以这种格式存储日期26-03-2018。虽然它对用户来说很自然,但它是一种在排序和过滤方面存在问题的格式。相反,要么将它们存储为时间戳,要么以 ISO 8601 格式存储,例如 2018-03-26。这些格式都允许对日期进行排序和过滤。
  • @PeterHaddad 我的目标是显示一整周而不是特定日期的项目列表。
  • 是的 item1 和 item2 是以 2018-03-19 开头的那一周的项目
【解决方案2】:

一种自然的结构方式是在用户下有一个列表子集合。

所以一个例子是:

Collection: /users
  -> Document: <auto id> (acts as user ID)
     {
       user: 'Karl Taylor'
     }
     Collection /lists
     -> Document: "2018-03-19"
        {
          items: ['milk', 'eggs']
        }
     -> Document: "2018-03-26"
        {
          items: ['pasta', 'cheese']
        }

在控制台中,users 集合如下所示:

lists 集合如下所示:

这使您可以获取以下用户的所有周列表:

db.collection("users").doc(userid).collection("lists")
  .get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());
    });
  })
  .catch(function(error) {
    console.log("Error getting documents: ", error);
  });

或者只是一个带有查找的特定列表:

db.collection("users").doc(userid).collection("lists").doc("2018-03-19")
  .get().then(function(doc) {
    if (doc.exists) {
      console.log("Document data:", doc.data());
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
    }
  }).catch(function(error) {
    console.log("Error getting document:", error);
  });

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 2021-08-11
    • 2020-06-19
    • 2022-01-03
    • 1970-01-01
    • 2021-07-18
    • 2020-07-24
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多