I'm stuck a while ago with a task that I have to do. The objective was to make an api rest with an enpoint to objeter data and another to post them. So far, everything works, but now I must put a condition to that post, which depends on my function get. If the "total" is greater than the req.body.amount I should be able to post but, no. What I did was create an empty array, and push it into my total, but when I want to use it in the post function, it does not read anything ... it's empty. I have an idea of how to continue working, so the post is incomplete, but I can not move forward if I do not have my total array. what am I doing wrong? Thank you very much for your time! (other suggestions are accepted;))
This is my code: Here I get the mongo data and calculate the total, which I put into my array.
var todo = []
function getTransactions(req, res, next){
Transaction.find()
.then(resolve => {
res.send(resolve)
const a = resolve
const total = a.map(function(element){
return element.aumount
})
.reduce(function(prev, element, index, sum){
return prev + element
}, 0)
todo.push(total)
console.log('total', todo) // <-- funciona ok.
})
.catch(error => {
console.log('Se produjo un error', error)
})
}
function postDebit(req, res, next){
const transaction = new Transaction({
type: req.body.type,
aumount: req.body.aumount,
effectiveDate : new Date()
})
console.log('total', todo.length) <-- devuelve []
}