How to use the Sequelize function from sequelize

Find comprehensive JavaScript sequelize.Sequelize code examples handpicked from public code repositorys.

sequelize.Sequelize is a constructor function for creating a new Sequelize instance, which is a promise-based ORM for Node.js, MySQL, MariaDB, SQLite, Microsoft SQL Server, and PostgreSQL.

80
81
82
83
84
85
86
87
88
89
    HEROKU: process.env.HEROKU === undefined ? false : convertToBool(process.env.HEROKU),
    API_KEY: process.env.HEROKU_API_KEY === undefined ? '' : process.env.HEROKU_API_KEY,
    APP_NAME: process.env.HEROKU_APP_NAME === undefined ? '' : process.env.HEROKU_APP_NAME
},
DATABASE_URL: DATABASE_URL,
DATABASE: DATABASE_URL === './whatsasena.db' ? new Sequelize({ dialect: "sqlite", storage: DATABASE_URL, logging: DEBUG }) : new Sequelize(DATABASE_URL, { dialectOptions: { ssl: { require: true, rejectUnauthorized: false } }, logging: DEBUG }),
RBG_API_KEY: process.env.REMOVE_BG_API_KEY === undefined ? false : process.env.REMOVE_BG_API_KEY,
NO_ONLINE: process.env.NO_ONLINE === undefined ? true : convertToBool(process.env.NO_ONLINE),
SUDO: process.env.SUDO === undefined ? '919074309534,0' : process.env.SUDO,
DEBUG: DEBUG,
fork icon787
star icon121
watch icon14

+ 9 other calls in file

17
18
19
20
21
22
23
24
25
26
    defaultValue: ""
  },
  modify_time: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: Sequelize.Sequelize.literal('CURRENT_TIMESTAMP')
  }
}, {
  sequelize,
  tableName: 't_proxy_cache',
fork icon190
star icon731
watch icon55

How does sequelize.Sequelize work?

sequelize.Sequelize is a constructor function that initializes a Sequelize instance, which provides an object-relational mapping (ORM) for interacting with SQL databases. When calling new Sequelize(...), you provide configuration options such as the database name, user, password, and dialect (e.g. 'mysql', 'postgres', 'sqlite'). You can then use the Sequelize instance to define models that map to tables in your database, query and manipulate data using the model's methods, and perform other operations like migrations and seeding.

23
24
25
26
27
28
29
30
31
32

```js
const { Sequelize } = require('sequelize')

// Вариант 1: передача `URI` для подключения
const sequelize = new Sequelize('sqlite::memory:') // для `sqlite`
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // для `postgres`

// Вариант 2: передача параметров по отдельности
const sequelize = new Sequelize({
fork icon76
star icon348
watch icon12

+ 41 other calls in file

0
1
2
3
4
5
6
7
8
9
const { Sequelize } = require('sequelize');
const Op = Sequelize.Op;

const DATABASE_URI = process.env.DATABASE_URI;

const database = new Sequelize(DATABASE_URI, { logging: false });

const Torrent = database.define('torrent',
    {
      infoHash: { type: Sequelize.STRING(64), primaryKey: true },
fork icon24
star icon92
watch icon2

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
const Sequelize = require("sequelize");

const sequelize = new Sequelize("database", "username", "password", {
  host: "localhost",
  dialect: "mysql",
  logging: false,
});

// Define your models and associations here

sequelize.sync().then(() => {
  console.log("Database is synced!");
});

In this example, we first require the sequelize library and create a new instance of the Sequelize class. We provide the database name, username, password, and other options to the constructor. After creating the instance, we can define our models and associations using the sequelize.define() method. Finally, we call the sequelize.sync() method to synchronize the models with the database schema. When the synchronization is complete, the console.log() statement will be executed.

24
25
26
27
28
29
30
31
32
33
    comment: "Number of failed authentication attempts in a row"
  },
  lock_expires_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: Sequelize.Sequelize.fn('current_timestamp'),
    comment: "Lock expiration time"
  }
}, {
  sequelize,
fork icon15
star icon60
watch icon11

+ 9 other calls in file

5
6
7
8
9
10
11
12
13
14
if (bizSequelize) {
  return bizSequelize
}
// dtm_busi中存在 user_account 和 barrier两张表
// 可替换自己本地db地址
bizSequelize = new Sequelize('dtm_busi', 'root', '***', {
  host: '127.0.0.1',
  port: 3306,
  dialect: 'mysql',
})
fork icon3
star icon6
watch icon9

+ 3 other calls in file

233
234
235
236
237
238
239
240
241
242

```js
require('dotenv').config()
const { Sequelize } = require('sequelize')

const sequelize = new Sequelize(process.env.DATABASE_URL, {
  dialectOptions: {
    ssl: {
      require: true,
      rejectUnauthorized: false
fork icon0
star icon19
watch icon1

+ 11 other calls in file

24
25
26
27
28
29
30
31
32
33

### 使用 [`sequelize.define`](https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-method-define):

```js
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

const User = sequelize.define('User', {
  // 在这里定义模型属性
  firstName: {
fork icon506
star icon0
watch icon63

+ 23 other calls in file

29
30
31
32
33
34
35
36
37
38
```js
// index.js
const { Sequelize } = require('sequelize');
const { Umzug, SequelizeStorage } = require('umzug');

const sequelize = new Sequelize({ dialect: 'sqlite', storage: './db.sqlite' });

const umzug = new Umzug({
  migrations: { glob: 'migrations/*.js' },
  context: sequelize.getQueryInterface(),
fork icon149
star icon0
watch icon23

+ 7 other calls in file

1
2
3
4
5
6
7
8
9
10
import { logger } from './utils/logger'
const { Sequelize } = require('sequelize')
import { Table, Column, Model, HasMany } from 'sequelize-typescript'
require('sequelize-hierarchy-fork')(Sequelize)

const sequelize = new Sequelize(environment.databaseConnectionString, {
  logging: environment.logSQLQueries ? (sql: any) => logger.trace(sql) : false,
  pool: {
    max: 20,
    min: 1,
fork icon2
star icon6
watch icon3

175
176
177
178
179
180
181
182
183
To use the association is described as follows:

```javascript
const { Sequelize } = require('sequelize');

const sequelize = new Sequelize({...});
const MyModel1 = sequelize.import('./path/to/MyModel');
const MyModel2 = sequelize.import('./path/to/MyMode2');
...
fork icon1
star icon3
watch icon4

+ 3 other calls in file

84
85
86
87
88
89
90
91
92
93
    HEROKU: process.env.HEROKU === undefined ? false : convertToBool(process.env.HEROKU),
    API_KEY: process.env.HEROKU_API_KEY === undefined ? '' : process.env.HEROKU_API_KEY,
    APP_NAME: process.env.HEROKU_APP_NAME === undefined ? '' : process.env.HEROKU_APP_NAME
},
DATABASE_URL: DATABASE_URL,
DATABASE: DATABASE_URL === './WhiteDevil.db' ? new Sequelize({ dialect: "sqlite", storage: DATABASE_URL, logging: DEBUG }) : new Sequelize(DATABASE_URL, { dialectOptions: { ssl: { require: true, rejectUnauthorized: false } }, logging: DEBUG }),
RBG_API_KEY: process.env.REMOVE_BG_API_KEY === undefined ? false : process.env.REMOVE_BG_API_KEY, 
NO_ONLINE: process.env.NO_ONLINE === undefined ? true : convertToBool(process.env.NO_ONLINE),
SUDO: process.env.SUDO === undefined ? false : process.env.SUDO,
DEBUG: DEBUG,
fork icon172
star icon53
watch icon4

29
30
31
32
33
34
35
36
37
38
GOODBYE_MSG: process.env.GOODBYE_MSG || "Hi @user It was Nice Seeing you",
AUTHOR: process.env.AUTHOR || "Jsl",
DATABASE_URL: DATABASE_URL,
DATABASE:
  DATABASE_URL === "./lib/database.db"
    ? new Sequelize({
        dialect: "sqlite",
        storage: DATABASE_URL,
        logging: false,
      })
fork icon821
star icon45
watch icon5

57
58
59
60
61
62
63
64
65
66
#### Connecting to a Database
```js
const { Sequelize } = require('sequelize');

// Option 1: Passing a connection URI
const sequelize = new Sequelize('sqlite::memory:') // Example for sqlite
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Example for postgres

// Option 2a: Passing parameters separately (sqlite)
const sequelize = new Sequelize({
fork icon2
star icon17
watch icon2

+ 9 other calls in file

234
235
236
237
238
239
240
241
242
### Sequelize的单表操作

```js
const { Sequelize, DataTypes, Model, Op } = require('sequelize');

const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', {
  host: 'localhost',
  dialect: 'mysql'
})
fork icon2
star icon28
watch icon1

+ 7 other calls in file

140
141
142
143
144
145
146
147
148
149

### 扩展 `Model`

```js
const { Sequelize, DataTypes, Model } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory');

class User extends Model {}

User.init({
fork icon1
star icon12
watch icon3

+ 13 other calls in file

10
11
12
13
14
15
16
17
18
19
20
21
22
var { Sequelize } = require('sequelize');


var { initModels, person, item, trans_items, transaction } = require("../models/init-models");


var con_string = require('../config/keys').PostgresURI;
const sequelize = new Sequelize(con_string)
initModels(sequelize);


const { ensureAuthenticated } = require('../config/auth');

fork icon36
star icon2
watch icon5

+ 6 other calls in file

2
3
4
5
6
7
8
9
10
11
const { Sequelize, DataTypes, fn, col, literal } = require('sequelize');
const Op = Sequelize.Op;

const DATABASE_URI = process.env.DATABASE_URI;

const database = new Sequelize(
    DATABASE_URI,
    {
      logging: false
    }
fork icon24
star icon0
watch icon0