0

Hello everybody !! Here I have a big problem, I would like to do a registration in back with Node.js sequelize and mySql. I looked here and there but I did not find the answer to my problem so I came to ask you for help. With mongoDb, it was easier but I admit that I am going in circles.

Here is my code:

// Importation :

// Bcrypt:
const bcrypt = require("bcrypt");

// Jsonwebtoken d'authentification:
const jwt = require("jsonwebtoken");

// Import du models user:
const models = require("../models/user")

//////////////////////////////////////////////////////////////////////////////////////////////
// Fonction/

// Incription:
exports.signup = (req, res) => {

  const username  = req.body.username;
  const email     = req.body.email;
  const password  = req.body.password;
  const bio       = req.body.bio;
  const admin     = req.body.admin;

  console.log(req.body)
  try {

    models.User.findOne({
      attributes: ['email'],
      where: {
        email: email
      }
    })

    .then((userFound => {
      if (!userFound) {

        bcrypt.hash(password, 10, function (err, bcryptPassword) {

          const newUser = models.User.create({
            username  : username,
            email     : email,
            password  : bcryptPassword,
            bio       : bio,
            admin     : false
            })

            .then(newUser => {
              res.status(201).json({
                'userId': newUser.id
              })
            })
            .catch(err => {
              res.status(500).json({
                'error': 'Impossible d\'ajouter un utilisateur'
              })
            })

          })

        } else {
          return res.status(409).json({
            error: 'Ce compte existe déjà '
          })
        }

      })
      .catch((err) =>
        res.status(500).json({
          'err': err + 'Impossible de vérifier l\'utilisateur',
        })
      )

      )
  }catch (error) {
    res.status(400).json({
      error: error.message
    });
  }

}

response from Postman's console

And the model User:

'use strict'
const { db } = require('../config/connexion')

const { Sequelize, DataTypes } = require('sequelize')

const user = db.define('User', {
  // Model attributes are defined here
  username: DataTypes.STRING,
  email: DataTypes.STRING,
  password: DataTypes.STRING,
  bio: DataTypes.TEXT,
  admin: DataTypes.BOOLEAN,
})

module.exports = user

and connexion.js:

// Connexion de sequelize à mysql:
const {
  Sequelize
} = require('sequelize')

const db = new Sequelize(
  process.env.NAMEDB,
  process.env.USERDB,
  process.env.PASSWORDDB, {
    host: process.env.HOSTDB,
    dialect: process.env.DIALECTDB,
    pool: {
      min: 0, //  nombre minimum de connexion dans le pool
      max: 5, //  nombre maximum de connexion dans le pool
      acquire: 30000, //  durée maximale, en millisecondes, pendant laquelle ce pool essaiera d'obtenir la connexion avant de lancer une erreur
      idle: 10000, //  temps maximum, en millisecondes, pendant lequel une connexion peut être inactive avant d'être libérée
    },
  }
)

//////////////////////////////////////////////////////////////////////////////////////////////
// Etablit la connexion à mysql:
const dbConnect = async (db) => {
  await db
    .authenticate()
    .then(() => {
      db.sync()
      console.log('Connecté à la base de données MySQL!')
    })
    .catch((err) => {
      console.error('error: ' + err.message)
      setTimeout(() => {
        dbConnection(db)
      }, 5000)
    })
}

//////////////////////////////////////////////////////////////////////////////////////////////
// Exportation:
module.exports = {
  db,
  dbConnect,
}

Certainly there is still a lot to do, but being a beginner I improve as I go.

Do not be angry with me if my English is not at the top, I admit that it is not my strong point.

Thanking you in advance for all the help provided.

  • Hello and welcome to Stackoverflow. A picture can be worth a thousand words but they are worth significantly less than that on Stackoverflow. Please have a read of this: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/1048425) – GarethD Jul 22 '21 at 16:31
  • @ GarethDah, actually as much for me I correct it afterwards –  Jul 22 '21 at 16:38
  • Could you please check module.exports of models module? Maybe User is missing... – Kemal Kaplan Jul 22 '21 at 16:44
  • @Kemal Kaplan, I added the model user, sorry;) –  Jul 22 '21 at 16:48
  • I think we also need to see the connexion file, o/w we need sequelize.define instead of db.define... – Kemal Kaplan Jul 22 '21 at 17:00
  • Try models.findOne instead of models.User.findOne – Tushar Shahi Jul 22 '21 at 17:02
  • @KemalKaplan, I just added it if you need another file, tell me;) –  Jul 22 '21 at 17:04
  • @TusharShahi, I just tried I still have the same error :( –  Jul 22 '21 at 17:06
  • Hm, `console.log(models)` before this statement `models.User.findOne({` – Tushar Shahi Jul 22 '21 at 17:08
  • @TusharShahi, the console returns me: User –  Jul 22 '21 at 17:11
  • Suggest you to add new info to the question too. And what does `User` mean, just a string? – Tushar Shahi Jul 22 '21 at 17:12
  • @TusharShahi, as I said to lejlun, I didn't change the second models.user so that's why it didn't work, head in the air that I am ... But now postman turns me around: "error": "(intermediate value).catch is not a function" –  Jul 22 '21 at 17:21
  • Thanks to @everyone for helping out, now postman returns to me: "error": "(intermediate value) .catch is not a function" I don't know what wrestling he's talking to me about and even less why –  Jul 22 '21 at 17:32
  • Thank you very much to everyone for your help! I solved my second problem by removing the penultimate catch. Thanks again ! –  Jul 22 '21 at 17:39

4 Answers4

1

You are directly setting the export object equal to the user object.

When you do this const models = require("../models/user"), models is equal to the user value directly.

You can directly use models.findOne. Read this

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

Check your "model" file to see if the "User" model exists there. Also check if you are using the 'module.exports'

Ivan
  • 81
  • 5
  • I just added the model user in my post, I forgot to send it with ;) –  Jul 22 '21 at 16:53
0

You are exporting the User model directly, but calling it like it is in an object property named User. You can either access it directly, changing:

models.User.findOne

to:

models.findOne

and then you'd probably want to rename models to User.

Or change your export to:

module.exports = { User: user };
Mikey Thomas
  • 26
  • 1
  • 3
0

You are setting the user variable to be the export of the file

module.exports = user

You then import the user variable as models.

const models = require("../models/user")

this means that you do not need to access user as a property. Instead use:

models.findOne({ // Changed from models.User to models
    attributes: ["email"],
    where: {
        email: email,
    },
});

This should stop your current error, but you will keep on getting errors until you change all instances of models.User to models.

Your main file should end up looking like this:

// Importation :

// Bcrypt:
const bcrypt = require("bcrypt");

// Jsonwebtoken d'authentification:
const jwt = require("jsonwebtoken");

// Import du models user:
const models = require("../models/user");

//////////////////////////////////////////////////////////////////////////////////////////////
// Fonction/

// Incription:
exports.signup = (req, res) => {
  const username = req.body.username;
  const email = req.body.email;
  const password = req.body.password;
  const bio = req.body.bio;
  const admin = req.body.admin;

  console.log(req.body);
  try {
    models
      .findOne({
        attributes: ["email"],
        where: {
          email: email,
        },
      })

      .then(
        ((userFound) => {
          if (!userFound) {
            bcrypt.hash(password, 10, function (err, bcryptPassword) {
              const newUser = models
                .create({
                  username: username,
                  email: email,
                  password: bcryptPassword,
                  bio: bio,
                  admin: false,
                })

                .then((newUser) => {
                  res.status(201).json({
                    userId: newUser.id,
                  });
                })
                .catch((err) => {
                  res.status(500).json({
                    error: "Impossible d'ajouter un utilisateur",
                  });
                });
            });
          } else {
            return res.status(409).json({
              error: "Ce compte existe déjà ",
            });
          }
        }).catch((err) =>
          res.status(500).json({
            err: err + "Impossible de vérifier l'utilisateur",
          })
        )
      );
  } catch (error) {
    res.status(400).json({
      error: error.message,
    });
  }
};
lejlun
  • 4,140
  • 2
  • 15
  • 31
  • Thank you indeed I have just corrected the 2 models.user and it returns me this error more .. Mias instead postman returns this one to me: "error": "(intermediate value) .catch is not a function" –  Jul 22 '21 at 17:15