前言
nodejs在使用mongdb數據庫中經常會使用到嵌套,比如一個多級分類等。這里我使用學校-->學院-->學生來展示使用populate處理嵌套。
定義modal
在模式中,我們需要使用Schema.ObjectId
來表示要指向數據在mongodb數據庫中的_id。
學校
在學校的Schema中,colleges屬性是要包含的學院的_id屬性數組。
var SchoolSchema = new Schema({ name: String, colleges: [{ type: Schema.ObjectId, ref: 'College' }], createTime: { type: Date, default: Date.now() }});var School = mongoose.model('School', SchoolSchema);
學院
var CollegeSchema = new Schema({ name: String, students: [{ type: Schema.ObjectId, ref: 'Student' }], createTime: { type: Date, default: Date.now() }});var College = mongoose.model('College', CollegeSchema);
學生
var StudentSchema = new Schema({ name: String, sex: String, age: Number, createTime: { type: Date, default: Date.now() }});var Student = mongoose.model('Student', StudentSchema);
查找
直接查找
查找學校并找到指向的學院
School .find() .populate('colleges', ['_id','name']) .exec((err, schools) => { if (err) { console.log(err) } console.log(schools) })
populate的第一個參數是學校表中需要指向學院表的屬性,即colleges;第二個參數為要在學院中查找的屬性。如果不填寫第二個參數,則默認全都查出。
這樣查找出的結果中,學院的學生屬性是該學院包含的學生的_id屬性。如果需要都查找出來需要使用嵌套populate。
嵌套
School .find() .populate({ path: 'colleges', select: ['_id', 'name'], // model: 'College', populate: { path: 'students', select: ['_id', 'name'] // model: 'Student' } }) .sort({ createTime: -1 }).exec(function(err, schools) { if (err) { console.log(err) } });
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答