K ACHARYA
K ACHARYA

Reputation: 43

User.findAll is not a function

This is my models/user.js

var sequelize = require('sequelize');
var bcrypt = require('bcrypt');

module.exports = function(sequelize, DataTypes) {
    const User = sequelize.define('users', {
        user_id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        user_name: DataTypes.DATE,
        email: DataTypes.STRING,
        password: DataTypes.STRING
    }, {
        freezeTableName: true,
        instanceMethods: {
            generateHash(password) {
                return bcrypt.hash(password, bcrypt.genSaltSync(8));
            },
            validPassword(password) {
                return bcrypt.compare(password, this.password);
            }
        }
    });

    return User;
}

This is my models/index.js

module.exports = {
    User: require('./user')
  };

This is my UserController.js

var sequelize = require("sequelize");
var models = require("../models/index");

var userController = {};

// Show list of users
userController.list = function(req, res) {
 models.User.findAll()
  .then( userResponse => {
    res.status( 200 ).json( userResponse )
  })
  .catch( error => {
    res.status( 400 ).send( error )
  });
};  

On executing the above code in localhost it is giving error that "User.findAll is not a function". I have tried in various ways but no result. Need help. I am using express - nodejs - Sequelize(mysql2)

Upvotes: 1

Views: 6516

Answers (2)

errakeshpd
errakeshpd

Reputation: 2552

The trick is in index.js file. try by sequelize init that will create a a fully fledge models/index.js file automatically.

Then add this in your UserController.js

const db = require('../models/index');
const User = db['users'];

Then you will be able to use User.findAll().

User.findAll()
  .then( userResponse => {
    res.status( 200 ).json( userResponse )
  })

Thanks

Upvotes: 0

Enzo Beltrami
Enzo Beltrami

Reputation: 81

you need to pass a sequelize instance and a DataTypes to your User.js

module.exports = function(sequelize, DataTypes)

So in order to do so you should change your models/index.js to something like this.

var Sequelize = require("sequelize");
var user = require("./user");
var sequelize = new Sequelize("your db config goes here");

module.exports = {
    User: user(sequelize, Sequelize.DataTypes),
}

And you don't need to require sequelize in every file, remove it from the controller and the model

There is an example repo here that shows you how to use sequelize with express.js, we usually use a index.js like this that will go through your models folder and you would be able to access the model using db['User']

Upvotes: 3

Related Questions