mongodbmongoosechatschemaless

MongoDB: Designing a db for saving chats / offline / undelivered chats


I am trying to create a mongodb design to support a chat application. The system needs to write the message to a collection with a status of delivered (boolean) and read (boolean).

1 message would be able to be sent to more than 1 person.

Anybody know of a good schema for this type of thing in the mongodb schemaless design?

I was thinking of have a array inside the collection that would contain another document that would have 3 properties.. "name of person addressed to", "read (boolean)" and "delivered (boolean)".

This way at runtime I can reach into the db using dot notation to find all messages addressed to a specific person, all unread messages, all undelivered messsages etc.

I think I need to have another property too "name of person sent from", so i am able to rebuild the a list of messages sent and there status

Has anyone seen a good setup for this ?

Am I thinking this correctly or is there a better way of achieving such a solution


Solution

  • If I understand correctly, you want to keep track of the status of a message. A message is sent by one person, but can be received by many. The status of the message depends on which recipient we're talking about - Joe may have read the message from Tim, while Sally has it in her inbox but hasn't read it, and Joan hasn't received it yet. Based on your rough requirements I would model this with a message_status collection where each document represents the status of one message with respect to one recipient:

    {
        "message_id" : ObjectId(...) // some unique identifier or reference for the message
        "sender" : { "name" : "Tim", "ref" : ObjectId(...) }
        "recipient" : { "name" : "Sally", "ref" : ObjectId(...) }
        "status" : { "delivered" : true, "read" : false }
    }
    

    I'm unclear on to what extent I need to use references versus just embedding in the names because your full use case isn't specified. Getting the kinds of information you mentioned is pretty easy:

    all messages addressed to a specific person

    db.message_status.find({ "recipient" : ObjectId(...) })
    

    all unread messages [sent to a specific person?]

    db.message_status.find({ "recipient" : ObjectId(...), "status.read" : false })
    

    all undelivered messsages [sent to a specific person?]

    db.message_status.find({ "recipient" : ObjectId(...), "status.delivered" : false })
    

    rebuild the a list of messages sent and there status

    db.message_status.find({ "sender" : ObjectId(...) })