简体   繁体   English

检查 Node-Postgres 中的 UNIQUE 约束

[英]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.我在我的表的“电子邮件”列上设置了 UNIQUE 约束,现在在我使用 Node-Postgres (pg) 的 Express API 中,我想确保用户在发布学生时输入的 email 不是没有重复。

My question is that how can I show a response like "Email already taken?"我的问题是如何显示“电子邮件已收到?”之类的回复。 in my JSON object when that constraint gets violated?在我的 JSON object 中,当该约束被违反时?

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],
     });
  });
};

You can find error codes returned by postgresql here:您可以在此处找到 postgresql 返回的错误代码:

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

Error code of unique_violation is 23505 . unique_violation的错误代码是23505 Additionally error object has constraint field that reports name of the constraint being violated.此外,错误 object 具有constraint字段,报告违反约束的名称。 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], 
            });
   }

I managed to fix the problem by using async/await and try/catch and providing the error logic in the catch statement.我设法通过使用async/awaittry/catch并在 catch 语句中提供错误逻辑来解决问题。

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.我使用了 Express Error Handling 中间件,但其他方法也可以。

Thanks to @boran for his great help!感谢@boran 的大力帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM