【问题标题】:Mongoose - populate multiple idsMongoose - 填充多个 id
【发布时间】:2019-09-15 11:32:28
【问题描述】:

我是猫鼬的新手,我整天都在努力理解填充。我设法做了简单的例子,但现在我创建了两个模式:

首先是带有一些用户详细信息的 UserSchema:

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

第二个是 MatchSchema 女巫,我想填充用户详细信息,但我不确定这样的方法是否可行:

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

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

【问题讨论】:

    标签: mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

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

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

    那么当你想用用户数据填充 Match 模型时:

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

    【讨论】:

    • 谢谢 :) 它的工作原理就像一个魅力。我不知道我需要使用 .populate('player_one.player_details') 在对象内部填充它解决了我所有的问题。
    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 2020-12-08
    • 2021-11-03
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多