Deisy Laymi
Deisy Laymi

Reputation: 343

_.map() not working when playing with real data

I'm querying two collections to get the data from bills and transactions.

After I get both, I loop transactions array for each billId.

Once the billId from the transaction array matches with the _id from the bill array, I store the transaction under the bill array.

So instead of having:

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

I can have:

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

The code below is working in my JSfiddle test, however, when I try with real data (from the db), I can't get the map to insert the new object into the bills array. Here is the working sample: http://jsfiddle.net/dennislaymi/usanwkcL/

And here is the (not working) code on my machine:

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);
    });
});

Upvotes: 0

Views: 118

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51480

_.map is an immutable operation, meaning that it doesn't change initial object.

If you want to overwrite it with mapped data, you should write something like:

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

I would also suggest using something like _.filter instead of _.each in your case:

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

Upvotes: 2

Related Questions