问题
I'm developing an chat app in Swift and when the user creates a chatroom for the first time, it obviously doesn't exist yet in Firebase. Only until the first message gets created does everything build out.
When my app first loads, in the viewDidLoad(), I'm setting a reference to the chat at this path (keep in mind it doesn't exist):
reference = db.collection("chatrooms").document("\(chatRoomId)").collection("thread").document("\(threadId)").collection("messages")
So when I add my snapshot listener just below this, and the user creates his first message on the thread, the listener doesn't fire for everyone (I assume, anyway, because it doesn't fire for me)
I do like that once you add your first message, it creates the whole document structure above, but this means my first users who might be watching the thread (however unlikely this is) won't get the message.
Is this an uncommon edge case I'm trying to guard against, or do I need to do something like this (pseudo-code)?
IF (this collection doesn't exist yet) THEN
CREATE GROUP/THREAD/EMPTY MESSAGE COLLECTION
reference = db.collection("chatrooms").document("\(chatRoomId)").collection("thread").document("\(threadId)").collection("messages")
ELSE
reference = db.collection("chatrooms").document("\(chatRoomId)").collection("thread").document("\(threadId)").collection("messages")
END
I was wondering if there is some sort of initializer I can call to make the structure for me, but still set it up so my first message to the collection fires the snapshot listener.
Thanks!
回答1:
What you're doing is unnecessary. There is no formal method required to create a collection. A collection simply springs into existence when you first write a document into it. You can listen on an empty collection with no problems, and listeners should be invoked even if the collection wasn't visible in the dashboard at the time it was added.
来源:https://stackoverflow.com/questions/52675190/firebase-cloud-firestore-initializing-a-collection