0

When I'm trying to import user into database with User.create(), sequelize trows me error that says that table doesn't exist. Even tho I created a table line above the create function. My goal is to add user without using .then() function on .sync function.

I've tried to put sync function in await as I imagined that the sync function takes longer to finish.

// imports ...

// Connecting to database
// Creating ORM object
const db = new sequelize(format("%s://%s:%s@%s:%s/%s", gvars.db_soft, gvars.db_user, gvars.db_pass, gvars.db_host, gvars.db_port, gvars.db_daba));
db.authenticate().then(() => {
    console.log("Connection established.");
}).catch(err => {
    console.error(err);
});

// Define users table
const User = db.define("users", {
    firstName: {
        type: sequelize.STRING,
        allowNull: false
    },
    lastName: {
        type: sequelize.STRING,
        allowNull: false
    }}, { freezeTableName: true,
});
db.sync({ force: true }).then(() => { console.log("Table created."); });
User.create({
    firstName: "Milan",
    lastName: "Vjestica"
});

//...starting app

I expect for user to be added in table.

  • I bet this is the async issue. `User.create` needs to be inside of `then(() => { // here })`. ref: https://eloquentjavascript.net/11_async.html – Emma Nov 07 '19 at 23:40

1 Answers1

0

You have to use promise in sequelize as it is a promised based ORM,try following changes:

User.create({ firstName: "Milan",lastName: "Vjestica"}).then(function(user) 
{
    console.log(user.get('firstName'));
    console.log(user.get('lastName')); 
});
Prabhjot Singh Kainth
  • 1,831
  • 2
  • 18
  • 26