Although the ultimate goal of the previous post is to make a signup page for our site, it would do little good now to accept information for new users: we don’t currently have any place to put it. Thus, the first step in signing up users is to make a data structure to capture and store their information.
Database migrations
Create the database configuration with generate database command.
The analogous command for making a model is generate model, which we can use to generate a User model with name and email attributes.
Install all modules listed as dependencies in package.json
One of the results of the generate command is a new file called a migration. Migrations provide a way to alter the structure of the database incrementally, so that our data model can adapt to changing requirements. In the case of the User model, the migration is created automatically by the model generation script; it creates a user table with two columns, name and email
db/migrate/[timestamp]_create_users.js
Note that the name of the migration file is prefixed by a timestamp based on when the migration was generated. We can run the migration, known as migrating up, using the sequelize command
Creating user objects
Using node console to explore data models.
Load config file and models file
In the console session, we created a new user object with User.build
When called with no arguments, User.build returns an object with all NULL attributes. Now we created a user with name and email attributes.
User.build only creates an unsaved object. In order to save the User object to the database, we need to call the save method on the user variable.
You may have noticed that the new user object had null values for the id and the magic columns createdAt and updatedAt attributes. Let’s see if our save changed anything
We see that the id has been assigned a value of 1, while the magic columns have been assigned the current time and date. As with the User class, instances of the User model allow access to their attributes using a dot notation
We can create an user into one step with User.create
The inverse of create is destroy
Finding user objects
Sequelize provides several options for finding objects. Let’s use them to find the first user we created while verifying that the third user (foo) has been destroyed. We’ll start with the existing user
Here we’ve passed the id of the user to User.find; Sequelize returns the user with that id.
Let’s see if the user with an id of 3 still exists in the database
Since we destroyed our third user, Sequelize can’t find it in the database.
Sequelize also allows us to find users by specific attributes
Updating user objects
Once we’ve created objects, we often want to update them. There are two basic ways to do this. First, we can assign attributes individually
The second main way to update multiple attributes is to use update