Sequelize - Insert row

By xngo on September 4, 2022

// Reference: https://zetcode.com/javascript/sequelize/
 
const { Sequelize, DataTypes } = require('sequelize');
 
// Connect to database.
const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'C:/xuan/vbox-shared/github-projects/treeorg/treeorg7.sqlite'
});
 
// Define the User model.
const User = sequelize.define('User', {
    username: DataTypes.STRING,
    birthday: DataTypes.DATE,
});
 
// Sync() is to create all tables defined by models.
sequelize.sync()
    .then(() => {
 
        // Create a user.
        const jane = User.create({
            username: 'janedoe',
            birthday: new Date(1980, 6, 20),
        });
 
        // Create another user.
        const joe = User.create({
            username: 'joesmith',
            birthday: new Date(1990, 7, 30),
        });
    })
    .catch((err) => {
        console.error(err);
    });
 
////////////////////////////////////////////////
// OR call directly but can't catch error.
    (async() => {
        // Create all tables defined by models.
        sequelize.sync();
 
        // Create a user.
        const jane = User.create({
            username: 'janedoe2',
            birthday: new Date(1982, 9, 22),
        });
 
        // Create another user.
        const joe = User.create({
            username: 'joesmith2',
            birthday: new Date(1992, 5, 28),
        });
 
    })();

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.