2

如何将其他字段添加到用户集合中。我了解选项对象允许四个字段 - 用户名、电子邮件密码和个人资料。那么在 Accounts.onCreateUser 上,有没有办法在根级别(不在配置文件字段内)添加其他字段?

截至目前,解决方案是使用 Accounts.createUser 在配置文件中添加字段,将此字段复制到根级别,然后使用 Accounts.onCreateUser 删除配置文件中的字段。这是在下面的示例中为“userType”完成的

客户端.js

Template.joinForm.events({
'submit .form-join': function(e, t) {
    e.preventDefault();
    var firstName = t.find('#firstName').value,
    lastName = t.find('#lastName').value,
    email = t.find('#email').value,
    password = t.find('#password').value,
    username = firstName + '.' + lastName,
    profile = {
            name: firstName + ' ' + lastName,
            userType: selectedUserType // this is copied to root level and deleted from profile.
};

    Accounts.createUser({
        //NEWFIELD1: [],
        //NEWFILED2: [],
        email: email,
        username: username,
        password: password,
        profile: profile
    }, function(error) {
        if (error) {
            alert(error);
        } else {
            Router.go('/');
        }
    });
}
});

服务器.js

Accounts.onCreateUser(function(options, user) {
if (options.profile) {
if (options.profile.userType) {
  user.userType = options.profile.userType;
  delete options.profile.userType;
}
user.profile = options.profile;
}
return user;
});
4

2 回答 2

4

设置字段的唯一其他方法是在通过方法调用创建帐户后更新用户文档。例如:

客户

var extraFields = {
  newField1: 'foo',
  newField2: 'bar'
};

Accounts.createUser(..., function(err1) {
  if (err1) {
    alert(err1);
  } else {
    Meteor.call('setUserFields', extraFields, function(err2) {
      if (err2) {
        alert(err2);
      } else {
        Router.go('/');
      }
    });
  }
});

服务器

Meteor.methods({
  setUserFields: function(extraFields) {
    // TODO: change this check to match your user schema
    check(extraFields, {
      newField1: Match.Optional(String),
      newField2: Match.Optional(String)
    });

    return Meteor.users.update(this.userId, {$set: extraFields});
  }
});

这种方法的主要问题是用户可以随时打开控制台并调用该setUserFields方法。这可能是也可能不是问题,具体取决于您的用例。如有必要,您始终可以向该方法添加其他检查以防止后续更新。

于 2014-12-13T16:01:02.990 回答
1

我已经能够在 Accounts.onCreateUser 上创建没有任何值(null)的附加字段。

请指出此解决方案的任何问题。请记住发布附加字段。

服务器.js

Accounts.onCreateUser(function(options, user) {
if (options.profile) {
if (options.profile.userType) {
  user.userType = options.profile.userType;
  delete options.profile.userType;
  user.newfieldone = options.newfieldone; //this is the line to insert new field
  user.newfieldtwo = options.newfieldtwo;
}
user.profile = options.profile;
}
return user;
});


Meteor.publish(null, function() {
// automatically publish the userType for the connected user
// no subscription is necessary
return Meteor.users.find(this.userId, {fields: {newfieldone: 1, newfieldtwo: 1}});
});
于 2014-12-13T16:30:01.170 回答