Mongoose 填充复杂的嵌套文档

问题描述 投票:0回答:1

有人可以向我提供使用 mongoose populate 函数填充 MongoDB 中嵌套文档的所有变体吗?嵌套应该很复杂。

我想在嵌套文档中使用多个键进行填充。我知道如何使用单键填充。

mongodb mongoose populate
1个回答
0
投票

我的

User
模型如下:

const userSchema = new Schema ({
  ...,
  student: {
    type: Schema.Types.ObjectId,
    ref: 'Student',
  }
})
export const User = model('User', userSchema);

学生模型如下

const studentSchema = new Schema({
  ...,
  academicFaculty: {
    type: Schema.Types.ObjectId,
    ref: 'AcademicFaculty',
  },
})
export const Student = model('Student', studentSchema);

因此,当我检索用户时,我将填充嵌套字段,如下所示

cost user = await User.findOne({ id: finalUser.id }).populate({
    path: 'student',
    populate: [
      {
        path: 'academicFaculty',
      }
    ],
  });

按照此模式,您可以填充更多嵌套文档。

© www.soinside.com 2019 - 2024. All rights reserved.