0

I have a problem with Meteor and MongoDB. I'm coding a little game. I use accounts-ui and when an account is created I add some fields to this account :

Accounts.onCreateUser(function(options, user) {
    user.money = 0;
    user.rate = 0;
    user.employees = [];
    return user;
})

As you can see, I have a table named "employees".

When the user will click on a button to hire an employee, I want to update this table. Imagine the user hire a programmer, I want to update my table like this :

Accounts.onCreateUser(function(options, user) {
    user.money = 0;
    user.rate = 0;
    user.employees = [{"programmer": 1}];
    return user;
})

If the user hire an other programmer I want to increment the number of programmer. And if the user hire a designer I want to add it to the table like this :

Accounts.onCreateUser(function(options, user) {
    user.money = 0;
    user.rate = 0;
    user.employees = [{"programmer": 2}, {"designer": 1}];
    return user;
})

I'm a beginner in Meteor and MongoDB, I don't understand how I can do this.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
DeepSiderZ
  • 67
  • 1
  • 2
  • 9

3 Answers3

0

If your employees is a key-value pair as you described, I'd use an object instead of an array.

user.employees = {};

It makes MongoDB operations easier:

Meteor.users.update({_id: someId}, {$inc: {"employees.programmer": 1}});

This server-side code adds one to the user's programmers. If the user doesn't have a programmer yet, this code will create the first one.

aedm
  • 5,596
  • 2
  • 32
  • 36
0

You can add an employeesattribute to the user like this :

Accounts.createUser( {
   username: 'test',
   email: 'email@email.com',
   password: 'test',
   employees: {} 
});

And update the employees :

  • Add an employee Meteor.users.update(idUser, {$addToSet: {employees: {'a': 1}}}); Meteor.users.update(idUser, {$addToSet: {employees: {'b': 1}}});

  • Increment the number of employee a : Meteor.users.update(idUser, {$pull: {employees: {'a': 1}}}); Meteor.users.update(idUser, {$addToSet: {employees: {'a': 2}}});

0

You can simply write query like this:

If( programmer hired ) {
   Meteor.users.update({_id: someId}, {$inc: {"employees.programmer": 1}});
} else if ( designer hired ) {
   Meteor.users.update({_id: someId}, {$inc: {"employees.designer": 1}});
} else if ( programmer and designer hired ) {
  Meteor.users.update({_id: someId}, {$inc: {"employees.programmer": 1, "employees.designer": 1}});
}
Pankaj Jatav
  • 2,158
  • 2
  • 14
  • 22
  • Thank you for your answer, I will use the solution of aedm because I will have a lot of kind of employee so if I use if/else it will be difficult to maintain the code :) – DeepSiderZ Apr 21 '16 at 10:39