1,先寫一個clazz班級類:c++
var mongoose=require('mongoose'); var clazzschema=new mongoose.Schema({ clazzname:String }); mongoose.model('Clazz',clazzschema);
2:在寫一個student類,關聯clazz。mongoose
/** * Created by 1 on 2016/4/12. */ var mongoose=require('mongoose'); var studentschema=new mongoose.Schema({ studentname:String, //關聯clazz clazzid:{ type:mongoose.Schema.ObjectId, ref:'Clazz' } }); //寫一個靜態類;查詢該學生的班級 studentschema.statics={ findClazzNameByStudentId:function(studentid,callback){ return this.findOne({_id:studentid}) .populate('clazzid') .exec(callback); } } mongoose.model('Student',studentschema);
3,在訪問連接裏面調用。先存一個班級和一個學生;ui
//var clazz=new Clazz({ // clazzname:'c++' //}); // //console.log(clazz); // // //clazz.save(function(err){ // if(err){ // console.log(err); // } // var student=new Student({ // studentname:'aaaa', // clazzid:clazz._id // }); // console.log(student); // student.save(function(err){ // if(err){ // console.log(err); // } // console.log('success'); // }); //});
4:而後找該學生對應的班級this
Student.findClazzNameByStudentId('570ca4956747c9b41e2a5da3',function(err,student){ if(err){ console.log(err); } console.log(student.clazzid.clazzname); });