2015-01-04 1 views
0

두 개의 모음을 쿼리하여 청구서 및 거래에서 데이터를 가져옵니다.실제 데이터로 재생할 때 _map()이 작동하지 않습니다.

두 가지를 모두 얻은 후에는 billId에 대한 트랜잭션 배열을 반복합니다.

트랜잭션 배열의 billId이 bill 배열의 _id과 일치하면 bill 배열에 트랜잭션을 저장합니다.

그래서 대신 갖는

bill_array = [{ 
    "_id": "549bf0597886c3763e000001", 
    "billName": "Leasing", 
    "startDate": "2014-12-25T00:00:00.000Z", 
    "endDate": "2017-10-14T22:00:00.000Z", 
    "amount": 16500, 
    "type": 4, 
    "timestamp": "2014-12-25T11:09:13.957Z", 
    "__v": 0 
}] 

내가 가질 수

bill_array = [{"_id": "549bf0597886c3763e000001", 
    "billName": "Leasing", 
    "startDate": "2014-12-25T00:00:00.000Z", 
    "endDate": "2017-10-14T22:00:00.000Z", 
    "amount": 16500, 
    "type": 4, 
    "transactions": {[all transactions]} 
    "timestamp": "2014-12-25T11:09:13.957Z", 
    "__v": 0}] 

I합니다 (dB에서) 실제 데이터하려고 할 때 아래, 그러나, my JSfiddle test에서 일하고 코드, I 청구서 배열에 새 개체를 삽입하는지도를 가져올 수 없습니다. 다음은 작업 샘플입니다 : http://jsfiddle.net/dennislaymi/usanwkcL/

그리고 여기 내 컴퓨터에 (작동하지 않는) 코드 :

app.get('/getbills', function(req, res) { 
    //get all bills 
    allBills = Bills.find().exec(); 
    //get all transactions 
    allTransactions = Transactions.find().exec(); 
    //aggregate bills and transactions in a promise 
    promise.all([allBills, allTransactions]).then(function(results) { 
     var bills = results[0]; 
     var transactions = results[1]; 

     _.map(bills, function(bValue) { 
      bValue.transactions = []; 
      _.each(transactions, function(tValue) { 
       if (tValue.billId == bValue._id) { 
        bValue.transactions.push(tValue); 
       } 
      }); 
      console.log("transactons: " + bValue.transactions); 
      return bValue.transactions; 
     }); 
     console.log(bills); 
     res.send(bills); 
    }); 
}); 
+0

돈 '나는 또한 귀하의 경우 _.filter 대신 _.each 같은 것을 사용하는 것이 좋습니다 것

bills = _.map(bills, function (bValue) { bValue.transactions = []; _.each(transactions, function (tValue) { if (tValue.billId == bValue._id) { bValue.transactions.push(tValue); } }); return bValue; }); 

: 당신이 매핑 된 데이터로 덮어 쓰기하려면

, 당신은 뭔가를 작성해야 'bill_array = [{ "_id": "01", "value": "100"}]'? – thefourtheye

+0

@thefourtheye, 오타라고 생각하세요. – BatScream

+0

내부의'_.each '를'_.map' (또는보다 나은 네이티브'array # map')으로 리펙토링 할 수 있습니다. 또한 thefoureye와 마찬가지로 객체 표기법이 올바르지 않다는 것을 참고하십시오. –

답변

2

_.map는 초기 개체를 변경하지 않는 것을 의미 불변의 작업입니다.

bills = _.map(bills, function (bValue) { 
    bValue.transactions = _.filter(transactions, function (tValue) { 
    return (tValue.billId == bValue._id); 
    }); 
    return bValue; 
}); 
+0

제 코드를 적용 할 수있는 기회가 있습니까? _.map 또는 _.each와 관련된 웹 예제가 충분하지 않습니다. 내 예제에서. 감사합니다 –

+0

_map()에서 결과를 변수로 가져 오는 경우에도 여전히 원하는 결과를주지 못합니다. 제발, 시간이 있다면, 제가 빠진 것이 무엇인지 알려주세요 : http://jsfiddle.net/dennislaymi/usanwkcL/3/ 감사합니다 –

+0

@DeisyLaymi 내 업데이트를 참조하십시오. 또한 jsfiddle : [버전 1] (http://jsfiddle.net/usanwkcL/5/), [버전 2] (http://jsfiddle.net/usanwkcL/6/)을 업데이트했습니다. –