I have been trying to take the json data outputted from the database and create an new array that groups the data by month and year.
The problem is my new array doesn't output in the format that i need so i need to add the month and year but can't get the month grouping to work first. I think that might be right and resolve my issue, but I need help as arrays are confusing.
I have a codepen demo https://codepen.io/james182/pen/yLaqybP
var data = [
{ name: "First", timestampSent: "Wed, 25 Nov 2020 - 11:01 AM" },
{ name: "Second", timestampSent: "Wed, 25 Nov 2020 - 11:21 AM" },
{ name: "Third", timestampSent: "Thu, 26 Nov 2020 - 10:21 AM" },
{ name: "Fourth", timestampSent: "Fri, 27 Nov 2020 - 13:52 PM" },
{ name: "Fifth", timestampSent: "Tue, 24 Dec 2020 - 11:01 AM" },
{ name: "Sixth", timestampSent: "Wed, 25 Dec 2020 - 01:01 AM" }
];
// Clear console before running
console.clear();
var list = [];
for (i = 0; i < data.length; i++) {
var dates = data[i].timestampSent.slice(5, 16);
var mth = data[i].timestampSent.split(" ")[2];
if (!list[mth]) {
list[mth] = [];
}
list[mth].push({ name: data[i].name, date: data[i].timestampSent });
console.log(mth);
}
console.log(JSON.stringify(list));
//console.log('list', list);
/*
outcome:
[{
'Nov': [
{
'name': 'First',
'timestampSent': 'Wed, 25 Nov 2020 - 11:01 AM'
},
{
'name': 'Second',
'timestampSent': 'Wed, 25 Nov 2020 - 11:21 AM'
},
{
'name': 'Third',
'timestampSent': 'Thu, 26 Nov 2020 - 10:21 AM'
},
{
'name': 'Fourth',
'timestampSent': 'Fri, 27 Nov 2020 - 13:52 PM'
}
],
'Dec': [
{
'name': 'Fifth',
'timestampSent': 'Tue, 24 Dec 2020 - 11:01 AM'
},
{
'name': 'Sixth',
'timestampSent': 'Wed, 25 Dec 2020 - 01:01 AM'
}
]
}]
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Your list should not be an array. Since you are using the month name ('Nov', 'Dec') as keys you should use an object.
var list = {};
try change the line
list = []
to
list = {}
You will be using an object, not a list.
Try it here
Related
Having an array of dictionaries I'd like to obtain the most updated record. For instance, consider the following record:
var myArray = [{
itemA: {
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
itemB: {
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
},
itemC: {
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
}}];
which then I would need to get the most updated record first:
myArray.sort((d1, d2) => new Date(d2.date).getTime() - new Date(d1.date).getTime());
However, I am not getting the correct result. Would you know how to get it working?
Thanks :)
I have refactored your code a little bit.
first of all, your myArray contains only one object. you cannot sort an object like that. therefore I change the structure of your array.
here is a working example:
var myArray = [
{
id: 1,
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
id: 2,
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
id: 3,
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray.sort((d1, d2) => new Date(d2.date).getTime() - new Date(d1.date).getTime());
console.log(myArray)
This snippet should help you:
const myArray = [
{
itemA: {
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
itemC: {
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
},
itemB: {
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
}
}
];
const sortedArray = myArray.map(entry => {
let tmpObj = {};
let tmpSorted = Object.keys(entry).sort((prev, next) => {
return Date.parse(entry[next]?.date) - Date.parse(entry[prev]?.date);
});
tmpSorted.forEach(e => {
tmpObj[e] = entry[e];
})
return tmpObj;
});
console.log(sortedArray);
Your current approach attempts to sort an array of length 1, and the item in the array is an object that represents each record as a property (another object). This makes it a bit inefficient to iterate over your data. Do you need the ItemA labeling for each record and, if so, why not make this part of the object describing the record itself along with date and name?
You can look at Object.entries(), Object.keys(), or Object.values() for ways to make use of object data in an array in order to sort or map over your data.
Assuming your current schema and assuming you had an array with many such objects, if you wanted to find the most recent record in the list for some item i in your array, here is a solution.
You can create a sorted array of objects representing each record for the array item in question. Once sorted, you can take the first or last record to get the oldest or newest. See example below.
const myArray = [
{
itemA: {
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
itemC: {
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
},
itemB: {
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
}
}
];
const sortedEntries = myArray.map((entry) => {
const records = Object.values(entry);
const sortedRecords = records.sort(function (prev, next) {
return new Date(prev.date) < new Date(next.date) ? -1 : 1;
});
return sortedRecords;
});
// the array with records for each entry now sorted as an array from oldest to most recent date
console.log("sorted entries: ", sortedEntries);
// for example purposes, accessing your array by index, assuming you had more than 1 item in the array
const i = 0;
// get the record with most recent date for this array item
console.log(
"most recent record for example entry is: ",
sortedEntries[i][sortedEntries[i].length - 1]
);
https://codesandbox.io/s/festive-shadow-s36cf3
If you want to find the record with the latest date, you can iterate through the collection and store a record if it satisfies the comparator.
const
identityFn = (x) => x,
findBy = (collection, accessor, comparator) => {
let result, prev, record, i;
if (collection && collection.length) {
for (i = 0; i < collection.length; i++) {
record = collection[i];
if (!prev || comparator(accessor(record), prev)) {
result = record;
prev = accessor(record);
}
};
}
return result;
},
findMax = (collection, accessor = identityFn) =>
findBy(collection, accessor, (curr, prev) => curr > prev);
const
myArray = [{
itemA: { name: "Joe Blow" , date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)" },
itemB: { name: "Sam Snead" , date: "Sun Mar 30 2016 00:00:00 GMT-0700 (PDT)" },
itemC: { name: "John Smith" , date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)" },
itemD: { name: "Jane Doe" , date: null },
itemE: null,
}],
extractDate = (data) => data ? new Date(data?.date) : null,
[key, record] = findMax(
Object.entries(myArray[0]), // Access the entries (key/val pairs)
([key, val]) => extractDate(val) // Map the parsed date
);
console.log(record); // Data for key "itemC"
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to sort the records, you can modify the code above like so:
const sortBy = (collection, accessor, comparator) =>
collection.sort((a, b) => comparator(accessor(a), accessor(b)));
const
myArray = [{
itemA: { name: "Joe Blow" , date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)" },
itemB: { name: "Sam Snead" , date: "Sun Mar 30 2016 00:00:00 GMT-0700 (PDT)" },
itemC: { name: "John Smith" , date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)" },
itemD: { name: "Jane Doe" , date: null },
itemE: null,
}],
extractDate = (data) => data ? new Date(data?.date) : null,
sorted = sortBy(
Object.entries(myArray[0]), // Access the entries (key/val pairs)
([key, val]) => extractDate(val), // Map the parsed date
(curr, prev) => prev - curr // Same as (DESC): (curr - prev) * -1
);
console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Edit
Added null values
Changed ([key, { date }]) => new Date(date) to ([key, val]) => extractDate(val) to handle null values
I have the following structure on my firebase database:
I need to get an array of all the data with a special structure. This is how I do it:
const isObject = obj => {
return Object.prototype.toString.call(obj) === '[object Object]' ? true : false;
};
function snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
if (isObject(item)){
returnArr = returnArr.concat(snapshotToArray(childSnapshot));
}
});
return returnArr;
};
And call it:
snapshotToArray(snapshot); // 'snapshot' is the data from database in a snapshot format
Getting:
[ { 'Diciembre-2018': { '-LJV5UxepDNSR5yUCDbf': [Object] },
'Julio-2018': { '-LJUt8yTjpK3oq2wRd_g': [Object] },
key: '2018' },
{ '-LJV5UxepDNSR5yUCDbf':
{ pin: 'mi-pin-dic',
timestamp: 'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)' },
key: 'Diciembre-2018' },
{ pin: 'mi-pin-dic',
timestamp: 'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
key: '-LJV5UxepDNSR5yUCDbf' },
'mi-pin-dic',
'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
{ '-LJUt8yTjpK3oq2wRd_g':
{ pin: 'mi-pin-julio',
timestamp: 'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)' },
key: 'Julio-2018' },
{ pin: 'mi-pin-julio',
timestamp: 'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)',
key: '-LJUt8yTjpK3oq2wRd_g' },
'mi-pin-julio',
'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)' ]
But as you can see, in the 3rd and 5th iteration it gets an extra data:
'mi-pin-dic',
'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
'mi-pin-julio',
'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)'
My question:
How can I avoid this issue? Any ideas?
Given the following array of objects, I need to ascending sort them by the date field.
var myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
In the above example, the final result would be John Smith, Sam Snead, and Joe Blow.
I am trying to use lodash's _.sortBy(), but I can't get any sorting to take place no matter how I try to use it:
_.sortBy(myArray, function(dateObj) {
return dateObj.date;
});
or
_.sortBy(myArray, 'date');
What do I need to change to get my array sorted properly? I also have Moment.js, so I can use it to format the date string if needed. I tried converting the date property using .unix(), but that didn't make a difference.
Thanks.
You don't really need lodash. You can use JavaScript's Array.prototype.sort method.
You'll need to create Date objects from your date strings before you can compare them.
var myArray = [{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
}, {
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
}, {
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}];
myArray.sort(function compare(a, b) {
var dateA = new Date(a.date);
var dateB = new Date(b.date);
return dateA - dateB;
});
console.log(myArray);
Here's a solution using standard Javascript by converting both values to date object and comparing their value.
myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
A complete snippet:
var myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
console.log(myArray);
Your date values are strings, so you need to use the new Date() constructor to change them to javascript date objects. This way you can sort them (using _.sortBy).
var myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray = _.sortBy(myArray, function(dateObj) {
return new Date(dateObj.date);
});
console.log(myArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
If you are trying to use lodash to sort dates in ascending or descending order for your array of objects, you should use _.orderBy instead of _.sortBy
https://lodash.com/docs/4.17.15#orderBy, this method allows specifying sort orders either by 'asc' or 'desc'
An example would be:
const sortedArray = _(myArray.orderBy([
function(object) {
return new Date(object.date);
}],["desc"])
A cleaner way using Lodash orderBy:
import _ from 'lodash'
const sortedArray = _.orderBy(myArray, [(obj) => new Date(obj.date)], ['asc'])
just write _.sortBy({yourCollection}, {the field name});
lodash will automatically figure that this is a date and it'll work like a magic!
Awesome!
Inspired by others answers and noticing that you used moment.js and lodash, you can combine both with _.orderBy lodash method:
import moment from 'moment'
import * as _ from 'lodash'
let myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray = _.orderBy(myArray, [(item) => {
return moment(item.date).format('YYYY-MM-DD')
}], ['desc'])
this has worked for me
myArray = _.orderBy(myArray, [item => item.lastModified], ['desc']);
I am trying to add data from 2 csv files which have timestamp data like this: 9/30/2015 6:39:14 PM,20.709217.
I am trying to read these values from the file and converting the string to date-time format which highcharts accepts.
For every file I am adding this converted data to the data array which I push to the chart.
It gives the following error: Invalid value for <path> attribute d="M 687.5 "
Here is the code which I am trying: jsfiddle
My csv data files are as below.
Data1.csv
9/30/2015 6:39:14 PM,20.709217
9/29/2015 6:38:16 PM,32.215775
9/28/2015 6:38:16 PM,32.215775
Data2.csv
9/30/2015 6:39:14 PM,24.709217
9/29/2015 6:38:16 PM,18.012775
9/28/2015 6:38:16 PM,33.245775
Kindly help me with this.
$.get()is asynchronous, so when you call drawChart, data1array is not completely set: the ajax call is not finished.
You need to move the drawChartcall in the end of the $.get() call.
Here is the working code:
var options1 = {
chart: {
renderTo: 'container'
},
title: {
text: ''
},
xAxis: {
title: {
text: 'Select on Parameters to change data in chart.'
},
},
vAxis: {
title: {
text: ''
},
},
tooltip: {
enabled: true,
shared: true
},
series: []
};
var drawChart = function(data, type, name, color) {
var newSeriesData = {
name: name,
type: type,
data: data,
color: color
};
options1.series.push(newSeriesData);
var chart = new Highcharts.Chart(options1);
};
var data1 = [
[]
],
data2 = [
[]
];
$.get('data1.csv', function(csv) {
var lines = csv.trim().split('\n');
console.log("CSV: ", csv);
$.each(lines, function(lineNo, line) {
var items = line.split(',');
console.log('Item1:', items[0])
if ((line !== " ")) {
var datetime = new Date(items[0]);
console.log("Datetime variable: ", datetime);
var value = parseFloat(items[1]);
var year = datetime.getFullYear();
var month = datetime.getUTCMonth();
var day = datetime.getDay();
var hour = datetime.getHours();
var min = datetime.getMinutes();
var thisDate = Date.UTC(year, month, day, hour, min);
console.log("Date: ", thisDate);
console.log("Value: ", value);
// console.log("Date Generated: ",thisDate);
data1.push([thisDate, value]);
}
});
$.each(lines, function(lineNo, line) {
var items = line.split(',');
console.log('Item1:', items[0])
if ((line !== " ")) {
var datetime = new Date(items[0]);
console.log("Datetime variable: ", datetime);
var value = parseFloat(items[1]);
var year = datetime.getFullYear();
var month = datetime.getUTCMonth();
var day = datetime.getDay();
var hour = datetime.getHours();
var min = datetime.getMinutes();
var thisDate = Date.UTC(year, month, day, hour, min);
console.log("Date: ", thisDate);
console.log("Value: ", value);
// console.log("Date Generated: ",thisDate);
data1.push([thisDate, value]);
}
});
console.log("Data1 Array: ", data1);
drawChart(data1, 'line', 'DC Voltage (V)', 'red');
});
Here is the ouput in the console:
CSV: 9/30/2015 6:39:14 PM,20.709217
9/29/2015 6:38:16 PM,32.215775
9/28/2015 6:38:16 PM,32.215775
Item1: 9/30/2015 6:39:14 PM
Datetime variable: Wed Sep 30 2015 18:39:14 GMT+0200 (Paris, Madrid (heure d’été))
"Datetime variable: "
[date] Wed Sep 30 2015 18:39:14 GMT+0200 (Paris, Madrid (heure d’été))
Date: 1441305540000
Value: 20.709217
Item1: 9/29/2015 6:38:16 PM
Datetime variable: Tue Sep 29 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
"Datetime variable: "
[date] Tue Sep 29 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
Date: 1441219080000
Value: 32.215775
Item1: 9/28/2015 6:38:16 PM
Datetime variable: Mon Sep 28 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
"Datetime variable: "
[date] Mon Sep 28 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
Date: 1441132680000
Value: 32.215775
Item1: 9/30/2015 6:39:14 PM
Datetime variable: Wed Sep 30 2015 18:39:14 GMT+0200 (Paris, Madrid (heure d’été))
"Datetime variable: "
[date] Wed Sep 30 2015 18:39:14 GMT+0200 (Paris, Madrid (heure d’été))
Date: 1441305540000
Value: 20.709217
Item1: 9/29/2015 6:38:16 PM
Datetime variable: Tue Sep 29 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
"Datetime variable: "
[date] Tue Sep 29 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
Date: 1441219080000
Value: 32.215775
Item1: 9/28/2015 6:38:16 PM
Datetime variable: Mon Sep 28 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
"Datetime variable: "
[date] Mon Sep 28 2015 18:38:16 GMT+0200 (Paris, Madrid (heure d’été))
Date: 1441132680000
Value: 32.215775
Data1 Array: ,1441305540000,20.709217,1441219080000,32.215775,1441132680000,32.215775,1441305540000,20.709217,1441219080000,32.215775,1441132680000,32.215775
"Data1 Array: "
[
0: [ ],
1: [ ],
2: [ ],
3: [ ],
4: [ ],
5: [ ],
6: [ ],
length: 7
]
Highcharts error #15: www.highcharts.com/errors/15
Highcharts error #15: www.highcharts.com/errors/15
Highcharts error #15: www.highcharts.com/errors/15
Highcharts error #15: www.highcharts.com/errors/15
My goal:
Call an API and inside this API I would like to:
Find Bills
Find all transactions under each bill (by billId)
Return the values in a JSON ARRAY
The bill array look like this:
{ _id: 549bf0597886c3763e000001,
billName: 'Leasing',
startDate: Thu Dec 25 2014 01:00:00 GMT+0100 (CET),
endDate: Sun Oct 15 2017 00:00:00 GMT+0200 (CEST),
amount: 16500,
type: 4,
timestamp: Thu Dec 25 2014 12:09:13 GMT+0100 (CET),
__v: 0 },
{ _id: 54a014bfac01ca3526000001,
billName: 'Test',
startDate: Tue Oct 28 2014 01:00:00 GMT+0100 (CET),
endDate: Wed Dec 20 2017 00:00:00 GMT+0100 (CET),
amount: 1000,
type: 4,
timestamp: Sun Dec 28 2014 15:33:35 GMT+0100 (CET),
__v: 0 }
From this array, which I get in the step 1, I would like to query the transactions collections and get each transaction for each bill.
The array would have the following transformation:
From:
{ _id: 549bf0597886c3763e000001,
billName: 'Leasing',
startDate: Thu Dec 25 2014 01:00:00 GMT+0100 (CET),
endDate: Sun Oct 15 2017 00:00:00 GMT+0200 (CEST),
amount: 16500,
type: 4,
timestamp: Thu Dec 25 2014 12:09:13 GMT+0100 (CET),
__v: 0 },
{ _id: 54a014bfac01ca3526000001,
billName: 'Test',
startDate: Tue Oct 28 2014 01:00:00 GMT+0100 (CET),
endDate: Wed Dec 20 2017 00:00:00 GMT+0100 (CET),
amount: 1000,
type: 4,
timestamp: Sun Dec 28 2014 15:33:35 GMT+0100 (CET),
__v: 0 }
To:
{ _id: 549bf0597886c3763e000001,
billName: 'Leasing',
startDate: Thu Dec 25 2014 01:00:00 GMT+0100 (CET),
endDate: Sun Oct 15 2017 00:00:00 GMT+0200 (CEST),
amount: 16500,
type: 4,
timestamp: Thu Dec 25 2014 12:09:13 GMT+0100 (CET),
__v: 0 ,
transactions: {
{
"_id" : ObjectId("549ea8c957b654ef64000003"),
"billId" : "5499aece1d7be6c6a3000001",
"paymentDate" : ISODate("2014-12-27T12:40:41.311+0000"),
"amount" : NumberInt(2400),
"timestamp" : ISODate("2014-12-27T12:40:41.311+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("549ea9446163b3c666000001"),
"billId" : "5499aece1d7be6c6a3000001",
"paymentDate" : ISODate("2014-12-27T12:42:44.975+0000"),
"amount" : NumberInt(2400),
"timestamp" : ISODate("2014-12-27T12:42:44.975+0000"),
"__v" : NumberInt(0)
}
}
},
{ _id: 54a014bfac01ca3526000001,
billName: 'Test',
startDate: Tue Oct 28 2014 01:00:00 GMT+0100 (CET),
endDate: Wed Dec 20 2017 00:00:00 GMT+0100 (CET),
amount: 1000,
type: 4,
timestamp: Sun Dec 28 2014 15:33:35 GMT+0100 (CET),
__v: 0 }
In my attempt, Im succeding until I get the bills ID from the bill collection but I cannot succeed to get the transaction IDs into an array.
My attempt looks like this:
app.get('/getbills', function(req,res) {
function getTransactions(item, key){
var billId = item._id;
Transactions.find({billId : billId}, function(err, transactions){ // TODO: Needs to look for transactions inside the date.
if (err)
console.log('error: '+ err)
else if (transactions.length !== 0){
return transactions;
}
});
};
Bills.find({type: bill_type}).find(function(err, bills){
if(err)
res.send(err);
details.bills = bills;
details.bills.transations = _.each(bills, getTransactions);
res.send(details);
});
});
I'm using _.each to hold the billId and query the transactions table but there are not enough examples explaining how to use this function in the way I'm trying. Or maybe my attempt is wrong.
Any help is welcome.
Thanks in advance.
You are not waiting for you second call to finish, so you don't have all data at hand. Your return statement does not work as you think it will.
You should read a bit about asynchronicity in JavaScript :)
This code should work. Please take some time to study it and understand why. The trySend function acts as a simple synchronizer and only responds when all data is available. This is not the best way to do it - only the simplest.
app.get('/bills', function( req, res ) {
Bills.find({type: bill_type}, function( err, bills ) {
if( err ) return res.send(err);
var tries = 0;
var details = { bills: bills };
var trySend = function (){
tries++;
if (tries === bills.length) {
res.send(details);
}
};
bills.forEach( function ( bill ) {
Transactions.find({billId : bill._id}, function ( err, transactions ) {
if ( err ) return res.send( err );
bill.transations = transactions;
trySend();
});
});
});
});