CNode

设计标签功能时,如何统计标签下文章数量?

问答
Wwmui发布于7 年前最后回复7 年前5 回复3865 浏览0 收藏

下面是简单的示例:

// 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)

C
captainblue2013#1·7 年前

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

W
wmui#2·7 年前
引用 captainblue2013不用,另外建一个关系表,比较舒服,正向反向都好算

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

C
captainblue2013#3·7 年前
引用 wmui@captainblue2013 能否细说下,没太理解。。。

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

C
cctv1005s#4·7 年前

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
  • 查询标签的文章: 略

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

W
wmui#5·7 年前

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

参与回复
登录后即可参与回复。登录