Search code examples
mongodbmongoosemongoose-schemamongoose-populate

Mongoose - populate multiple ids


I am new to mongoose and I was strugling whole day trying to understand populate. I managed to do simple examples but now I created two schemas:

First which is UserSchema with some user details:

const UserSchema: mongoose.Schema = new mongoose.Schema ({
  name: String,
  email: String
});

And second which is MatchSchema witch I want to be populated with user details but I am not sure if something like this will work:

const MatchSchema: mongoose.Schema = new mongoose.Schema ({
  player_one: {
    id: String,
    score: Number,
    player_details: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }
  },
  player_two: {
    id: String,
    score: Number,
    player_details: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }
  },
  winner: String
  },{timestamps: true});

Probably I used something which wont work and any help will be appriciated.


Solution

  • You need to create a Mongoose model using the UserSchema and name it 'User'. You can then create a Match model using the MatchSchema. Assuming the UserSchema and MatchSchema are in the same file, you can add the following:

    const User = mongoose.model('User', UserSchema)
    const Match = mongoose.model('Match', MatchSchema)
    
    

    Then when you want to populate the Match model with User data:

    let data = Match.find({})
                 .populate('player_one.player_details')
                 .populate('player_two.player_details')