U
U
urajo2020-02-03 20:15:07
Node.js
urajo, 2020-02-03 20:15:07

How to add data to database using sequelize?

the roures folder contains the auth file with the code

const express = require('express'),
  router = express.Router(),
  bcrypt = require('bcrypt-nodejs'),
  models = require('../models');

router.post('/register', (request, response)=>{
  const login = request.body.name,
    mail = request.body.email,
    pass = request.body.password,
    repass = request.body.repassword;
  if(!login || !mail || !pass || !repass){
    response.json({
      ok: false,
      error: 'Все поля должны быть заполнены!',
      fields: ['login', 'mail', 'pass', 'repass']
    });
  }else if(login.length < 3 || login.length > 16){
    response.json({
      ok: false,
      error: 'Длина логина от 3 до 16 символов!',
      fields: ['login']
    });
  }else if(pass !== repass){
    response.json({
      ok: false,
      error: 'Не совпадают пароль',
      fields: ['pass', 'repass']
    })
  }else{
    bcrypt.hash(pass, null, null, function(err, hash){
      models.User.create({
        login: login,
        mail: mail,
        password: hash,
        privilege: 1
      }).then(user => {
        console.log(user);
        response.json({
          ok:true
        })
      }).catch(err => {
        console.log(err);
      })
    }) 
  }
});

module.exports = router;

Fragment doesn't work
models.User.create({
        login: login,
        mail: mail,
        password: hash,
        privilege: 1
      })

Writes in the log
models.User.create({

TypeError: models.User.create is not a function


The index file for models is located in the adjacent models folder, its contents
const Book = require('./book'),
  User =  require('./user');

module.exports = {
  Book,
  User
}

And the user file lies next to the index, contains
const database = require('../database'),
  User = database.sequelize.define('user',{
    id: {
      type: database.Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false
    },
    login: {
      type: database.Sequelize.STRING,
      allowNull: false,
      unique: true
    },
    password: {
      type: database.Sequelize.STRING,
      allowNull: false
    },
    mail: {
      type: database.Sequelize.STRING,
      allowNull: false,
      unique: true
    },
    privilege:{
      type: database.Sequelize.INTEGER,
      allowNull: false
    }
  });

module.exports = {
  User: User
}


What is the error I can't figure out?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-02-04
@Robur

const Book = require('./book').Book,
  User =  require('./user').User;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question