2

I'm having a user with a group reference. i'm wondering how i populate the game, users and ranks within the group? so what i basically want is to populate these 3 values in the user.group in the code

user mode

var userSchema = new Schema({
  fb: {
    type: SchemaTypes.Long,
    required: true,
    unique: true
  },
  name: String,
  birthday: Date,
  country: String,
  image: String,
  group: { type: Schema.Types.ObjectId, ref: 'Group'}

});

group model

var groupSchema = new Schema({
  users: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }],
  game: { type: Schema.Types.ObjectId, ref: 'Game' },
  ranks: [{
    type: Schema.Types.ObjectId, ref: 'Ladder'
  }]

});

code

  User.findByIdAndUpdate(params.id, {$set:{group:object._id}}, {new: true}, function(err, user){
    if(err){
      res.send(err);
    } else {
      res.send(user);
    }
  })
Peter Pik
  • 11,023
  • 19
  • 84
  • 142

1 Answers1

6

Mongoose 4 supports populate over multiple levels. Populate Docs If your schema is:

var userSchema = new Schema({
  name: String,
  friends: [{ type: ObjectId, ref: 'User' }]
});

Then you can use:

User.
  findOne({ name: 'Val' }).
  populate({
    path: 'friends',
    // Get friends of friends - populate the 'friends' array for every friend
    populate: { path: 'friends' }
  });

So in your case it should be something like:

User.findById(params.id)
.populate({
  path: 'group',
  populate: {
    path: 'users game ranks'
  }
})
.exec( function(err, user){
    if(err){
      res.send(err);
    } else {
      res.send(user);
    }
  })

Similar question here

Community
  • 1
  • 1