I'm trying to add all mongoDB results to an array and send it as a post response. The individual console.log
s for each response from mongodb outputs data. But when i try to push that data into the events
array it doesn't seem to work. When i do console.log(events)
at the end, it just logs an empty array. Any ideas?
calendar.post('/getEvents', (req, res) => {
let events = []
// Add all budget dates to events array
Budget.find({
userEmail: req.body.userEmail
})
.then(budgets => {
// console.log(budgets)
for (let i = 0; i < budgets.length; i++) {
events.push(budgets[i])
}
})
// Add all notes dates to events array
Notes.find({
userEmail: req.body.userEmail
})
.then(notes => {
// console.log(notes)
for (let i = 0; i < notes.length; i++) {
events.push(notes[i])
}
})
// Add all study plan dates to events array
StudyPlan.find({
userEmail: req.body.userEmail
})
.then(studyplans => {
// console.log(studyplans)
for (let i = 0; i < studyplans.length; i++) {
events.push(studyplans[i])
}
})
// Add all todo list dates to events array
TodoList.find({
userEmail: req.body.userEmail
})
.then(todolists => {
// console.log(todolists)
for (let i = 0; i < todolists.length; i++) {
events.push(todolists[i])
}
})
console.log(events)
res.send(events)
})
EDIT:
This is the console after i make a post request to this route (I added 'Budgets:' and 'Events:' to the console logs to make it easier to read):
Events: []
Budgets: [ { duration: 7,
_id: 5ccd88cb4c13380d84446673,
title: 'bla',
amount: null,
startDate: 2019-05-04T12:42:45.000Z,
userEmail: 'test@gmail.com',
spending: [],
__v: 0,
expenses: [] },
{ duration: 7,
_id: 5ccd89c04c13380d84446674,
title: 'bla2',
amount: null,
startDate: 2019-05-04T12:46:52.000Z,
userEmail: 'test@gmail.com',
spending: [],
__v: 0,
expenses: [] } ]