Defining Models
suggest changeDefine models with sequelize.define(...). Sequelize 6 removed sequelize.import(). A model file should export a function, and the caller invokes it.
1. sequelize.define(modelName, attributes, [options])
Use define when the models live in one file, or when you want the definition inline.
var Sequelize = require("sequelize");
var sequelize = new Sequelize("database name", "database username", "database password", {
host: "database's host URL",
dialect: "mysql" // Other options are postgres, sqlite, mariadb, and mssql.
});
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.
2. One file per model
If each model has its own file, export a function and call it. Do not call sequelize.import(); Sequelize 6 removed it.
var defineMyModel = require("./models/my_model.js");
defineMyModel(sequelize, Sequelize);
The model file looks like this:
module.exports = function(sequelize, DataTypes) {
return sequelize.define("MyModel", {
name: DataTypes.STRING,
comment: DataTypes.TEXT,
date: {
type: DataTypes.DATE,
allowNull: false
}
});
};
The Sequelize express example shows this one-file-per-model layout.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents