There are two ways to define models in sequelize; with sequelize.define(...)
, or sequelize.import(...)
. Both functions return a sequelize model object.
This is the way to go if you'd like to define all your models in one file, or if you want to have extra control of your model definition.
/* Initialize Sequelize */ const config = { username: "database username", password: "database password", database: "database name", host: "database's host URL", dialect: "mysql" // Other options are postgres, sqlite, mariadb and mssql. } var Sequelize = require("sequelize"); var sequelize = new Sequelize(config); /* Define Models */ sequelize.define("MyModel", { name: Sequelize.STRING, comment: Sequelize.TEXT, date: { type: Sequelize.DATE, allowNull: false } });
For the documentation and more examples, check out the doclets documentation, or sequelize.com's documentation.
If your model definitions are broken into a file for each, then import
is your friend. In the file where you initialize Sequelize, you need to call import like so:
/* Initialize Sequelize */ // Check previous code snippet for initialization /* Define Models */ sequelize.import("./models/my_model.js"); // The path could be relative or absolute
Then in your model definition files, your code will look something like this:
module.exports = function(sequelize, DataTypes) { return sequelize.define("MyModel", { name: DataTypes.STRING, comment: DataTypes.TEXT, date: { type: DataTypes.DATE, allowNull: false } }); };
For more information on how to use import
, check out sequelize's express example on GitHub.