所以基本上它是用于博客文章及其類別和子類別。一篇博文可以有多個類別,每個類別可以有多個子類別(基于帖子)。
例如,假設我有兩個帖子,帖子 1 和帖子 2。帖子 1 屬于動機和旅程類別。根據帖子 1 的內容,動機可以有子類別,如成功和金錢。
同樣,帖子 2 可以屬于“教育”和“旅程”類別。教育有一個子類別知識和旅程有一個子類別稱為成功。
我已經設計了 Post 和 Category 架構,但是我在使用 Subcategory 架構時遇到了困難。
Post 架構如下所示:
const postSchema = new mongoose.Schema( {
post: {
type: String,
required: true,
trim: true
},
category: [ {
_id: false,
categoryID: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Category'
}
} ]
});
這是類別架構:
const categorySchema = new mongoose.Schema( {
catName: {
type: String,
required: true
},
count: {
type: Number,
default: 0
}
});
*******COUNT field shows the total number of posts that have that specific category.
For example, Motivation category could be in 100 posts.*******
所以我的問題是,如何為子類別撰寫架構?
如果我將子類別參考放在帖子模式中,那么我將無法將子類別與類別鏈接,因為每個類別將根據帖子具有不同的子類別。
如果我將子類別參考放在類別架構中,那么這也是不可行的,因為一個類別可以在多個帖子中。
或者我應該將 Post 參考和 Category 參考放在 Subcategory 模式中?
請建議我最好的方法來做到這一點。
uj5u.com熱心網友回復:
對于這樣的用例,我會做這樣的事情 -
集合 1 - 帖子
post : string
集合 2 - 類別
name : string
count : number
集合 3 - 子類別
categoryId : ObjectId // FK to category
name : string
集合 4 - 帖子類別
postId : ObjectId // FK to post
categoryId : ObjectId // FK to category
subCategories : [ (ObjectId) ] // array of sub-categories, pointing to sub-category
資料庫設計主要取決于您的用例。如果您只想查看每個帖子的數量,您可以將類別和子類別關系存盤在單個陣列中(在 PostCategories 集合中)
PostCategories,我在這里提到過,如果您想根據 categoryId 進行搜索,可以使用它(如果想在 UI 上顯示與某個類別相關的帖子,您可以在 categoryId 上建立索引,這將是最快的方法)
如果您也想根據子類別進行搜索,您可以修改 PostCategories 表以具有多對多關系。
postId : ObjectId // FK to post
categoryId : ObjectId // FK to category
subCategories : ObjectId // FK to sub-category
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338561.html
