Home > Net >  Firebase database structure for one-on-one messaging?
Firebase database structure for one-on-one messaging?

Time:10-06

I'm relatively new to Firebase and I'm trying to figure out the best way to structure my DB for 1:1 chats.

It basically has to function like Whatsapp - you have your active conversations on the left when a person sends a message that conversation is then put on top of the list and a basic one-on-one chat on the right.

Right now the best that I have got is to create a firestore "chats" collection

chats : {
chat : { users : [user_id, user_id], messages : {user_id, message, created_at} created_at } 
}

Would this solution allow me to :

  • Get all the chats based on the logged-in user?

  • Then Sort the returned chats by date?

  • Get the latest message from the messages collection for each returned chat?

  • On new message change the order of the chat and update the latest message?

And if all of that is doable would this be effective or is a there a better way?

Any help would be appreciated - thanks!

CodePudding user response:

How would a logged in user be associated with any given chat they participated into?

Right now your structure doesn't seem to allow for an easy handling of this, given that "user_id" are nested within the chat document.

Personally, here's what I would do.

First I would create 2 collections, one called chats one called users. users would have the following structure:

{"users": {
    "userID_1": {
        "name": "John",
        "surname": "Smith",
        "chats": [
            "chatID_1",
            "chatID_2",
            "chatID_3"
        ]
    },
    "userID_2": {
        "name": "Betty",
        "surname": "Sue",
        "chats": [
            "chatID_1",
            "chatID_4"
        ]
    }
}}

Chats would instead be stored like this:

{"chats": {
    "chatID_1": {
        "chatName": "foo",
        "otherInfo": "..",
        "messages": {
             "messageID_1": {"senderID": "..", "message": "..", "timestamp": 999},
             "messageID_2": {"senderID": "..", "message": "..", "timestamp": 999}
        }
    },
    "chatID_2": {
        "chatName": "bar",
        "otherInfo": "..",
        "messages": {
            ...
        }
    }
}}

This way, when a user is logged in, you can easily fetch all his chats by querying users.userID.chats, and retrieve the content of any selected chat by querying chats.chatID.messages.

  • Related