meteorminimongo

Meteor and MongoDB: How to set an object in a table


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.


Solution

  • 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.