How do I remove a database entry when Session ends?


I’m creating an anonymous chat application, so there is no standard account package. Instead, a user is presented with a form on the landing page, and when they enter a tagline and description, they will be taken to the anonymous chat part of the application and their tagline and description will go into a collection.

I want their profile to be removed from the collection if they close their browser or refresh. How do I do this? Is their a way to have a Session variable be true when they are connected, that triggers a function when it goes to false?


window.onunload might be the best way to do this. Useful S.O. post.


window.onunload = removeUser;
function removeUser() {'removeUser', Session.get('userId'));
  // Assuming you've got the current userId in the Session
  // Not recommending that, but you get the idea ...


  removeUser: function (userId) {
    check(userId, String);
    CurrentUsers.remove({_id: userId});

Disclaimer: I haven’t actually tested this.

#3 should help you out.

You can peridically delete guests:

/* clean out all guest accounts more than 2 hours old */
var before = new Date();
before.setHours(before.getHours() - 2);

Combined with:

Should lead to some nice stuff!

Meteor.publish(null, function(){
    //do some stuff upon user connection if needed

        //do needed operations when user disconnects


Very nice! I take back my approach above. @copleykj’s approach is infinitely superior.


@copleykj Thanks for the solution!! I realize this.onStop gets triggered when I refresh the page as well… (and every time meteor updates) is there something that will differentiate between the page being refreshed and the page being closed?