'Best way to store chat in mongodb to reduce calls to database
I am creating a nodejs chat application, which estimatedly will recieve chat message in every 5-10 second from each of its connected client, want to know the best way to store chats in database to reduce calls to database.I am using mongodb with nodejs. like with a basic approach I will be storing the chat immediately when it is recieved from the client but I was thinking of some ways like:-
- Queuing the chat in a list until it reaches specified length then store it to database.
- Set timeout like 5 minutes and then store them.
Or any best practices that are followed by companies like Instagram or Telegram. Any suggestions would be appriciated. Thanks in advance.
Here's is my chat schema:-
let userSchema = new mongoose.Schema({
chatType:{
type:String,
enum:[
'chat',
'group'
],
default:()=>{this.members.length>2?'group':'chat'}
},
members:[
{
id:mongoose.Schema.Types.ObjectId
}
] ,
createdOn:{
type:Date,
default:Date.now
},
chats:[
{
sentOn:{
type:Date,
default:Date.now
},
message:{
type:String
},
sentBy:{
id:mongoose.Schema.Types.ObjectId,
// validate:{
// validator:(value)=>{
// return this.members.map(e=>e.id).includes(value)
// },
// message:(props)=>{`${props.value} is not in chat members` }
// }
}
}
]
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
