【发布时间】:2016-10-08 20:34:02
【问题描述】:
好吧,在用 50 种不同的方式尝试了这段代码之后,我正在敲我的脑袋。
所以我有一个 2v2 的示例游戏,在每个游戏模式中,玩家都被引用到用户和他们的用户名。
现在在游戏中,我想从这些用户那里获取评分并相应地更新它们,这必须同时发生。
我似乎无法处理我的用户对象(来自长期使用 Java,因此其中一些直接使用没有意义)。
如果可能的话,我想扩展它,所以一大堆嵌套的代码不是我想要的。
废话不多说:
游戏架构:
var gameSchema = mongoose.Schema({
teamA_player1: { type: String, ref: "userModel", required: true},
teamA_player2: { type: String, ref: "userModel", required: true},
teamB_player1: { type: String, ref: "userModel", required: true},
teamB_player2: { type: String, ref: "userModel", required: true},
teamA_score: { type: Number, required: true},
teamB_score: { type: Number, required: true},
author: { type: String, ref: "userModel", required: true},
verification: [{ type: String, ref: "userModel", required: true}],
verified: { type: Boolean},
timestamp: { type: Date}
});
用户架构:
var userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true},
password: { type: String, required: true},
firstName: { type: String},
lastName: { type: String},
about: { type: String},
email: { type: String},
clubs: { type: [{type: ObjectId, ref: "clubModel"}]},
games: { type: [{type: ObjectId, ref: "gameModel"}]},
rating: { type: Number}
});
我的游戏控制器中的代码存在问题:
updateRating = function(game){
// The following code blob doesn't work and calling a_1.rating just gives Nan / undefined.
var a_1 = users.findOne({username: game.teamA_player1});
var a_2 = users.findOne({username: game.teamA_player2});
var b_1 = users.findOne({username: game.teamB_player1});
var b_2 = users.findOne({username: game.teamB_player2});
var a_rating_old = (a_1.rating+a_2.rating)/2;
var b_rating_old = (b_1.rating+b_2.rating)/2;
var a_rating_new = 0;
var b_rating_new = 0;
if(game.teamA_score>game.teamB_score){
a_rating_new = ratingChange(a_rating_old, b_rating_old, true);
b_rating_new = ratingChange(b_rating_old, a_rating_old, false);
}else{
a_rating_new = ratingChange(a_rating_old, b_rating_old, false);
b_rating_new = ratingChange(b_rating_old, a_rating_old, true);
}
var a_rating_change = a_rating_new - a_rating_old;
var b_rating_change = b_rating_new - b_rating_old;
a_1.rating += Math.round(a_rating_change * (a_rating_old/a_1.rating));
a_2.rating += Math.round(a_rating_change * (a_rating_old/a_2.rating));
b_1.rating += Math.round(b_rating_change * (b_rating_old/b_1.rating));
b_2.rating += Math.round(b_rating_change * (b_rating_old/b_2.rating));
a_1.save();
a_2.save();
b_1.save();
b_2.save();
}
所以基本上我想知道在这里获取我的用户的正确方法是什么,提取他们的评分,更新它,然后用新的评分保存用户(游戏本身不会发生任何变化)。
代码也都可以在这里找到:https://github.com/mathieudevos/pinkiponki
【问题讨论】:
标签: node.js mongodb mongoose mongoose-schema