Sequelize is an Object-Relational Mapping (ORM) tool that simplifies data interaction by treating database entities as JavaScript objects.
-
Initialize Sequelize Project
- Run
sequelize init
to set up a new Sequelize project.
- Run
-
Configure Sequelize
- Edit the configuration file (
config/config.json
) based on your requirements, specifying database details.
- Edit the configuration file (
-
Database Creation
- Use
sequelize db:create
to create a database based on the configured settings.
- Use
-
Generate a Model
- Create a model using
sequelize model:generate --name <name>
and specify attributes using--attributes <name>:<type>
.
- Create a model using
-
Synchronizing the Model
- Use
sequelize.sync()
within an asynchronous function to sync the model with the database. Usesequelize.sync({ alter|<force>: true })
to modify the existing model.
- Use
-
Production Use and Migrations
- In production, use
sequelize db:migrate
instead ofsequelize db:create
to manage database changes. Usesequelize.authenticate()
instead of sync for authentication.
- In production, use
-
Database Cleanup
- To drop the database, run
sequelize db:drop
.
- To drop the database, run
-
Data Privacy and
toJSON
- Ensure data privacy by customizing the JSON output using
toJSON
in the model. Hide sensitive information and redefine the output format.
- Ensure data privacy by customizing the JSON output using
-
Associations
- Define relationships between models using associations. Use
belongsTo
for N->1 andhasMany
for 1<-N relationships.
- Define relationships between models using associations. Use
-
Fetching Associated Models
- Utilize
{ include: Model }
infindAll
to retrieve the full associated model with the current one. - For aliasing and specific associations, use
{ include: [{ model: User, as: 'user' }] }
and add the alias usingas
.
- Utilize
This guide was created while learning the basics of Sequelize and provides a step-by-step approach to utilizing Sequelize as an ORM with Express and Node.js, enhancing data interaction and management within your applications.