我在Meteor中建立一个多人游戏
每个game
集合都有一个player1
和player2
,它们是包含用户ID的对象,以及一些与游戏相关的数据。
问题:
我需要更新game
上与游戏相关的数据,但我不知道该播放器是player1
还是player2
。
以下内容会更新player1
,但我需要该函数是通用的,只更新右侧播放器对象上的游戏相关数据。
我是否在架构上犯了错误,或者我错过了可以帮助我的MongoDB功能?
Meteor.methods({
changeHand: function(gameId, hand) {
Games.update(gameId, {
player1: {
_id: Meteor.userId(),
hand: hand
}
});
}
});
答案 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}});
}
}
});