so I am inserting a document into mongo db as such
io.sockets.on('connection', function (socket) {
connectLog(socket.handshake.address.address);
function connectLog(ipAddress) {
db.collection('tracking', function (err, collection) {
var currentTime = new Date();
var doc={"ip":ipAddress, "connect": currentTime, "culture": "en" };
collection.insert(doc, function () { });
});
}
I have another event
function logout(id, disconnect) {
I'd like to update (or replace?) that record and add disconnect: (time)
to it. How would I go about doing this? This way I can tell when a person connects and when they disconnect from the chat.
I am using socket.io so I'll know their exact disconnect time
Thank you in advance
First, read this about explicit vs. implicit disconnects: Socket.io: How to handle closing connections?. Basically, your handler for explicit logouts (which are good!) should call the same code as your disconnect handler, in case the user doesn't get a chance to explicitly logout.
So in addition to your logout code, you'll also want:
socket.on('disconnect', handleDisconnect)
And in that disconnect/logout handler, you'll want to find the most recent connection document for that user and update it.
collection.findAndModify(
{"address" : address}, //same address
[['connect', 'descending']], //the most recent, findAndModify only changes the first doc
{$set: {disconnect: currentTime}}, //set the disconnect time
function(err, object){/*deal with errors*/}
)