0

First of all, this is the structure.

{ "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 
}

I have selected just that with,

var game = db.model('Game');
game.find({_id : new ObjectID(data.game)}, function(err, res) {

Which works great. Inside the function however i want to traverse the players array, i've tried this

 res.players.forEach(function(player) {
    console.log(player.name +' | '+ data.name);
    if(player.name == data.name) permitted = true;
  });

Which seems not to work, i guess it because i a mongoCursor object, of some kind.

Since i'm using mongoose, i can't use toArray(), i feel a bit lost, how can i traverse my Players array easely?

whole code

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

1 Answer 1

1

The second parameter to your find callback (res in your example) with Mongoose is the array of documents that were found. Use findOne or findById when you're only expecting a single match (like in this case). So try and change your code to something like this:

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();
  }
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.