Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to query parent document based on child reference document value? #4043

Closed
aniinprni opened this issue Apr 5, 2016 · 2 comments
Closed

Comments

@aniinprni
Copy link

Hi,
I am using mongoose. Here i have an requirement that i need to fetch student document when matches to its classRoomName name and rollNo. Here below is my student and classRoom schemas as follows:

1.student
===========
new Schema({

    rollNo:{type:Number, required:true},
    name:{type:String},
    classRoomRef:{type:Schema.Types.ObjectId,ref:'classRoom', required:true}
});

2.classRoom
============
new Schema({

    classRoomNo:{type:Number},
    classRoomName:{type:String}
});

I managed to get student document with rollNo . i have written the mongoose query like this below:

student.findOne({rollNo:"xxx"}),function(err,data){
  //printing data 
});

Now I need to retrieve student document based on classRoomName , i written below query but not working. Giving null.

student.findOne({rollNo:"xxx","classRoomRef.classRoomName":"yyy"}).populate("classRoomRef").exec(function(err,data){
  //printing data 
});

Kindly help me.

@aniinprni
Copy link
Author

Hi,

Is there any update regarding this. Kindly let me know.

@vkarpov15
Copy link
Collaborator

Not possible to do that. .populate() is not a join, the above query simply finds students and then executes a separate query for the students' corresponding classRoomRef. If you want to query students by classRoomName, store classRoomName in the student doc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants