Home > database >  Express return next() not ending the request
Express return next() not ending the request

Time:04-13

Whenever I send a request, I reach the .then() block and after executing the check(it gets confirmed), the route returns the error as expected. However, the function keeps going and adds the createdAppointment to the database. I've made tried returning just next(), using next(error) only but it keeps giving the same results - it always inserts into the database. Of course, I have the error middleware at the end.

    async (err, client) => {
      if (err) {
        res.status(500).send("Failed Connection!");
        return;
      }

      const forename = req.body.professional.split(" ")[0];
      const surname = req.body.professional.split(" ")[1];
      const professional = await client
        .db("FYP")
        .collection("Users")
        .findOne({ forename: forename }, { surname: surname });

      if (!professional) {
        const error = new Error("Professional doesn't match with any in the database")
        error.code = 422
        return next(error)
      }

      if(professional.type != "Therapist") {
        const error = new Error("The chosen user is not a therapist.")
        error.code = 422
        return next(error)
      }

      const user = await client
        .db("FYP")
        .collection("Users")
        .findOne({ _id: res.locals.uid });

      const clientUserName = user.forename   " "   user.surname;
      const professionalUserName = professional.forename   " "   professional.surname

      await client
      .db("FYP")
      .collection("AppointmentsTherapists")
      .find({ client: clientUserName}, { complete: false})
      .toArray()
      .then(async data => {
          if(data) {
            console.log(data.length)
            for(let i=0; i<data.length; i  ) {
              console.log(dateInPast(data[i].startTime))
            if(dateInPast(data[i].startTime) == false) {
              console.log(data[i]._id)
              const error = new Error("You already have a booked appointment with a therapist. Please attend the current appointment before booking another.")
                error.status = 422
                return next(error)
              }
          } 
        }
        
      })

      if (professionalUserName == clientUserName || user.type == "Therapist" || user.type == "Rehabilitator") {
        const error = new Error("A professional cannot book an appointment for themselves.")
        error.code = 422 
        return next(error)
      }

      const appointment = {
        client: clientUserName,
        professional: req.body.professional,
        information: req.body.information,
        startTime: req.body.startTime,
        endTime: req.body.endTime,
        status: "Pending",
        complete: false,
        date: new Date()
      };

      const createdAppointment = await client
        .db("FYP")
        .collection("AppointmentsTherapists")
        .insertOne({ ...appointment });

      res.status(200).send(createdAppointment);
      return next();
    }
);
});

  app.use((error, req, res, next) => {

  res.status(error.status || 500);
  res.json({
      message: error.message
  })
}) 

CodePudding user response:

Use async / await or .then() but not both...

  let data = await client
  .db("FYP")
  .collection("AppointmentsTherapists")
  .find({ client: clientUserName}, { complete: false})
  .toArray()
  if(data) {
    console.log(data.length)
    for(let i=0; i<data.length; i  ) {
      console.log(dateInPast(data[i].startTime))
      if(dateInPast(data[i].startTime) == false) {
          console.log(data[i]._id)
          const error = new Error("You already have a booked appointment with a therapist. Please attend the current appointment before booking another.")
            error.status = 422
            return next(error)
        }
      } 
    }
  • Related