How to use sequelize

Comprehensive sequelize code examples:

How to use sequelize.TimeoutError:

18
19
20
21
22
23
24
25
26
27
match: [
  Sequelize.ConnectionError,
  Sequelize.ConnectionTimedOutError,
  Sequelize.ConnectionRefusedError,
  Sequelize.DatabaseError,
  Sequelize.TimeoutError
],
max: 3, // maximum amount of tries
timeout: 10000, // throw if no response or error within millisecond timeout
backoffBase: 3000, // Initial backoff duration in ms. Default: 100

How to use sequelize.NUMBER:

13
14
15
16
17
18
19
20
21
// BD MODEL
const Player = sequelize.define('players', {
    id: {type: Sequelize.SMALLINT, primaryKey: true},
    name: Sequelize.STRING,
    team: Sequelize.STRING,
    score: Sequelize.NUMBER
}, {
    timestamps: true
})

How to use sequelize.define:

40
41
42
43
44
45
46
47
48
49
var spaces = '  ';

_.forEach(jsonObj,function(key,val){
  test[val] = "/* mytestfile */\n\n";
  test[val] += "module.exports = function(sequelize, DataTypes) {\n";
  test[val] += spaces + "return sequelize.define('" + val + "', { \n";
  var fields = Object.keys(key.properties);
  fields.forEach(function(field, i){
    test[val] += spaces + spaces + field + ": {\n";
    var fieldAttr = Object.keys(key.properties[field]);

How to use sequelize.js:

0
1
2
3
4
5
6
7
8
---
metaTitle: "Node.js - Sequelize.js"
description: "Installation, Defining Models"
---

# Sequelize.js



How to use sequelize.Error:

16
17
18
19
20
21
22
23
24
25
26


const getPosts = async () => {
    try {
        const result = await PostRepo.getPosts();
        if(!result){
            throw new Error("fail to get posts or not found any posts");
        }
        answer = result.map((post) => {
            return convertToReadingPossibility(post)
        })

How to use sequelize.Utils:

How to use sequelize.NUMERIC:

18
19
20
21
22
23
24
25
26
27
for (let attributeName of Object.keys(joiSchema)) {
  const attribute = joiSchema[attributeName]
  if (attribute._type === 'number') {
    if (typeof attribute._flags.precision !== 'undefined') {
      this[attributeName] = {
        type: DataTypes.NUMERIC(32, attribute._flags.precision),
        allowNull: true
      }
    } else {
      this[attributeName] = {

How to use sequelize.SMALLINT:

28
29
30
31
32
33
34
35
36
37
}, 
cid: {
    type: Sequelize.STRING
}, 
level: {
    type: Sequelize.SMALLINT
}, 
rg: {
    type: Sequelize.SMALLINT
}, 

How to use sequelize.UniqueConstraintError:

149
150
151
152
153
154
155
156
157
158
const found = await User.findAll({ where, paranoid: false });
return Promise.map(users, userData => Promise.try(() => {
  const user = find(found, { email: userData.email });
  if (user && !user.deletedAt) {
    const message = this.rawAttributes.email.unique.msg;
    throw new UniqueConstraintError({ message });
  }
  if (user) {
    user.setDataValue('deletedAt', null);
    return user;

How to use sequelize.RANGE:

53
54
55
56
57
58
59
60
61
62
exports._UUIDV4    = Sequelize.UUIDV4;
exports._HSTORE    = Sequelize.HSTORE;
exports._JSON      = Sequelize.JSON;
exports._JSONB     = Sequelize.JSONB;
exports._ARRAY     = Sequelize.ARRAY;
exports._RANGE     = Sequelize.RANGE;
exports._GEOMETRY  = Sequelize.GEOMETRY;
exports._GEOGRAPHY = Sequelize.GEOGRAPHY;
exports._VIRTUAL   = Sequelize.VIRTUAL;
exports._ENUM      = function (arr) {

How to use sequelize.TIME:

44
45
46
47
48
49
50
51
52
53
exports._BOOLEAN   = Sequelize.BOOLEAN;
exports._BLOB      = Sequelize.BLOB;
exports._DATE      = Sequelize.DATE;
exports._DATE0     = Sequelize.DATE;
exports._DATEONLY  = Sequelize.DATEONLY;
exports._TIME      = Sequelize.TIME;
exports._NOW       = Sequelize.NOW;
exports._UUID      = Sequelize.UUID;
exports._UUIDV1    = Sequelize.UUIDV1;
exports._UUIDV4    = Sequelize.UUIDV4;

How to use sequelize.JSONB:

51
52
53
54
55
56
57
58
59
60
exports._UUID      = Sequelize.UUID;
exports._UUIDV1    = Sequelize.UUIDV1;
exports._UUIDV4    = Sequelize.UUIDV4;
exports._HSTORE    = Sequelize.HSTORE;
exports._JSON      = Sequelize.JSON;
exports._JSONB     = Sequelize.JSONB;
exports._ARRAY     = Sequelize.ARRAY;
exports._RANGE     = Sequelize.RANGE;
exports._GEOMETRY  = Sequelize.GEOMETRY;
exports._GEOGRAPHY = Sequelize.GEOGRAPHY;

How to use sequelize.HSTORE:

49
50
51
52
53
54
55
56
57
58
exports._TIME      = Sequelize.TIME;
exports._NOW       = Sequelize.NOW;
exports._UUID      = Sequelize.UUID;
exports._UUIDV1    = Sequelize.UUIDV1;
exports._UUIDV4    = Sequelize.UUIDV4;
exports._HSTORE    = Sequelize.HSTORE;
exports._JSON      = Sequelize.JSON;
exports._JSONB     = Sequelize.JSONB;
exports._ARRAY     = Sequelize.ARRAY;
exports._RANGE     = Sequelize.RANGE;

How to use sequelize.query:

2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
  GROUP BY year_month,sub_products.sub_pro_id
  ORDER By sub_products.sub_pro_id`;
}


const result = await sequelize.query(query, { type: QueryTypes.SELECT });

if(!result.length)
{
  res.status(500).send({

How to use sequelize.VIRTUAL:

5
6
7
8
9
10
11
12
13
14
email: {
  type: Sequelize.STRING,
  unique: true
},
password: {
  type: Sequelize.VIRTUAL
},
password_digest: {
  type: Sequelize.STRING,
},

How to use sequelize.GEOGRAPHY:

55
56
57
58
59
60
61
62
63
64
exports._JSON      = Sequelize.JSON;
exports._JSONB     = Sequelize.JSONB;
exports._ARRAY     = Sequelize.ARRAY;
exports._RANGE     = Sequelize.RANGE;
exports._GEOMETRY  = Sequelize.GEOMETRY;
exports._GEOGRAPHY = Sequelize.GEOGRAPHY;
exports._VIRTUAL   = Sequelize.VIRTUAL;
exports._ENUM      = function (arr) {
  return Sequelize.ENUM.apply(this, arr);
};

How to use sequelize.BLOB:

74
75
76
77
78
79
80
81
82
83
  sig: Sequelize.BLOB,
  signed_state: Sequelize.BLOB,

  // All the safety Byzantine checks start with cheat_
  CHEAT_profitable_state: Sequelize.BLOB,
  CHEAT_profitable_sig: Sequelize.BLOB
},
{
  indexes: [
    {

How to use sequelize.Array:

31
32
33
34
35
36
37
38
39
40
"Games",
"wordsForValidation",
{
    "type": Sequelize.JSONB,
    "field": "wordsForValidation",
    "defaultValue": Sequelize.Array
},
{
    transaction: transaction
}

How to use sequelize.JSON:

50
51
52
53
54
55
56
57
58
59
exports._NOW       = Sequelize.NOW;
exports._UUID      = Sequelize.UUID;
exports._UUIDV1    = Sequelize.UUIDV1;
exports._UUIDV4    = Sequelize.UUIDV4;
exports._HSTORE    = Sequelize.HSTORE;
exports._JSON      = Sequelize.JSON;
exports._JSONB     = Sequelize.JSONB;
exports._ARRAY     = Sequelize.ARRAY;
exports._RANGE     = Sequelize.RANGE;
exports._GEOMETRY  = Sequelize.GEOMETRY;

How to use sequelize.NOW:

45
46
47
48
49
50
51
52
53
54
  defaultValue: 'open'
},
lockedTill: {
  type: Sequelize.DATE,
  allowNull: false,
  defaultValue: Sequelize.NOW
},
lockedBy: {
  type: Sequelize.STRING
},

How to use sequelize.UUIDV1:

47
48
49
50
51
52
53
54
55
56
exports._DATE0     = Sequelize.DATE;
exports._DATEONLY  = Sequelize.DATEONLY;
exports._TIME      = Sequelize.TIME;
exports._NOW       = Sequelize.NOW;
exports._UUID      = Sequelize.UUID;
exports._UUIDV1    = Sequelize.UUIDV1;
exports._UUIDV4    = Sequelize.UUIDV4;
exports._HSTORE    = Sequelize.HSTORE;
exports._JSON      = Sequelize.JSON;
exports._JSONB     = Sequelize.JSONB;

How to use sequelize.Transaction:

48
49
50
51
52
53
54
55
56
57
// we lock the database
logger.info(`Gateway backup: Locking Database`);
// It's possible to get "Cannot start a transaction within a transaction" errors
// So we might want to retry this part a few times
await retry(async (bail, attempt) => {
  await db.sequelize.transaction({ type: Sequelize.Transaction.TYPES.IMMEDIATE }, async () => {
    logger.info(`Backup attempt n°${attempt} : Cleaning backup folder`);
    // we delete old backups
    await fse.emptyDir(this.config.backupsFolder);
    // We backup database

How to use sequelize.and:

342
343
344
345
346
347
348
349
350
351
input.TCHAT_REQUEST_Status = 'Request';
input.TCHAT_REQUEST_Created_On = new Date().toISOString().slice(0, 19).replace('T', ' ');
// input.TCHAT_REQUEST_Mobile_dateTime=req.body.TCHAT_REQUEST_Mobile_dateTime
Chatrequest.findAll({
  where: Sequelize.or(
    Sequelize.and(
      { TCHAT_REQUEST_Sender: input.TCHAT_REQUEST_Sender },
      { TCHAT_REQUEST_Receiver: input.TCHAT_REQUEST_Receiver },
      { TCHAT_REQUEST_IS_Delete: false }
    ),

How to use sequelize.UUID:

46
47
48
49
50
51
52
53
54
55
exports._DATE      = Sequelize.DATE;
exports._DATE0     = Sequelize.DATE;
exports._DATEONLY  = Sequelize.DATEONLY;
exports._TIME      = Sequelize.TIME;
exports._NOW       = Sequelize.NOW;
exports._UUID      = Sequelize.UUID;
exports._UUIDV1    = Sequelize.UUIDV1;
exports._UUIDV4    = Sequelize.UUIDV4;
exports._HSTORE    = Sequelize.HSTORE;
exports._JSON      = Sequelize.JSON;

How to use sequelize.DATEONLY:

43
44
45
46
47
48
49
50
51
52
exports._REAL1     = Sequelize.REAL;
exports._BOOLEAN   = Sequelize.BOOLEAN;
exports._BLOB      = Sequelize.BLOB;
exports._DATE      = Sequelize.DATE;
exports._DATE0     = Sequelize.DATE;
exports._DATEONLY  = Sequelize.DATEONLY;
exports._TIME      = Sequelize.TIME;
exports._NOW       = Sequelize.NOW;
exports._UUID      = Sequelize.UUID;
exports._UUIDV1    = Sequelize.UUIDV1;

How to use sequelize.or:

10
11
12
13
14
15
16
17
18
19

var keyword = req.query.keyword || '';
keyword = keyword.trim();

if(keyword != ''){
    filter = Sequelize.or(
        { AdminMemberID: { $like : '%'+keyword+'%'} },
        { AdminMemberEmail: { $like : '%'+keyword+'%'} },
        { Name1: { $like : '%'+keyword+'%'} },
        { AdminGroup: { $like : '%'+keyword+'%'} }

How to use sequelize.UUIDV4:

28
29
30
31
32
33
34
35
36
37
Users.init({
        id: {
                allowNull: false,
                primaryKey: true,
                type: Sequelize.UUID,
                defaultValue: Sequelize.UUIDV4
        },   
    email: {
        type: Sequelize.TEXT,
        allowNull: false,

How to use sequelize.CHAR:

17
18
19
20
21
22
23
24
25
26
  has_debts: {
    type: Sequelize.BOOLEAN,
    defaultValue: false
  },

  pubkey: Sequelize.CHAR(32).BINARY,

  batch_nonce: {type: Sequelize.INTEGER, defaultValue: 0}
},
{

How to use sequelize.REAL:

37
38
39
40
41
42
43
44
45
46
exports._DOUBLE0   = Sequelize.DOUBLE;
exports._DOUBLE1   = Sequelize.DOUBLE;
exports._DECIMAL   = Sequelize.DECIMAL;
exports._DECIMAL0  = Sequelize.DECIMAL;
exports._REAL      = Sequelize.REAL;
exports._REAL0     = Sequelize.REAL;
exports._REAL1     = Sequelize.REAL;
exports._BOOLEAN   = Sequelize.BOOLEAN;
exports._BLOB      = Sequelize.BLOB;
exports._DATE      = Sequelize.DATE;

How to use sequelize.TEXT:

32
33
34
35
36
37
38
39
40
41
  comment: '描述',
  field: 'description'
},
content: {
  // 内容
  type: Seq.TEXT('long'),
  comment: '内容',
  field: 'content'
},
origin_content: {