Lima9 Lima9 - 16 days ago 5
Node.js Question

Return collection inside collection in node by url parameters

I have two collections:
Students:

{
name: {type: String, required: true, unique: true},
address: {type: String, required: true},
phones: {
name: {type: String},
address: {type: String}
}


And subjects:

{
name: {type: String, required: true, unique: true},
students: {studentid}
}


I want to create inside my API a function that by writing in the URL something like:
http:apiurl/api/subjects/subject/studentid


it returns me the info of the student that belongs to that subject

So far I have done this:

router.get('/subjects/:subject/:studentid', function (req, res) {
Subject.find({name: req.params.name}, function (err, subject) {
Student.find({id:req.params.studentid},function (err, student))
if (err) res.send(500, err.message);
console.log(student);
res.status(200).jsonp(student);
});
});


But I can't get it to work

Answer

Make sure that studentId is exactly the same type as _id of Students.

Then you can use population to achieve what you want. For example:

Subjects
  .find({
    // Conditions
  })
  .populate('students')
  .exec(function(err, subject) {
    // Some code here
  });