Sunday 29 September 2019

Having trouble with Mongoose/Promises

I'm fairly new to Mongoose and the idea of promises, so I've been having some trouble with creating this API.\ var deserialized = (JSON.parse(tournament.content)); //console.log(deserialized[0]['team']); Robot.find().then(robot => { for (var i = 0; i < robot.length; i++) { Wheel.findOne({ type: robot[i].wheel }).then(wheel => { if (!wheel) { const wheel = new Wheel({ type: robot[i].wheel, total: total += deserialized[i]['score'], teams: 1, average: total }); wheel.save(); } else { wheel.teams++; wheel.total += deserialized[i]['score']; wheel.save(); } Wheel.find().then(wheel => { Robot.find({ wheel: wheel[0].type }).then(finalRobot => { for (var k = 0; k < finalRobot.length; k++) { for (var j = 0; j < deserialized.length; j++) { if (deserialized[j]['team'] == finalRobot[i].team) { deserialized[j]['score'] *= 1.1; console.log(deserialized[j]['score']); } console.log(deserialized[j]['team']); console.log(finalRobot[i].team); } } }) .catch(err => console.error(err)) }) }) } }) When I run this in my app, I keep getting this error: TypeError: Cannot read property 'team' of undefined, which I presume is because it's trying to access data that hasn't been returned yet. How would I chain these promises together in order to prevent that from happening?​Thanks!

Submitted September 29, 2019 at 03:15PM by dayofboredom

No comments:

Post a Comment