[英]Querying sub documents mongoose nodejs
I have below document structure in my sample app 我的示例应用程序中具有以下文档结构
The models are Student and Phone. 这些模型是学生和电话。 I have configured it as like 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 could able to insert a Student document and multiple phone documents within the student as shown. 如图所示,我可以在学生中插入一个学生文档和多个电话文档。
I am trying to query the subdocument 我正在尝试查询子文档
compound.models.Student.findOne({ "name" : "prabhu" }, function(err, student){
console.log(student);
console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
###########This line shows error, no method find one for student.phone.
student.phone.findOne({ "number" : "123456" }, function(err, phone){
console.log(phone);
});
});
Please suggest the best method to do it. 请提出最佳方法。
Note : I am aware i can loop through the student.phone object, but i find its not efficient way. 注意:我知道我可以遍历student.phone对象,但是我发现它不是有效的方法。
According to the documentation http://mongoosejs.com/docs/queries.html 根据文档http://mongoosejs.com/docs/queries.html
You need to pass on the selectors as well if you want to use findOne, so your function call will be like 如果要使用findOne,还需要传递选择器,因此函数调用将像
compound.models.Student.findOne({ "name" : "prabhu" }, 'name dept', function(err, student) {
//Do what you want;
});
EDITED: 编辑:
compound.models.Student.findOne({ "name" : "prabhu","phone.number":1234 }, 'name dept', function(err, student) {
//Do what you want;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.