0

首先,这是结构。

{ "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();
  }
});
4

1 回答 1

1

findMongoose回调的第二个参数(res在您的示例中)是找到的文档数组。当您只期待一个匹配项时使用findOneor (如本例中)。findById所以试着把你的代码改成这样:

var game = db.model('Game');
game.findById(data.game, function(err, game) {

  if(err || !game) {
    // game not found, close connection.
    socket.emit('disconnected', 'Error: game was not found.')
    socket.disconnect();
    return;
  }

  var permitted = false;
  game.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();
  }
});
于 2012-10-07T13:05:57.570 回答