设计标签功能时,如何统计标签下文章数量?
发布于 5 年前 作者 wmui 2914 次浏览 来自 问答

下面是简单的示例:

// article
const ArticleSchema = new Schema({
	title: {
        type: String,
        required: true,
    },
    content: {
        type: String,
        required: true,
    },
    tags: [{
        type: Schema.Types.ObjectId,
        ref: 'Tag',
    }],
})

// tag
const TagSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: true,
    },
    sort: {
        type: Number,
        default: 0,
    },
    articles: [{
        type: Schema.Types.ObjectId,
        ref: 'Article',
    }],
})

我现在的做法是,添加文章时,更新tag下的articles字段,push 进去 article id。但我感觉这样是错的,因为如果修改了文章的标签,需要先删除原标签下的文章id,再添加到新标签下。求问有没有比较好的解决方式

5 回复

不用,另外建一个关系表,比较舒服,正向反向都好算

@captainblue2013 能否细说下,没太理解。。。

@wmui 你这个需求,其实RDB的实践更好,用文档的话,我比较担心性能

Mysql

对于msql来说,需要设计三张表,因为这个是多对多的关系

  • article {id, title}
  • tag {id, title}
  • article-tag {id, articleId, tagId}

则有:

  • 统计文章的标签: Select * From article-tag Where articleId = ${articleId}
  • 统计标签属于哪些文章: Select * From article-tag Where tagId = ${tagId}

Neo4j

就更加方便了

  • 查询文章的标签 Match (article: Article)-[: ArticlehasTag]-(tag: Tag) Where ID(article) = xx Return tag
  • 查询标签的文章: 略

不知道你懂了吗?另外没学过数据库的话,可以去找阮一峰老师教程入一下门

@cctv1005s @captainblue2013 感谢两位,我已经懂了,万分感谢

回到顶部