蒙哥。返回父级的相关集合

假设有这样一个 mongoose 数据库架构,

const teacherSchema = new mongoose.Schema({
name: {type: String,required: true,trim: true},})


const courseSchema = new mongoose.Schema({
name: {type: String,teacher: { type: 'ObjectId',ref: 'Teacher',required: true },})


const studentSchema = new mongoose.Schema({
name: {type: String,course: { type: 'ObjectId',ref: 'Course',})


const hobbySchema = new mongoose.Schema({
name: {type: String,student: { type: 'ObjectId',ref: 'Student',})

如何查询和返回特定教师的数据,同时嵌套他们教授的课程、参加课程的学生和他们的爱好? 注意:我使用 url 参数 (id) 找到老师

{
_id: "61040a6dec6d054128fa8eae",name: "John Doe",others: ...,courses: [
 {
   content: ...,students: [
    {
     content: ....,hobbies: [{
      content:...
     }
     ]
    },{...other students taking the course}
   ]
 },{...other subjects by John Doe}
]
}
b454545 回答:蒙哥。返回父级的相关集合

您只需要 mongo aggregate 即可链接和获取来自不同架构的数据。

首先,引入一个链接所有模式的关系,就像你如何处理 ref 一样,我建议有一个 usersSchema 并引入一个 userType 字段,用于标识学生或教师的用户类型,因此您可以取消教师架构和学生架构

UserSchema.aggregate([
        {
            $match: { id: teacherId }
        },{
          $lookup: {
            from: "users",localField: "students",foreignField: "_id",as: "students",},{
          $lookup: {
            from: "hobbies",localField: "hobbyId",as: "hobbies",{
          $lookup: {
            from: "course",localField: "courseId",as: "courses",{
          $sort: {
            createdAt: -1,{
          $unwind: "$users",])
        .then((data) => {
          return data
        })
本文链接:https://www.f2er.com/4209.html

大家都在问