2015-02-10 29 views
-1

我正在使用IBM Worklight。我需要訪問兩個集合中的數據。是否有任何解決方案來加入2個集合並獲得必填字段?如何在json商店中加入兩個集合?

+0

[在JSON商店接合兩個集合]的可能重複(http://stackoverflow.com/questions/28408301/joining-two-collections-in- JSON-店) – 2015-02-11 05:36:05

回答

0

JSONSTORE無法合併集合。

但是後續的博客文章的細節來實現一個方法:https://mobilefirstplatform.ibmcloud.com/blog/2015/02/24/working-jsonstore-collections-join/

  1. 創建集合:

    var data = [ 
             {order_id : 462, order_date : '1-1-2000'}, 
             {order_id: 608, order_date : '2-2-2001'}, 
             {order_id: 898, order_date : '3-3-2002'} 
             ]; 
          var counter = 0; 
          var q = async.queue(function (task, callback) { 
           setTimeout(function() { 
            WL.JSONStore.get('orders').add(task.data, {additionalSearchFields: {customer_id: task.customer_id}}); 
            callback(++counter); 
           },0); 
          },1); 
          for(var i = 0; i < data.length; i++){ 
          q.push({data : data[i], customer_id: i+1}, function(counter){ 
           console.log("Added Order Doc " + counter); 
          }); 
          } 
         q.drain = function(){ 
          setTimeout(function() { 
           console.log("Finished adding order documents"); 
           WL.JSONStore.get("orders").findAll({filter : ["customer_id", "order_id", "order_date"]}) 
            .then(function (res) { 
             ordersCollectionData = res; 
             document.getElementById("orders").innerHTML = JSON.stringify(res, null, "\t"); 
            }) 
            .fail(function (err) { 
              console.log("There was a problem at " + JSON.stringify(err)); 
            }); 
          },0); 
         }; 
    
  2. var OrdersCollection = { 
         orders: { 
         searchFields: { 
          order_id: 'integer', 
          order_date: 'string' 
         }, 
         additionalSearchFields: { 
          customer_id: 'integer' 
         } 
         } 
    }; 
    var CustomerCollection = { 
         customers: { 
          searchFields: { 
           customer_name : 'string', 
           contact_name : 'string', 
           country : 'string' 
          }, 
          additionalSearchFields : { 
           customer_id : 'integer' 
          } 
         } 
        }; 
    
  3. 使用其他搜索字段添加數據

    查找要合併的文檔:

    WL.JSONStore.get('orders').findAll({filter : ['customer_id', 'order_id', 'order_date']}) 
            .then(function (res) { 
             ordersCollectionData = res; 
            }); 
    
  4. 合併

    var shared_index = 'customer_id'; 
    var mergedCollection = []; 
    mergedCollection =_.merge(customerCollectionData, ordersCollectionData, function(a, b){ 
         if(_.isObject(a) && (a[shared_index] == b[shared_index])) { 
          return _.merge({}, a, b); 
         } 
    });