MOCKSTACKS
EN
Questions And Answers

More Tutorials









NodeJS Sequelize js

Defining Models


There are two ways to define models in sequelize; with sequelize.define(...), or sequelize.import(...). Both functions return a sequelize model object.

1. sequelize.define(modelName, attributes, [options])


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
 }
});

2. sequelize.import(path)


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
}
 });
};


Conclusion

In this page (written and validated by ) you learned about NodeJS Sequelize js . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS PostgreSQL integration.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.