流星:如果值等于 X,则更新对象 1,否则更新对象 2

Meteor: Update object1 if value equals X, else update object2

本文关键字:更新 对象 如果 流星      更新时间:2023-09-26

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

问题:
我需要在game上更新游戏相关数据,但不知道玩家是player1还是player2

以下内容将更新player1但我需要该函数是通用的,并且仅更新右侧玩家对象上的游戏相关数据。

我是否在架构上犯了错误,或者我错过了一个可以帮助我的MongoDB函数?

Meteor.methods({
    changeHand: function(gameId, hand) {
        Games.update(gameId, {
            player1: {
                _id: Meteor.userId(),
                hand: hand
            }
        });
    }
});
我不知道有

Mongo 函数允许这种条件更新。我推荐带有查找然后更新的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}});
    }
  }
});