Search code examples
javascriptcouchdbcouchdb-futon

Link documents in CouchDB


I have two types of documents(both are in same database) in my couch-db, now I have created a view which can linkup the two documents by "_id" and return the data by using the couch-db view URL. And now I want to get data from the two types in map function. The types of documents and code are as shown below.

Documents

department {
               "_id": "1", 
               "department": "Computers",
               "type": "Department", 
               "room_no": "102", 
               "HOD": "Mr. G Rahul",
               "floor": "1st Floor" 
            }

student {
             "_id": "fdf370e2f43d4af1b505b8913502a5e4",
             "_rev": "1-16df9a4cd45ca69009ab6c9767425a8e",
             "student Name": "H Ravi",
             "date_of_birth": "March 1, 1993",
             "roll_no": "55",
             "inter_marks": "820",
             "secondary_marks": "420"
             "department_id": "1",
             "type": "student"
         }

Map-Function

function(doc) {
          var id,department,student,hod,dob;
          if(doc.type == 'student') {
                  id = doc.department_id;
                  dob = new Date(doc.date_of_birth)
              student = doc;    
         }
         if(doc.type == 'department') {
           if(doc._id == 'id') {
           hod = doc.HOD;
               department = doc;
         }
         }
   emit([dob,hod], {'_id': id,"student_doc": student,"depart_doc":department});
 }

The second if condition is not executing in the above function. The above code is map-function only.


Solution

  • Wrap the two tests inside a single if statement:

    function(doc) {
        var id,department,student,hod,dob;
        if(doc.type) {
          if(doc.type === 'student') { ... }
          if(doc.type === 'department') { ... }
        }
        emit([dob,hod], {'_id': id,"student_doc": student,"depart_doc":department});
     }