Denis Brezhitskiy
Denis Brezhitskiy

Reputation: 424

How to add custom fields to Meteor.users collection?

Sorry for my english. I use the package useraccounts:bootstrap for login, registration and so on. How can I add arbitrary data to Meteor.users collection after registration. For example, I want, that users after registration had a field 'status' with a value of 'false' or the field 'time' with time of registration. Thank you.

Upvotes: 4

Views: 2051

Answers (3)

Tomachi
Tomachi

Reputation: 1765

Here is how I'm doing it; matches the meteor docs style and doesn't require 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;
});

Upvotes: 0

wilddesign
wilddesign

Reputation: 46

useraccounts:bootstrap provides you a way to customize your registration panel templates by adding visible, explicit and editable fields into the registration form, as explained in useraccounts/core's GitHub documentation(look for AccountTemplates.addFields method).

However, useraccounts:bootstrap is dependent on accounts-password, so you can use its Accounts.createUser method, simply by passing additional fields in the object passed into Accounts.createUser method. Your createUser method would be like:

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

    });

This problem was discussed on Meteor forums:forums.meteor.com.

A more elegant way of solving your problem is calling a server-side function Accounts.onCreateUser every time a user account is created. This function would assign the registrationTime and status to the newly created account. Check this in Meteor's docs: Accounts.onCreateUser docs.meteor.com

Upvotes: 2

MasterAM
MasterAM

Reputation: 16478

If the user needs to supply the data, you will need to customize the UI and add the desired fields.

On the server, you can attach an onCreateUser() callback to set the data when a new user is created.

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;
});

the options argument contains the data from the client side.

Upvotes: 3

Related Questions