There is no join feature in MongoDB, so joins and associated queries cannot be used with joins, the populate method is encapsulated in mongoose, and the field (property) can be specified as a reference to another schema when defining a schema. When querying a document, you can use the Populate method to find the specified field value for another document or document that is associated by referencing the Schema and ID. Here is a simple chestnut:
"Scene": Find Student's class by student ID, corresponding collection: Student students, Class Clazzs
1 varMongoose = require (' Mongoose '))2 varApp = require (' Express ')()3 varMongoose = require (' Mongoose '))4Mongoose.connect (' Mongodb://localhost/test ')5 6 //Define student Mode7 varStudentschema =NewMongoose. Schema ({8 name:string,9 Clazzid: {Ten Type:mongoose. Schema.objectid, OneRef: ' Clazz '//model name of Clazz A } - }) - //even table Query method theStudentschema.statics = { -Findclazznamebystudentid:function(StudentID, callback) { - return This -. FindOne ({_id:studentid}). Populate (' Clazzid ')//Correlation Query + . EXEC (callback) - } + } A at //Define class Mode - varClazzschema =NewMongoose. Schema ({ - clazzname:string - }); - - //Model in varStudent = Mongoose.model (' Student '), Studentschema) - varClazz = Mongoose.model (' Clazz '), Clazzschema) to + //Create a new class document and save - /*var clazz = new Clazz ( the { * clazzname: ' Sports Class 9 ' $ }Panax Notoginseng ); - Clazz.save (function (argument) { the console.log (' true '); + }); A */ the + //Create a new student document and save - /*var student = new Student ({ $ name: ' Ma Dongmei ', $ clazzid: ' 56e1440f508c947b0f32c16b '//Sports Class 3 _id - }) - Student.save (function (err) { the console.log (' true '); - })*/Wuyi the -Student.findclazznamebystudentid (' 56e1446c64a8f59c0f866df3 ',function(err, student) { Wu if(Err) console.log (err); -Console.log (Student.name + "in the class:" +student.clazzID.clazzName); About /*through StudentID query to the corresponding student object, and through the association property Clazzid get to the corresponding ClassID class object, $ returning class names through the object's Clazzname property*/ - }) - - varLogger = require (' Morgan '); A if(' development ' = = = = App.get (' env '))){ +App.set (' Showstackerror ',true);//Output error message theApp.use (Logger (': Method:url:status '));//Output Information field -App.locals.pretty =true;//Source code Formatting $Mongoose.set (' Debug ',true);//Database error message the}
First insert a few classes of records in the database:
Then create a new student object:
You can tell by the value of Clazzid that the class of Ma Dongmei is 3 classes of P.E.
Run the code and query the student's class through StudentID, the results are as follows:
Use of associated query populate in Mongoose