简体   繁体   中英

Traversing subdocuments, in a mongodb cursor

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM