Sequelize is available via NPM and Yarn.
$ npm install --save sequelize
# And one of the following:
$ npm install --save pg pg-hstore
$ npm install --save mysql2
$ npm install --save sqlite3
$ npm install --save tedious
$ yarn add sequelize
# And one of the following:
$ yarn add pg pg-hstore
$ yarn add mysql2
$ yarn add sqlite3
$ yarn add tedious
Setting up a connection
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
storage: 'path/to/database.sqlite'
});
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
Test the connection
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
Your first model
const User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
}
});
User.sync({force: true}).then(() => {
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
Your first query
User.findAll().then(users => {
console.log(users)
})
Application wide model options
const sequelize = new Sequelize('connectionUri', {
define: {
timestamps: false,
freezeTableName: true,
},
});
const User = sequelize.define('user', {});
const Post = sequelize.define('post',
{
user_id:{
type: Sequelize.STRING,
primaryKey: true
},
name: Sequelize.STRING,
phone: Sequelize.STRING,
create_date: Sequelize.DATE, update_date: Sequelize.DATE
},
{
timestamps: true
}
);
Promises
User.findOne().then(user => {
console.log(user.get('firstName'));
});