Sequelize is an Object Relational Mapper (ORM), which simplifies interacting with relational databases by abstracting away the need to use SQL directly. This lesson introduces defining models with Sequelize in Node.js.
I've preconfigured Sequelize for the database, MyDB, running on Postrest. I'm going to use the Sequelize define method to create a post model as if I'm creating a blog engine.
Define needs two arguments, the model name -- in this case "Post," and on object defining the model's attributes. The first attribute will be ID. It's type will be "Integer," and it will be a Primary Key that auto-increments.
Every blog post needs a title, and my title attribute will be a string.
My post model will need an attribute to hold content, and since I don't want content to be constrained by the 8K row limit, I'll use the blob-type text instead of string.
Lastly, I'll add a visible attribute to control whether or not the post is publicly visible, and it will default to "False."
Now that my model is defined, I need to insure the table has been created if it doesn't exist already. The sync method on the post model will handle this for me. "Sync" is an asynchronous operation. All asynchronous operations in Sequelize return promises, which means I can wait for the promise to resolve using VEN.
From here, I can go ahead and create some data to insert into my database. I'll only define title and content. The other attributes will be defaulted, and I'll use data to create a new instance of my post model, using the function "Create."
Create will not only create an instance of post, it will also perform an insert into my posts table using the data I've provided it. Once the create is complete, I'm going to print out the resulting post instance to show that it was created.
When I run the code in Node.js, I can see Sequelize has executed a "Create Table" query, a second query to describe the table, and finally an insert of the data I specified. Below that is the logged representation of the data in the posts table.
Opening the Postrest console, I run a select query on the posts table to validate that my post has been created. It's worth noting here that although I named my model post, Sequelize used the plural version, "Posts," to create the table.
Running the query shows data has been inserted into the table, and the visible field and the ID field have both been given default values.