How do I remove a database entry when Session ends?


#1

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?


#2

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

CLIENT

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

SERVER

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

Disclaimer: I haven’t actually tested this.


#3

https://atmospherejs.com/artwells/accounts-guest 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);
Accounts.removeOldGuests(before);

Combined with: https://atmospherejs.com/mizzao/user-status

Should lead to some nice stuff!


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

    this.onStop(function(){
        //do needed operations when user disconnects
    });
},{is_auto:true})

#5

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


#6

@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?