0
votes

I'm building a group chat system using Google Firestore. For each group, I'm using a custom Firestore document ID to identify the chat room where messages belong. Every time a user send a message to a room, this snippet works even if the document with that ID does not exists as documents are created implicitly:

this._firestore
        .collection('rooms')
        .doc('group' + group.id)
        .collection('messages')
        .add({
            uid: message.from.id,
            content: message.content,
            date: firebase.firestore.FieldValue.serverTimestamp()
        })

The benefit of this method resides in that the document that represents a chat room is not created until one user sends a message. But how can I store the channel creation time without having to check every time a message is sent if the document exists or it has the createdAt property? Is thery any signal or event that detects implicitly created documents?

1

1 Answers

0
votes

No document is implicitly created in the snippet you gave. If the document in the top-level doesn't exist yet, you merely end up with a subcollection that doesn't have a "parent" document. In the Firestore console this is indicated by the fact that the document ID is shown in italics: the document ID exists, but there is no document data for it.

You could create a Cloud Function that detects this situation and creates the document in the top-level collection. That's then also where you'd put the default values in that document.