【问题标题】:Create FireStore Data Structure创建 FireStore 数据结构
【发布时间】:2019-02-25 09:48:40
【问题描述】:

myPosts 是收藏。 我想做如下的数据结构。

< Data Structure A >
myPosts(collection)
   ┣ userID1(document)
   ┃   ┣ postID1(collection)
   ┃   ┃   ┗ timestamp: 2018/09/21/22:22(field)
   ┃   ┣ postID2
   ┃   ┗ postID3
   ┣ userID2
   ┣ userID3

为了使数据结构如上,我写的代码如下

myPostsRef.document(userID).collection(postID).addDocument(data: [
        timestamp_field: FieldValue.serverTimestamp()
    ]) { (error) in
        if let _ = error { return }
    }

但是,当执行这段代码时,它具有以下结构。

< Data Structure B >
myPosts
   ┗ userID
      ┗ postID 
          ┗ AutoGeneratedID 
                  ┗ timestamp: 2018/09/21/22:22

我怎样才能制作像数据结构 A 这样的结构?

【问题讨论】:

  • 我不确定我是否理解。您能否编辑您的问题并在第一张图中指出哪些节点是集合、哪些节点是文档以及哪些节点是字段?
  • @FrankvanPuffelen 根据他的代码,我猜 userID 是一个文档,postID 是一个集合,时间戳是理想情况下无法在集合中应用的字段
  • 感谢您的评论。我编辑了数据结构 A,如果您能看到,我将不胜感激。
  • 我想做的是创建一个只提取我的帖子的函数。提出一个新问题是否更好,因为它有点偏离问题的标题?在回答问题时,如果您能告诉我缺少的东西是必要的,我会很高兴
  • 字段只能存在于文档中,而文档又只能存在于集合中。还建议使用固定的集合名称,因为您无法查询以获取子集合列表。所以我推荐:/myPosts(collection)/userId1(document)/posts(collection)/post1(document)/timestamp(field).

标签: swift firebase google-cloud-firestore


【解决方案1】:

字段只能存在于文档中,而文档又只能存在于集合中。还建议使用固定的集合名称,因为您无法查询以获取子集合列表。所以我建议:

/myPosts (collection)
  userId1 (document)
    posts (collection)
      post1 (document)
        timestamp (field)

您可以通过以下方式获得:

myPostsRef.document(userID).collection("posts").document(postID).setData([
  ...

【讨论】:

  • 一如既往地感谢您!代码也很有帮助!
猜你喜欢
  • 2018-06-17
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 2021-11-22
  • 2017-01-25
  • 2021-10-23
相关资源
最近更新 更多