Sunteți pe pagina 1din 5

Sequelize

"migrate-test": "NODE_ENV=test sequelize db:migrate:undo:all && NODE_ENV=test sequelize


db:migrate",
"test": "npm run migrate-test && NODE_ENV=test jest --forceExit",

To create an empty project you will need to execute init command


$ node_modules/.bin/sequelize init

Creating first Model (and Migration)


Once you have properly configured CLI config file you are ready to create your first
migration. It's as simple as executing a simple command.

We will use model:generate command. This command requires two options


 name,Name of the model
 attributes, List of model attributes
Let's create a model named User.
$ node_modules/.bin/sequelize model:generate --name User --attributes
firstName:string,lastName:string,email:string

Note: Sequelize will only use Model files, it's the table representation. On the
other hand, the migration file is a change in that model or more specifically that
table, used by CLI. Treat migrations like a commit or a log for some change in
database.

Running Migrations
Until this step, we haven't inserted anything into the database. We have just created
required model and migration files for our first model User. Now to actually create that
table in database you need to run db:migrate command.
$ node_modules/.bin/sequelize db:migrate
This command will execute these steps:

 Will ensure a table called SequelizeMeta in database. This table is used


to record which migrations have run on the current database
 Start looking for any migration files which haven't run yet. This is
possible by checking SequelizeMeta table. In this case it will
run XXXXXXXXXXXXXX-create-user.jsmigration, which we created in last step.
 Creates a table called Users with all columns as specified in its
migration file.

You can use db:migrate:undo, this command will revert most recent migration.
$ node_modules/.bin/sequelize db:migrate:undo
You can revert back to initial state by undoing all migrations
with db:migrate:undo:all command. You can also revert back to a specific migration
by passing its name in --tooption.
$ node_modules/.bin/sequelize db:migrate:undo:all --to XXXXXXXXXXXXXX-create-
posts.js

Let's create a seed file which will add a demo user to our User table.
$ node_modules/.bin/sequelize seed:generate --name demo-user
This command will create a seed file in seeders folder. File name will look something
like XXXXXXXXXXXXXX-demo-user.js. It follows the same up / down semantics as the
migration files.
Now we should edit this file to insert demo user to User table.
'use strict';

module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Users', [{
firstName: 'John',
lastName: 'Doe',
email: 'demo@demo.com'
}], {});
},

down: (queryInterface, Sequelize) => {


return queryInterface.bulkDelete('Users', null, {});
}
};

Running Seeds
In last step you have create a seed file. It's still not committed to database. To do that
we need to run a simple command.
$ node_modules/.bin/sequelize db:seed:all
This
demo user inserted into User table.
Note: Seeders execution is not stored anywhere unlike migrations, which use
the SequelizeMeta table. If you wish to override this please read Storage section

2
Undoing Seeds
Seeders can be undone if they are using any storage. There are two commands
available for that:

If you wish to undo most recent seed


node_modules/.bin/sequelize db:seed:undo
If you wish to undo all seeds
node_modules/.bin/sequelize db:seed:undo:all
Models.users.findAll().

Models.users.create

 Model.bulkCreate
 Model.update
 Model.destroy

Models.book.create({
bookid: book.id,
author: book.Author,
name: book.Name,
rating: book.rating,
});

Postgres

Select database

\c testdb;

3
Timestamp:false. For no time stamps in model
FreezeTableName: prevent sequealzie to pluralise the table name

connection.sync does not update table, it just creates new one if it does not exists.
Title:{
type: Sequelize.STRING,
unique:true,
allowNull:false
validate:{
len:[10,150] // validation that it is stringlength is between 10 to 150 characters long
}
}

Above validation could be written as validate:{


Len:{
args:[10,150],
msg:’Please enter sdasdasd some error message ‘
}

Connection.sync({
Force:true, it forces the current model on database to create even if it exists, delete the
old ones and create this one.
Logging: console.log
}).then(function(){});

//To add data inside model


Users.create({
Title:’some data’,

Body:’asdjasndasnkjd’})

Build and save for creating non persistence instance of model, and then
saving it to make persistence model.

4
Create directly creates persistence model

The above two methods return promises, so we can use it in then portion,
useful thing is datavalue properties, which contains data

Whitelisting the attributes to allow updation of data, while non whitelisted


will not be allowed to change.

To insert multiple data into model, use bulkCreate([


{
Key:value,
Key:value
}
,
{}
])

S-ar putea să vă placă și