node.js - Sequelize : "Cannot read property ' length' of undefined"

标签 node.js sequelize.js

有人知道怎么解决吗?有些东西我没有看到。为了查看 Controller 是否正常工作,我返回了以 json 格式接收请求的响应,它正常工作,没有错误。

问题好像出在 Controller 上,但是 Controller ...

编辑

Controller

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

最佳答案

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

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

这将允许 sequelize 在这些列上插入适当的数据。例如: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: 在你的 Controller 中,试试这个(according to docs):

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

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

编辑 3: 您需要在调用 Controller 之前导入 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();

关于node.js - Sequelize : "Cannot read property ' length' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62042290/

相关文章:

javascript - 创建一个读取文本并使用它的 API

angularjs - 从nodejs将内容添加到mongodb对象数组

javascript - Sequelize : How can I prevent virtual columns from included relation from appearing in query result?

mysql - Sequelize - 如何修复 "DataTypes is not defined"?

javascript - 如何在express中使用sequelize检索用户帖子?

node.js - meteor : “Failed to receive keepalive! Exiting.”

javascript - Node js 在日期上使用错误的格式

node.js - Sequelize js 如何获得关联模型的平均值(聚合)

node.js - Sequelize getter 方法中的异步表查询

javascript - coffeescript、jade、stylus -> js、css Assets 管理器? Node .js