2014-02-06 66 views
0

我在示例應用程序查詢子文件貓鼬的NodeJS

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對象循環,但我發現它不是有效的方式。

回答

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; 

}); 
+0

其實我可以得到學生工作的查詢..但我正在尋找能夠查詢子文件,就像我在問題中提到的。 – balanv

+0

讓我編輯查詢子文件的答案。請讓我知道這是否有幫助,或者您之前已經嘗試過。 – V31

+0

是的,我試過了,它工作。但是,如果我能像使用Rails一樣查詢生成的學生對象,那將會很棒。 – balanv