Sequelize + Express TypeError: User.find не является функцией - PullRequest
0 голосов
/ 28 мая 2019

Я следую онлайн-учебнику по , используя PostgreSQL, Express и Passport , и при попытке войти в систему я получаю следующую трассировку стека ошибок:

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 /в / 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));
});

Почему User.find () не распознается как метод?и как мне исправить эту проблему?

1 Ответ

1 голос
/ 28 мая 2019

Я искал метод find в sequelize doc и не смог найти метод find, просто findAll и findOne.Возможно, он был устаревшим на более новых версиях docs.sequelizejs.com/manual/querying.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...