简体   繁体   中英

Sequelize: TypeError: Cannot read property 'length' of undefined when try to create data on DB

i'm working on a personal project. Basically a node based blog to learn the language...

I already created the category and articles migration and models, now i'm trying to start the users creation.

Here's my Users migration (20201124222940-create_users.js):

"use strict";

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable("users", {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
      },
      email: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      password: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("users");
  },
};

This is my Model (User.js):

const { Model, DataTypes } = require('sequelize');

class User extends Model {
    static init(sequelize) {
        super.init({
            email: DataTypes.STRING,
            password: DataTypes.STRING,
        }, {
            sequelize,
            tableName: 'users'
        });
    }
}

module.exports = User;

//? Model de usuários

And, here's my controller (UsersController.js) that try to create a user. I'm using bcrypt to create a hash and secure the password.

const express = require("express");
const router = express.Router();
const User = require('../models/User');
const bcrypt = require('bcryptjs');

router.get("/admin/users", (req, res) => {
    res.send("Listagem de usuários");
});

router.get("/admin/users/new", (req, res) => {
    res.render("admin/users/new");
});

router.post("/admin/users/create", (req, res) => {
    const email = req.body.email;
    const password = req.body.password;

    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);

    User.create({
        email: email,
        password: hash,
    }).then(() => {
        res.redirect("/");
    }).catch((err) => {
        console.log(err);
        console.log(email, password, hash, salt)
    });

});

module.exports = router;

And the error that i get:

TypeError: Cannot read property 'length' of undefined
    at User._initValues (D:\dev\blog_node\node_modules\sequelize\lib\model.js:140:49)
    at new Model (D:\dev\blog_node\node_modules\sequelize\lib\model.js:118:10)
    at new User (D:\dev\blog_node\models\User.js:3:1)
    at Function.build (D:\dev\blog_node\node_modules\sequelize\lib\model.js:2157:12)
    at Function.create (D:\dev\blog_node\node_modules\sequelize\lib\model.js:2207:23)
    at D:\dev\blog_node\controllers\UsersController.js:21:10
    at Layer.handle [as handle_request] (D:\dev\blog_node\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\dev\blog_node\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\dev\blog_node\node_modules\express\lib\router\route.js:112:3)       
    at Layer.handle [as handle_request] (D:\dev\blog_node\node_modules\express\lib\router\layer.js:95:5)

I already test the constants hash, password, salt, email.. Already tried to create some manual data like: password: "123", email: "asda@asda.com". Already compared to the other two models and controllers and nothing came up.

So, where i'm failling?

Thanks!

EDIT @Anatoly noticed that don't called my User.init

So... before the comment:

const Sequelize = require("sequelize");
const dbConfig = require('./database');

const Category = require("../models/Category");
const Article = require("../models/Article");

const connection = new Sequelize(dbConfig);

Category.init(connection);
Article.init(connection);

Category.associate(connection.models);
Article.associate(connection.models);


module.exports = connection;

After his comment:

const Sequelize = require("sequelize");
const dbConfig = require('./database');

const Category = require("../models/Category");
const Article = require("../models/Article");
const User = require("../models/User");

const connection = new Sequelize(dbConfig);

Category.init(connection);
Article.init(connection);
User.init(connection);

Category.associate(connection.models);
Article.associate(connection.models);


module.exports = connection;

AWESOMEEEE!!! <3 Solved the problem!

You should initialize the User model before use it like this:

User.init(connection);

Add this initialization along with other models' initialization code.

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