1 回答

TA貢獻1783條經驗 獲得超4個贊
如果您將評論 CommentSchema 硬合并到 Post Schema 中,您將始終受到硬編碼層數的限制。
相反,最好的做法是引用其他文檔而不合并它們。例如(這只是眾多方式中的一種):
comments: [CommentSchema]從 PostSchema 中刪除。
const CommentSchema = new mongoose.Schema({
// always require all comments to point to the top post, for easy query of all comments whether nested or not
postId: {
type: ObjectId,
ref: 'posts',
required: true,
}
parentCommentId: {
type: ObjectId,
ref: 'comments',
required: false, // if not populated, then its a top level comment
}
username: {
type: String,
required: true,
},
detail: {
type: String,
required: true,
},
})
現在,當您加載帖子時,執行查詢以獲取所有評論postId: post._id并根據需要以圖形方式顯示它們。另一個可能的主要模式是,您不是從評論到帖子向上引用,而是從帖子到評論 [到評論等] 向下引用,這允許查找但不是那么簡單的簡單查詢。
祝你好運!
添加回答
舉報