Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firestore data storing in sub collections

I am making a "chatting demo" in Firestore for saving messages I am doing it like this:

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

But the problem is that the finalChatRoom document shows that it does not exist although it contains a subcollection.

database screenshot

As it's written there: "this document does not exist" although it contains a sub-collection named messages in it which contains further documents.

But I need to check if the document with a specific name is present under the chatRoomsMessages collection or not.

Is there any problem with my code or do I need to do it in some other way?

Thanks in advance.

like image 290
Anmol317 Avatar asked Mar 13 '26 06:03

Anmol317


1 Answers

Creating a subcollection in a document that does not exist is much like creating a document with a subcollection and then deleting the document. From the Subcollections section of the Data Model documentation this means:

When you delete a document that has associated subcollections, the subcollections are not deleted. They are still accessible by reference. For example, there may be a document referenced by db.collection('coll').doc('doc').collection('subcoll').doc('subdoc') even though the document referenced by db.collection('coll').doc('doc') no longer exists.

If you want the document to exist, I'd suggest creating the finalChatRoom document first, with at least one field, and then creating the subcollection underneath it. For example:

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);

Where the ChatRoom class is something like:

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;
    }

    // ...
}

This is making use of the custom objects functionality of Firestore. If you don't want to use a custom object at this stage, you could just create a simple Map instead to represent the chat room:

Map<String, Object> chatRoomModel = new HashMap<>();
chatRoomModel.put("name", "Chat Room 1");
like image 165
Grimthorr Avatar answered Mar 14 '26 21:03

Grimthorr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!