【问题标题】:firestore data storing in sub collectionsfirestore 数据存储在子集合中
【发布时间】:2017-10-24 07:52:14
【问题描述】:

我正在 Firestore 中制作“聊天演示”以保存消息我这样做是这样的:

FirebaseFirestore.getInstance()
    .collection(Consts.R_CHAT_ROOM)
    .document(finalChatRoom)
    .collection("messages")
    .document(currentTime)
    .set(chatModel);

但问题是finalChatRoom 文档显示它不存在,尽管它包含一个子集合。

正如它所写的那样:“此文档不存在”,尽管其中包含一个名为 messages 的子集合,其中包含更多文档。

但我需要检查具有特定名称的文档是否存在于 chatRoomsMessages 集合下。

我的代码有什么问题,还是我需要以其他方式处理?

提前致谢。

【问题讨论】:

  • 您的新文档将位于messages 子集合下。
  • 是的,但我需要检查document with a specific name 是否存在于chatRoomsMessages collection 下。

标签: android firebase google-cloud-firestore


【解决方案1】:

在不存在的文档中创建子集合很像创建带有子集合的文档然后删除该文档。从Subcollections section of the Data Model documentation 这意味着:

当您删除具有关联子集合的文档时,子集合不会被删除。它们仍然可以通过参考访问。例如,即使db.collection('coll').doc('doc') 引用的文档已不存在,也可能存在db.collection('coll').doc('doc').collection('subcoll').doc('subdoc') 引用的文档。

如果您希望文档存在,我建议先创建finalChatRoom 文档,其中至少包含一个字段,然后在其下创建子集合。例如:

DocumentReference chatRoomDocument = FirebaseFirestore.getInstance()
        .collection(Consts.R_CHAT_ROOM)
        .document(finalChatRoom);

// Create the chat room document
ChatRoom chatRoomModel = new ChatRoom("Chat Room 1");
chatRoomDocument.set(chatRoomModel);

// Create the messages subcollection with a new document
chatRoomDocument.collection("messages")
        .document(currentTime).set(chatModel);

ChatRoom 类类似于:

public class ChatRoom {
    private String name;

    public ChatRoom() {}

    public ChatRoom(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // ...
}

这是使用custom objects functionality of Firestore。如果你不想在这个阶段使用自定义对象,你可以创建一个简单的Map 来代替聊天室:

Map<String, Object> chatRoomModel = new HashMap<>();
chatRoomModel.put("name", "Chat Room 1");

【讨论】:

  • 感谢您的回复,我是really helpful for me to understand things in a better way,让我试试您告诉我的方式,如果一切顺利,我会将其标记为答案。谢谢。
猜你喜欢
  • 2018-04-23
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2019-10-01
  • 2020-06-26
  • 1970-01-01
相关资源
最近更新 更多