두 개의 모음을 쿼리하여 청구서 및 거래에서 데이터를 가져옵니다.실제 데이터로 재생할 때 _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);
});
});
돈 '나는 또한 귀하의 경우
_.filter
대신_.each
같은 것을 사용하는 것이 좋습니다 것: 당신이 매핑 된 데이터로 덮어 쓰기하려면
, 당신은 뭔가를 작성해야 'bill_array = [{ "_id": "01", "value": "100"}]'? – thefourtheye
@thefourtheye, 오타라고 생각하세요. – BatScream
내부의'_.each '를'_.map' (또는보다 나은 네이티브'array # map')으로 리펙토링 할 수 있습니다. 또한 thefoureye와 마찬가지로 객체 표기법이 올바르지 않다는 것을 참고하십시오. –