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

MeteorJS user profile object property doesn't exist

本文关键字:属性 不存在 对象 配置文件 用户 MeteorJS      更新时间:2023-09-26

嘿,伙计们,我正试图使它使默认用户包的用户配置文件具有user.profile.friendList的属性,这将只是一个引号反引号外键到friendList集合,我存储用户的朋友。它说未定义的属性friendList不存在。

这是我与它相关的服务器端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.userId是onCreateUser内部的null(帐户尚未创建)。一种可能性是检查onLogin内部的好友列表。试一下:

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作业中扫描所有新用户。

还要注意,friendsPub需要返回游标而不是文档(您希望您的发布者调用find而不是findOne)。

就像其他人所说的那样,userId还不存在于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;
});

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

中所记录的那样

http://docs.meteor.com//全/meteor_publish。

friendsPub发布返回使用findOne的单个文档。引用:

如果publish函数没有返回游标或游标数组,则假定它使用了低级的添加/更改/删除接口,并且在初始记录集完成后还必须调用ready。