Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda