Collection helper抛出一个未定义的错误

时间:2016-01-17 03:36:05

标签: javascript meteor iron-router

我试图建立一个“房间”列表。预期的顺序:

  1. 在他/她的个人资料页面上点击该用户的姓名
  2. 检查现有房间。如果是,请到那个房间,如果没有设置新房间。
  3. 我同时使用dburles:collection-helpersreywood:publish-composite

    它给我这个错误。

      

    TypeError:无法读取undefined的属性“username”       在Document.Rooms.helpers.recName(rooms.js:18)

         

    第18行是:   返回Meteor.users.findOne({_ id:this.receiver})。用户名;

    即。 _id:this.receiver未定义。

    我还尝试在集合助手中添加保护性检查但仍然存在错误。即返回user && user.username for example

    我注意到的一件事是,我注意到当我点击用户时,它会转到与用户ID相关联的房间。然而,当我点击它时,它跳转到一个空白房间,其中不同的ID无法识别。

    相关代码:

    服务器发布

    Meteor.publish("onlusers", function (){
     return Meteor.users.find({}); 
    });
    

    Rooms.js collection helper

    Rooms.helpers({
      recName: function() { 
        return Meteor.users.findOne({ _id: this.receiver }).username;
      }
    });
    

    User.js(适用于个人资料页面事件)

    Template.usersShow.events({
      'click .user': function() {
        var receiver = this._id;
        Session.set('chatId', this._id);
        var res = Rooms.findOne({  
          $or: [ 
            { owner     : this._id },
            { receiver  : this._id }
          ]
        });
        if(res){     
          Router.go('roomDetail', { "_id" : res._id });
        } else {
          var newRoom = Rooms.insert({
            owner     : Meteor.userId(),
            receiver  : receiver, 
            username  : Meteor.user().username,
          });
          Session.set('roomid', newRoom);
          Router.go('roomDetail', { "_id" : newRoom });
        }
      }
    });
    

1 个答案:

答案 0 :(得分:2)

您的诊断:

  

_id:this.receiver未定义。

可能会产生误导。还有可能的是,当您的帮助程序运行时,用户订阅不会被完全加载。前几天我正在帮助其他与发布复合有类似问题的人 - 当父母准备好但孩子们可能还没有完成加载时,订阅被标记为准备就绪。我认为这是发布复合中的一个错误,所有相关对象确实需要存在才能将订阅标记为就绪。

而不是返回:

return Meteor.users.findOne({ _id: this.receiver }).username;

你可以这样做:

var user = Meteor.users.findOne({ _id: this.receiver });
return user && user.username;

因此,在用户对象加载之前,您将无法获得任何回报,但您不会抛出错误。