Meteor:如果value等于X,则更新object1,否则更新object2

时间:2016-02-23 17:14:36

标签: javascript mongodb meteor

我在Meteor中建立一个多人游戏 每个game集合都有一个player1player2,它们是包含用户ID的对象,以及一些与游戏相关的数据。

问题:
我需要更新game上与游戏相关的数据,但我不知道该播放器是player1还是player2

以下内容会更新player1,但我需要该函数是通用的,只更新右侧播放器对象上的游戏相关数据。

我是否在架构上犯了错误,或者我错过了可以帮助我的MongoDB功能?

Meteor.methods({
    changeHand: function(gameId, hand) {
        Games.update(gameId, {
            player1: {
                _id: Meteor.userId(),
                hand: hand
            }
        });
    }
});

1 个答案:

答案 0 :(得分:1)

我不知道允许这种条件更新的Mongo函数。我推荐使用find然后更新的javascript端逻辑:

Meteor.methods({
  changeHand: function(gameId, hand){
    var game = Games.findOne({_id: gameId});
    if(game.player1._id===Meteor.userId()){
      Games.update({_id: gameId}, {$set: {'player1.hand': hand}});
    }else{
      Games.update({_id: gameId}, {$set: {'player2.hand': hand}});
    }
  }
});