查询子文件mongoose nodejs

时间:2014-02-06 07:06:01

标签: node.js mongoose

我的示例应用程序中有以下文档结构

enter image description here

模特是学生和电话。我已将其配置为如下所示

    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;

我可以在学生中插入学生文档和多个电话文档,如图所示。

我正在尝试查询子文档

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

});

请建议最好的方法。

注意:我知道我可以遍历student.phone对象,但我觉得它没有效率。

1 个答案:

答案 0 :(得分:0)

根据文件http://mongoosejs.com/docs/queries.html

如果你想使用findOne,你也需要传递选择器, 所以你的函数调用就像

compound.models.Student.findOne({ "name" : "prabhu" }, 'name dept', function(err, student)       {

//Do what you want;

});

编辑:

  compound.models.Student.findOne({ "name" : "prabhu","phone.number":1234 }, 'name dept', function(err,     student)       {

//Do what you want;

});