【问题标题】:Category and Subcategory Schema design类别和子类别架构设计
【发布时间】:2021-12-12 04:35:10
【问题描述】:

所以基本上它适用于博客文章及其类别和子类别。一篇博文可以有多个类别,每个类别都可以有多个子类别(基于博文)。

例如,假设我有两个帖子,帖子 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.*******

所以我的问题是,如何编写子类别的架构?

如果我将子类别引用放在帖子架构中,那么我将无法将子类别与类别链接,因为每个类别都会根据帖子有不同的子类别。

如果我将子类别引用放在类别架构中,那也是不可行的,因为一个类别可以在多个帖子中。

或者我应该将帖子引用和类别引用放在子类别架构中?

请建议我最好的方法。

【问题讨论】:

    标签: mongodb mongoose database-design schema mongoose-schema


    【解决方案1】:

    对于这样的用例,我会做这样的事情 -

    集合 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
    

    【讨论】:

    • 你好。非常感谢您的回答。但是,请多容忍我一点。在主页中,我想查看基于类别的帖子。然后每个类别都会有内页。我的意思是在一个页面中,我想查看基于特定类别的所有帖子。还将有子类别的内页以及基于每个子类别查看帖子。
    • 此外,还有内页,我需要根据类别和子类别查看帖子。例如,在一个页面中,我需要查看 Motivation for Success 的所有帖子,其中 Motivation 是一个类别,Success 是一个子类别。那么上述解决方案是否满足所有这些最佳性能标准?
    • 很高兴您发现它有帮助。我的回答中涵盖了所有 3 个用例。如果没有基于类别的页面,只需将所有类别 + 子类别存储在每个帖子的一行中(在 PostCategories 集合中),如果基于类别搜索,架构Collection 4 - PostCategories & 如果您也需要搜索子类别,使用最后一个架构/ 或将类别和子类别 id 存储在一行中。
    • 谢谢,这就够了。顺便说一句,我还有另一个关于聚合的问题。是否可以根据 Collection 4 统计 Collection 2 中的类别?我的意思是,假设我在 Collection 2 中有一个 id 为 1 的类别。所以这个类别可能在 Collection 4 的 5 个帖子中。所以 Collection 2 中的计数将自动为 5。有可能吗?
    • 是的,当然。如果你只需要计数,你可以把它放在聚合中,如果你想要所有基于类别 ID 的帖子,你也可以这样做。聚合可以轻松实现。
    猜你喜欢
    • 2015-10-15
    • 2020-08-04
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多