将数组对象添加到 Meteor.js 中的用户集合 [英] Adding an array object to Users collection in Meteor.js

查看:53
本文介绍了将数组对象添加到 Meteor.js 中的用户集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Meteor.js 很陌生,我发现文档有点难以理解.

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

我从一个非常简单的应用开始,用户只需点击一个按钮就可以将现有的游戏添加到他们的个人资料中.游戏 存储在另一个 Meteor Collection 中.

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.

在 rails 中,我只会创建一个 has_and_belongs_to_many 关系,但这不是 Meteor 的工作方式.我认为最好的方法是在创建用户帐户时添加一个空数组 - 然后,当他们单击添加游戏"按钮时,它会将游戏的标题传递到用户数组中.

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.

我的 /server/users.js 文件中有这个:

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

我正在我的 /client/views/games/games_list.js 文件中调用 addGame 方法,如下所示:

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?

推荐答案

你在正确的轨道上,但是声明一个数组而不是一个对象:

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

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

直接推送值而不是对象,并使用 $addToSet 避免重复推送相同的 gameId 多次:

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

这篇关于将数组对象添加到 Meteor.js 中的用户集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆