Mongodb Mongoose-填充多个ID

Mongodb Mongoose-填充多个ID,mongodb,mongoose,mongoose-schema,mongoose-populate,Mongodb,Mongoose,Mongoose Schema,Mongoose Populate,我是刚接触猫鼬的,为了理解猫鼬,我挣扎了一整天。我尝试了一些简单的例子,但现在我创建了两个模式: 首先是UserSchema,其中包含一些用户详细信息: const UserSchema: mongoose.Schema = new mongoose.Schema ({ name: String, email: String }); 第二个是MatchSchema witch,我希望填充用户详细信息,但我不确定这样做是否有效: const MatchSchema: mongoose.S

我是刚接触猫鼬的,为了理解猫鼬,我挣扎了一整天。我尝试了一些简单的例子,但现在我创建了两个模式:

首先是UserSchema,其中包含一些用户详细信息:

const UserSchema: mongoose.Schema = new mongoose.Schema ({
  name: String,
  email: String
});
第二个是MatchSchema witch,我希望填充用户详细信息,但我不确定这样做是否有效:

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

可能我使用了一些不起作用的东西,任何帮助都会得到感谢。

您需要使用UserSchema创建一个Mongoose模型,并将其命名为“User”。然后可以使用MatchSchema创建匹配模型。假设UserSchema和MatchSchema位于同一文件中,可以添加以下内容:

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

然后,当您要使用用户数据填充匹配模型时:

let data = Match.find({})
             .populate('player_one.player_details')
             .populate('player_two.player_details')
谢谢:)它工作起来很有魅力。我不知道我需要使用
在对象内部填充。填充('player\u one.player\u details')
它解决了我所有的问题。