Reputation: 422
I am developing a simple chatting app with Mongoose (MongoDB) and NodeJS as my backend.
I have this Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
isActive: {
type: Boolean,
default: true,
}
}, {timestamps: true});
My problem is how should I update if the user is offline? should I define some routes to change that or how should I do it, please?
I'm not sure if I designed the Schema correctly, especially the isActive field
. you can suggest to me a better Schema as well.
Thank you so much as you help me out!!! 🙏🙏
Upvotes: 1
Views: 739
Reputation: 1609
You can do it using socket.io
Client-side you can fire emit with userId like
const socket = io();
socket.emit('online',{userId:'LoggedInUserId'});
Server-side
const onlineUsers = {};
io.on('connection', function(socket){
socket.on('online', function(data){
onlineUsers[socket.id] = data.userId;
const doc = await User.findOneAndUpdate({
id: data.userId
}, { isActive: true }, { upsert: true });
});
socket.on('disconnect', function(){
const oflineUserId = onlineUsers[socket.id];
const doc = await User.findOneAndUpdate({
id: oflineUserId
}, { isActive: false }, { upsert: true });
});
});
Upvotes: 2
Reputation: 497
Well you should create a middleware that will set the status into cache. Now define a function that will fetch the status of user from cache. And call this function in the parent layout.
Upvotes: 0