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