我有这个mongo集合opponents
来存储每个玩家的对手详情
{username:foo, foo:{foo1:0,foo2:0,foo3:0}}
{username:foo1,foo1:{foo:0,foo2:0,foo3:0}}
{username:foo2,foo2:{foo:0,foo1:0,foo3:0}}//i.e player foo2 play 0 games with foo,foo1 and foo3
node.js服务器端的这个table
对象:
var table =[{name:"foo",rounds:3},{name:"foo1",rounds:3},{name:"foo2",rounds:3},{name:"foo3",rounds:3}] //all players' name in a table with their rounds number
对于桌上的每个玩家,我想追加他们的对手'相应的opponent
集合的名称和轮次(当然不需要追加)。期望的结果是:
{username:foo, foo:{foo1:3,foo2:3,foo3:3}}
{username:foo1,foo1:{foo:3,foo2:3,foo3:3}}
{username:foo2,foo2:{foo:3,foo1:3:foo3:3}}
{username:foo3,foo3:{foo:3,foo1:3,foo2:3}}
我有一个自定义函数fun(name)
,可以为每位玩家返回一系列对手的名字。因此fun(table[0].name)
会返回[foo1,foo2,foo3]
function fun(name){
var result = [];
for (var i = 0; i <players.length; i++){
if(players[i].name!=name){
result.push(players[i].name)
}
}
return result;
}
这是我目前的代码:
for (var i =0;i<table.length;i++){
db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[0] ] :table[i].rounds}})
if (table.length>2){
db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[1] ] :table[i].rounds}})
}
if (table.length>3){
db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[2] ] :table[i].rounds}})
}
但它是严格的硬编码,如果table.length
增加,我需要更多的代码行。如何使用变量使其更紧凑?我试图使用嵌套循环,但这更糟糕。
答案 0 :(得分:0)
问题解决了:
for (var i = 0; i < table.length; i++) {
db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[0] ] :table[i].rounds}})
for (var j = 1;j<fun(table[i].name).length;j++){
db.opponents.update({username:table[i].name},{$inc:{[table[i].name + '.' + fun(table[i].name)[j] ] :table[i].rounds}})
}
}