0

I have an app with chatrooms. Each chatroom has its own collection in mongodb. Along with other info, I want to save the chat history for each chat chatroom, in a "messages" field.

Database: myApp
Collection: "chatroom_1"

For example, the collection "chatroom_coders" should have:

{
    roomName: coders,
    messages: {
        0: {sentByUserID: 1, message: 'hi', chatID: 0},
        1: {sentByUserID: 1, message: 'hi', chatID: 1},
        100: {sentByUserID: 1, message: 'hi', chatID: 100},
    },
    filesShared: ['penguin.png', 'turtle.png'],
    created_at: null,
    updated_at: null

}

Then I want to retrieve the data as it is stored above. Then I will be manipulating it (on my side, in JS) for example delete chatrooms['chatroom_coders'].messages[0], and will need to update the collection to remove that field.

Not sure yet how to achieve what I want and couldn't find the right info yet on the web. How do I add my message to the messages (and create that messages object, as well) to that specific chatroom collection? Suggestions on improving the way I want to store data in mongodb would be appreciated too.

jSmith
  • 275
  • 1
  • 4
  • 13
  • So... delete a specific message based on the index? (http://stackoverflow.com/questions/4588303/in-mongodb-how-do-you-remove-an-array-element-by-its-index) – tymeJV Sep 28 '15 at 21:43
  • @tymeJV First thing I need to do is adding the message into the messages object of the specific chatroom collection. – jSmith Sep 28 '15 at 21:47
  • you probably don't really want to store all the messages in a single mongodb object. It would probably be better to store each message object as an independent object. Where each message object has a field that references the the chatroom object. – bhspencer Sep 28 '15 at 22:03
  • I'm now thinking about creating collections like {chatroomName}_chatHistory, {chatroomName}_filesShared, does that make sense for mongodb? – jSmith Sep 28 '15 at 22:22

1 Answers1

0

You'd probably want to have an index that keeps track of last index of the messages, so you'd have a structure like

{
    roomName: coders,
    messages_index : 100,
    messages: {
        0: {sentByUserID: 1, message: 'hi', chatID: 0},
        1: {sentByUserID: 1, message: 'hi', chatID: 1},
        100: {sentByUserID: 1, message: 'hi', chatID: 100},
    },
    filesShared: ['penguin.png', 'turtle.png'],
    created_at: null,
    updated_at: null
}

You can then update the index, query it and use it as the key for the new object

Anugerah Erlaut
  • 990
  • 13
  • 23