0
router.post('/register', (req, res, next) => {
var subjectsID = [];
if (req.body.hasOwnProperty('subjects')) {
    console.log("Teacher have subjects");
    for (var i = 0; i < req.body.subjects.length; i++) {
        Subject.getSubjectByName(req.body.subjects[i], (error, subject) => {
            if (error) throw error;
            if (!subject) {
                res.json({
                    success: false,
                    msg: "One of the entered subjects dosent exist",
                    subject: req.body.subjects[i],
                    error: error
                });
            } else{
                console.log("Subject by id : " + subject._id + " is verified");
                subjectsID.push(subject._id);
            }
        });
    }
    console.log("All subjects verified");
    console.log(subjectsID);
}

My Main problem is : When I enter info to this URL , I get the console.log("All subjects verified"); before I get the subjectsID.push(subject._id); So in the next code segment(not posted) the array is empty and I cant pull the needed info for it. How can I fix it so it will do the for loop first and only then will proceed to the next code segment.

Sub Question : when I enter a subject that isnt in the DB (mongoDB,mongoose) The line subject: req.body.subjects[i] shutdown my program with the error : Can't set headers after they are sent. I'm sure its connected to my main question ,so a basic explanation will be welcomed.

Zed Evans
  • 126
  • 1
  • 12

0 Answers0