Ramsay Lanier
Ramsay Lanier

Reputation: 426

Adding an array object to Users collection in Meteor.js

I'm very new to Meteor.js and I'm finding the documentation a bit hard to understand.

I'm starting with a very simple app where Users will simply be allowed to add existing Games to their profile by clicking a button. The Games are stored in another Meteor Collection.

In rails I would just create a has_and_belongs_to_many relationship but that isn't how Meteor works. I thought the best way would be to add an empty array when the user's account is created - then, when they click the "add game" button it would pass the game's title into the users array.

I have this in my /server/users.js file:

Accounts.onCreateUser(function(options, user){
    user.games = [];
    return user;
});

Meteor.methods({
    addGame: function(title) {
        Meteor.users.update(Meteor.userId(), { $addToSet: { games: title}});
    }
});

And I'm making a call to the addGame method in my /client/views/games/games_list.js file as such:

Template.gamesList.events({
    'click .add-to-chest-btn': function(e){
        var title = $(e.target).attr('name');
        e.preventDefault();
        Meteor.call('addGame', title, function(title){ console.log(title)});
    }
});

Am I on the right track or is there a better way to do this?

Upvotes: 1

Views: 4505

Answers (1)

Ze Jibe
Ze Jibe

Reputation: 1043

You're on the right track, but do declare an array instead of an object:

Accounts.onCreateUser(function(options, user){
    user.games = [];
    return user;
});

Push the value directly instead of an object, and use $addToSet to avoid duplicates in case you push the same gameId multiple times:

Meteor.methods({
    addGame: function(gameId) {
        Meteor.users.update(Meteor.userId(), { $addToSet: { games: gameId }});
    }
});

Upvotes: 6

Related Questions