简体   繁体   中英

User.create not a function sequelize

I just started using express js. I want to do a database insertion in to user table. I used the sequelize model:generate to create a user model. This is it

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      password: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

This is the model generated

'use strict';

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    name: DataTypes.STRING,
    username: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  });
  User.associate = function(models) {
    // associations can be defined here


  };  

  return User;
};

Then i have a controller where i have a register method.

const Validator = require('validatorjs');
const bcrypt = require('bcrypt');
const privateKey = require('../config.json').secretKey;
const saltRounds = require('../config.json').saltRounds;
const User = require('../models/user');

exports.register = async (req, res, next) => {
    rules = {
        username: 'required|string|max:255|alpha_num',
        email: 'required|email',
        password: 'required|string|max:255',
        name: 'required',
    }

    const validation = new Validator(req.body, rules);

    if(validation.passes()){
        let password = await bcrypt.hash(req.body.password, saltRounds);        
        User.create({
            username: req.body.username,
            password: password,
            name: req.body.name,
            email: req.body.email,            
        }).then(response => {
            return res.status(200).json(response);
        }).catch(err => {
            return res.status(500).json(err);
        });
    }else{
        return res.status(422).json(validation.errors);
    }

}

But I get an error saying User.create is not a function. This is my file structure here

Please i need help with this. Appreciate

When you generate your models with sequelize CLI sequelize-cli model:generate --name User you should import them from the index.js file in the models folder

const db = require('../models');
db.User.create({})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM