3

I want check a table and if table is empty create a record.

my code:

module.exports = (sequelize, DataTypes) => {
    const About = sequelize.define("About",
        {
            id: {
                type: DataTypes.BIGINT,
                autoIncrement: true,
                allowNull: false,
                primaryKey: true,
            },
            title: DataTypes.STRING(150),
            content: DataTypes.TEXT("medium"),
        },
        {
            freezeTableName: true,
            timestamps: false,
        },
    );

    About.findAll()
    .then(about => {
        if (about.length === 0) {
            About.create({
                title: "About Us",
                content: "Lorem ipsum dolor sit amet...",
            });
        }
    });

    return About;
};

But when table doesn't exist I get this error:

Executing (default): SELECT id, title, content FROM About AS About;

Unhandled rejection SequelizeDatabaseError: Table 'mydb.about' doesn't exist

how can I handle this issue?

Community
  • 1
  • 1
Nima Kaviyani
  • 103
  • 3
  • 13

1 Answers1

2

I finally found the answer to my problem.

I added .sync() and create table before find. Both of .findOrCreate() and .findAll() is working.

module.exports = (sequelize, DataTypes) => {
    const About = sequelize.define("About",
        {
            title: DataTypes.STRING(150),
            content: DataTypes.TEXT("medium"),
        },
        {
            freezeTableName: true,
            timestamps: false,
        },
    );

    About.sync();

    About.findOrCreate({
        where: {id: 1},
        defaults: {
            title: "About Us",
            content: "Lorem ipsum dolor sit amet...",
        },
    });

    return About;
};
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Nima Kaviyani
  • 103
  • 3
  • 13