首先,这是结构。
{ "isActive" : true,
"playerLimit" : 2,
"mode" : "Maul",
"map" : "Dark woods",
"name" : "Come and play with me",
"_id" : ObjectId( "506fde5d7066645b8c000001" ),
"players" : [
{ "hero" : "Brock, the summoner",
"state" : "in lobby",
"name" : "Elvar" },
{ "hero" : "Neal, the demon",
"state" : "in lobby",
"name" : "Test Spiller" } ],
"__v" : 0
}
我已经选择了,
var game = db.model('Game');
game.find({_id : new ObjectID(data.game)}, function(err, res) {
效果很好。在函数内部但是我想遍历玩家数组,我试过这个
res.players.forEach(function(player) {
console.log(player.name +' | '+ data.name);
if(player.name == data.name) permitted = true;
});
这似乎不起作用,我猜是因为 ia mongoCursor 对象,某种。
由于我使用的是mongoose,所以我不能使用toArray(),我感觉有点迷茫,我怎样才能轻松地遍历我的Players数组?
整个代码
var game = db.model('Game');
game.find({_id : new ObjectID(data.game)}, function(err, res) {
if(err) {
// game not found, close connection.
socket.emit('disconnected', 'Error: game was not found.')
socket.disconnect();
}
var permitted = false;
res.players.forEach(function(player) {
if(player.name == data.name) permitted = true;
});
if(!permitted) {
// game not found, close connection.
socket.emit('disconnected', 'Error: you are not permitted, to enter this game.');
socket.disconnect();
}
});