Node.jsExpressnodemon- watches file changes and restarts server automatically@babel/cli- compiles files from the command line@babel/node- compiles recent JS features down to a version that node understands@babel/preset-env- tells Babel to convert any recent feature used in the app to the target version specified in the Babel config filebody-parser- middleware that parses incoming request bodies, makes it available under thereq.bodypropertysequelize- Node.js ORM for Postgressequelize-cli- creates CLI for running Sequelize related commandspg- PostgreSQL client for Node.js; creates app's database connectionpg-hstore- serializes/deserializes JSON data tohstoreformatdotenv- gives access to node environment from the app
.babelrc- Babel config file.sequelizerc- Sequelize config file; bootstrap the app with the paths specified in the file.env- Contains all node enviroment variables
-
$ yarn add sequelize-cli sequelize pg pg-hstore
-
Create the config file called
.sequelizercin the root directory, should contain the following code:// .sequelizerc const path = require('path'); module.exports = { config: path.resolve('config', 'database.json'), 'models-path': path.resolve('db', 'models'), 'migrations-path': path.resolve('db', 'migrations') };
- Use
config/database.jsonfile for config settings - Use
db/modelsas models folder - Use
db/migrationsas migrations folder
- Use
-
$ node_modules/.bin/sequelize init
This will create an empty project by creating the corresponding folders specified in the config file.
Dependencies installed locally will use the command pattern
node_modules/.bin/sequelizeinstead of usingsequelizedirectly -
The
index.jsfile lives in models folder has the following code:// db/models/index.js ... const env = process.env.NODE_ENV || 'development'; const config = require(__dirname + '/../../config/database.json')[env]; ... if (config.use_env_variable) { sequelize = new Sequelize(process.env[config.use_env_variable], config); } else { sequelize = new Sequelize(config.database, config.username, config.password, config); } ...
The
config.use_env_variableis what needs to be setting its value with the environment variables. Also note that theconfigvariable is pointed todatabase.jsonfile in config folder, will update that file as well later.-
$ yarn add dotenv
-
// db/models/index.js require('dotenv').config();
-
// .env DATABASE_URL=postgres://username@localhost:5432/database_name
This will contain all node environment variables, for now it only contains the DB endpoint.
-
// config/database.json "development": { "use_env_variable": "DATABASE_URL" },
With all that being set,
config.use_env_variablewill now have the value of the DB endpoint ondevelopmentenvironment. -
-
The goal is to have each
Todowith multipleTodoItems.-
Create
Todomodel with the following command:$ node_modules/.bin/sequelize model:create --name Todo --attributes title:string
--namerefers to the name of the model--attributerefers to the attributes the model should have
This will generate a
todo.jsfile in the models folder and a corresponding migration file in the migration folder. -
Create
TodoItemswith the following command:$ node_modules/.bin/sequelize model:create --name TodoItem --attributes description:string
-
Create relationship between
TodoandTodoItemAdd the following code in
todo.jsfile:// db/models/todo.js ... Todo.associate = function(models) { // associations can be defined here Todo.hasMany(models.TodoItem, { foreignKey: 'todoId' }); }; ...
The
Todo.hasManysets the relationship as one-to-many. While theforeignKey: 'todoId'means thattodoIdis going to be the foreign key column inTodoItem. Let's add that:// db/models/todoitem.js ... TodoItem.associate = function(models) { // associations can be defined here TodoItem.belongsTo(models.Todo, { foreignKey: 'todoId', onDelete: 'CASCADE' }); }; ...
The
TodoItem.belongsTosets eachTodoItemto be linked to oneTodo. TheonDelete: 'CASCADE'means if aTodois deleted then the associatedTodoItemshould also be deleted. -
Modify the migration script for
TodoItemto include atodoIdfieldAdd the following code to the file:
... todoId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Todos', key: 'id', as: 'todoId', }, }, ...
modeltells which model this ForeignKey refers to
-
-
$ node_modules/.bin/sequelize db:migrate
The database should now have the tables created with the relationship being set and defined.
-
Install Postgres.app and follow setup instructions.
-
Install the postgres CLI tools.
-
Open up a new terminal window to ensure your changes have been saved.
-
Verify that it worked correctly. The
psqlshould point to the path containing the Postgres.app directory.$ which psql /Applications/Postgres.app/Contents/Versions/latest/bin/psql