Homunculus Reticulli
Homunculus Reticulli

Reputation: 68376

Sequelize + Express TypeError: User.find is not a function

I am following an online tutorial on using PostgreSQL, Express and Passport and when I try to sign in, I get the following error stack trace:

at /path/to/server/routes/api.js:30:8
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at next (/path/to/server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/path/to/server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at /path/to/server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)
at next (/path/to/server/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)
at router (/path/to/server/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)
at /path/to/server/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)
at next (/path/to/server/node_modules/express/lib/router/index.js:275:10)
at /path/to/server/node_modules/express/lib/router/index.js:635:15
at next (/path/to/server/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)
at router (/path/to/server/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)
at /path/to/server/node_modules/express/lib/router/index.js:284:7

/path/to/server/models/index.js

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

/path/to/server/models/user.js

'use strict';

var bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    username: DataTypes.STRING,
    password: DataTypes.STRING
  }, {});
  User.beforeSave((user, options) => {
    if (user.changed('password')) {
      user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
    }
  });
  User.prototype.comparePassword = function (passw, cb) {
    bcrypt.compare(passw, this.password, function (err, isMatch) {
        if (err) {
            return cb(err);
        }
        cb(null, isMatch);
    });
  };
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

/path/to/server/api.js

const express = require('express');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const router = express.Router();
require('../config/passport')(passport);
const User = require('../models').User;

router.post('/signin', function(req, res) {
  User
      .find({
        where: {
          username: req.body.username
        }
      })
      .then((user) => {
        if (!user) {
          return res.status(401).send({
            message: 'Authentication failed. User not found.',
          });
        }
        user.comparePassword(req.body.password, (err, isMatch) => {
          if(isMatch && !err) {
            var token = jwt.sign(JSON.parse(JSON.stringify(user)), 'nodeauthsecret', {expiresIn: 86400 * 30});
            jwt.verify(token, 'nodeauthsecret', function(err, data){
              console.log(err, data);
            })
            res.json({success: true, token: 'JWT ' + token});
          } else {
            res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
          }
        })
      })
      .catch((error) => res.status(400).send(error));
});

Why is User.find() not being recognised as a method? and how do I fix this issue?

Upvotes: 3

Views: 7215

Answers (2)

Victor
Victor

Reputation: 11

As it was already stated, it's due to it being deprecated now.

The official guide to upgrade sequelize to v5, in the model section, removed the aliases subsection.

Upvotes: 1

viniciusjssouza
viniciusjssouza

Reputation: 1275

I was looking for a find method on the sequelize doc and couldn't find the find method, just a findAll and findOne. Perhaps it was deprecated on newer versions docs.sequelizejs.com/manual/querying.html

Upvotes: 14

Related Questions