Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1:1 and group chat schema in NoSQL / MongoDB

Tags:

mongodb

nosql

I want to create a chat app for 1:1 and group chat activities.

I've created a schema for both scenarios:

{ // group 
    "id": 1 // id of the group
    "name": "Chat Group" // name of group; if there are more than 2 members
    "members": [ "member1", "member2", ...] // ids of the group chat members; only they have access to the JSON document
    "chatlog": [ "timestamp1": ["member1", "message1"], "timestamp2": ["member2", "message2"], ...] // who sent which message in chronological order
}

Would it be better to store the access list of users in "members" array as seen above or is this solution with "chat_groups" better:

{ // user 
    "id": 1 // id of the user
    "name": "Max" // name of the user
    "chat_groups": [ "1", "2", ...] // ids of the groups, the user is a member of
}
like image 770
MJQZ1347 Avatar asked Feb 06 '16 20:02

MJQZ1347


1 Answers

As per this post, there should be 3 nodes, user, convo and messages. And convo decides whether it is 1:1 chat or group chat. Additionally, you can add another property as creator in convo to set group admin rights.

Example: User

{ // user
  "id": 123,
  "name": "Omkar Todkar"
}

Example: Convo

{ // group
  "id": 1,
  "members": [123, 234, 345]
  "creator": 123
},
{ // 1:1
  "id": 2,
  "members": [123, 345]
  "creator": 123
}

Example: Messages

{ // group message
  "convo_id: 1,
  "author": 123,
  "content": "Welcome, to our new group."
},
{ // 1:1 message
  "convo_id: 2,
  "author": 123,
  "content": "Hey, you wanna join us in group?."
},
{ // 1:1 message
  "convo_id: 2,
  "author": 345,
  "content": "Sure, I would love to join."
},
{ // group chat
  "convo_id: 1,
  "author": 234,
  "content": "Hi, Happy to see you both here."
}

and if you need to maintain state when one of participents deletes some message or conversation itself the model would be

conversation :{
id:String,
participants:[String], //user_id's
deleted_by:[String] //user_id's
....
}
message:{
  conversation_id:String,
  deleted_by:[String] //user_ids,
  content:String
  ...
}

at some point all participants deletes the conversation or message i added a trigger pre save to check that and if participants ===deleted_by then permanently remove the conversation or message

its worked for me!

like image 187
Omkar Avatar answered Sep 22 '22 14:09

Omkar