there! I've been trying to use two variables on my code (total
and soldTickets
) but they're not being summed up or show the correct value. I think it's something related with the scope. console.log()
returns 0
and []
, respectively.
class SaleController {
constructor() {
this.Sale = require('../models/Sale')
this.Show = require('../models/Show')
}
buyTickets(req, res) {
const json = req.body
let soldTickets = []
let total = 0
json.tickets.forEach(ticket => {
for (let i = 0; i < ticket.qty; i++) {
this.Show.findById(ticket.showId, 'sectors', (err, shows) => {
if (err) return res.status(500).json({
status: 'failed',
message: 'Something happened while finding the show!'
})
const foundTicket = shows.sectors.find(sector => sector.name === ticket.sector)
total += foundTicket.price
soldTickets.push({
number: this.generateTicketNumber(),
showId: ticket.showId,
sector: ticket.sector,
price: foundTicket.price
})
})
}
})
console.log(total)
console.log(soldTickets)
res.json({
tickets: soldTickets,
total: total
})
}
generateTicketNumber() {
return Math.floor(Math.random()*90000) + 10000
}
}
module.exports = new SaleController()