Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

firebase - Construct Model from different Collections Firestore - Swift Programmatically

I'm using MVC pattern to deploy iOS application. When I'm implementing a chat feature like whatsapp I get confused:

The basic idea is that I need to populate the collection view with all the users present in a firestore collection documents adding a listener to the latest message sent.

the schema for for the collection looks like this:

User_lastMessages (collection)

|

userid (document)

|

ChatUsers (collection)

|

finalDocumentId (document)

This latest document contains:

-user id
-lastMessageSent
-timestampLastMessage
-username 

The UI representation I need to accomplish is this one:

UI

1)the username and lastmessage come from the collection I previously mentioned

2)the ImageView (white square) comes from another collection and I can retrieve it through the uid of the user

Question: the number you see on the right side of the cell comes from another collection and it can constantly change. How can I be sure that whenever it changes the UI changes accordingly?

I'm confused whether it's a bad approach to construct a model using different Firestore collection documents or it is mandatory that a model is composed by only one Firestore document.

question from:https://stackoverflow.com/questions/65862943/construct-model-from-different-collections-firestore-swift-programmatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can easily utilise several documents in your model. In your case, the appropriate configuration would be:

  1. Your view controller loads one document
  2. Each cell in your list is responsible for loading another two documents (with image view and message counts). You can attach listeners to ensure that this info changes realtime

However, before you deploy, you really need to think about the number of those "read" operations. When you design a schema in Firestore, you should always consider your use case and minimise unnecessary reads.

For example, you could have another collection called "Chats" which would contain:

  1. user1_id
  2. user2_id
  3. number_of_messages
  4. chat_icon
  5. unique_chat_id

In this case, a simple query "where user1_id == ID" would give you an array containing all the info you need.

Messages could then contain a field chat_id which would enable you to load all messages belonging to a specific chat.

What I outlined above is not necessarily the best or most optimal schema. However, I advise you to watch Firestore videos on this (they are awesome): https://www.youtube.com/watch?v=haMOUb3KVSo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...