Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
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],
     });
  });
};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can find error codes returned by postgresql here:

https://www.postgresql.org/docs/current/errcodes-appendix.html

Error code of unique_violation is 23505. Additionally error object has constraint field that reports name of the constraint being violated. Therefore

  pool.query(..., (error, results) => {
     if (error.code == 23505 && error.constraint == 'your_unique_cons_name') { 
        // handle error
     }        
  });

Edit: Here is the full code, I don't know where exactly are you getting these errors, maybe post your code and full error messages.

   if (error != null && error.code == 23505 && error.constraint == 'your_unique_cons_name') {
            res.status(418).json({
                message: `email taken!`,
            });
   }
   else {
            res.status(201).json({
                message: `Student Created Successfully!`,
                student: results.rows[0], 
            });
   }
about 4 years ago · Juan Pablo Isaza Report

0

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!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!