【问题标题】:SEQUELIZE: "Cannot read property 'length' of undefined"SEQUELIZE:“无法读取未定义的属性‘长度’”
【发布时间】:2020-09-14 10:41:27
【问题描述】:

有谁知道如何解决这个问题?有些东西我没有看到。为了查看控制器是否正常工作,我以 json 格式返回了接收请求的响应,它工作正常,没有错误。

问题似乎出在控制器上,但是控制器...

编辑

控制器

import Post from '../models/Post';
import *  as Yup from 'yup';

class PostController {
    async store(req, res) {

        try {
            //Checks if the fields have been filled correctly
            const schema = Yup.object().shape({
                title: Yup.string()
                    .required(),
                content: Yup.string()
                    .required()
            });


            if(!(await schema.isValid(req.body))) {
                return res.status(400).json({ error: 'Error 1' });
            }

            //Abstraction of fields
            const { title, content } = req.body;
            const createPost = await Post.create(title, content);

            if(!createPost) {
                return res.json({error: 'Error 2'})
            }

            //If everything is correct, the information will be registered and returned.
            return res.json({
                title,
                content,
            });
        }
        catch (err) {
            console.log("Error: " + err);
            return res.status(400).json({error: 'Error 3'});
        }
    }
}

export default new PostController();

型号:

import Sequelize, { Model } from 'sequelize';

class Post extends Model {
    static init(sequelize) {
        //Fields registered by the user
        super.init({
            id: {
                type: Sequelize.INTEGER,
                primaryKey: true
            },
            title: Sequelize.STRING,
            content: Sequelize.TEXT,
            created_at: {
                type: Sequelize.DATE,
                defaultValue: Sequelize.NOW,
            },
            updated_at: {
                type: Sequelize.DATE,
                defaultValue: Sequelize.NOW,
            },
        },
        {
            sequelize,
            tableName: 'posts'
        });

        return this;
    }
}

export default Post;

迁移:

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('posts', {
        id: {
            type: Sequelize.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        title: {
            type: Sequelize.STRING,
            allowNull: false,
        },
        content: {
            type: Sequelize.TEXT,
            allowNull: false,
        },
        created_at: {
            type: Sequelize.DATE,
            allowNull: false,
        },
        updated_at: {
            type: Sequelize.DATE,
            allowNull: false,
        }
    });
  },

  down: (queryInterface) => {
    return queryInterface.dropTable('posts');
  }
};

终端错误:

TypeError: Cannot read property 'length' of undefined

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    您需要在模型中定义所有用于迁移的列。当您输入allowNull: false 时,数据库需要列信息。

    我相信您可以解决在 Model 中添加您在 migration 上声明的列的问题,如果您不想在 Controller 上声明这些列,请添加 defaultValue 属性那些列。

    这将允许在这些列上插入适当的数据。例如:defaultValue: Sequelize.NOWcreated_at 列上。

    您需要输入的另一件事是表名,如下所示(这是我在一个项目中使用的一个模型:

    static init(sequelize) {
            super.init(
                {
                    categoryId: {
                        type: Sequelize.INTEGER,
                        primaryKey: true,
                        field: 'id',
                    },
                    dateUpdated: {
                        type: Sequelize.DATE,
                        field: 'updated_at',
                        defaultValue: Sequelize.NOW,
                    },
                    // ... other fields here,
                },
                {
                    sequelize,
                    tableName: 'categories',
                }
            );
        }
        // ... 
    }
    
    export default Category;
    
    

    因此,请尝试作为实例导入,而不是作为类导入。

    编辑 1: 别的东西。您的答案中的错误位于文件 lib/model.js (see here on github on the master repo of sequelize) 的第 140 行。

    看看这个,如果你还没有的话,试着在模型上声明你的主键。

    编辑 2: 在你的控制器中,试试这个(according to docs):

    await Post.create({ title, content });
    

    尝试传递一个带有您想要存储的信息的 json 对象,而不是作为参数。

    编辑 3: 您需要在调用控制器之前导入database.js,我在这一点上遇到了问题(请关注正在工作的database.js):

    // Imports here
    import Category from '../app/models/Category';
    //...
    
    const models = [
        // Models that I want to use
        Category,
        //...
    ];
    
    class Database {
        constructor() {
            this.init();
        }
        // Load on database init
        init() {
            this.connection = new Sequelize(databaseConfig);
            models.forEach(model => model.init(this.connection));
        }
    }
    
    export default new Database();
    

    【讨论】:

    • 更新了答案,举了一个适用于我的一个项目的例子。希望有所帮助。检查我声明tableName的点,似乎也是这个细节。
    • 它给出了同样的错误。在这个项目中,我制作了一个带有验证和身份验证的用户系统。您可以毫无问题地创建、更新和删除用户,没有错误,但现在您开始将此错误赋予类别。
    • 我放了一个 try catch 并返回了终端错误:“错误:TypeError:无法读取未定义的属性'长度'”
    • 我查看了model.js。检查答案上的 EDIT 以查看该方法是否可以帮助您。
    • 成功了!谢谢你,我真的很感谢你。编程很久了,心累,开始自动做,没想到需要在Database类中实例化模型,就像实例化User一样。当你提到这一点时,我想起来了。说真的,非常感谢。
    【解决方案2】:

    我遇到了同样的问题

    我的代码的问题是我忘记将模块名称添加到我的 models 数组中的 database's index.js 文件中

    例如:const **models** = [User,**Task**]

    我在这篇文章中找到了答案: https://github.com/sequelize/sequelize/issues/11111#issuecomment-697078832

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2015-08-10
      • 2018-01-11
      • 2020-12-23
      相关资源
      最近更新 更多