I'm developing an algorithm to create a list of dates, and i need in every monday of week the code break to another array. But I don't know how to do that.
PS: Even though the monday not exists in original array, i want do create another array, for the next dates.
const mealsRooms = await prisma.users.findUnique({
where: {
id: req.params.userId
},
select: {
MealsRooms: {
select: {
id: true,
servingSabado: true,
servingDomingo: true
}
}
}
});
const monthFull = req.params.month.split(".");
const month = monthFull[0];
const year = monthFull[1];
const totalDays = new Date(parseInt(year), parseInt(month), 0).getDate();
let semana = [];
for(let i = 1; i <= totalDays; i++){
const data = new Date(year + "-" + (parseInt(month)+1).toString() + "-" + i);
const indexMealZone = mealsRooms.MealsRooms.findIndex((room) => { return (room.id === req.params.zonaConsumo); })
if(mealsRooms.MealsRooms[indexMealZone].servingSabado && data.getDay() === 6){
semana.push({
date: data.toDateString(),
price: 1.46,
status: 0,
type: "NB",
cosumZone: "NB"
});
}else if(mealsRooms.MealsRooms[indexMealZone].servingDomingo && data.getDay() === 0){
semana.push({
date: data.toDateString(),
price: 1.46,
status: 0,
type: "NB",
cosumZone: "NB"
});
}
if(data.getDay() !== 6 && data.getDay() !== 0){
semana.push({
date: data.toDateString(),
price: 1.46,
status: 0,
type: "NB",
cosumZone: "NB"
});
}
}
res.status(200).json({
listRefeicoes: [semana]
});
Original Array
{"listRefeicoes":[[
{"date":"Thu Sep 01 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 02 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 05 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 06 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 07 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 08 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 09 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 12 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 13 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 14 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 15 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 16 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 19 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 20 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 21 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 22 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 23 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 26 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 27 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 28 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 29 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 30 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}
]]}
Final Array
{"listRefeicoes":[[Week 1], [Week2], ...]}
I tried to separate by weeks but this creates the problem that if the second one doesn't exist in the week it doesn't create the new array.
We can fold our list down into a nested list by keeping track of when our day of the week decreases. We do that by scanning the date property for any of "Mon", "Tue", "Wed", etc, keeping track of the index where that matched. If it's smaller than our current entry, we start a new array. If not, we append to the existing one. Here's one way to do this:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
const splitWeeks = (os) => os .reduce (
({curr, weeks}, o) => {
const next = days .findIndex (dow => o .date .includes (dow))
return next < curr
? {curr: 0, weeks: weeks .concat ([[o]])}
: {curr: next, weeks: [...weeks .slice (0, -1), weeks .at (-1) .concat (o)]}
},
{curr: Infinity, weeks : []}
) .weeks
const update = ({listRefeicoes, ...rest}) => ({
listRefeicoes: splitWeeks (listRefeicoes [0]),
...rest
})
const input = {"listRefeicoes":[[{"date":"Thu Sep 01 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 02 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 05 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 06 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 07 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 08 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 09 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 12 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 13 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 14 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 15 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 16 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 19 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 20 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 21 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 22 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 23 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 26 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 27 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 28 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 29 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 30 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}]]}
console .log (update (input))
.as-console-wrapper {max-height: 100% !important; top: 0}
Related
I have date range like this and I want to create array based on each month.
1 => Thu Feb 16 2023
1 => Fri Feb 17 2023
1 => Sat Feb 18 2023
1 => Sun Feb 19 2023
1 => Mon Feb 20 2023
1 => Tue Feb 21 2023
1 => Wed Feb 22 2023
1 => Thu Feb 23 2023
1 => Fri Feb 24 2023
1 => Sat Feb 25 2023
1 => Sun Feb 26 2023
1 => Mon Feb 27 2023
1 => Tue Feb 28 2023
2 => Wed Mar 01 2023
2 => Thu Mar 02 2023
2 => Fri Mar 03 2023
I need array like
1 => [Fri Feb 17 2023, Sat Feb 18 2023, ...],
2 => [Wed Mar 01 2023, Thu Mar 02 2023, ...]
And this is my code
let dts = {};
newDates.forEach((dt, i) => {
let mn = new Date(dt).getMonth();
dts[mn] = dt;
});
console.log(dts);
I got result like this
1 : Tue Feb 28 2023
2 : Fri Mar 03 2023
Got last element only. How to solve this? Thanks
You have the right basic idea. You need to create an array and push the value to it.
Your way with forEach
const dts = {};
newDates.forEach((dt, i) => {
const mn = new Date(dt).getMonth();
dts[mn] = dts[mn] || [];
dts[mn].push(dt);
});
Using reduce
const dts = newDates.reduce((acc, dt) => {
const mn = new Date(dt).getMonth();
acc[mn] = acc[mn] || [];
acc[mn].push(dt);
return acc;
}, {});
I have two user objects:
const user = {
startDate: new Date('2022-10-06'),
endDate: new Date('2022-10-10'),
id:'1234',
title: 'Title 1'
};
const user2 = {
startDate: new Date('2022-10-12'),
endDate: new Date('2022-10-17'),
id: '1112',
title: 'Title 2'
};
and an array with these two objects and an empty object called dateToUserMap:
const users = [user, user2];
const dateToUserMap = {};
I want to add data to dateToUserMap and it needs to look like this:
dateToUserMap = {
'01.11.2022': [
{
id: 'asd',
title: 'asd'
}
],
'02.11.2022': [
{
id: 'asd',
title: 'asd'
},
{
id: 'asd1',
title: 'asd1'
}
],
'03.11.2022': [
{
id: 'asd1',
title: 'asd1'
}
]
};
dateToUserMap should be an object with the days of the intervals of each user in chronological order (in my case should be days from 10/6 until 10/10 and 10/12 until 10/17), and each day should have an array of objects with the id and title of the users in that interval.
I tried using forEach to loop trough the users in the users array and calculated the interval of each user but I don't know how to pass that data in the object with all the dates and the id and title
users.forEach(user => {
const interval = eachDayOfInterval({ start: user.startDate, end: user.endDate });
console.log(interval);
});
I use date-fns library to help me work with dates and when I log the interval to console I get this:
(6) [Wed Oct 12 2022 00:00:00 GMT+0300 (Eastern European Summer Time), Thu Oct 13 2022 00:00:00 GMT+0300 (Eastern European Summer Time), Fri Oct 14 2022 00:00:00 GMT+0300 (Eastern European Summer Time), Sat Oct 15 2022 00:00:00 GMT+0300 (Eastern European Summer Time), Sun Oct 16 2022 00:00:00 GMT+0300 (Eastern European Summer Time), Mon Oct 17 2022 00:00:00 GMT+0300 (Eastern European Summer Time)]
0
:
Wed Oct 12 2022 00:00:00 GMT+0300 (Eastern European Summer Time) {}
1
:
Thu Oct 13 2022 00:00:00 GMT+0300 (Eastern European Summer Time)
[[Prototype]]
:
Object
2
:
Fri Oct 14 2022 00:00:00 GMT+0300 (Eastern European Summer Time) {}
3
:
Sat Oct 15 2022 00:00:00 GMT+0300 (Eastern European Summer Time) {}
4
:
Sun Oct 16 2022 00:00:00 GMT+0300 (Eastern European Summer Time) {}
5
:
Mon Oct 17 2022 00:00:00 GMT+0300 (Eastern European Summer Time) {}
length
:
6
[[Prototype]]
:
Array(0)
I have a simple helper function to find date in the array of dates based on given day, in this function I convert day name to day number, and then I want to find all dates with the given day number:
function findDatesByWeekday(date, weekdayArr) {
const dayNumbers = weekdayArr.map(({ day }) => textToDayNumber(day));
return dayNumbers.find(n => {
console.log(
`n: ${n}, getDay: ${new Date(date).getDay()} result: ${new Date(
date
).getDay() === n} date: ${date}`
);
return new Date(date).getDay() === n;
});
}
However, it does not find Sundays, although the result of return statement is true.
n: 6, getDay: 6 result: true date: Sat Oct 16 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 0 result: false date: Sun Oct 17 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 0, getDay: 0 result: true date: Sun Oct 17 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 6 result: true date: Sat Oct 23 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 0 result: false date: Sun Oct 24 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 0, getDay: 0 result: true date: Sun Oct 24 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 6 result: true date: Sat Oct 30 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 0 result: false date: Sun Oct 31 2021 12:00:00 GMT+0100 (Central European Standard Time)
n: 0, getDay: 0 result: true date: Sun Oct 31 2021 12:00:00 GMT+0100 (Central European Standard Time)
What is more, it generated unwanted output as I was asking for five dates, and it returned five Saturdays instead of three Saturdays and two Sundays.
0: Sat Oct 16 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
1: Sat Oct 23 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
2: Sat Oct 30 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
3: Sat Nov 06 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
4: Sat Nov 13 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
With every other week day it works just fine, it's just the Sunday, so I am quite sure that it comes down to zero being a falsy value, and I know how to fix it function below works as intended
function findDatesByWeekday(date, weekdayArr) {
const dayNumbers = weekdayArr.map(({ day }) => textToDayNumber(day));
return dayNumbers.includes(new Date(date).getDay());
}
I just want to understand why :)
Thanks
Hi is a start of the edit of the question as you have requested. You are right, I am sorry I should have included the context by default. I do not use filter as I use this helper in the filter method as a predicate
newHighlightedDays = benchmark.filter(date =>
findDatesByWeekday(date, weekDaysWithTime))
.filter((_, i) => i < lessonCount);
weekdaysWithTime is an array of objects like these:
{
day: "Piątek",
time: {h: 12, m: 30}
},
{
day: "Sobota",
time: {h: 12, m: 30}
},
{
day: "Niedziela",
time: {h: 12, m: 30}
}
and textToDayNumber is this function:
export function textToDayNumber(text) {
switch (text.toLowerCase()) {
case "niedziela":
return 0;
case "poniedziałek":
return 1;
case "wtorek":
return 2;
case "środa":
return 3;
case "czwartek":
return 4;
case "piątek":
return 5;
case "sobota":
return 6;
default:
throw new Error("invalid day name");
}
}
I am sure that this is not a timezone issue as it compares not dates per se, but a weekday name parsed to day number with the date from react-day-picker, here is an example of benchmark array to reproduce the code:
Tue Oct 19 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Wed Oct 20 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Thu Oct 21 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Fri Oct 22 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sat Oct 23 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sun Oct 24 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Mon Oct 25 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Tue Oct 26 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Wed Oct 27 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Thu Oct 28 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Fri Oct 29 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sat Oct 30 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sun Oct 31 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Mon Nov 01 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Tue Nov 02 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Wed Nov 03 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Thu Nov 04 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Fri Nov 05 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sat Nov 06 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sun Nov 07 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Mon Nov 08 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Tue Nov 09 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Wed Nov 10 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Thu Nov 11 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Fri Nov 12 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sat Nov 13 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sun Nov 14 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Mon Nov 15 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Tue Nov 16 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Wed Nov 17 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Thank you! :)
Not sure I understood the question:
and then I want to find all dates with the given day number:
find returns only the first matching item. Use filter to return an array of matching items.
function findDatesByWeekday(date, weekdayArr) {
const dayNumbers = weekdayArr.map(({ day }) => textToDayNumber(day));
return dayNumbers.filter(n => {
console.log(
`n: ${n}, getDay: ${new Date(date).getDay()} result: ${new Date(
date
).getDay() === n} date: ${date}`
);
return new Date(date).getDay() === n;
});
}
I have an array of Javascript Objects, which contain two important values date and status
I want to reduce them into an array of unique dates, where all the values are parsed into an object, that contains each of the status and the date.
I have tried using the reduce funtion, but i can't seem to collect the dates properly, so that all the data is collected properly.
The unique statuses are: "System Labelled", "Discarded", "Saved", "Reviewed"
So for example:
[{status: "System Labelled", date: Thu Mar 05 2020 01:00:00 GMT+0100 (Central European Standard Time)},
{status: "System Labelled", date: Thu Mar 05 2020 01:00:00 GMT+0100 (Central European Standard Time)},
{status: "System Labelled", date: Thu Mar 05 2020 02:00:00 GMT+0200 (Central European Summer Time)},
{status: "Discarded", date: Tue Mar 10 2020 01:00:00 GMT+0100 (Central European Standard Time)},
{status: "Saved", date: Sat Jan 11 2020 01:00:00 GMT+0100 (Central European Standard Time)}]
---->
[{System Labelled: 1, Discarded: 0, Saved: 0, Reviwed: 0, date: Thu Mar 05 2020 01:00:00 GMT+0100 (Central European Standard Time)},
{System Labelled: 2, Discarded: 0, Saved: 0, Reviwed: 0, date: Sun Apr 05 2020 02:00:00 GMT+0200 (Central European Summer Time)},
{System Labelled: 0, Discarded: 1, Saved: 0, Reviwed: 0, date: Tue Mar 10 2020 01:00:00 GMT+0100 (Central European Standard Time)},
{System Labelled: 0, Discarded: 0, Saved: 1, Reviwed: 0, date: Sat Jan 11 2020 01:00:00 GMT+0100 (Central European Standard Time)},
Here is the code i have so far:
const objects= [{status: "System Labelled", date: new Date("19-03-2020")},
{status: "System Labelled", date: new Date("19-03-2020")},
{status: "Discarded", date: new Date("19-03-2020")},
{status: "Saved", date: new Date("19-03-2020")}]
objects.reduce((acc, curr) =>{
console.log(acc.includes(curr.status))
if(acc.includes(curr.status)){
curr[acc.status]++
}
},[])
You can take an object for grouping and get the values as result array.
You need valid dates for it.
const
statuses = ["System Labelled", "Discarded", "Saved", "Reviewed"],
objects = [{ status: "System Labelled", date: "2020-03-19" }, { status: "System Labelled", date: "2020-03-19" }, { status: "Discarded", date: "2020-03-19" }, { status: "Saved", date: "2020-03-19" }],
result = Object.values(objects.reduce((acc, { status, date }) => {
acc[date] = acc[date] || { date, ...Object.fromEntries(statuses.map(k => [k, 0])) };
acc[date][status]++;
return acc;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
what if you get the timestamp of each date and then add it as a string after the status it has to create one single string.
Example Object
[{status: "System Labelled", date: Thu Mar 05 2020 01:00:00 GMT+0100 (Central European Standard Time)}
Would Be
"System Labelled 1583366400"
And then you could just substring the timestamp to convert it to a date again
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();
});
});
});
});