If you’re using NoSQL MongoDB for your next chat application, then below, you will find the best example of schema designs for you MongoDB chat application, In this Tutorial, we will discuss MongoDB chat schema and Mongoose chat schema for Chat Application.
Before you proceed, things to keep in mind:
- Design schema according to the requirements of your app.
- Keep performance in the mind, while designing your schema for MongoDB.
- Every schema is good and there is always room for improvement.
Article Contents
MongoDB Database structure for chat application
Requirements:
- User Details: email, full name, username, password, etc
- Chat conversations or messages.
User details Structure:
{ username: 'stackfame', email: 'stackfame@gmail.com, salt: 'hashing code', password: 'hashing with salt', dob: date, logs: { last_login: date, last_password_reset: date, last_activity }, state: { online: true or false, available: true or false }, contacts: [ user_id[1], user_id[2], user_id[3], user_id[4] ] }
Chat conversations Structure:
{ members: [ user_id[1], user_id[2], user_id[3], user_id[4] ], messages: [ { from: user_id[1], body: 'Hello everyone, what's up?' }, { from: user_id[3], body: 'just work :)' }, { from: user_id[4], body: 'Busy with familia' }, { from: user_id[2], body: 'Okay, Catch you later folks' }, { from: user_id[1], body: 'bye :)' } ] }
You can also join both User and Message, but two separate DB makes work lot easier to query the database.Now we will discuss Mongoose Schema for MongoDB Chat application.
Mongoose Schema for MongoDB Chat Application
This can be done in a lot of ways, but No schema is good or bad, it’s just the requirement and ease of access.
var user = new mongoose.Schema({ username: { type: String, lowercase: true, unique: true }, email: { type: String, lowercase: true, unique: true }, password: String, is_active: { type: Boolean, default: false }, }); var room = new mongoose.Schema({ name: { type: String, lowercase: true, unique: true }, topic: String, users: [user], messages: [message], created_at: Date, updated_at: { type: Date, default: Date.now }, }); var message = new mongoose.Schema({ room: room, user: user, message_body: String, message_status:{type: Boolean, default: false}, created_at: { type: Date, default: Date.now }, }); var User = mongoose.model('User', user); var Room = mongoose.model('Room', room); var Message = mongoose.model('Message', message);
Thanks to StackOverflow user Andres.
Conclusion:
MongoDB – the NoSQL leader, can be used to store data effectively and without any complex table creations, which makes it ideal for modern progressive web apps and It is Used with Nodejs and AngularJS, which developers famously call MEAN Stack and No schema is Good or Bad, it’s just Each Developer’s View and Actually we need to design it according to project requirement and Performance.You can also check out the code of Chat app using MEAN stack here.