1

My Couchdb database as a main document type that looks something like:

{
   "_id" : "doc1",
   "type" : "main_doc",
   "title" : "the first doc"
   ...
}

There is another type of document that stores user information. I want users to be able to tag documents as favorites. Different users can save the same or different documents as favorites. My idea was to introduce a favorite document to track this something like:

{
   "_id" : "fav1",
   "type" : "favorite",
   "user_id" : "user1",
   "doc_id" : "doc1"
}

It's easy enough to create a view with user_id as the key to get a list of their favorite doc IDs. E.g:

function(doc) {
   if (doc.type == "favorite") {
      emit(doc.user_id, doc.doc_id);
   }
 }

However I want to list of favorites to display the user_id, doc_id and title from the document. So output something like:

{ "key" : "user1", "value" : ["doc1", "the first doc"] }
4

2 回答 2

2

在 CouchDB 0.11(刚刚发布)中,该include_docs=true功能允许您在视图行中查找任何文档。例如:

function(doc) {
    if(doc.type == "favorite") {
        emit(doc.user_id, {_id: doc.doc_id});
    }
}

当您使用 查询视图时include_docs=true,您应该会看到如下所示的 JSON:

// ... normal stuff
rows: [
  {
    "key":"user1",
    "value":{"_id":"doc1"},
    "doc": {
      "_id" : "doc1",
      "type" : "main_doc",
      "title" : "the first doc"
      // ...
     }
  },
  {
    // another doc, etc...
  }
]
于 2010-03-23T02:31:39.603 回答
0

如果您不能在include_docs=truev0.11 中使用该功能,那么当您为视图/地图发出数据时,您必须准备好所有信息。

main_doc考虑在文档中存储“收藏”用户列表,而不是传统的“加入”样式。

{
   "_id" : "doc1",
   "type" : "main_doc",
   "title" : "the first doc",
   "favorited_by": ["user1", "user2"]
   // ...
}

这样,当您的视图运行时,您可以根据该文档中的信息发出所有内容。

function(doc) {
    if(doc.type == "main_doc") {
        for (var a in doc.favorited_by) {
            emit(doc.favorited_by[a], [doc._id, doc.title]);
        }
    }
}
于 2010-03-23T21:58:31.130 回答