Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js : What's the difference between sequelize.define and model.init?

Tags:

sequelize.js

The documentation doesn't explain the difference between sequelize.define and Model.init. All it says is Internally, sequelize.define calls Model.init

What things do I need to consider when choosing which one to use? What are the main differences between the two and what are the consequences for choosing one over the other? It seems like sequelize.init is the preferred method in the documentation - why is that?

like image 729
Jake Avatar asked Apr 27 '19 03:04

Jake


People also ask

What is INIT in Sequelize?

The Sequelize init() method is a method of the Model class that is used to initialize a model. A Sequelize Model represents a single table in your database. Just like you specify a table's columns in the CREATE TABLE statement, you also need to define a model's attributes in Sequelize Model.

What is Sequelize define?

Sequelize is a promise-based, Node. js ORM (Object-relational mapping) for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication, and more.

How do I require a Sequelized model?

To import Sequelize models, you need to export the model as a module first. The code above creates a new instance of the Sequelize class to connect to your database. The sequelize instance needs to be passed into the user. js model file when you call the require() function.


1 Answers

I was recently wondering the same thing when I came across this question. I did some further investigation and found some additional details explained in the documentation that may be useful here.

TL:DR

Overall, the differences are strictly related to syntax, and using sequelize.define or Model.init comes down to personal preference. I do not believe one is preferred over the other, especially since the Sequelize CLI tool generates model definitions using the sequelize.define method, and it is not explicitly stated anywhere.

Models can be defined in two equivalent ways in Sequelize:

  1. Calling sequelize.define(modelName, attributes, options) API documentation on define

  2. Extending Model and calling init(attributes, options) API documentation on init

After a model is defined, it is available within sequelize.models by its model name.

As you mentioned and as stated in the documentation:

Internally, sequelize.define calls Model.init, so both approaches are essentially equivalent.

like image 81
Dillon Avatar answered Sep 23 '22 07:09

Dillon