【问题标题】:How to populate the every element inside array of objects in mongoose?如何在猫鼬中填充对象数组中的每个元素?
【发布时间】:2021-03-06 06:42:54
【问题描述】:

我的数据库架构是这样的:-

const CategorySchema = new Schema({
  title: {
    type: String,
    required: true,
    unique: true,
  },
  albums: [
    {
      album: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "albums",
      },
    },
  ],
});

const AlbumSchema = new Schema({
  albumName: {
    type: String,
    required: true,
    unique: true,
  },
  by: {
    type: String,
    required: true,
  },
  albumImageUri: {
    type: String,
    required: true,
  },
  artistHeadline: {
    type: String,
    required: true,
  },
  songs: [
    {
      song: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "songs",
      },
    },
  ],
});

const SongSchema = new Schema({
  songName: {
    type: String,
    required: true,
  },
  songImageUri: {
    type: String,
    required: true,
  },
  songAudioUri: {
    type: String,
    required: true,
  },
});

所以有一个歌曲类别,其中包含专辑,其中包含歌曲。 我想检索所有类别并填充专辑数组中的每个元素。 我不想用循环来达到同样的效果

【问题讨论】:

    标签: node.js mongodb mongoose nosql


    【解决方案1】:

    在使用 get 查询时,在填充数组中,提供路径,以及要在选择字段中检索的所有元素。 它应该看起来像这样。

    "populate": [{
                "path": 'albums',
                "select": 'albumName by albumImageUri artistHeadline songs'
            }]
    

    【讨论】:

    • 我错误地在类别架构中的专辑对象数组中的对象内添加了对象
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2021-08-16
    • 2014-11-25
    • 1970-01-01
    • 2019-11-27
    • 2020-10-13
    • 2017-04-29
    相关资源
    最近更新 更多