2017-09-28 31 views
0

我正在嘗試使用貓鼬的populate virtuals。比方說,我有這個帖子的模式:如何在Mongoose中使用填充虛擬物時進行聚合?

const postSchema = new mongoose.Schema({ 
    title: { 
    type: String, 
    required: true 
    }, 
    content: { 
    type: String, 
    required: true 
    } 
}); 
postSchema.virtual('comments', { 
    ref: 'Comment', 
    foreignField: '_id', 
    localField: 'post' 
}); 

現在,讓我們說,我想用aggregate評論內容過濾:

Post.aggregate([ 
    { 
    $match: { 
     $or: [{ 'comments.content': /match this content/ }] 
    } 
    }, 
    { 
    $project: { title: 1, comments: 1 } 
    } 
)] 

這不起作用,因爲comments尚未填充。任何替代品?

+0

通常你會使用[$查找(https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/)加入評論然後過濾評論。 – Veeram

+0

@Veeram,右所以像'$查找:{ 從: '意見', localField: '意見', foreignField: '_id', 爲: '意見' }'不幸的是它不返回任何評論 – nachocab

+0

看起來像'localField'是一個數組。在'$ lookup'之前嘗試{'$ unwind:「$ comments」}',看看它是否有幫助。在3.4版本中不需要'$ unwind'。 – Veeram

回答

1

我覺得你可以做:

Post.aggregate([ 
    { 
    $lookup:{ 
     from:"comments", 
     localField:"_id", 
     foreignField:"post", 
     as:"comments" 
    }, 
    $unwind:{ 
     "$comments" 
    }, 
    $match: { 
     $or: [{ 'comments.content': /match this content/ }] 
    } 
    }, 
    { 
    $project: { title: 1, comments: 1 } 
    } 
)]` 
+0

事實證明我有本地和外地翻轉。我剛剛更新了你的答案。謝謝! – nachocab

相關問題