【问题标题】:How to add extra attributes to users collection?如何为用户集合添加额外的属性?
【发布时间】:2017-04-12 22:56:30
【问题描述】:

我正在使用Accounts.createUser向数据库添加新用户,但问题是,并没有添加所有属性。

这是我添加新用户的代码:

import {Accounts} from 'meteor/accounts-base';

Template.addingUser.events({
    'submit #addUser': function (e, t) {

        e.preventDefault();

        Session.set('name', t.find('#name').value);
        Session.set('email', t.find('#email').value);
        Session.set('telephoneOffice', t.find('#telephoneOffice').value);
        Session.set('telephoneHouse', t.find('#telephoneHouse').value);
        Session.set('salary', t.find('#salary').value);

        let userId = Accounts.createUser({
            username: Session.get('name'),
            password: "123456",
            email: Session.get('email'),
            telephoneOffice: Session.get('telephoneOffice'),
            telephoneHouse: Session.get('telephoneHouse'),
            employeeSalary: Session.get('salary'),
            annualLeave: 14

        }, function (err) {
            if (err)
                console.log(err);
            else
                console.log('It worked...');
        });

        Accounts.sendEnrollmentEmail(userId);


    }
});

仅添加姓名、电子邮件和密码。

我如何包含其他信息,例如telephoneOffice?

【问题讨论】:

    标签: meteor meteor-accounts


    【解决方案1】:

    Accounts.createUser 不接受除用户名、电子邮件、密码和配置文件之外的自定义参数。传递自定义用户信息的默认功能是将telephoneOffice 等字段作为profile 对象的一部分传递,该对象将复制到插入到用户集合的文档中的user.profile。

    例如:

    let userId = Accounts.createUser({
            username: Session.get('name'),
            password: "123456",
            email: Session.get('email'),
            profile: {
              telephoneOffice: Session.get('telephoneOffice'),
              telephoneHouse: Session.get('telephoneHouse'),
              employeeSalary: Session.get('salary'),
              annualLeave: 14
            }
        });
    

    请注意,user.profile 字段为 by default modifiable by users。所以它是遗留下来的,但 Meteor 实际上建议避免将它用于存储。

    如果您希望这些字段位于user 而不是user.profile,您可以做的是如上所述在profile 对象上传递您的自定义参数,然后使用Accounts.onCreateUser 覆盖默认行为。像这样的:

    Accounts.onCreateUser(function(options, user) {
      if (options.profile)
        _.extend(user, options.profile);
      return user;
    });
    

    在此处查看更多信息:https://guide.meteor.com/accounts.html#custom-user-data

    【讨论】:

      【解决方案2】:

      您需要在profile 对象中传递额外的数据。

      Accounts.createUser({
        username: Session.get('name'),
        password: "123456",
        email: Session.get('email'),
        profile: {
          telephoneOffice: Session.get('telephoneOffice'),
          telephoneHouse: Session.get('telephoneHouse'),
          employeeSalary: Session.get('salary'),
          annualLeave: 14
        }
        ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多