在 Meteor 应用程序中离开和返回页面后,项目没有从数组中拉出

Item not being pulled from array after navigating away from and back to page in Meteor app

所以在我的 Meteor 应用程序中,用户可以将自己添加到比赛中,也可以将自己删除。请参阅我的 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

    else

        RaceList.update id, $push: users: user

这里是调用此方法的模板事件助手:

Template.race.events

    'click .join-race-btn': ( event ) ->

        Meteor.call 'update_users_array', @_id, Meteor.user()

只要用户不离开页面,它就可以正常工作,但是一旦他们离开页面并 return 并尝试删除自己,它就不再工作了。正在执行代码,但未删除用户。

真的不确定我哪里出错了所以任何帮助将不胜感激。

谢谢。

我不完全确定为什么会失败。这可能是因为您正在存储用户对象而不是 ID,并且它们的字段必须完全相等才能使更新工作。我强烈 建议修改您的架构以使用 ID 数组而不是对象。它更 space 高效,避免了删除时的相等性问题,并且通常是最佳实践。

我会重写方法如下:

update_users_array: (id) ->
  # ensure id is a string
  check id, String

  # you must be logged in to call this method
  unless @userId
    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
  unless raceList
    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
  else
    # add this user to the list and prevent duplicates
    RaceList.update id, $addToSet: users: @userId