2016-11-22 56 views
0

我喜歡使用MongoDB,但不能完全吞下它的非關係方面。據我從mongo用戶和文檔中可以看出:「沒關係,只是重複部分數據」。使MongoDB更'關係'

由於我很擔心縮放問題,基本上只是不記得更新部分代碼來更新數據的正確部分,所以當我的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用戶爲避免關係造成的,或者在設計我的模式時犯了錯誤嗎?

回答

0

您可以使用模式對象作爲參考使用貓鼬UR模式將會像使用貓鼬 http://mongoosejs.com/docs/populate.html

實現關係映射:

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] 
    })