Search code examples
couchbasecouchbase-view

Querying couchbase by passing parameter


I am having couchbase report documents stored in below format:

{
   "agree_allowed":true,
   "assigned_by":"",
   "assigned_to":"",
   "closed":[

   ],
   "comments_allowed":true,
   "details":"Test",
   "email":"",
   "status":"In Progress",
   "subscribed":{
      "user_cfd29b81f0263a380507":true,
      "user_cfd29b81f0263a380508":true,
      "user_cfd29b81f0263a380509":true,
      "user_cfd29b81f0263a3805010":true
   },
   "summary":"Test",
   "time_open":0,
   "timestamp":"2015-07-17T15:34:30.864Z",
   "type":"report",
   "user_id":"user_cfd29b81f0263a380507",
   "username":"test17"
}

json contain subscribed filed, it is list of user_id who follow reports. Problem is i have to emit report document if subscribed field contain user_id, if i pass user_id ='user_cfd29b81f0263a380507' pass as key parameter. i am wondering how can use user_id to compare in view

here is the code i write:-

function map(doc, meta) {
        if (doc.type == 'report' && doc.subscribed) {
            for (var user_id in doc.subscribed) {
                emit(doc.user_id, doc);
            }

        }
    }

but it didn't return expected result. Can anybody help.


Solution

  • If I understand your question I think you want the ability to query the users who have subscribed.

    If that is the case the view code is wrong it is submitting doc.user_id and not user_id, which is the variable you assign values to in the loop but never use. In any case I think it would be better to use a different names to avoid confusion.

    function map(doc, meta) {
            if (doc.type == 'report' && doc.subscribed) {
                for (var subscriber in doc.subscribed) {
                    emit(subscriber);
                }
            }
        }
    

    To query the users who have subscribed you would use key=user_cfd29b81f0263a380507. The result would be:

    {
      "total_rows": 4,
      "rows": [
        {
          "id": "docs",
          "key": "user_cfd29b81f0263a380507",
          "value": null
        }
      ]
    }