首页 > 解决方案 > 如何使用 mongoose refs 处理一对多关系

问题描述

我有两个模式,如下所示

学生.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);
};

主题.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
      }
    ]
  }
]

我怎样才能通过使用 refs 来实现它?

标签: node.jsexpressmongoosemongoose-schemamongoose-populate

解决方案


您可以使用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: [ ... ] }
} );

推荐阅读