如何使用猫鼬引用处理一对多关系

时间:2018-11-19 11:19:33

标签: node.js express mongoose mongoose-schema mongoose-populate

我有两种模式,如下所示

Student.js

module.exports = (mongoose) => {
const Schema = mongoose.Schema;
const studentsSchema = new Schema({
    name :  {
        type : String,
        required : true
    },
    roll : {
        type : Number,
        default : null
    },
    class : {
        type : String,
        default : null
    }
});

return mongoose.model('students', studentsSchema);
};

Subject.js

module.exports = (mongoose) => {
 const Schema = mongoose.Schema;
 const subjectSchema = new Schema({
    title :  {
        type : String,
        required : true
    },
    author : {
        type : String,
        default : null
    },
    price : {
        type : Number,
        default : null
    },
    studentId : {
        type : String
    }
});

return mongoose.model('subjects', subjectSchema);
};

我需要在Student模型上运行find查询以获取学生数组。每个学生都将包含一系列的科目。主题数组的每个索引都将包含主题的完整对象。如下。

[
  {
    name : "student 1",
    roll : 1234,
    class : "TEN",
    subjects : [
      {
        title : 'English',
        author : 'peter',
        price : 210
      },
      {
        title : 'Math',
        author : 'Nelson',
        price : 222
      }
    ]
  }
]

我如何使用裁判来实现?

1 个答案:

答案 0 :(得分:0)

您可以使用ref功能并进行填充。

它看起来像:

 const subjectSchema = new Schema({
    title :  {
        type : String,
        required : true
    },
    author : {
        type : String,
        default : null
    },
    price : {
        type : Number,
        default : null
    }
    // studentId : {
    //     type : String
    // }
    // ^ You don't need to save the student id, since the ids of the subject
    //   will be saved in your Student schema
});

mongoose.model('subjects', subjectSchema);

const studentsSchema = new Schema({
    name :  {
        type : String,
        required : true
    },
    roll : {
        type : Number,
        default : null
    },
    class : {
        type : String,
        default : null
    },
    subjects: [{ type: Schema.Types.ObjectId, ref: 'subjects' }]
    // ^ Add the reference to subjects
});

mongoose.model('students', studentsSchema);

然后您可以查询

mongoose.model( "students" ).find().populate( "subjects" ).exec( ( results, error ) => {
   console.log( results ); // { ... subjects: [ ... ] }
} );