用mongodb中的作者信息设计博客模式

时间:2021-06-19 05:29:23

标签: node.js mongodb

我有一些博客,有标题、正文等。每个博客文档都会有 author 属性,其中包含作者信息。

{
  title:"..",
  body:"...",
  authorId:"1"
}

我有一个 users 集合,它具有以下架构。

{
  _id:"1",
  name:"..",
  imageUrl:".."
}

在查询数据库时,我想获取所有带有作者信息的博客。

在回复中,我想得到以下内容...

[
    {
        _id:"blog1",
        title:"..",
        body:"..",
        author:{
            _id:"...",
            name:"..",
            imageUrl:"..."
        }
    },
    {
        _id:"blog2",
        title:"..",
        body:"..",
        author:{
            _id:"...",
            name:"..",
            imageUrl:"..."
        }
    }
]

解决方案 1

在创建博客时,我可以保存每个blog文档的作者信息。

缺点

作者信息会随处重复。

解决方案 2

我可以使用 ref 的 mongodb。

db.blogs.insert({_id:1,title:"Blog",body:"...",author:{"$ref":"users","$id":"1"}});
db.blogs.aggregate([{"$lookup":{"from":"users","localField":"author.$id","foreignField":"_id","as":"user"}}])

问题

在我的主页上,我想显示所有带有用户个人资料图片的博客。

<块引用>

见下图

blogs

最佳

哪种解决方案在内存和速度方面是有效的?

0 个答案:

没有答案
相关问题