1

So I'm trying to add an 'account_type' field to the user collection.

Meteor.startup(function () {
    if (Meteor.users.find().count() === 0){
        var user = Accounts.createUser({
            email: 'email@fake.com',
            password: 'password'
        });
        Meteor.users.update({_id: user}, {$set : {account_type: 'admin'}});
    }
});

When I call Meteor.user().account_type, it's undefined.

I also read somewhere that something like this may be necessary:

Meteor.methods({
    get_user: function(user_id){
        return Meteor.users().find({ _id: user_id}, {fields: {account_type: 1}});
    }
});

But I get undefined again when I call it:

console.log(Meteor.call('get_user', Meteor.userId()));

What is the proper way to add to the user model?

Bill Johnston
  • 1,160
  • 1
  • 14
  • 31
  • 3
    Tip: instead of `find({_id: uid})` it's enough to write the shorthand form `find(uid)`, they are equivalent. – Hubert OG Aug 21 '13 at 22:05

2 Answers2

5

If you want to have account type visible on the client, you need to create publish / subscribe channel with needed field. Meteor only publishes username, email and profile by default. Calling a method to get a field from db is a bad idea in 99% of cases.

To start with, server code:

Meteor.publish('users', function() {
    return Meteor.users.find({}, {fields: {accountType: 1}});
});

Client:

Deps.autorun(function() {
    Meteor.subscribe('users');
});

When you get this running, next make sure that client doesn't get sensitive information about other users.

Hubert OG
  • 19,314
  • 7
  • 45
  • 73
  • This doesn't seem to be working still. I tried logging `Meteor.users.update({_id: user}, {$set : {account_type: 'admin'}});` and it says undefined. Could there be a reason this is failing? – Bill Johnston Aug 22 '13 at 19:14
-1

You should use the callback of the function to get the result:

Meteor.call('get_user', Meteor.userId(), function(error, result){
    // do something with result
    console.log(error, result);
});

For the other bit, try with:

Meteor.startup(function () {
    if (Meteor.users.find().count() === 0){
        var user = Accounts.createUser({
            email: 'email@fake.com',
            password: 'password'
        });
        Meteor.users.update({_id: user._id}, {$set : {account_type: 'admin'}});
    }
});

Notice that I added user._id.

Romeo Mihalcea
  • 9,714
  • 12
  • 50
  • 102