build a blog database using sequelize !!
- Post
- Comment
posts can have multiple comments ?
- Create a new project file
mkdir blog
cd blog
- Initiate an npm
npm init -y
- Install the project dependencies
npm install --save sequelize pg pg-hstore path
- Tell sequelize to create all the files inside db folder
mkdir db
touch .sequelizerc
- Edit .sequelizerc file
const path = require('path');
module.exports = {
"config": path.resolve('./db/config', 'config.json'),
"models-path": path.resolve('./db/models'),
"seeders-path": path.resolve('./db/seeders'),
"migrations-path": path.resolve('./db/migrations'),
}
- Generate Sequelize files
sequelize init
- make sure that all your files inside the db folders like this
db
├── config
│ └── config.json
├── migrations
├── models
│ └── index.js
├── seeders
- update the config file
// db/config/config.json
{
"development": {
"username": <your username>,
"password": null,
"database": "blog",
"host": "127.0.0.1",
"dialect": "postgres",
"define": {
"underscored": true
}
},
...
}
- Generate the models
// write the commands
- Update the models that sequelize generated:
- Change the table name to make it all lower case
postgres naming conventions
- Add the assocation
- update the migration file Change the table name to make it all lower case
postgres naming conventions
and add the assocation field then change the updatedAt to updated_at and createdAt to created_at
// add post id in the comment table
...
post_id: {
type: Sequelize.INTEGER,
onDelete: "CASCADE",
references: {
model: "posts",
key: "id"
}
}
....
- create the database
createdb blog
- run the migration files
write the command
- create an index.js file to write your query
- Create a new post
- Create a new comment
- List all the posts with thier comments
don't forget to require the modesl before running the queries const db = require("./db/models");
- what is the diffrent between running migration and using ?
db.sequelize.sync({force: true})