javascriptcouchbasecouchbase-viewnosql

Loop through all documents in a nested function


I started using Couchbase for a new project of mine and I hope you can help me solve a problem. I have two types of documents in my bucket. For example:

{
  "id": "A1",
  "name": "Name of A",
  "type": "A"
}

and

{
  "id": "B1",
  "name": "Name of B",
  "type": "B",
  "parentIDs": ["A1", "A4", "A5"]
}

I want to create a view with the following result:

{
  "id": "A1",
  "name": "Name of A",
  "type": "A",
  "children": [
    {JSON document of child 1}, 
    {JSON document of child 2}, 
    {JSON document of child 3}
  ]
}

I started to write a function and a nested one, which should iterate through all documents but I must surrender... Can you help me?

function (doc, meta) 
{
  if(doc.type == "A")
  {
    emit(doc, GetAllSites(doc));
  }

  function GetAllSites(doc)
  {
    var sites = [];

    for(var i = 0; i < doc.length; i++)
    {
      sites.push(doc.id);
    }

    return sites;
  }
}

Thanks

-----------------UPDATE-----------------

I solved my problem this way:

// map function
function (doc, meta)
{
  emit(meta.id, doc);
}

// reduce function
function (key, values, rereduce) 
{
  var result = [];

  for(var i = 0; i < values.length; i++)
  {    
    var val1 = values[i];

    if(val1.type != "A")
      continue;

    val1.childrenIDs = [];

    for(var j = 0; j < values.length; j++)
    {
      var val2 = values[j];

      switch(val2.type)
      {
        case "B":
          if(contains(val2.parentIDs, val1.id))
             val1.childrenIDs.push(val2);
          break;
        default:
          break;
      }
    }
    result.push(val1);
  }

  return result;

  function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
  }
}

May be no "blue-print" solution but it works and I'll optimize it later. :-)


Solution

  • You can't use nested functions, in you case I'll recommend to use reduce function after map function. So you need paste you GetAllSites function code to reduce And don't forget to realize rereduse logic