一形庭、模型關(guān)聯(lián)
1坤邪、一對(duì)多/多對(duì)多
在一中關(guān)聯(lián)多中的字段灸撰,type為mongoose.Schema.Types.ObjectId
,并關(guān)聯(lián)關(guān)聯(lián)模型的名稱(chēng)挪捕。
const categorySchema = new mongoose.Schema({
name: {type: String}
})
const tagSchema = new mongoose.Schema({
name: {type: String}
})
const articleSchema = new mongoose.Schema({
title: {type: String},
content: {type: String},
/* 一對(duì)多字段為一個(gè)對(duì)象 */
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category' // 關(guān)聯(lián)的模型
},
/* 多對(duì)多字段為一個(gè)數(shù)組 */
tags: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag'
}]
})
2粗梭、關(guān)聯(lián)模型的查詢(xún)
(1)一對(duì)多查詢(xún)
從關(guān)聯(lián)對(duì)象中查詢(xún)
const category = await Article.find().populate('category')
console.log(category)
結(jié)果為一個(gè)數(shù)組,數(shù)組中的對(duì)象含有category對(duì)象
[ { tags: [ 5ced005cf0b6b50fe429ffdb, 5ced005df0b6b50fe429ffdc ],
_id: 5cecff6c9d129a1520c4fa9c,
title: 'article1',
content: 'article1',
__v: 1,
category: { _id: 5ced0007037e041ec0560c1a, name: 'node', __v: 0 } },
{ tags: [ 5ced005df0b6b50fe429ffdc ],
_id: 5cecff6d9d129a1520c4fa9d,
title: 'article2',
content: 'article2',
__v: 1,
category: { _id: 5ced0008037e041ec0560c1b, name: 'vue', __v: 0 } } ]
(2)多對(duì)多查詢(xún)
const tag = await Article.find().populate('tags')
console.log(tag)
結(jié)果為數(shù)組,被關(guān)聯(lián)對(duì)象字段也是一個(gè)數(shù)組级零,包含多個(gè)對(duì)象
[ { tags: [ [Object], [Object] ],
_id: 5cecff6c9d129a1520c4fa9c,
title: 'article1',
content: 'article1',
__v: 1,
category: 5ced0007037e041ec0560c1a },
{ tags: [ [Object] ],
_id: 5cecff6d9d129a1520c4fa9d,
title: 'article2',
content: 'article2',
__v: 1,
category: 5ced0008037e041ec0560c1b } ]
3断医、從被關(guān)聯(lián)模型中查詢(xún)關(guān)聯(lián)模型
(1)設(shè)置虛擬字段
在被關(guān)聯(lián)模型中設(shè)置虛擬字段
categorySchema.virtual('articles', { // 定義虛擬字段
ref: 'Article', // 關(guān)聯(lián)的模型
localField: '_id', // 內(nèi)鍵,Category模型的id字段
foreignField: 'category', // 外鍵妄讯,關(guān)聯(lián)模型的category字段
justOne: false // 只查詢(xún)一條數(shù)據(jù)
})
const tagSchema = new mongoose.Schema({
name: {type: String}
})
tagSchema.virtual('articles', {
ref: 'Article',
localField: '_id',
foreignField: 'tags',
justOne: false
})
(2)查詢(xún)
const article = await Tag.find().populate('articles')
console.log(article)
結(jié)果表面上看起來(lái)沒(méi)有其他字段的信息孩锡,但虛擬字段的內(nèi)容已經(jīng)包括在內(nèi)了;
[ { _id: 5ced005cf0b6b50fe429ffdb, name: 'tag1', __v: 0 },
{ _id: 5ced005df0b6b50fe429ffdc, name: 'tag2', __v: 0 } ]
繼續(xù)在結(jié)果的數(shù)組中選擇一個(gè)對(duì)象,并查詢(xún)articles字段亥贸;
const article = await Tag.find().populate('articles')
console.log(article[0].articles)
結(jié)果就會(huì)為tag為tag1的所有文章。
[ { tags: [ 5ced005cf0b6b50fe429ffdb, 5ced005df0b6b50fe429ffdc ],
_id: 5cecff6c9d129a1520c4fa9c,
title: 'article1',
content: 'article1',
__v: 1,
category: 5ced0007037e041ec0560c1a } ]