使用真实数据时_.map()无法正常工作

时间:2015-01-04 11:50:09

标签: javascript express mongoose underscore.js

我查询两个集合以从账单和交易中获取数据。

在我得到两者后,我为每个billId循环交易数组。

一旦来自交易数组的billId与账单数组中的_id匹配,我就将交易存储在账单数组下。

所以不要:

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}]

下面的代码在my JSfiddle test中工作,但是,当我尝试使用真实数据(来自数据库)时,我无法获取地图以将新对象插入到账单数组中。 以下是工作示例: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);
    });
});

1 个答案:

答案 0 :(得分:2)

_.map是一个不可变的操作,意味着它不会改变初始对象。

如果要使用映射数据覆盖它,则应编写如下内容:

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

我还建议您使用_.filter而不是_.each之类的内容:

bills = _.map(bills, function (bValue) {
  bValue.transactions = _.filter(transactions, function (tValue) {
    return (tValue.billId == bValue._id);
  });
  return bValue;
});
相关问题