【问题标题】:avoid duplicating in Sequelize, Nodejs & Reactjs?避免在 Sequelize、Nodejs 和 Reactjs 中重复?
【发布时间】:2021-09-06 05:18:39
【问题描述】:

我正在使用

  1. nodejs 与
  2. 续集
  3. reactjs

**,问题是如何避免在sequelize中重复,我有一个注册表如下

fullName
emad_address
password

而且我不希望有重复的电子邮件和全名: 这是代码。

  module.exports = (sequelize, DataTypes) => {
      const Users = sequelize.define("Users", {
        fullName: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        emailAddress: {
          type: DataTypes.STRING,
          allowNull: false,
        },
        password: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      });

这是路由器:

    router.post("/", async (req, res) => {
  const { fullName, emailAddress, password } = req.body;
  bcrypt.hash(password, 10).then((hash) => {
    Users.create({
      fullName: fullName,
      emailAddress: emailAddress,
      password: hash,
    });
    res.json("User, Success");
  });
});

有什么建议吗?

【问题讨论】:

    标签: mysql node.js reactjs sequelize.js


    【解决方案1】:

    您需要在 DB 级别添加唯一约束,并在创建过程中处理 SequelizeUniqueConstraintError 以向用户返回验证消息。

    如果您使用sequelize.sync() 对数据库架构应用模型更改,那么您可以像这样定义约束:

    module.exports = (sequelize, DataTypes) => {
      const Users = sequelize.define('Users', {
        fullName: {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true // unique constrain of the column `fullName`
        },
        emailAddress: {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true // unique constrain of the column `emailAddress`
        },
        password: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      }, {
        // define constrain like this if you need combination of columns unique
        // indexes: [
        //   {
        //     unique: true,
        //     fields: ['fullName', 'emailAddress']
        //   }
        // ]
      });
    
      return Users;
    };
    

    如果您使用迁移创建数据库架构,您可以像这样创建约束:

    module.exports = {
      up: async (queryInterface, Sequelize) => {
        await queryInterface.addColumn('Users', 'fullName', {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true // unique constrain of the column `fullName`
        });
        await queryInterface.addColumn('Users', 'emailAddress', {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true // unique constrain of the column `emailAddress `
        });
        // define constrain like this if you need combination of columns unique
        // return queryInterface.addConstraint('Users', ['fullName', 'emailAddress'], {
        //   'type': 'unique',
        //   'name': 'UK_Users_fullName_emailAddress'
        // })
      },
      down: async (queryInterface, Sequelize) => {
        await queryInterface.removeColumn('Users', 'emailAddress');
        await queryInterface.removeColumn('Users', 'fullName');
        // return queryInterface.removeConstraint('Users', 'UK_Users_fullName_emailAddress')
      }
    }
    

    所以在这种方法中,数据库永远不会让您添加重复的条目。

    更新 #1

    如果我没看错,你的代码 sn-p 就是一个快速路由器。如果是这样,那么您需要检查是否存在具有电子邮件或全名的用户,例如使用 sequelize:

    router.post("/", async (req, res) => {
      const { fullName, emailAddress, password } = req.body;
    
      const user = await Users.findOne({ fullName, emailAddress });
    
      if (!user) {
        res.status(400).send({ error: "This email is in use by someone els, please try something else, thanks." });
      } else {
        bcrypt.hash(password, 10).then((hash) => {
          Users.create({
            fullName: fullName,
            emailAddress: emailAddress,
            password: hash,
          });
          res.json("User, Success");
        });
      }
    });
    

    【讨论】:

    • 您好,非常感谢您的回复。我试过了,但我仍然得到了 doulicates。
    • 我在检查用户是否存在时遇到问题,请看下面的答案,您可能会理解问题。
    • @MurtazaHassani 请参阅更新 #1
    • 嘿,它不起作用,所以改变了我的数据库,现在我不允许创建重复用户,但它给出了错误提示:原始:错误:重复条目 'Booker' for key' users.fullName_UNIQUE'
    • @MurtazaHassani 预计 DB 会出错,但很可能您不愿意在 FE 中显示它,因此您必须使用 try/catch 块在 BE 中捕获它并返回用户友好的验证消息.
    【解决方案2】:

    你可以从 router.post 开始。 通过查询数据库检查是否有用户使用此电子邮件,如果存在则抛出错误,说明用户已经在这里。

    【讨论】:

    【解决方案3】:

    这是我尝试过的。

     router.post("/", async (req, res) => {
      const { fullName, emailAddress, password } = req.body;
      if (fullName && emailAddress) {
        console.log(
          "This email is in use by someone els, please try something else, thanks."
        );
      } else {
        bcrypt.hash(password, 10).then((hash) => {
          Users.create({
            fullName: fullName,
            emailAddress: emailAddress,
            password: hash,
          });
          res.json("User, Success");
        });
      }
    });
    

    现在它正在工作,但我需要在用户界面中为用户显示一些消息。

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2015-01-04
      • 2019-01-10
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2015-04-05
      相关资源
      最近更新 更多