-1

I have two schemas just as the following

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);
};

I need to run find query on the Student model to get an array of students. And Every Student will contain an array of his subjects. Every index of subjects array will contain the complete object of subjects. just as following.

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

How can i achieve it by using refs ?

Ahmad Raza
  • 21
  • 7
  • Possible duplicate of [Referencing another schema in Mongoose](https://stackoverflow.com/questions/18001478/referencing-another-schema-in-mongoose) – drinchev Nov 19 '18 at 11:48

1 Answers1

0

You can use ref functionality and populate.

It will look like :

 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);

And then you can query

mongoose.model( "students" ).find().populate( "subjects" ).exec( ( results, error ) => {
   console.log( results ); // { ... subjects: [ ... ] }
} );
drinchev
  • 19,201
  • 4
  • 67
  • 93
  • Hello @drinchev, studentId is needed in the subject. because, i dont want to get all the subjects in collection. I just want to get the selective subjects that contains the target studentId. – Ahmad Raza Nov 19 '18 at 12:11