I am trying to make MVC project with node js and sequelize (mysql).
Now I have made the connection to database in the index.js
index.js
const express = require('express')
const msyql = require ('mysql')
const app = express()
const Sequelize = require ('sequelize')
app.set("view engine", "ejs")
app.use(express.static('public'))
app.listen(3000, ()=> {
console.log ("Server is running on 3000")
})
// routes
const homeRoute = require('./routes/homeRoute.js')
app.use(homeRoute)
// db confg
const db = new Sequelize ('maxDev', 'root', '', {
host: '127.0.0.1',
dialect: 'mysql'
})
db.authenticate().then(()=>{
console.log("DB connected!")
}).catch(error=>{
throw error
})
//
module.exports = db
At line 16: it will import the model that will also Import the migrtation and inside the migration file it will import the db which we have declared in index.js file.
but when I start the execution it gives me the error C:\Users\hmada\Desktop\maxSite\migrations\products.js:4 const Products = db.define('Products', { ^
TypeError: db.define is not a function
I realize that the db.authenticate return a promise so it should take some time before using so What should i do know ??
model file
const Products = require('.././migrations/products.js')
function getMainProducts () {
const sql = "SELECT * FROM products"
conn.query(sql, (err, result)=>{
if (err) return console.log(err)
return console.log(result)
})
}
module.exports = {
getMainProducts,
}
migration file
const {Sequelize, DataTypes} = require('sequelize')
const db = require('.././index.js')
const Products = db.define('Products', {
id: {
type: DataTypes.INTEGER,
allowNull:false,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull:false
},
price: {
type: DataTypes.STRING,
allowNull:false
},
specs: {
type:DataTypes.STRING,
allowNull: false
},
imgUrl: {
type: DataTypes.TEXT,
}
})
db.sync().then ().catch (error=> {
throw error
})
module.exports = Products