I am new to Firebase and I have to create a chat system. I found that the doc structure should be nested e.g if a person sends a message, a new doc with its id will be created in the main collection and then a new collection will be added to the doc. now each doc in that nested collection will be considered as a message obj.
a rough sketch of how the new message in the nested document will be added but the problem is when there is no doc with UI exist or no collection in that doc exist
firestore().collection("chatBox").doc(uid).collection("message").add( { text: "this is my first message", user: {_id:356}, avatar: "link of avatar", name: "john", createdAt: new Date().getTime() } )
const sendMessage = async (messages = []) => {
const msg = messages[0];
const id = msg.user?._id?.toString();
const collectionRef = firestore().collection(CHATBOX);
const doc = collectionRef.doc(id);
const docExists = await doc.get().then(function (doc) {
return doc.exists;
});
if (docExists) {
const collection = doc.collection(MESSAGES);
const isCollectionEmpty = collection.get().then(col => {
return col.empty;
});
if (isCollectionEmpty) doc.set({id: MESSAGES});//creating new collection
else collection.add({...msg, createdAt: new Date().getTime()});//inserting doc if collection exist
} else {
collectionRef.add(id);// creating doc in main collection
}
};
The ability to create a document only if it does not exist can be done using the following Transaction. Here, the
createDocIfNotExist
method creates the document with the given data, only if it does not already exist. It returns aPromise<boolean>
indicating whether the document was freshly created or not.Applying this to your code then gives:
This can be further reduced to:
Note: Avoid using the variable name
doc
as it is ambiguous and could be an instance ofDocumentData
,DocumentReference
, orDocumentSnapshot
(at minimum, usedocData
,docRef
anddocSnap
/docSnapshot
respectively). Similarly, usecolRef
for aCollectionReference
andqSnap
/querySnap
forQuerySnapshot
objects.