2011-03-27 57 views
4

我已經閱讀了「CouchDB的 - 權威指南」,並在網絡上找到許多文章。 我已經理解了沙發的工作原理,但我仍然有一些問題。CouchDB的博客應用

假設在一個簡單的博客應用程序上工作: 在帖子頁面中,我想顯示帖子的數據和作者的數據。 所以我認爲我必須把所有內容放在同一個文檔中。 好的。 如果我只需要在單個頁面中顯示作者的數據,我可以使用視圖來完成。 好的。

但如果作者更新他的數據,我需要更新在這裏筆者會出現在每個文件? 還是我錯了?

我真的很想明白這個邏輯。

在此先感謝。

回答

3

是的,你將需要更新每個文檔。這個想法是像這樣的大更新很少見的,所以即使它們在計算上昂貴,你也不應該做很多更新。

+0

好,謝謝。將作者的數據存儲在單獨的文檔中並分別加載它是否有意義? (在後期文檔中僅存儲作者的ID - 使用SQL風格) – user232028 2011-03-27 15:38:38

8

的一些信息可以留在同一文件中,在大多數情況下,將工作就好了。

{ 
    "title": "Blog Article Title", 
    "content": "... blah blah blah ...", 
    "author": { 
     "name": "someguy", 
     "email": "[email protected]" 
    }, 
    "type": "post" 
} 

其他時候,你可以用另一個文檔的_id以創建2個文件之間的鏈接。

{ 
    "_id": "...", 
    "title": "Blog Article Title", 
    "content": "... blah blah blah ...", 
    "author": "someguy", 
    "type": "post" 
} 

{ 
    "_id": "someguy", 
    "name": "Some Guy", 
    "email": "[email protected]", 
    "type": "author" 
} 

乍一看,您需要2個獨立的查詢來檢索兩個實體。但是,視圖查詢可能會暴露一個很好的小竅門。

function (doc) { 
    if (doc.type === "post") { 
     emit([doc.title, 0], null);    // output the main post 
     emit([doc.title, 1], { _id: doc.author }); // output the author 
    } 
} 

視圖即可輸出這樣的結果:(注意視圖的排序)

{ ... 
    "rows": [ 
     { 
      "key": ["Blog Article Title", 0], 
      "value": null 
     }, 
     { 
      "key": ["Blog Article Title", 1], 
      "value": { "_id": "someguy" } 
     } 
    ] 
} 

這還不是全部,因爲它是有用的,但如果添加include_docs=true到您的視圖URL,你」我會得到這個結果:

{ ... 
    "rows": [ 
     { 
      "key": ["Blog Article Title", 0], 
      "value": null, 
      "doc": { 
       "_id": "...", 
       "title": "Blog Article Title", 
       "content": "... blah blah blah ...", 
       "author": "someguy", 
       "type": "post" 
      }, 
     }, 
     { 
      "key": ["Blog Article Title", 1], 
      "value": { "_id": "someguy" }, 
      "doc": { 
       "_id": "someguy", 
       "name": "Some Guy", 
       "email": "[email protected]", 
       "type": "author" 
      } 
     } 
    ] 
} 

現在兩個實體都包含在1個查詢中。 :)

有關CouchDB中的實體關係的更多信息,請參閱this article