使MongoDB更具关系性{'

时间:2016-11-22 02:24:09

标签: node.js mongodb api database-design relational-database

我喜欢使用MongoDB,但不能完全吞噬它的非关系方面。据我所知,mongo用户和文档:"没关系,只需重复部分数据"。

由于我担心缩放,并且基本上只是不记得更新部分代码以更新数据的正确部分,因此在我的API上执行额外查询似乎是一个很好的权衡必须返回包含帖子摘要的用户数据:

{
  "id": 1,
  "name": "Default user",
  "posts_summary": [
    {
      "id": 1,
      "name": "I am making a blog post",
      "description": "I write about some stuff and there are comments after it",
      "tags_count": 3
    },
    {
      "id": 2,
      "name": "This is my second post",
      "description": "In this one I write some more stuff",
      "tags_count": 4
    }
  ]
}

...当帖子数据如下所示:

//db.posts
{
  "id": 1,
  "owner": 1,
  "name": "I am making a blog post",
  "description": "I write about some stuff and there are comments after it",
  "tags": ["Writing", "Blogs", "Stuff"]
},
{
  "id": 2,
  "owner": 1,
  "name": "This is my second post",
  "description": "In this one I write some mores tuff",
  "tags": ["Writing", "Blogs", "Stuff", "Whatever"]
}

因此,在API的后面,当获取用户成功的查询时,我正在对posts集合进行额外的查询以获取" posts_summary"我需要的数据,并在API发送响应之前添加它。

考虑到以后解决的问题,这似乎是一个很好的权衡。这是一些mongo用户做的事情,而不是关系,或者我在设计模式时犯了错误?

1 个答案:

答案 0 :(得分:0)

您可以使用模式对象作为引用来使用mongoose实现关系映射 http://mongoosejs.com/docs/populate.html

使用mongoose ur schema会像:

User:Schema({
  _id     : Number,
  name    : String,
  owner     : String,
  Post : [{ type: Schema.Types.ObjectId, ref: 'Post' }]
}); 

    Post:Schema({
      _id     : Number,
      name    : String,
      owner     : String,
      description     : String,
      tags:[String]
    })