TypeError: Невозможно прочитать свойство 'create' неопределенной ошибки в express, postgres, sequelize - PullRequest
0 голосов
/ 04 ноября 2018

Я пытаюсь создать систему входа в систему с Express, используя Postgres и ORM с именем Sequelize

Вот мой код:

user.js

var express = require('express');
var bodyParser = require('body-parser');
var db = require('../config/database');
var path = require('path');
var router = express.Router();
var {alumno, profesor} = require('../models/articles');

router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());

    router.post("/doregister_profesor", function(req, res) {
      console.log("FIRST REQUEST ======>", req.body);
      console.log("STEP 1 ======>", Date.parse(req.body.edad));
      const edad = Date.parse(req.body.edad);
      try {
        db.sequelize.sync().then(() =>
            profesor.create({
            username : req.body.username,
            password: req.body.password,
            email: req.body.email,
            pdni: req.body.pdni,
            pdniinput: req.body.pdniinput,
            edad: new Date(Date.now()),
            grado: req.body.grado
          })
        ); 
          var newProfesor = new profesor({
          username : username,
          password: password,
          email: email,
          pdni: pdni,
          pdniinput: pdniinput,
          edad: new Date(Date.now()),
          grado: grado
        });
        profesor.createProfesor(newProfesor, function(){
          if(err) throw err;
          console.log(user)
        });
        res.render('entrar_profesores');
      } catch (e) {
        console.log(e);
      }
    });

это мои статьи.js

var db = require('../config/database');

const profesores = db.sequelize.define('profesores', {
  username: db.Sequelize.STRING,
  password: db.Sequelize.STRING,
  email : db.Sequelize.STRING,
  pdni: db.Sequelize.STRING,
  pdniinput: db.Sequelize.INTEGER,
  edad : db.Sequelize.DATEONLY,
  grado : db.Sequelize.STRING
},
);


var profesor = module.exports = {'profesores': profesores};

var alumno = module.exports = {'alumnos': alumnos};

module.exports.createAlumnos = function(newAlumno, callback){
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(newAlumno.password, salt, function(err, hash) {
      newAlumno.password = hash;
      newAlumno.save(callback);
    });
});
}


module.exports.createProfesor = function(newProfesor, callback){
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(newProfesor.password, salt, function(err, hash) {
      newProfesor.password = hash;
      newProfesor.save(callback);
    });
});
}

passport.js

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
const {profesores, alumnos} = require('../models/articles');
const config = require('../config/database');
var express = require('express');
let session = require('express-session')
let router = express.Router();


module.exports = function(passport){
    console.log('llego hasta aqui 1', profesores);
    passport.use('local', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
      }, function(req, email, password, done){
          profesores.findOne({where: {email: email, password:password}}).then(function(user) {//function(err, user){
            console.log('consulta hecha');
            //console.log(user);
            if (!user) {
                return done(null, false);
            }
            /*if (!user.validPassword(password)) {
                return done(null, false);
            }*/
            return done(null, user);
          });
      })
      );


      passport.serializeUser(function(user, done) {
        console.log('llego hasta aqui 32 ', err);
        done(null, user.id)
        console.log('=================== ',err);

      });
      try{
         passport.deserializeUser(function(id, done) {
        console.log('llego hasta aqui ===============');
        profesores.findById(id).then(function(user){
          done(user);
        });
        console.log('llego hasta aqui 53');
      });
    }catch (err) {
        console.log(err);
    }

}

Я получаю следующие сообщения об ошибках:

Unhandled rejection TypeError: Cannot read property 'create' of undefined
at db.sequelize.sync.then (/Users/antoniotoche/Desktop/nodeterax/routes/users_logic.js:45:18)
at tryCatcher (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/promise.js:694:18)
at _drainQueueStep (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/Users/antoniotoche/Desktop/nodeterax/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:694:18)
at tryOnImmediate (timers.js:665:5)
at processImmediate (timers.js:647:5)

1 Ответ

0 голосов
/ 05 ноября 2018

Похоже, ваш экспорт неправильный:

module.exports.profesor = profesores;
module.exports.alumno = alumno;

Возможно, это то, что вы хотите сделать, обратите внимание, что alumno не определено.

Обратите внимание, что ваш импорт в passport.js и user.js не совпадает.

...