2012-07-16 116 views
0

,所以我將原稿到蒙戈DB這樣更新蒙戈文件

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() { }); 
    }); 

} 

我有另一個事件

function logout(id, disconnect) { 

我想更新(或替換?)這個紀錄並添加disconnect: (time)。我會如何去做這件事?通過這種方式,我可以判斷一個人何時連接以及何時與聊天斷開。

我使用socket.io這樣我就知道他們的確切斷開時間

預先感謝您

回答

1

首先,對隱斷開閱讀關於明確:Socket.io: How to handle closing connections?。基本上,你的顯式註銷處理程序(這是很好!)應該調用與斷開連接處理程序相同的代碼,以防用戶沒有明確註銷的機會。

所以除了你的註銷碼,你也想:

socket.on('disconnect', handleDisconnect) 

而且在斷開/註銷處理程序,你會希望找到該用戶最近的連接文件和更新。

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*/} 
) 
+0

非常感謝! – Jordan 2012-07-17 16:44:55