I have a while loop that matches a condition to filter data from mongodb. However, when I use the callback I only receive one result to the console.log. If I console.log inside the while loop, I should receive three entries. Why is only one piece of data making it to the callback?
while(i--) {
if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) {
theWeekend = results[i];
console.log(theWeekend); //returns three results (correct)
}
}
callback(err, theWeekend)
console.log(theWeekend); //returns one results (incorrect)
Correct data
{ _id: 56fffb5ceb76276c8f39e3f3,
url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham',
title: 'Where To Eat And Drink In... Balham | Londonist',
selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST),
__v: 0 }
{ _id: 56fffb8eeb76276c8f39e3f5,
url: 'https://news.ycombinator.com/item?id=11404770',
title: 'The Trouble with CloudFlare | Hacker News',
selectedDate: Sun Apr 03 2016 01:00:00 GMT+0100 (BST),
__v: 0 }
{ _id: 56fffb6ceb76276c8f39e3f4,
url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
__v: 0 }
Incorrect data
{ _id: 56fffb6ceb76276c8f39e3f4,
url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
__v: 0 }
You need to use an array to store all the results as follows:
var theWeekends = []
while(i--) {
if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) {
theWeekends.push(results[i]);
}
}
callback(err, theWeekends)
console.log(theWeekends); //returns 3 results (correct)
Related
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
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?
I have a function that filters through documents in mongoDB collection and returns all results that has a date that matches a Friday, Saturday or Sunday. This behaves as expected. However, now I need to match those results to determine if they fall on the weekend coming, however my while loop is only returning one result when it should return three. What is going wrong?
//FIND ALL ENTRIES THAT FALL ON A WEEKEND
function weekendPlans(callback) {
Entry.aggregate(
[
{ "$redact": {
"$cond": {
"if": {
"$or": [
{ "$eq": [ { "$dayOfWeek": "$selectedDate" }, 1 ] },
{ "$eq": [ { "$dayOfWeek": "$selectedDate" }, 6 ] },
{ "$eq": [ { "$dayOfWeek": "$selectedDate" }, 7 ] }
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
],
// GET THE RESULTS AND RETURN IF selectedDate MATCHES THIS WEEKEND
function(err,results) {
var i = results.length;
var theWeekend;
console.log(results)
// EVERYTHING WORKS UNTIL HERE
while(i--) {
if(results[i].selectedDate === friday || saturday || sunday) {
theWeekend = results[i];
//console.log(theWeekend);
break;
}
}
callback(err, theWeekend)
}
)};
Expected result:
[ { _id: 56fffb6ceb76276c8f39e3f4,
url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
__v: 0 },
{ _id: 56fffb8eeb76276c8f39e3f5,
url: 'https://news.ycombinator.com/item?id=11404770',
title: 'The Trouble with CloudFlare | Hacker News',
selectedDate: Sun Apr 03 2016 01:00:00 GMT+0100 (BST),
__v: 0 },
{ _id: 56fffb5ceb76276c8f39e3f3,
url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham',
title: 'Where To Eat And Drink In... Balham | Londonist',
selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST),
__v: 0 } ]
Current result:
{ _id: 56fffb5ceb76276c8f39e3f3,
url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham',
title: 'Where To Eat And Drink In... Balham | Londonist',
selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST),
__v: 0 }
Change
results[i].selectedDate === friday || saturday || sunday
to
~results[i].selectedDate.indexOf('Fri') ||
~results[i].selectedDate.indexOf('Sat') ||
~results[i].selectedDate.indexOf('Sun')
because you need to check every variable with a value and if the day string is in the date string.
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();
});
});
});
});
I am developing a application in Node.js with use of mongodb and mongoose. I want to get the index of object from array of object returned by mongoose the data is given below, how can I get the index from details Array where record contains particular id like
_id: 5334032ad1c4d2d616ad3a47
The actual problem is that I am rendering a page which shows data of single nested record of details record, the id of that record is contained in my url like this
http://localhost:3000/id-of-parent-course/id-of-nested-doc-in-details
I am passing all the data to that page because I want to access the total count of details record, may be my way of doing this is wrong you can correct me with answer
course:
{ __v: 1,
_id: 5334032ad1c4d2d616ad3a46,
updatedAt: Fri Mar 28 2014 13:14:07 GMT+0530 (IST),
createdAt: Thu Mar 27 2014 16:23:30 GMT+0530 (IST),
comments: [],
details:
[ { status: 'Core',
course_type: 'New',
_id: 5334032ad1c4d2d616ad3a47,
books: [Object],
course_content: [Object],
learning_outcomes: [Object],
objectives: [Object],
senate_approval_on: Fri Mar 14 2014 00:00:00 GMT+0530 (IST),
ac_approval_on: Wed Mar 19 2014 00:00:00 GMT+0530 (IST),
center_approval_on: Wed Mar 12 2014 00:00:00 GMT+0530 (IST),
focus_group_approval_on: Tue Mar 11 2014 00:00:00 GMT+0530 (IST),
effect_from: Tue Apr 01 2014 00:00:00 GMT+0530 (IST),
pre_requisite: 'Javascript',
offered_for: 'B.Tech',
structure: [Object],
department: 'ICT',
course_no: 12345,
title: 'Course 1' },
{ status: 'Core',
course_type: 'New',
_id: 533528472ad1706170b502b0,
books: [Object],
course_content: [Object],
learning_outcomes: [Object],
objectives: [Object],
senate_approval_on: Fri Mar 14 2014 00:00:00 GMT+0530 (IST),
ac_approval_on: Wed Mar 19 2014 00:00:00 GMT+0530 (IST),
center_approval_on: Wed Mar 12 2014 00:00:00 GMT+0530 (IST),
focus_group_approval_on: Tue Mar 11 2014 00:00:00 GMT+0530 (IST),
effect_from: Tue Apr 01 2014 00:00:00 GMT+0530 (IST),
pre_requisite: 'Javascript',
offered_for: 'B.Tech',
structure: [Object],
department: 'ICT',
course_no: 12345,
title: 'Course 1' } ] } }
You'll have to iterate over the array and keep the index, like:
var i=0,
found=false;
for(i = 0; i < course.details.length; i++) {
var detail = course.details[i];
if(detail._id === idYouReSearchingFor) {
found=true;
break;
}
}
if(found) //your index is on variable i