Home > Software design >  Check if user exists in router before creation in database with Sequelize
Check if user exists in router before creation in database with Sequelize

Time:02-17

I have a function to check if a user exists, and a function to create a new user in my User model.

What I want to do is call them in the router to check if a user with the email adress in req.body already exists.

If it does, I want to return a message, and if not, I want to create the user.

When I try to call the route in Postman, I get this error in node console :

node_modules/express/lib/response.js:257
  var escape = app.get('json escape')

TypeError: Cannot read properties of undefined (reading 'get')

User model :

const Sequelize = require("sequelize");
const connexion = require("../database");

    const User = connexion.define(
      "users",
      {
        id: {
          type: Sequelize.INTEGER,
          autoIncrement: true,
          allowNull: false,
          primaryKey: true,
        },
    
        email: {
          type: Sequelize.STRING(100),
          allowNull: false,
        },
    
        password: {
          type: Sequelize.STRING(100),
          allowNull: false,
        },
      },
      {
        freezeTableName: true 
      }
    );
    
    
    function checkUser(userEmail) {
      const findUser = User.findOne({ where: { userEmail } }).catch((err) => {
        console.log(err);
      });
    
      if (findUser) {
        return res.json({ message: "Cette adresse email est déjà enregistrée" });
      } else {
        return false;
      }
    }
    
    function createUser(userData) {
      console.log(userData);
      User.create(userData)
    
        .then((user) => {
          console.log(user);
        })
    
        .catch((err) => {
          console.log(err);
        });
    }
    
    module.exports = { createUser, checkUser };

user controller :

const createUser = require("../models/User");
const bcrypt = require("bcrypt");

const saltRounds = 10;

addUser = async (req, res) => {
  try {
    const userData = req.body;
    console.log(req.body);

    bcrypt.hash(userData.password, saltRounds, async function (err, hash) {
      userData.password = hash;

      const newUser = await createUser(req.body);

      res.status(201).json({ newUser });
    });
  } catch (err) {
    console.log(err);
    res.status(500).json("Server error");
  }
};

module.exports = addUser;

user router :

const express = require("express");
const router = express.Router();
const addUser = require("../controllers/userController");
const { checkUser } = require("../models/User");

router.post("/", async (req, res) => {
  const { email } = req.body;

  const alreadyExists = await checkUser(email);

  if (!alreadyExists) {
    addUser(req.body);
  }
});

module.exports = router;

EDIT : Finally I'm trying a more simple way. I will do the check part directly into the createUser function. But now, it creates the user even if the email already exists ^^

async function createUser(userData) {
  console.log(userData);

  const findUser = await User.findOne({ where: userData.email }).catch(
    (err) => {
      console.log(err);
    }
  );

  findUser
    ? console.log(findUser)
    : User.create(userData)

        .then((user) => {
          console.log(user);
        })

        .catch((err) => {
          console.log(err);
        });
}

CodePudding user response:

i think the problem is with this part you are trying to use res but it doesn't exist in your checkUser function

if (findUser) {
        return res.json({ message: "Cette adresse email est déjà enregistrée" });
      } else {
        return false;
      }

try this instead

if (findUser) {
return true });
      } else {
        return false;
      }

UPDATE to fix the problem of user creation if it already exists

async function createUser(userData) {
  console.log(userData);

  const findUser = await User.findOne({ where: userData.email }).catch(
    (err) => {
      console.log(err);
    }
  );
  if(!findUser){

  findUser
    ? console.log(findUser)
    : User.create(userData)

        .then((user) => {
          console.log(user);
        })

        .catch((err) => {
          console.log(err);
        });

}
}

CodePudding user response:

Problem solved by doing this (thanks super sub for your help):

async function createUser(userData) {
  console.log(userData);

  const email = userData.email;
  const findUser = await User.findOne({ where: { email } }).catch((err) => {
    console.log(err);
  });
  if (!findUser) {
    User.create(userData)

      .then((user) => {
        console.log(user);
      })

      .catch((err) => {
        console.log(err);
      });
  }
}
  • Related