You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Passing connection parameters to a Sequelize constructor
Passing a single connection URI
constSequelize=require('sequelize');// Option 1: Passing parameters separatelyconstsequelize=newSequelize('database','username','password',{host: 'localhost',dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */});// Option 2: Passing a connection URIconstsequelize=newSequelize('postgres://user:pass@example.com:5432/dbname');
Testing Connection
We use the authenticate() function to verify the connection is OK
sequelize.authenticate().then(()=>{console.log('Connection has been established successfully.');}).catch(err=>{console.error('Unable to connect to the database:',err);});
Closing a connection
Sequelize will keep the connection open by default, and use the same connection for all queries. If you need to close the connection, call sequelize.close() (which is asynchronous and returns a Promise).
Creating a model
Again, there are two ways to to define a model with Sequelize:
Finder methods are intended to query data from the database. They do not return plain objects but instead return model instances.
.find
// search for known idsProject.findByPk(123).then(project=>{// project will be an instance of Project and stores the content of the table entry// with id 123. if such an entry is not defined you will get null})// search for attributesProject.findOne({where: {title: 'aProject'}}).then(project=>{// project will be the first entry of the Projects table with the title 'aProject' || null})
Sync with Database
If you want Sequelize to automatically create the table (or modify it as needed) according to your model definition, you can use the sync method, as follows:
// Note: using `force: true` will drop the table if it already existsUser.sync({force: true}).then(()=>{// Now the `users` table in the database corresponds to the model definitionreturnUser.create({firstName: 'John',lastName: 'Hancock'});});
Note: If you want to avoid calling .sync() for every model, you can also call sequelize.sync() which will sync all models.
Querying
// Find all usersUser.findAll().then(users=>{console.log("All users:",JSON.stringify(users,null,4));});// Create a new userUser.create({firstName: "Jane",lastName: "Doe"}).then(jane=>{console.log("Jane's auto-generated ID:",jane.id);});// Delete everyone named "Jane"User.destroy({where: {firstName: "Jane"}}).then(()=>{console.log("Done");});// Change everyone without a last name to "Doe"User.update({lastName: "Doe"},{where: {lastName: null}}).then(()=>{console.log("Done");});
classTaskextendsModel{}Task.init({title: Sequelize.STRING},{ sequelize,modelName: 'task'});classUserextendsModel{}User.init({username: Sequelize.STRING},{ sequelize,modelName: 'user'});User.hasMany(Task);// Will add userId to Task modelTask.belongsTo(User);// Will also add userId to Task model
The above code will generate the following SQL:
CREATETABLEIF NOT EXISTS "users" (
"id"SERIAL,
"username"VARCHAR(255),
"createdAt"TIMESTAMP WITH TIME ZONENOT NULL,
"updatedAt"TIMESTAMP WITH TIME ZONENOT NULL,
PRIMARY KEY ("id")
);
CREATETABLEIF NOT EXISTS "tasks" (
"id"SERIAL,
"title"VARCHAR(255),
"createdAt"TIMESTAMP WITH TIME ZONENOT NULL,
"updatedAt"TIMESTAMP WITH TIME ZONENOT NULL,
"userId"INTEGERREFERENCES"users" ("id") ON DELETESETNULLONUPDATE CASCADE,
PRIMARY KEY ("id")
);
Create a CRUD API with Node, Express, & Sequelize
NPM Installs
npm install sequelize sequelize-cli pg pg-hstore
sequelize: npm library
sequelize-cli: allows us to interact with DB through sequelize
pg: postgresql client for Node.js
pg-hstore: node package for seralizing and deserializing JSON data
Create Connection
This part will be unique to your database parameters:
// takes in database name, username, passwordconstsequelize=newSequelize('class_demo','postgres','postgres',{host: 'localhost',dialect: "postgres"});sequelize.authenticate().then(()=>{console.log("Success!");}).catch((err)=>{console.log(err);});
To test database, run nodemon and see if you see a Success message.
module.exports=(sequelize,DataTypes)=>{constUser=sequelize.define('User',{name: DataTypes.STRING,email: DataTypes.STRING},{});User.associate=function(models){// associations can be defined hereUser.hasMany(models.Post,{foreignKey: 'userId',as: 'posts',onDelete: 'CASCADE',});User.hasMany(models.Comment,{foreignKey: 'userId',as: 'comments',onDelete: 'CASCADE',});};returnUser;};
/database/models/post.js
module.exports=(sequelize,DataTypes)=>{constPost=sequelize.define('Post',{title: DataTypes.STRING,content: DataTypes.TEXT,userId: DataTypes.INTEGER},{});Post.associate=function(models){// associations can be defined herePost.hasMany(models.Comment,{foreignKey: 'postId',as: 'comments',onDelete: 'CASCADE',});Post.belongsTo(models.User,{foreignKey: 'userId',as: 'author',onDelete: 'CASCADE',})};returnPost;};
/database/models/comment.js
module.exports=(sequelize,DataTypes)=>{constComment=sequelize.define('Comment',{postId: DataTypes.INTEGER,comment: DataTypes.TEXT,userId: DataTypes.INTEGER},{});Comment.associate=function(models){// associations can be defined hereComment.belongsTo(models.User,{foreignKey: 'userId',as: 'author'});Comment.belongsTo(models.Post,{foreignKey: 'postId',as: 'post'});};returnComment;};
Run Migrations
To execute the migration files, run: npx sequelize db:migrate
Seed Data
In order to populate the data with sample data, we want to run the following commands for each model:
npx sequelize seed:generate --name User
npx sequelize seed:generate --name Post
npx sequelize seed:generate --name Comment
You should see confirmation like the below figure:
Editing Seed Files
In our /seeders/ folder, we edit our seed files for each model.
/seeders/...Comment.js
module.exports={up: (queryInterface,Sequelize)=>queryInterface.bulkInsert("Comments",[{userId: 1,postId: 2,comment:
"Nulla mollis molestie lorem. Quisque ut erat. Curabitur gravida nisi at nibh.",createdAt: newDate(),updatedAt: newDate()},{userId: 2,postId: 1,comment:
"Maecenas tincidunt lacus at velit. Vivamus vel nulla eget eros elementum pellentesque. Quisque porta volutpat erat.",createdAt: newDate(),updatedAt: newDate()}],{}),down: (queryInterface,Sequelize)=>queryInterface.bulkDelete("Comments",null,{})};
/seeders/....Post.js
module.exports={up: (queryInterface,Sequelize)=>queryInterface.bulkInsert("Posts",[{userId: 1,title: "hispotan de nu",content:
"Nulla mollis molestie lorem. Quisque ut erat. Curabitur gravida nisi at nibh.",createdAt: newDate(),updatedAt: newDate()},{userId: 2,title: 'some dummy title',content:
"Maecenas tincidunt lacus at velit. Vivamus vel nulla eget eros elementum pellentesque. Quisque porta volutpat erat.",createdAt: newDate(),updatedAt: newDate()}],{}),down: (queryInterface,Sequelize)=>queryInterface.bulkDelete("Posts",null,{})};