Display all chat messages between 2 users in the same chat

Hi All,

I’m building an in-app chat feature. I’m currently storing the chat users (User A & User B) in “Chat” data type & their messages in “Message” data type along with a link to the “chat” datatype.

The issue that I’m facing now:
Whenever, User A sends a message to User B, each message is getting stored as each chat. Eg: When User A sends 10 messages to User B → it shows 10 different chats under User B’s name. When clicked on each chat, each individual message is getting displayed.

How to sort so that I can have all messages between User A and User B in one chat (irrespective of when the message was sent), all messages between User A and User C in a separate chat, etc.?

Please help me out! Thanks in advance!