开发者

How can I get a view of favorite user documents by user in Couchdb map/reduce?

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 favorite开发者_开发百科s. 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"] }


In CouchDB 0.11 (just recently released), the include_docs=true feature allows you to look up any document in your view row. For example:

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

When you query your view with include_docs=true, you should see JSON like this:

// ... normal stuff
rows: [
  {
    "key":"user1",
    "value":{"_id":"doc1"},
    "doc": {
      "_id" : "doc1",
      "type" : "main_doc",
      "title" : "the first doc"
      // ...
     }
  },
  {
    // another doc, etc...
  }
]


If you can't use the include_docs=true feature with v0.11, then you must have all information on-hand when you emit data for your view/map.

Instead of a traditional "join" style, consider storing a list of "favoriting" users in the main_doc documents.

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

That way when your view runs, you can emit everything based on the information in that one document.

function(doc) {
    if(doc.type == "main_doc") {
        for (var a in doc.favorited_by) {
            emit(doc.favorited_by[a], [doc._id, doc.title]);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜