I am trying to structure a firebase database for chat system. What I wanted to achieve is after user successfully logged in, they will see a list of message they have sent t
It sounds like you want to:
If those are your requirements, I'd model precisely those in your database.
So for each chat room (a chat between a certain set of users), model the messages for that room:
chats: {
$roomId: {
$messageId: {
senderId: "..."
message: "..."
}
}
}
Now for each user, model a separate list of their chats and the latest message:
userRooms: {
$uid: {
$roomId: {
"message: "..."
}
}
}
Now whenever a user posts a message to a room, you will need to push that message to /chats/$roomId
and for each user in that chat room write the message to /userRooms/$uid/$roomId
(overwriting the exiting message there).
This type of data duplication is known as fanning out data, because you're spreading a single snippet of information over multiple places in the database. It is quite common in NoSQL databases, and is part of the reason they scale so well: they trade write complexity for read performance.