【问题标题】:how to use mongoose refs to handle one-to-many relation如何使用 mongoose refs 处理一对多关系
【发布时间】:2019-04-21 17:56:10
【问题描述】:

我有两个架构,如下所示

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
      }
    ]
  }
]

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

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

  • 您好@drinchev,主题中需要studentId。因为,我不想收集所有主题。我只想获取包含目标 studentId 的选择性科目。
猜你喜欢
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多