Last active
December 18, 2018 06:39
-
-
Save Freizello/b7c0d099d1c885c9c8cf29afaeaaae77 to your computer and use it in GitHub Desktop.
[ExpressJS with Sequelize] equelize.js will be the place to bootstrap our ORM and define relationships. We will define our models in their respective files and app.js will be our Express app. #nodejs #expressjs #mysql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Sequelize = require('sequelize') | |
// models is optional based on app | |
const UserModel = require('./models/user') | |
const BlogModel = require('./models/blog') | |
const TagModel = require('./models/tag') | |
const dbname = 'DB_NAME'; | |
const dbuser = 'DB_USER'; | |
const dbpass = 'DB_PASS'; | |
const sequelize = new Sequelize(dbname, dbuser, dbpass, { | |
host: 'localhost', | |
dialect: 'mysql', | |
pool: { | |
max: 10, | |
min: 0, | |
acquire: 30000, // in ms | |
idle: 10000 // in ms | |
} | |
}) | |
/* -- MODEL DEFINITION -- | |
* | |
*/ | |
const User = UserModel(sequelize, Sequelize) | |
// BlogTag will be our way of tracking relationship between Blog and Tag models | |
// each Blog can have multiple tags and each Tag can have multiple blogs | |
const BlogTag = sequelize.define('blog_tag', {}) | |
const Blog = BlogModel(sequelize, Sequelize) | |
const Tag = TagModel(sequelize, Sequelize) | |
/* -- MODEL RELATIONSHIP -- */ | |
Blog.belongsToMany(Tag, { through: BlogTag, unique: false }) | |
Tag.belongsToMany(Blog, { through: BlogTag, unique: false }) | |
Blog.belongsTo(User); | |
/* SYNC DATABASE ORM */ | |
sequelize.sync({ force: true }) | |
.then(() => { | |
console.log(`Database & tables created!`) | |
}) | |
module.exports = { | |
User, | |
Blog, | |
Tag | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment