鍍金池/ 問答/數(shù)據(jù)庫/ mongoose關聯(lián)查詢

mongoose關聯(lián)查詢

// 這里是文章
let articleSchema = new Schema({
    title: String,
    content: String
)}
// 這里是評論
let commentSchema = new Schema({
    title: String,
    content: String,
    article: { type: Schema.Types.ObjectId, ref: 'Article' }
)}
var Article = mongoose.model('Article', articleSchema );
var Comment = mongoose.model('Comment', commentSchema );

我想再獲取文章列表的時候,再通過文章_id獲取該文章下的評論,想了好久”populate“只能從評論查回文章,該怎么搞呢,不可能再文章里面寫n個評論的ref吧。感覺不現(xiàn)實啊。難道只能再獲取到文章列表里再遍歷每篇文章查一次?求解

回答
編輯回答
陪我終

article 里面可以存儲一個comment的_id數(shù)組,就可以populate出評論了

let articleSchema = new Schema({
    title: String,
    content: String,
    comments:[{
    type: Schema.Types.ObjectId, ref: 'Comment'
    }]
)}
2018年1月1日 06:05