Node Sequelize set up
Make sure to install the sequelize and mysql2.
npm install sequelize and mysql2
Then create the db. It better to use db.js file.
const {Sequelize} = require('sequelize')
const sequelize = new Sequelize('learn', 'root', 'root', {
host: 'localhost',
dialect: 'mysql'
});
module.exports = sequelize
Then connect It to app.js file.
const sequelize = require('./util/db.js')
sequelize.sync().then(()=>{
app.listen(port, ()=>{
console.log('server is runs on port ', port);
})
}).catch(e=>{
console.log(e.message);
})
In sync we can have some options
sync({force:true}) // delete table data and create table again
sync({alter:true}) // check the neccessary changes that table needed.
To create model use this approach.
const { DataTypes } = require('sequelize');
const sequelize = require('../util/db')
const User = sequelize.define('user', {
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull defaults to true
}
}, {
// Other model options go here
});
module.exports = User