Your first database model
We will use the Sequelize CLI to generate our first database model. Install it globally with the following command:
npm install -g sequelize-cli
This gives you the ability to run the sequelize command inside of your Terminal.
The Sequelize CLI allows us to generate the model automatically. This can be done by running the following command:
sequelize model:generate --models-path src/server/models --migrations-path src/server/migrations --name Post --attributes text:text
Sequelize expects us to run the command in the folder in which we have run sequelize init, by default. Our file structure is a bit different, because we have two layers with src/server. For this reason, we specify the path manually, with the first two parameters: --models-path and --migrations-path.
The --name parameter gives our model a name under which it can be used. The --attributes option specifies the fields that the model should include.
This command creates a post.js model file in your models folder, and a database migration file, named XXXXXXXXXXXXXX-create-post.js, in your migrations folder. The X is the timestamp when generating the files with the CLI. You will see how migrations work in the next section.
The following model file was created for us:
'use strict';
module.exports = (sequelize, DataTypes) => {
var Post = sequelize.define('Post', {
text: DataTypes.TEXT
}, {});
Post.associate = function(models) {
// associations can be defined here
};
return Post;
};
We are using the define Sequelize function to create a database model:
- The first parameter is the name of the database model.
- The second option is the field configuration for this model.
A post object has the id, text, and user properties. The user will be a separate model, as seen in the GraphQL schema. Consequently, we only need to configure the id and text as columns of a post.
The id is the key that uniquely identifies a data record from our database. We do not specify this when running the model:generate command, because it is generated by MySQL automatically.
The text column is just a MySQL TEXT field, which allows us to write pretty long posts. Alternatively, there are other MySQL field types, with MEDIUMTEXT, LONGTEXT, and BLOB, which could save more characters. A regular TEXT column should be fine for our use case.
The Sequelize CLI created a model file, exporting a function that, after execution, returns the real database model. You will soon see why this a great way of initializing our models.
Let's take a look at the migration file that is also created by the CLI.