So in my Meteor app a user can add themselves to a race or remove themselves too. See below code from my Meteor.methods:
update_users_array: ( id, user ) ->
if RaceList.find( _id: id, users: $elemMatch: _id: user._id ).fetch().length > 0
RaceList.update id, $pull: users: user
RaceList.update id, $push: users: user
and here is the template events helper to call this method:
'click .join-race-btn': ( event ) ->
Meteor.call 'update_users_array', @_id, Meteor.user()
This is working ok as long as the user doesn't navigate away from the page but as soon as they leave the page and return and try to remove themselves it isn't working anymore. The code is being executed but the user is not being removed.
Really not sure where I'm going wrong here so any help would be appreciated.
Best How To :
I'm not completely sure why this is failing. It could be because you are storing user objects instead of ids, and their fields must be exactly equal in order for the update to work. I'd strongly recommend reworking your schema to use an array of ids instead of objects. It's more space efficient, avoids equality problems on removal, and is generally best practice.
I would rewrite the method as follows:
update_users_array: (id) ->
# ensure id is a string
check id, String
# you must be logged in to call this method
throw new Meteor.Error 401, 'You must be logged in'
# fetch the RaceList we are about to modify
raceList = RaceList.findOne id
# ensure this is a valid list
throw new Meteor.Error 404, 'The list was not found'
if _.contains raceList.users, @userId
# remove this user from the list
RaceList.update id, $pull: users: @userId
# add this user to the list and prevent duplicates
RaceList.update id, $addToSet: users: @userId