如何将自定义字段添加到 Meteor.users 集合?

How to add custom fields to Meteor.users collection?

对不起我的英语。我使用包 useraccounts:bootstrap 进行登录、注册等。如何在注册后将任意数据添加到 Meteor.users 集合。例如,我想,注册后的用户有一个值为 'false' 的字段 'status' 或带有注册时间的字段 'time'。谢谢。

useraccounts:bootstrap 为您提供了一种通过在注册表中添加可见、明确和可编辑的字段来自定义注册面板模板的方法,如 useraccounts/core 的 GitHub 文档(寻找 AccountTemplates.addFields 方法)。

但是,useraccounts:bootstrap 依赖于 accounts-password,因此您可以使用其 Accounts.createUser方法,只需将对象中的附加字段传递给Accounts.createUser方法即可。您的 createUser 方法类似于:

Accounts.createUser({
   username:'newuser',
    password:'pass1234',
    profile:{ //no sensitive data here, this can be modified by the user
          },
    registrationTime: new Date, //date & time of registration
    status: false

    });

这个问题在 Meteor 论坛上被讨论过:forums.meteor.com

解决问题的更优雅的方法是在每次创建用户帐户时调用服务器端函数 Accounts.onCreateUser。此函数会将注册时间和状态分配给新创建的帐户。在 Meteor 的文档中查看:Accounts.onCreateUser docs.meteor.com

如果用户需要提供数据,您将需要customize the UI并添加所需的字段。

在服务器上,您可以附加一个onCreateUser()回调来设置新用户创建时的数据。

import _ from 'lodash';

Accounts.onCreateUser((options, user) => {
  // add your extra fields here; don't forget to validate the options, if needed
  _.extend(user, {
    status: false,
    createdAt: new Date()
  });

  return user;
});

options 参数包含来自客户端的数据。

这是我的做法;匹配 meteor 文档样式并且不需要 lodash:

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

Accounts.onCreateUser((options, user) => {
  const userToCreate = Object.assign({
    status: false,
    createdAt: new Date(),
  }, user);

  if (options.profile) userToCreate.profile = options.profile;

  return userToCreate;
});