0

Let's say there is a multiplayer game defined as such:

    var GameSchema = new Schema({
      players : {type : [Schema.ObjectID], ref : 'User', required : true}
    });

I am wondering what would be the best way to store the score for each user, knowing that each game has its own score. Here are a few options:

  1. adding a separate array of attributes

    var GameSchema = new Schema({
      players : {type : [Schema.ObjectID], ref : 'User', required : true}
     ,scores  : {type : [Number]}
    });
    

    The only way to create a relationship is by referencing the index position. Doesn't seem like a good idea.

  2. adding a Player Embedded Doc

    var PlayerSchema = new Schema({
      user  : {type : [Schema.ObjectID], ref : 'User', required : true}
     ,score : {type : Number, default : 0 }
    });
    
    var GameSchema = new Schema({
      players : {type : [PlayerSchema], required : true}
    });
    

    My main problem with this approach is that user info gets buried a level deeper. Having to call game.players.user instead of game.players doesn't seem right either.

  3. extending the DBRref as a Embedded Doc?

    Ideally, I should be able to do

    var PlayerSchema = new Schema({
      _id  : {type : [Schema.ObjectID], ref : 'User'}
     ,score : {type : Number, default : 0 }
    });
    
    var GameSchema = new Schema({
      players : {type : [PlayerSchema], required : true}
    });
    

    This approach is essentially like #2, except that the user is directly referenced as the id of Player. I assumed this "map" User to Player so that it would be possible to call game.players[player_id].score. Unfortunately, the code above won't work.

What's best practice? Any other alternative?

thanks!

Gregory M
  • 494
  • 1
  • 4
  • 11

1 Answers1

1

There is an id method on MongooseArrays that can help. This gist is a working example. It's closer, though not perfectly clean b/c the _id needs to stay separate.

What you want (game.players[player_id].score) doesn't really make sense b/c when you populate the field it will be completely replaced with the result of the query.

aaronheckmann
  • 10,625
  • 2
  • 40
  • 30
  • So we can't avoid duplication of _id and user._id... all right. Most importantly, it works! Thanks, Aaron. – Gregory M Jun 20 '12 at 21:02