Search code examples
javascriptsqlpostgresqlexpressnode-postgres

Check for UNIQUE constraint in Node-Postgres


I have put a UNIQUE constraint on the "email" column of my table and now in my Express API which is using Node-Postgres (pg), I want to make sure than the email that the user puts in when POSTing a student, isn't duplicated.

My question is that how can I show a response like "Email already taken!" in my JSON object when that constraint gets violated?

const createStudent = (req, res) => {
  const { name, email, age, dob } = req.body;
  pool.query(insertStudent, [name, email, age, dob], (error, results) => {
     if (error) throw error;
     res.status(201).json({
       message: `Student Created Successfully!`,
       student: results.rows[0],
     });
  });
};

Solution

  • I managed to fix the problem by using async/await and try/catch and providing the error logic in the catch statement.

    This now works as expected:

    const createStudent = async (req, res, next) => {
      const { name, email, age, dob} = req.body;
    
      try {
        const create = await pool.query(insertStudent, [
          name,
          email,
          age,
          dob,
        ]);
        res
          .status(201)
          .json({ message: "Student Created Successfully!", user: create.rows[0] });
      } catch (err) {
        // If UNIQUE constraint is violated
        if (err.code == "23505") {
          console.error(err.message);
          const error = new Error("Email Already Exists!");
          error.status = 400;
          next(error);
        } else {
          console.error(err.message);
          const error = new Error("Something Went Wrong!");
          error.status = 500;
          next(error);
        }
      }
    };
    

    I have used Express Error Handling middleware but the other way work as well.

    Thanks to @boran for his great help!