I'm learning node.js and mySQL. I have tried Sequelize and according to my learning source sync should create new table if doesn't exist. But for some reason it doesn't create new table.
Here is my database.js file
const Sequelize = require('sequelize');
const sequelize = new Sequelize('test-schema', 'root', 'mypassword',{dialect:'mysql', host:'localhost'});
module.exports = sequelize;
Here is my model Product file
const Sequelize = require('sequelize');
const sequelize = require('../util/database')
const Product = sequelize.define('product', {
id: {type: Sequelize.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},
title: Sequelize.STRING,
price: {type: Sequelize.DOUBLE, allowNull: false}
});
module.exports = Product;
and here is my server.js file
const express = require('express');
const sequelize = require('./util/database')
const app = express();
app.get('/',(req,res,next)=>{
res.send({"id": "1"});
});
sequelize.sync().then(result=>{
//console.log(result);
app.listen(3000);
}).catch(err => {
console.log(err);
});
Once I start server I get
Executing (default): SELECT 1+1 AS result
I tried to change the name of my schema in my database file to wrong name and I get an error schema doesn't exist so I believe that connection to db is correct
Here are my installed packages
"dependencies": {
"express": "^4.17.1",
"mysql2": "^2.1.0",
"sequelize": "^5.21.10"
}
Define all models as functions so that you can call them to register models in sequelize and then register models in database.js just like I described in this answer. You can see in the question of this answer how to define a model like a function.
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: { type: DataTypes.BIGINT, allowNull: false, autoIncrement: true, unique: true, primaryKey: true },
first_name: DataTypes.STRING,
last_name: DataTypes.STRING
}, {});
User.associate = function(models) {
User.belongsTo(models.Role, { foreignKey: 'role_id' });
};
return User;
};