简体   繁体   中英

mysql create table with long string data

I was making online forum. I made writing function. My writing form is devided into title and content. Normally, it works well. But if I type a little bit longer in content, error occurs. I use mysql and sequelize. Here is error message在此处输入图像描述 and here is my code

router.post('/', isLoggedIn, upload2.none(), async (req, res, next) => {
    try{
        const post = await Post.create({
            title: req.body.title.toLowerCase(),
            content: req.body.editordata,
            img: req.body.url,
            UserId: req.user.id,
        });
        res.redirect('/');
    } catch (error) {
        console.error(error); 
        next(error);
    }
});

(code which error occures)

and my post module looks likes this

const Sequelize = require('sequelize');

module.exports = class Post extends Sequelize.Model {
    static init(sequelize) {
        return super.init({
        title: {
            type: Sequelize.STRING(100),
            allowNull: false,
        },
        content: {
            type: Sequelize.STRING(20000),
            allowNull: false,
        },
        img: {
            type: Sequelize.STRING(250),
            allowNull: true,
        },
        }, {
        sequelize,
        timestamps: true,
        underscored: false,
        modelName: 'Post',
        tableName: 'posts',
        paranoid: false,
        charset: 'utf8mb4',
        collate: 'utf8mb4_general_ci',
        });
    }

    static associate(db) {
        db.Post.belongsTo(db.User);
        db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag' });
    }
};

Is there any way to save long data in table?

I tried increasing number in here. (post module)

content: {
    type: Sequelize.**STRING(20000),**
    allowNull: false,
},

It was still same.

use Sequelize.TEXT('long')

content: {
    type: Sequelize.TEXT('long'),
    allowNull: false,
},

LONGTEXT

A TEXT column with a maximum length of 4,294,967,295 or 4GB (232 - 1) in bytes. The effective maximum length is less if the value contains multi-byte characters. The effective maximum length of LONGTEXT columns also depends on the configured maximum packet size in the client/server protocol and available memory. Each LONGTEXT value is stored using a four-byte length prefix that indicates the number of bytes in the value.

Ref: https://mariadb.com/kb/en/longtext/

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