user15474257
user15474257

Reputation:

"error": "Cannot read property 'findOne' of undefined"

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.

Upvotes: 0

Views: 2283

Answers (4)

lejlun
lejlun

Reputation: 4419

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

Upvotes: 0

Tushar Shahi
Tushar Shahi

Reputation: 20486

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

Upvotes: 1

Mikey Thomas
Mikey Thomas

Reputation: 26

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 };

Upvotes: 0

Ivan
Ivan

Reputation: 121

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

Upvotes: 0

Related Questions