【问题标题】:How to populate Mongoose subdocument with data from another subdocument如何使用来自另一个子文档的数据填充 Mongoose 子文档
【发布时间】:2016-04-13 06:45:24
【问题描述】:

我有一个 MongoDB 数据库,其中包含有关足球俱乐部的数据。俱乐部有球员和赛季。一个球员每个赛季可以有不同的球队号码。

考虑以下 Mongoose 架构:

const clubSchema = new mongoose.Schema({
    players: [playerSchema],
    seasons: [seasonSchema]
});

const personSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
});

const playerSchema = new mongoose.Schema({
    person: personSchema,
    picture: String
});

const seasonSchema = new mongoose.Schema({
    name: String,
    seasonPlayers: [seasonPlayerSchema]
});

const seasonPlayerSchema = new mongoose.Schema({
    player: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Player"
    },
    squadNumber: Number
});

如何检索完全填充的Club 文档?所以不要得到这样的东西:

{
  players: [
    {
      _id: ObjectId("abc123"),
      person: {
        firstName: "John",
        lastName: "Doe"
      }
      picture: "john.jpg"
    }
  ],
  seasons: [
    name: "2015-2016",
    seasonPlayers: [
      {
        player: ObjectId("abc123"),
        squadNumber: 10
      }
    ]
  ]
}

我想要这样的东西:

{
  players: [
    {
      _id: ObjectId("abc123"),
      person: {
        firstName: "John",
        lastName: "Doe"
      }
      picture: "john.jpg"
    }
  ],
  seasons: [
    name: "2015-2016",
    seasonPlayers: [
      {
        player: {
          person: {
            firstName: "John",
            lastName: "Doe"
          }
          picture: "john.jpg"
        },
        squadNumber: 10
      }
    ]
  ]
}

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    您可以在 Mongoose 的 population 路径中使用点表示法来指定要填充的子文档层次结构中的路径:

    Club.findOne().populate('seasons.seasonPlayers.player').exec(function(err, club) {...});
    

    【讨论】:

    • @Korneel playerSchema 是否只嵌入在俱乐部文件中,而不是嵌入在它自己的模型/集合中?
    • 确实,只嵌入,不在自己的集合中
    • 好的,那么您需要的所有数据都在 Club 文档中,对吧?我认为 Mongoose 不能帮助您,您只需要进行自己的后处理来修复您的文档以执行您自定义的“本地”人口。
    • 这就是我最终所做的,但我想也许 Mongoose 有帮助方法。感觉就像我做错了什么或不好的做法。使用嵌入式文档而不是对文档中已有数据的引用会更好吗?这是我第一个使用 MongoDB 的项目。我应该以不同的方式建模我的架构,还是您认为我建模架构的方式有意义?
    • MongoDB 模式设计在很大程度上支持数据的查询和更新方式,找到嵌入和引用的正确平衡。因此,您的架构本质上没有任何问题,我想说不在您的文档中复制数据是有道理的。
    猜你喜欢
    • 2014-08-16
    • 2017-01-27
    • 1970-01-01
    • 2015-10-31
    • 2017-03-21
    • 2017-06-06
    • 1970-01-01
    • 2019-01-08
    • 2018-08-16
    相关资源
    最近更新 更多