【问题标题】:What is the best way to get all my categories in my mongodb collection of posts在我的 mongodb 帖子集合中获取所有类别的最佳方法是什么
【发布时间】:2020-07-25 06:57:33
【问题描述】:

我正在使用 Express、MongoDB 和 React 开发一个博客应用程序。我肯定更喜欢使用关系数据库,但我想更喜欢基于文档的数据库,所以我在这里。

我有一个帖子集合,其当前状态如下所示:

[
    {
        "id": "001",
        "category": "fishing",
        "title": "jigs",
        "body": "Lorem ipsum dolor sit amet, consectetu"
    },
    {
        "id": "002",
        "category": "cooking",
        "title": "tuna casserole",
        "body": "Lorem ipsum dolor sit amet, consectetur"
    },
...]

当你转到 url/posts 时,你会得到所有的帖子。当你转到 url/posts/cooking 时,你当然会做饭。

当我在前端处理存根数据时,我正在从一个 json 文件中创建一个类别列表,如下所示:

const uniqueCategories = [
    ...new Set(props.posts.map((post) => post.category)),
];

但是,我是这样按类别获取我的帖子的:

useEffect(() => {
    async function fetchPosts() {
        fetch(`api/posts/${category}`)
            .then((res) => res.json())
            .then(
                (result) => {
                    setPosts(result);
                    console.log('result', result);
                }
            );
    }
    fetchPosts();
}, [category]);

我还没有实现所有类别,但这没关系。现在,如果我得到烹饪类别,我上面的 uniqueCategories 函数将只会映射 cooking

所以问题是。构建这个的最佳方法是什么?

我应该有一个类别集合吗?在帖子集合中,我应该引用类别集合的 id 吗?

或者有没有更好的方法?

【问题讨论】:

    标签: mongodb express


    【解决方案1】:

    这实际上取决于您的应用程序及其查询。

    选项 1

    如果您只想获取所有帖子类别,您可以只索引您的类别并使用distinct 方法。这样做的缺点是您不能为类别添加其他字段,例如类别描述。

    代码示例:

    db.posts.createIndex({ category: 1 }); // create index for category field
    
    db.posts.distinct("category") // ["fishing", "cooking"]
    

    选项 2

    创建类别集合:

    {
       _id: "fishing",
       ...
    }
    

    您不需要使用MongoDB默认的ObjectId作为_id,因为类别名称将是唯一的,您只需将类别名称设置为_id,这也允许您获取帖子类别名称而无需做任何额外的查找。使用此选项,您可以为类别添加其他字段,例如:

    {
       _id: "fishing",
       name: "Fishing",
       description: "Category for all of the fishing lovers!"
    }
    

    然后在您的post 集合上,您可以只使用类别_id 作为类别值

    {
      "id": "001",
      "category": "fishing",
      "title": "jigs",
      "body": "Lorem ipsum dolor sit amet, consectetu"
    },
    

    如果你想获取分类列表,你可以直接查询分类集合。

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多