node.js - Querying sub documents mongoose nodejs -
i have below document structure in sample app
the models student , phone. have configured below
var mongoose = compound.mongoose; var phoneschema = new mongoose.schema({ type: string, number: string }); var studentschema = new mongoose.schema({ name: string, dept: string, year: string, phone: [phoneschema] }); var phone = mongoose.model('phone',phoneschema); var student = mongoose.model('student',studentschema); phone.modelname = 'phone'; compound.models.phone = phone; student.modelname = 'student'; compound.models.student = student;
i able insert student document , multiple phone documents within student shown.
i trying query subdocument
compound.models.student.findone({ "name" : "prabhu" }, function(err, student){ console.log(student); console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); ###########this line shows error, no method find 1 student.phone. student.phone.findone({ "number" : "123456" }, function(err, phone){ console.log(phone); }); });
please suggest best method it.
note : aware can loop through student.phone object, find not efficient way.
according documentation http://mongoosejs.com/docs/queries.html
you need pass on selectors if want use findone, function call like
compound.models.student.findone({ "name" : "prabhu" }, 'name dept', function(err, student) { //do want; });
edited:
compound.models.student.findone({ "name" : "prabhu","phone.number":1234 }, 'name dept', function(err, student) { //do want; });
Comments
Post a Comment