MeteorJS 用户配置文件对象 属性 不存在

MeteorJS user profile object property doesn't exist

嘿,伙计们,我正在努力使默认用户包的用户配置文件具有 user.profile.friendList 的 属性,这将只是引用不引用外键我存储用户朋友的 friendList 集合。但是,它说 属性 friendList 的 undefined 不存在。

这是我与之相关的服务器端 JS:

friends = new Mongo.Collection("friends");

Accounts.onCreateUser(function(options, user) {
        // We're enforcing at least an empty profile object to avoid needing to check
        // for its existence later.
        user.profile = options.profile ? options.profile : {};
        friends.insert({owner:Meteor.userId()});
        user.profile.friendList = friends.findOne({owner:Meteor.userId()})._id;
        return user;
    });

Meteor.publish("friendsPub",  function(){
        list = this.userId.profile.friendList;
        if(list) return friends.findOne({owner:list});      
    });

这是与之交互的客户端js:

Template.login.helpers({
    getFriends: function(){
        if(Meteor.userId()){
            Meteor.subscribe("friendsPub"); 
            return friends.find().fetch();
        }
    },

所有应该做的就是创建一个用户,其好友 ID 作为用户配置文件的 属性 friendList。然后它使用它来获取朋友集合中列出的用户。我意识到它只会显示 friendsList 中用户的 ID,但我想在我让它显示实际的朋友用户名之前 运行。

Meteor.userIdonCreateUser (the account hasn't been created yet). One possibility is to examine the friend list inside of onLogin 里面的 null。试试这样的东西:

Accounts.onLogin(function(data) {
  var user = Meteor.users.findOne(data.user._id);
  if(_.isEmpty(user.profile.friendList)) {
    // insert stuff here
  }
});

或者,您可以让客户端调用这样的方法:

Meteor.methods({
  addFriendsList: function() {
    var user = Meteor.users.findOne(this.userId);
    if(_.isEmpty(user.profile.friendList)) {
      // insert stuff here
    }
  }
});

Accounts.createUser 的回调中。

第三种选择是将用户标记为 "new" 并在 cron 作业中清除所有新用户。有关详细信息,请参阅 this issue

另请注意,friendsPub 需要 return 光标而不是文档(您希望发布商调用 find 而不是 findOne)。

正如其他人所说,用户 ID 在 onCreateUser 中尚不存在。我建议您将电子邮件添加到通用列表或更好,只需将空的好友列表添加到配置文件并用其他用户 ID 填充即可。下面的代码是如何将您的属性正确添加到用户配置文件中。

Accounts.onCreateUser(function(options, user){
    console.log(options.email); // possible available identifier

    var customProfile = new Object();
    customProfile.friendList= [];

    user.profile = customProfile;
    return user;
});

我认为出版物应该 return 一个游标,正如

中所记录的那样

http://docs.meteor.com/#/full/meteor_publish.

friendsPub 出版物 return 是使用 findOne 的单个文档。引用:

If a publish function does not return a cursor or array of cursors, it is assumed to be using the low-level added/changed/removed interface, and it must also call ready once the initial record set is complete.