欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mongoose中利用populate處理嵌套的方法

 更新時(shí)間:2017年05月26日 11:38:02   作者:Jake  
這篇文章主要給大家介紹了關(guān)于mongoose中利用populate處理嵌套的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。

前言

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é)院中查找的屬性。如果不填寫(xiě)第二個(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ì)腳本之家的支持。

您可能感興趣的文章:

相關(guān)文章

最新評(píng)論