CoolFace
Datasetpublic

enigmare/v2-crawler

sourceHugging Faceupdated 28d agoView on Hugging Face
1likes904downloads
sequelize.jsonl1128 linesDownload Raw Back to stackoverflow
1{"id":"stack-36906500","source":"stackoverflow","questionId":36906500,"title":"Avoid created_at and updated_at being auto generated by sequelize","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Avoid created_at and updated_at being auto generated by sequelize\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do I define a model for which created_at and updated_at are provided rather than generated?\n\nI'm importing data from somewhere that already has data for `created_at` and `updated_at` fields that I would like to preserve rather than generating whenever the object is created/updated by sequelize (our secondary store).\n\nI've tried every likely permutation of model definition and options to get this to work and still sequelize overwrites my fields with it's own timestamps: `{silent: true}`, etc...\n\nTo be clear, the input data has createdAt and updatedAt and I'd like to use sequelize's bulkCreate(), etc such that input values provided are used and stored on the model as created_at and updated_at rather than generated by sequelize.\n\nThis is my current model definition:\n\n```\nconst Lead = sequelize.define('lead', {\n objectId: {\n type: Sequelize.STRING,\n field: 'objectId',\n primaryKey: true,\n allowNull: false\n },\n firstName: {\n type: Sequelize.STRING,\n field: 'first_name'\n },\n lastName: {\n type: Sequelize.STRING,\n field: 'last_name'\n },\n phoneNumber: {\n type: Sequelize.STRING,\n field: 'phone_number'\n },\n createdAt: {\n type: Sequelize.DATE,\n field: 'created_at',\n },\n updatedAt: {\n type: Sequelize.DATE,\n field: 'updated_at'\n }\n}, {\n freezeTableName: true, // Model tableName will be the same as the model name\n timeStamps: false,\n underscored: true\n});\n```\n\n========================================\n\nCode:\n```text\nconst Lead = sequelize.define('lead', {\n  objectId: {\n    type: Sequelize.STRING,\n    field: 'objectId',\n    primaryKey: true,\n    allowNull: false\n  },\n  firstName: {\n    type: Sequelize.STRING,\n    field: 'first_name'\n  },\n  lastName: {\n    type: Sequelize.STRING,\n    field: 'last_name'\n  },\n  phoneNumber: {\n    type: Sequelize.STRING,\n    field: 'phone_number'\n  },\n  createdAt: {\n    type: Sequelize.DATE,\n    field: 'created_at',\n  },\n  updatedAt: {\n    type: Sequelize.DATE,\n    field: 'updated_at'\n  }\n}, {\n  freezeTableName: true, // Model tableName will be the same as the model name\n  timeStamps: false,\n  underscored: true\n});\n```\n\n```text\ncreated_at\n```\n\n```text\nupdated_at\n```\n\n```text\n{silent: true}\n```\n\n```text\ntimestamps: false,\n```\n\n```text\ntimestamps\n```\n\n```text\nbulkCreate()\n```\n\n========================================\n\nComments:\n- original code was: timeStamps: false, @tyler-brock you shouldn't have edited that. It gets confusing.\n- Agreed, I've changed it back, thanks!\n- Ok thank you, i tried that as well though and it still didn't work, i'll change my model definition in the question to reflect that. All of the imported rows still have the same exact createdAt and updatedAt (time of insert), instead of using the provided createdAt and updatedAt.\n- looks like i will have to submit a patch, ok then, do you know if the maintainer is pretty active?\n- the last commit is from a day ago, so they look pretty active.","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":120,"estimatedTokens":756}}2{"id":"stack-37964763","source":"stackoverflow","questionId":37964763,"title":"What does 'separate' in sequelize mean?","tags":["sequelize.js"],"text":"Title: What does 'separate' in sequelize mean?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI searched in the official docs of sequelize and couldn't find any entry about '`separate`'.https://readthedocs.org/search/?q=separate\n\nI also searched on google but in vain.\n\n```\ndb.fooTable.find({\n where: {\n id: id\n },\n include: [{\n model: db.barTable1,\n separate: true\n }, {\n model: db.barTable2,\n separate: true\n }, {\n model: db.barTable3,\n separate: true\n }]\n })\n```\n\nTo find out what it means, I set '`separate`' to false, but the result of the query were the same as to when I put '`true`' instead.\n\n========================================\n\nTop Answer:\nAdditional to @robertklep response:\n\nAs you know now it separates an **otherwise** joined query.\n\nThis means that it would be more performant in some situations where you have many joins and nested joins (can have a huge impact in some). Nested joins make Sequelize take more time in a single big query than running multiple small ones. The problem is pointed out as a deduplication operation:\n\nSee here:\nSlow associations in SequelizeJS\n\n========================================\n\nCode:\n```text\ndb.fooTable.find({\n        where: {\n            id: id\n        },\n        include: [{\n            model: db.barTable1,\n            separate: true\n        }, {\n            model: db.barTable2,\n            separate: true\n        }, {\n            model: db.barTable3,\n            separate: true\n        }]\n    })\n```\n\n```text\nseparate\n```\n\n```text\nseparate\n```\n\n```text\ntrue\n```\n\n```text\nSELECT\n  `product`.`id`,\n  `product`.`title`,\n  `tags`.`id` AS `tags.id`,\n  `tags`.`name` AS `tags.name`,\n  `tags`.`productId` AS `tags.productId`\nFROM `products` AS `product`\nLEFT OUTER JOIN `tags` AS `tags`\nON \n  `product`.`id` = `tags`.`productId`;\n```\n\n```text\nSELECT \n  `product`.`id`,\n  `product`.`title`\nFROM `products` AS `product`;\n\nSELECT\n  `id`,\n  `name`,\n  `productId`\nFROM `tags` AS `tag`\nWHERE \n  `tag`.`productId` IN (1);\n```\n\n```text\nseparate\n```\n\n```text\nProduct\n```\n\n```text\nhasMany\n```\n\n```text\nTag\n```\n\n```text\nseparate : true\n```\n\n```js\ninclude: [\n        {\n          model: user,\n          include: [{\n            model: subjects,\n            required: true,\n            separate: true,\n            where: { subjectId },\n            include: [{\n              model: Result,\n              required: true,\n              where: {\n                resultId,              \n              }\n            }],\n          }],\n          required: true,\n          where: whereClashCase\n        },\n```\n\n```text\nseparate\n```\n\n```text\nseparate: true,\n```\n\n========================================\n\nComments:\n- How can this query help us get products with some specified tags as parameters ?\n- What's the benefit? From what you've written, I can only see the downside of performance-cost because it gets partially executed on code-side instead of inside the database!?\n- @C4d see this answer for a possible reason for its existence.\n- @robertklep Thanks. What a coincidence that I ran into another issue yesterday. I had so many joins that the aliases got cutted of because of a character limitation of max 63. \"separate\" is kinda solving this too (apart from the quite new option \"minifyAliases\").\n- @C4d Sequelize has the big issue of doing a huge JOIN of everything, you can easily start including too many things, and then be querying thousands or rows when you just needed a few. Separate allows to get the same include-able benefits but with less multiplicity.","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":160,"estimatedTokens":878}}3{"id":"stack-41728023","source":"stackoverflow","questionId":41728023,"title":"Sequelize - case-insensitive like","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize - case-insensitive like\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I achieve this in Sequelize?\n\n```\nSELECT * FROM table where lower(column) LIKE ('abcd%');\n```\n\nI can't find a way to mix *lower* function with *$like*\n\n========================================\n\nTop Answer:\nYou should use Sequelize.Op :\n\n```\nTable.findAll({\n where: {\n name: {\n [Sequelize.Op.iLike]: searchQuery\n }\n }\n})\n```\n\nDon't forget to add % before or after your searchQuery, if you want to make a partial query.\n\nSee the docs here\n\n========================================\n\nCode:\n```text\nSELECT * FROM table where lower(column) LIKE ('abcd%');\n```\n\n```text\nTable.findAll({\n  attributes: ['createdAt', 'col'],\n  where: {\n    $and:[\n      {\n        createdAt:{\n          $between:[minDate, maxDate]\n        }\n      },\n      Sequelize.where(\n        Sequelize.fn('lower', Sequelize.col('col')),\n        {\n          $like: 'abcd%'\n        }\n      )\n    ]\n  }\n});\n```\n\n```text\nTable.findAll({\n    where: {\n        createdAt: {\n            $between: [minDate, maxDate]\n        },\n        someOtherColumn: {\n            $like: '%mysearchterm%'\n        }\n    }\n})\n```\n\n```text\nTable.findAll({\n    where: {\n        name: {\n            [Sequelize.Op.iLike]: searchQuery\n        }\n    }\n})\n```\n\n```text\nconst values = ['adcd'].map(x => x.toLowerCase());\n\nconst results = await SomeModel.findAll({\n   attributes: [\n      ...Object.keys(SomeModel.rawAttributes),\n      [Sequelize.fn('LOWER', Sequelize.col('someColumn')), 'lower'],\n   ],\n   having: { lower: values, },\n});\n```\n\n========================================\n\nComments:\n- I learned that in MySQL you don't need to call `lower()` on the column. `Like` is implicitly a case-insensitive search. YMMV depending on your colation/character set if it's not `utf8`.\n- Also to add on all no binary (varchar, text) string comparisons in mysql are not case sensitive at all.\n- What was the solution? the % sign?\n- The solution was the combination between `where()` and `fn()`\n- So what's the new way with... \"Unhandled rejection Error: Support for `{where: 'raw query'}` has been removed.\" ? Like many \"slightly advanced but not horrifically terrible\" things in SQL where Sequelize is in the mix, I find just spinning through and doing it long hand ends up being slower, but far more readable and maintainable when looking back at the code 6 months or a year later. :\\\n- I had to add the table name (defined in the corresponding model) in the col method : `Sequelize.col('table.col')`\n- FWIW, MySQL doesn't support ILIKE\n- This is for PG only","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":106,"estimatedTokens":651}}4{"id":"stack-26062532","source":"stackoverflow","questionId":26062532,"title":"How can I run multiple raw queries with sequelize in MySql?","tags":["mysql","node.js","sequelize.js"],"text":"Title: How can I run multiple raw queries with sequelize in MySql?\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to run a script to drop all the tables from the database before sequelize syncs via `sequelize.sync({ force: true });`\n\nThe script runs with no problems when I run it from the console, the problem happens when I try to run it from my node.js application; MySql returns a parse error.\n\n### node.js\n\n```\nvar dropAllTables = [\n 'SET FOREIGN_KEY_CHECKS = 0;',\n 'SET GROUP_CONCAT_MAX_LEN = 32768;',\n 'SET @tables = NULL;',\n \"SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables FROM information_schema.tables WHERE table_schema = (SELECT DATABASE());\",\n \"SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);\",\n \"SELECT IFNULL(@tables, 'SELECT 1') INTO @tables;\",\n 'PREPARE stmt FROM @tables;',\n 'EXECUTE stmt;',\n 'DEALLOCATE PREPARE stmt;',\n 'SET FOREIGN_KEY_CHECKS = 1;',\n \"SET GLOBAL sql_mode = 'STRICT_ALL_TABLES';\"\n].join(' ');\n\nsequelize.query(dropAllTables, {\n raw: true\n}).then(function() {\n return sequelize.sync({ force: true });\n}).then(function() {\n console.log('Database recreated!');\n callback();\n}, function(err) {\n throw err;\n});\n```\n\n### error\n\n`{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET GROUP_CONCAT_MAX_LEN = 32768; SET @tables = NULL; SELECT GROUP_CONCAT('`', t' at line 1]\n code: 'ER_PARSE_ERROR',\n errno: 1064,\n sqlState: '42000',\n index: 0,\n sql: 'SET FOREIGN_KEY_CHECKS = 0; SET GROUP_CONCAT_MAX_LEN = 32768; SET @tables = NULL; SELECT GROUP_CONCAT(\\'`\\', table_name, \\'`\\') INTO @tables FROM information_schema.tables WHERE table_schema = (SELECT DATABASE()); SET @tables = CONCAT(\\'DROP TABLE IF EXISTS \\', @tables); SELECT IFNULL(@tables, \\'SELECT 1\\') INTO @tables; PREPARE stmt FROM @tables; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET FOREIGN_KEY_CHECKS = 1; SET GLOBAL sql_mode = \\'STRICT_ALL_TABLES\\';' }`\n\nI found nothing regarding multiple raw queries with sequelize in Google nor at sequelize docs page (I looked for a specific parameter for the `query` method).\n\n### EDIT:\n\nI found this thread from an SO clone, where people seem to have the same problem but I can't figure out what the solution was.\n\n========================================\n\nTop Answer:\nDepending on the underlying mysql module being used, at least `mysql`/`mysql2` supports the `multipleStatements: true` connection setting. This will allow you to send multiple queries at once. By default it is disabled for security reasons.\n\n========================================\n\nCode:\n```text\nvar dropAllTables = [\n    'SET FOREIGN_KEY_CHECKS = 0;',\n    'SET GROUP_CONCAT_MAX_LEN = 32768;',\n    'SET @tables = NULL;',\n    \"SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables FROM information_schema.tables WHERE table_schema = (SELECT DATABASE());\",\n    \"SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);\",\n    \"SELECT IFNULL(@tables, 'SELECT 1') INTO @tables;\",\n    'PREPARE stmt FROM @tables;',\n    'EXECUTE stmt;',\n    'DEALLOCATE PREPARE stmt;',\n    'SET FOREIGN_KEY_CHECKS = 1;',\n    \"SET GLOBAL sql_mode = 'STRICT_ALL_TABLES';\"\n].join(' ');\n\nsequelize.query(dropAllTables, {\n    raw: true\n}).then(function() {\n    return sequelize.sync({ force: true });\n}).then(function() {\n    console.log('Database recreated!');\n    callback();\n}, function(err) {\n    throw err;\n});\n```\n\n```text\nsequelize.sync({ force: true });\n```\n\n```text\n{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET GROUP_CONCAT_MAX_LEN = 32768; SET @tables = NULL; SELECT GROUP_CONCAT('`', t' at line 1]\n  code: 'ER_PARSE_ERROR',\n  errno: 1064,\n  sqlState: '42000',\n  index: 0,\n  sql: 'SET FOREIGN_KEY_CHECKS = 0; SET GROUP_CONCAT_MAX_LEN = 32768; SET @tables = NULL; SELECT GROUP_CONCAT(\\'`\\', table_name, \\'`\\') INTO @tables FROM information_schema.tables WHERE table_schema = (SELECT DATABASE()); SET @tables = CONCAT(\\'DROP TABLE IF EXISTS \\', @tables); SELECT IFNULL(@tables, \\'SELECT 1\\') INTO @tables; PREPARE stmt FROM @tables; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET FOREIGN_KEY_CHECKS = 1; SET GLOBAL sql_mode = \\'STRICT_ALL_TABLES\\';' }\n```\n\n```text\nquery\n```\n\n```text\nnew Sequelize(user, pass, db, {\n  dialectOptions: {\n    multipleStatements: true\n  }\n});\n```\n\n```text\nmultipleStatements\n```\n\n```text\ndialectOptions\n```\n\n```text\nmysql\n```\n\n```text\nmysql\n```\n\n```text\nmysql2\n```\n\n```text\nmultipleStatements: true\n```\n\n```text\ndialectOptions: {\n    multipleStatements: true\n  }\n```\n\n========================================\n\nComments:\n- By the way, I got this working script from; stackoverflow.com/questions/12403662/drop-all-tables/&hellip;\n- Do you know what is the proper way to pass this parameter to the underlying MySql module? Currently I am using `\"mysql\": \"^2.2.0\"` and `\"sequelize\": \"^1.7.3\"`.\n- Also I tried uninstalling `mysql` module and installing `mysql2` as a test but it says; 'You need to install mysql package manually'.\n- you can use `dialectModulePath: 'mysql2'` parameter if you want myql2 driver and mysql dialect with sequelize\n- what would the equivalent be in sqlite?\n- Wow, thank you for this. I can't believe it isn't enabled by default.\n- Hi @janaagaardmeier , Does this mean we can send multiple SQL queries in one single network call and get result of all those queries in one single object? If so, can you please guide me through? I am working on a NodeJS app which has ~12 SQL queries which I hope to club into 1 or 2 to decrease the database requests over the network","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":153,"estimatedTokens":1419}}5{"id":"stack-39658204","source":"stackoverflow","questionId":39658204,"title":"Sequelize: how to do a WHERE condition on joined table with left outer join","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize: how to do a WHERE condition on joined table with left outer join\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy database model is as follows:\n\nAn employee drives one or zero vehicles\n\nA vehicle can be driven by one or more employees\n\nA vehicle has a model type that tells us it's fuel type amongst other things.\n\nhttps://i.sstatic.net/VCKQY.png\n\nI'd like sequelize to fetch me all employees where they don't drive a vehicle, or if they do then the vehicle is not diesel.\n\nSo where VehicleID is null OR Vehicle.VehicleModel.IsDiesel = false \n\nMy current code is as follows:\n\n```\nvar employee = sequelize.define('employee', {\n ID: Sequelize.INTEGER,\n VehicleID: Sequelize.INTEGER\n});\n\nvar vehicle = sequelize.define('vehicle', {\n ID: Sequelize.INTEGER,\n ModelID: Sequelize.INTEGER\n});\n\nvar vehicleModel = sequelize.define('vehicleModel', {\n ID: Sequelize.INTEGER,\n IsDiesel: Sequelize.BOOLEAN\n});\n\nemployee.belongsTo(vehicle);\nvehicle.belongsTo(vehicleModel);\n```\n\nIf I run the following:\n\n```\noptions.include = [{\n model: model.Vehicle,\n attributes: ['ID', 'ModelID'],\n include: [\n {\n model: model.VehicleModel,\n attributes: ['ID', 'IsDiesel']\n }]\n}];\n\nemployee\n .findAll(options)\n .success(function(results) {\n // do stuff\n });\n```\n\nSequelize does a left outer join to get me the included tables. So I get employees who drive vehicles and who don't.\n\nAs soon as I add a where to my options:\n\n```\noptions.include = [{\n model: model.Vehicle,\n attributes: ['ID', 'ModelID'],\n include: [\n {\n model: model.VehicleModel,\n attributes: ['ID', 'IsDiesel']\n where: {\n IsDiesel: false\n }\n }]\n}];\n```\n\nSequelize now does an inner join to get the included tables.\n\nThis means that I only get employees who drive a vehicle and the vehicle is not diesel. The employees who don't drive a vehicle are excluded.\n\nFundamentally, I need a way of telling Sequelize to do a left outer join and at the same time have a where condition that states the column from the joined table is false or null.\n\n**EDIT:**\n\nIt turns out that the solution was to use required: false, as below:\n\n```\noptions.include = [{\n model: model.Vehicle,\n attributes: ['ID', 'ModelID'],\n include: [\n {\n model: model.VehicleModel,\n attributes: ['ID', 'IsDiesel']\n where: {\n IsDiesel: false\n },\n required: false\n }],\n required: false\n\n}];\n```\n\nI had already tried putting the first 'required:false' but I missed out on putting the inner one. I thought it wasn't working so I gave up on that approach. Dajalmar Gutierrez's answer made me realise I needed both for it to work.\n\n========================================\n\nTop Answer:\n**Eager loading**\n\nWhen you are retrieving data from the database there is a fair chance that you also want to get **associations** with the same query - this is called **eager loading**. The basic idea behind that, is the use of the attribute include when you are calling find or findAll.\nwhen you set\n\n**required: false**\n\nwill do\n\n```\nLEFT OUTER JOIN\n```\n\nwhen\n\n**required: true**\n\nwill do\n\n```\nINNER JOIN\n```\n\nfor more detail docs.sequelizejs eager-loading\n\n========================================\n\nCode:\n```text\nvar employee = sequelize.define('employee', {\n    ID: Sequelize.INTEGER,\n    VehicleID: Sequelize.INTEGER\n});\n\nvar vehicle = sequelize.define('vehicle', {\n    ID: Sequelize.INTEGER,\n    ModelID: Sequelize.INTEGER\n});\n\nvar vehicleModel = sequelize.define('vehicleModel', {\n    ID: Sequelize.INTEGER,\n    IsDiesel: Sequelize.BOOLEAN\n});\n\nemployee.belongsTo(vehicle);\nvehicle.belongsTo(vehicleModel);\n```\n\n```text\noptions.include = [{\n    model: model.Vehicle,\n    attributes: ['ID', 'ModelID'],\n        include: [\n        {\n            model: model.VehicleModel,\n            attributes: ['ID', 'IsDiesel']\n        }]\n}];\n\nemployee\n .findAll(options)\n .success(function(results) {\n     // do stuff\n });\n```\n\n```text\noptions.include = [{\n    model: model.Vehicle,\n    attributes: ['ID', 'ModelID'],\n    include: [\n        {\n            model: model.VehicleModel,\n            attributes: ['ID', 'IsDiesel']\n            where: {\n                IsDiesel: false\n            }\n        }]\n}];\n```\n\n```text\noptions.include = [{\n    model: model.Vehicle,\n    attributes: ['ID', 'ModelID'],\n    include: [\n        {\n            model: model.VehicleModel,\n            attributes: ['ID', 'IsDiesel']\n            where: {\n                IsDiesel: false\n            },\n            required: false\n        }],\n    required: false\n\n}];\n```\n\n```text\nrequired: true\n```\n\n```text\nrequired: false\n```\n\n```text\nLEFT OUTER JOIN\n```\n\n```text\nINNER JOIN\n```\n\n========================================\n\nComments:\n- Solved. Thanks very much. I have edited my post to show the correct solution. The key sentence on the page you linked to was: \"I was including nested includes and i had missed a require: false clause in one nested include.. setting it made the code work\". After reading that I realised that I had done the same thing.","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":232,"estimatedTokens":1238}}6{"id":"stack-62667269","source":"stackoverflow","questionId":62667269,"title":"Sequelize js , how do we change column type in migration","tags":["javascript","node.js","sequelize.js","feathers-sequelize"],"text":"Title: Sequelize js , how do we change column type in migration\nTags: javascript, node.js, sequelize.js, feathers-sequelize\nSource: Stack Overflow\n\nQuestion:\nhow do we change column type in migration. In my migration 1 I have a migration that added the column. Now I want to change the column type from string to text , should I create a new migration file which is like changeColumn or I can create new migration file the same with migration 1 but I have just to change the type to text ? Thank you.\n\n#Migration 1\n\n```\nawait queryInterface.addColumn(SampleModel.tableName, 'name', {\n type: Sequelize.STRING,\n allowNull: true,\n}, {\n transaction,\n});\n```\n\n### Migration 2 (does creating new migration would work like this ? still addColumn but i change the type to text)\n\n```\nawait queryInterface.addColumn(SampleModel.tableName, 'name', {\n type: Sequelize.TEXT,\n allowNull: true,\n }, {\n transaction,\n });\n```\n\n========================================\n\nTop Answer:\nyou can use `changeColumn` instead of `addColumn` because `addColumn` will add new column in your table .\nyou can define your migration like this :\n\n***Migration File***\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return Promise.all([\n queryInterface.changeColumn('your table name ', 'name', {\n type: Sequelize.TEXT,\n allowNull: true,\n }, {\n transaction,\n })\n ])\n },\n\n down: (queryInterface, Sequelize) => {\n return Promise.all([\n queryInterface.changeColumn('your table name ', 'name', {\n type: Sequelize.STRING,\n allowNull: true,\n }, {\n transaction,\n })\n ])\n }\n};\n```\n\n========================================\n\nCode:\n```text\nawait queryInterface.addColumn(SampleModel.tableName, 'name', {\n  type: Sequelize.STRING,\n  allowNull: true,\n}, {\n  transaction,\n});\n```\n\n```text\nawait queryInterface.addColumn(SampleModel.tableName, 'name', {\n      type: Sequelize.TEXT,\n      allowNull: true,\n    }, {\n      transaction,\n    });\n```\n\n```text\nup: async (queryInterface, Sequelize) => queryInterface.sequelize.transaction(async transaction => {\n    await queryInterface.changeColumn('User', 'ip',\n      {\n        defaultValue: undefined,\n      }, { transaction }\n    );\n  })\n```\n\n```text\nERROR: Cannot read property 'toString' of undefined\n```\n\n```text\nawait queryInterface.changeColumn('User', 'ip',\n      {\n        type: Sequelize.DataTypes.STRING,\n        defaultValue: undefined,\n      }, { transaction }\n    );\n```\n\n```text\nchangeColumn\n```\n\n```text\nALTER COLUMN\n```\n\n```text\nON DELETE CASCADE\n```\n\n```text\ntype:\n```\n\n```text\ntype\n```\n\n```text\nDataTypes.STRING\n```\n\n```text\ntype.toString()\n```\n\n```text\ntype\n```\n\n```text\nchangeColumn\n```\n\n```text\naddColumn\n```\n\n```text\nmodule.exports = {\n    up: (queryInterface, Sequelize) => {\n        return Promise.all([\n            queryInterface.changeColumn('your table name ', 'name', {\n                type: Sequelize.TEXT,\n                allowNull: true,\n            }, {\n                transaction,\n            })\n        ])\n    },\n\n    down: (queryInterface, Sequelize) => {\n        return Promise.all([\n            queryInterface.changeColumn('your table name ', 'name', {\n                type: Sequelize.STRING,\n                allowNull: true,\n            }, {\n                transaction,\n            })\n        ])\n    }\n};\n```\n\n```text\nchangeColumn\n```\n\n```text\naddColumn\n```\n\n```text\naddColumn\n```\n\n========================================\n\nComments:\n- ahh so the down on the migration is type: Sequelize.STRING, ?\n- if you want to undo migration than it'll set your type as older one which is `STRING` .\n- if the column already exist bay do i still need to invoke if (!Object.keys(tableDef).includes('name')) { ?\n- Bug 2 also applies to mysql-dialect (in my case MariaDB). You just saved me from digging through that code for hours. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":192,"estimatedTokens":945}}7{"id":"stack-21949554","source":"stackoverflow","questionId":21949554,"title":"How do sequelize getter and setters work?","tags":["node.js","sequelize.js"],"text":"Title: How do sequelize getter and setters work?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**Summary of question:** Conceptually, what are getters and setters and why would we use them?\n\nExcerpt from http://docs.sequelizejs.com/en/latest/docs/models-definition/?highlight=getterMethods#getters-setters:\n\n It is possible to define 'object-property' getters and setter functions on your models, these can be used both for 'protecting' properties that map to database fields and for defining 'pseudo' properties.\n\nWhat does it mean by 'protect'? Against what?\n\nWhat are 'psuedo' properties?\n\nI'm also struggling with the example code below. We appear to be setting 'title' twice. And what is the argument 'v'?\n\nSee below:\n\n```\nvar Foo = sequelize.define('Foo', {\n title: {\n type : Sequelize.STRING,\n allowNull: false,\n }\n}, {\n\n getterMethods : {\n title : function() { /* do your magic here and return something! */ },\n title_slug : function() { return slugify(this.title); }\n },\n\n setterMethods : {\n title : function(v) { /* do your magic with the input here! */ },\n }\n});\n```\n\n**A concrete example instead of \"do magic\" would be greatly appreciated!**\n\n========================================\n\nTop Answer:\n```\n@Column({\ntype: DataType.STRING,\nset : function (this: User, value: string) {\n this.setDataValue(\"password\", cryptService.hashSync(value));\n }\n})\npassword: string;\n\nThis is the snippet which is used to store hashed password in database in \nplace of normal string.\n```\n\n========================================\n\nCode:\n```text\nvar Foo = sequelize.define('Foo', {\n  title: {\n    type     : Sequelize.STRING,\n    allowNull: false,\n  }\n}, {\n\n  getterMethods   : {\n    title       : function()  { /* do your magic here and return something! */ },\n    title_slug  : function()  { return slugify(this.title); }\n  },\n\n  setterMethods   : {\n    title       : function(v) { /* do your magic with the input here! */ },\n  }\n});\n```\n\n```text\nvar foo = sequelize.define('foo', {\n    ..\n}, {\n    getterMethods: {\n        fullName: function () {\n            return this.getDataValue('firstName') + ' ' + this.getDataValue('lastName')\n        }\n    },\n    setterMethods: {\n        fullName: function (value) {\n            var parts = value.split(' ')\n\n            this.setDataValue('lastName', parts[parts.length-1])\n            this.setDataValue('firstName', parts[0]) // this of course does not work if the user has several first names\n        }\n    }\n})\n```\n\n```text\nconsole.log(user.fullName)\n```\n\n```text\nuser.fullName = 'John Doe'\n```\n\n```text\n@Column({\ntype: DataType.STRING,\nset : function (this: User, value: string) {\n  this.setDataValue(\"password\", cryptService.hashSync(value));\n  }\n})\npassword: string;\n\nThis is the snippet which is used to store hashed password in database in \nplace of normal string.\n```\n\n========================================\n\nComments:\n- Jan, when I add a pseudo property to findAll options.attributes it fails and says that my pseudo property does not exist in the database. This makes sense to me, but I would assume that Sequelize would know this and handle it for me. Is this the intended behavior or is there a way to select psuedo properties? I guess right now every pseudo property is included by default....\n- I was curious how Sequelize would handle asynchronous getters, so I tested it out, and it works great without any extra work. If you set a getter for full name like `fullName: async function () { ... }`, and then access the attribute with `user.fullName`, Sequelize will handle the generated promises correctly without you having to use `await` while accessing the attribute. Just though I would put that here in case anyone was interested.\n- It would be great to see this with the more object-oriented style of `User.getterMethods = function() { fullname: etc }`","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":125,"estimatedTokens":958}}8{"id":"stack-16319463","source":"stackoverflow","questionId":16319463,"title":"Cleaning out test database before running tests","tags":["node.js","express","mocha.js","sequelize.js"],"text":"Title: Cleaning out test database before running tests\nTags: node.js, express, mocha.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the best way to clean out a database before running a test suite (is there a npm library or recommended method of doing this).\n\nI know about the before() function.\n\nI'm using node/express, mocha and sequelize.\n\n========================================\n\nTop Answer:\nI usually do it like this (say for a `User` model):\n\n```\ndescribe('User', function() {\n before(function(done) {\n User.sync({ force : true }) // drops table and re-creates it\n .success(function() {\n done(null);\n })\n .error(function(error) {\n done(error);\n });\n });\n\n describe('#create', function() {\n ...\n });\n});\n```\n\nThere's also `sequelize.sync({force: true})` which will drop and re-create *all* tables (`.sync()` is described here).\n\n========================================\n\nCode:\n```text\nbefore(function(done) {\n   // remove database data here\n   done()\n})\n```\n\n```text\nrequire('./globalBefore')\n// actual test 1 here\n```\n\n```text\nrequire('./globalBefore')\n// actual test 2 here\n```\n\n```text\nbefore\n```\n\n```text\nbefore\n```\n\n```text\ndescribe('User', function() {\n  before(function(done) {\n    User.sync({ force : true }) // drops table and re-creates it\n      .success(function() {\n        done(null);\n      })\n      .error(function(error) {\n        done(error);\n      });\n  });\n\n  describe('#create', function() {\n    ...\n  });\n});\n```\n\n```text\nUser\n```\n\n```text\nsequelize.sync({force: true})\n```\n\n```text\n.sync()\n```\n\n```text\nbefore(function (done) {\n   prepare.start(['people'], function () {\n      done();\n   });\n});\n\nafter(function () {\n   prepare.end();\n});\n```\n\n```text\nconst SCRIPT_TO_TRUNCATE_AND_SEED_DATABASE = 'cd apps/backend && npx sequelize-cli db:migrate:undo:all && npx sequelize-cli db:migrate && cd ../.. && npx sequelize-cli db:seed:all'\ntest(\n    'TRUNCATE_AND_SEED_DATABASE',\n    done => {\n      exec(SCRIPT_TO_TRUNCATE_AND_SEED_DATABASE, (err, out) => {\n        try {\n          console.log(out);\n          expect(err).toBe(null);\n          done();\n        } catch (e) {\n          done(e);\n        }\n      });\n    },\n    TIME_CONSTANT.ONE_MINUTE,\n  );\n```\n\n========================================\n\nComments:\n- Any modern approach to this?\n- @coler-j Sequelize uses promises nowadays, so `before(() => User.sync({ force : true }))` should work as well now (if that's what you mean by \"modern approach\" :D)\n- I was just wondering if there were any native ways to automatically wrap test cases in transactions that were built in, as it seems like a very common requirement.\n- @coler-j `before` (and also `beforeEach`) can be applied to every set of tests, so you can start a transaction before each test (of set of tests) and either commit or roll back afterwards (using `after` or `afterEach`). Mocha as a test runner doesn't deal with databases at all, so it's not a built-in feature.\n- Ok, I was just seeing in issues (like github.com/sequelize/sequelize/issues/4189 and github.com/sequelize/sequelize/issues/3888 and github.com/sequelize/sequelize/issues/4823) this that the event loop is exited when a test is completed and that it is not possible to roll back a transaction in the afterEach due to something I don't understand with CLS\n- @coler-j ah sorry, I guess I thought it was going to be easy :/ the issues you're referring to are pretty old, but I guess they still apply? Not sure if I like Sequelize to be using something like CLS, because (apparently) it can cause unexpected issues with other frameworks (Mocha in this case).\n- The library you suggested is for MongoDB but the question states sequelize.","metadata":{"transformedAt":"2026-08-18T18:33:34.330Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":135,"estimatedTokens":914}}9{"id":"stack-47215961","source":"stackoverflow","questionId":47215961,"title":"Sequelize.js: join tables without associations","tags":["join","sequelize.js"],"text":"Title: Sequelize.js: join tables without associations\nTags: join, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to join tables that don't have associations defined using `include` in sequelize? This is not a duplicate of this. I am talking about tables that are not associated at all but having columns that I want to join on.\n\nExample:\n\n```\nselect * from bank\nleft outer join account \n on account.bank_name = bank.name\n```\n\nThe above query will return all records in table `bank` regardless of the existence of an `account` record where the specified constraints apply. \n\nIn sequelize this would look something like the following, if models `bank` and `account` were associated on `account.bank_name = bank.name`:\n\n```\nbank.findAll({\n include: [{\n model: account,\n required: false,\n }]\n})\n```\n\nHowever, what if the models are not associated? Is there a way to write my own custom `on` section or equivalent:\n\n```\nbank.findAll({\n include: [{\n model: account,\n required: false,\n on: {\n bank_name: Sequelize.col('bank.name')\n }\n }]\n})\n```\n\nI vaguely remember reading something about this but I cannot seem to find that doc anywhere now. If you can point to the correct section in the docs it would be greatly appreciated.\n\n========================================\n\nTop Answer:\nIt seem that while it is possible to define a custom `on` condition, it is not possible to `include` relations without defining associations first. This is implied by the documentation wording for `findAll` method (search for `options.include` on page):\n\n A list of associations to eagerly load using a left join. Supported is either { include: [ Model1, Model2, ...]} or { include: [{ model: Model1, as: 'Alias' }]} or { include: ['Alias']}. If your association are set up with an as (eg. X.hasMany(Y, { as: 'Z }, you need to specify Z in the as attribute when eager loading Y).\n\nThe docs on `options.include[].on` are even more terse: \n\n Supply your own ON condition for the join.\n\nI ended up solving my problem using Postgres views as a workaround. It is also possible to inject a raw query and bypass sequelize limitations but I would use that only as a development / prototyping hack and come up with something more robust / secure in production; something like views or stored procedures.\n\n========================================\n\nCode:\n```sql\nselect * from bank\nleft outer join account \n    on account.bank_name = bank.name\n```\n\n```javascript\nbank.findAll({\n    include: [{\n        model: account,\n        required: false,\n    }]\n})\n```\n\n```javascript\nbank.findAll({\n    include: [{\n        model: account,\n        required: false,\n        on: {\n            bank_name: Sequelize.col('bank.name')\n        }\n    }]\n})\n```\n\n```text\ninclude\n```\n\n```text\nbank\n```\n\n```text\naccount\n```\n\n```text\nbank\n```\n\n```text\naccount\n```\n\n```text\naccount.bank_name = bank.name\n```\n\n```text\non\n```\n\n```text\nconst res = await bank.findAll({\n        include: [\n            {\n                model: account,\n                association: new HasMany(bank, account, {/*options*/}),\n            },\n        ],\n    })\n```\n\n```text\n_injectAttributes()\n```\n\n```text\non\n```\n\n```text\ninclude\n```\n\n```text\nfindAll\n```\n\n```text\noptions.include\n```\n\n```text\noptions.include[].on\n```\n\n```js\nimport { Op, literal } from \"sequelize\"\n...\nfunction innerJoinWithMyModel() {\n  // Notice that the alias is used for the tables, and not for the fields!!\n  return {\n    model: MyModel,\n    required: true,\n    on: literal(\n      \"Alias1.field1 = Alias2.field2 AND Alias1.field3 = Alias2.field4\",\n    ),\n  }\n}\n...\nfunction paginatedResults(...) {\n...\n    if (needsJoin) {\n      config.include = [\n        {\n          ...innerJoinWithMyModel(),\n          where: {\n            [Op.and]: conditions,\n          },\n        },\n      ]\n    }\n...\n  return model.findAndCountAll({\n    ...config,\n    offset: ...,\n    limit: ...,\n  })\n}\n```\n\n```text\non\n```\n\n```text\ninclude[]\n```\n\n```text\nJOIN\n```\n\n```text\non\n```\n\n```text\nlet list = await ShipmentDevice.findAll({\n          where: where_clauses,\n          include: [\n            {\n              model: Shipment,\n              association: new BelongsTo(\n                ShipmentDevice, Shipment,\n                {\n                  targetKey: \"id\",\n                  foreignKey: \"shipment_id\",\n                  constraints: false\n                }),\n              required: true\n            },\n          ]\n        });\n```\n\n========================================\n\nComments:\n- Hi, any success finding the answer. Actually I am also facing a similar situation.\n- same. Can't seem to get my head around the fact that something like this can be missing\n- But how can we construct the array of children for child tables, since we get repeated results.\n- @CoderX not sure exactly what you mean by 'repeated results', do you want to continue the discussion in Stack Overflow Chat (actually, not sure how that works either)?\n- I get the following result: `[ { \"userTime\": \"14:00\", \"id\": 1, \"name\": \"Jack\", \"Category.id\": 11, \"Category.name\": \"Category1\", \"Category.userID\": 1}, { \"userTime\": \"14:00\", \"id\": 1, \"name\": \"Jack\", \"Category.id\": 12, \"Category.name\": \"Category2\", \"Category.userID\": 1 } ]` But I want to display the result as follows: `[ { \"userTime\": \"14:00\", \"id\": 1, \"name\": \"Jack\", Category: [ { id: 11,\tname: \"Category1\", userID: 1 }, { id: 12, name: \"Category2\", userID: 1 }\t] } ]`\n- Yea, that's the problem with something like raw queries; data is going to be returned as a flat table. You'll have to hack your own conversion to JS objects or make the query / view / stored proc return json(b) values that match your expected structure. It's pretty much a mess; ok for prototyping but for production you'll need a better solution that matches the \"bigger picture\" of your project whatever it may be.\n- @AlexanderF. `I ended up solving my problem using Postgres views as a workaround.` were you able to use findAndCountAll on the view with where clause (filtering and pagination). If so, would it be possible for you to some snnipet I was trying to achieve it from 2 days and tried almost all documented methods. Thanks\n- Hey @Karabur. Thanks for your answer! Could you provide some links to docs please (or a short excerpt)? It's been a while since I had to deal with Sequelize-js so you probably have a better idea how things work now.\n- There are no docs on that, I've found that looking to sequelize code. But there is more simple and better way, you can define association and explicitly tell sequelize to not create associations in db by using `constraints: false` in association options.sequelize.org/master/class/lib/&hellip; this way you define associations in a code but not in db so you will be able to write `include` statements in a regular way, to let sequelize generate joins, but it will not create real foreign keys in db. Works in v5, dont know about v6\n- According to docs, `constraints` is supposed to do the following: `Should on update and on delete constraints be enabled on the foreign key.` I set `constraints: false` and was able to use the `hasOne` association to perform includes without actually creating the foreign keys in the database. Still, the documentation says something different about the use for `constraints`\n- I just want to build on the answer since I ran into a similar requirement. I don't know if it's due to TypeScript or sequelize version 6, but instead of `new HasMany(...)` I had to use `this.hasMany(OtherModel, {&#47;*options*&#47;}`\n- @Karabur thx a million man ... saved my day !!!! `constraints: false` is the magic pill :)\n- I wasn't sure how to use this (what options to specify), but eventually succeeded with: `association: new BelongsTo(db.tableA, db.tableB, {foreignKey: 'account', targetKey: 'account', constraints: false})`. no FK was created\n- Updated link for @Karabur 's comment: sequelize.org/master/class/src/&hellip;\n- this does not work. getting an exception: name: 'SequelizeEagerLoadingError' message: 'tableA is not associated to tableB!'","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":238,"estimatedTokens":2004}}10{"id":"stack-42352090","source":"stackoverflow","questionId":42352090,"title":"Sequelize: Find All That Match Contains (Case Insensitive)","tags":["javascript","sequelize.js"],"text":"Title: Sequelize: Find All That Match Contains (Case Insensitive)\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to use sequelize.js to query a model for records with a contains restraint. How do I do that?\n\nThis is what I have right now:\n\n```\nAssets\n .findAll({ limit: 10, where: [\"asset_name like ?\", '%' + request.body.query + '%'] })\n .then(function(assets){\n return response.json({\n msg: 'search results',\n assets: assets\n });\n })\n .catch(function(error){\n console.log(error);\n });\n```\n\nbut I get the following error:\n\n```\n{ error: operator does not exist: character varying @> unknown\n at Connection.parseE (/home/travellr/safe-star.com/SafeStar/node_modules/pg/lib/connection.js:554:11)\n at Connection.parseMessage (/home/travellr/safe-star.com/SafeStar/node_modules/pg/lib/connection.js:381:17)\n at Socket. (/home/travellr/safe-star.com/SafeStar/node_modules/pg/lib/connection.js:117:22)\n at emitOne (events.js:96:13)\n at Socket.emit (events.js:188:7)\n at readableAddChunk (_stream_readable.js:176:18)\n at Socket.Readable.push (_stream_readable.js:134:10)\n at TCP.onread (net.js:548:20)\n name: 'error',\n length: 209,\n severity: 'ERROR',\n code: '42883',\n detail: undefined,\n hint: 'No operator matches the given name and argument type(s). You might need to add explicit type casts.',\n position: '246',\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'parse_oper.c',\n line: '722',\n routine: 'op_error',\n sql: 'SELECT \"id\", \"asset_name\", \"asset_code\", \"asset_icon\", \"asset_background\", \"asset_add_view\", \"asset_add_script\", \"asset_add_id_regex\", \"date_created\", \"uniqueValue\", \"createdAt\", \"updatedAt\" FROM \"assets\" AS \"assets\" WHERE \"assets\".\"asset_name\" @> \\'%a%\\' LIMIT 10;' },\n sql: 'SELECT \"id\", \"asset_name\", \"asset_code\", \"asset_icon\", \"asset_background\", \"asset_add_view\", \"asset_add_script\", \"asset_add_id_regex\", \"date_created\", \"uniqueValue\", \"createdAt\", \"updatedAt\" FROM \"assets\" AS \"assets\" WHERE \"assets\".\"asset_name\" @> \\'%a%\\' LIMIT 10;' }\n```\n\nHow do you use a contains query in sequelize?\n\n========================================\n\nTop Answer:\nIf you are using sequlize with Postgres better to use `[Op.iLike]: `%${request.body.query}%`` and you can forget about the sequlize functions.\n\n========================================\n\nCode:\n```text\nAssets\n  .findAll({ limit: 10, where: [\"asset_name like ?\", '%' + request.body.query + '%'] })\n  .then(function(assets){\n    return response.json({\n      msg: 'search results',\n      assets: assets\n    });\n  })\n  .catch(function(error){\n    console.log(error);\n  });\n```\n\n```text\n{ error: operator does not exist: character varying @> unknown\n       at Connection.parseE (/home/travellr/safe-star.com/SafeStar/node_modules/pg/lib/connection.js:554:11)\n       at Connection.parseMessage (/home/travellr/safe-star.com/SafeStar/node_modules/pg/lib/connection.js:381:17)\n       at Socket.<anonymous> (/home/travellr/safe-star.com/SafeStar/node_modules/pg/lib/connection.js:117:22)\n       at emitOne (events.js:96:13)\n       at Socket.emit (events.js:188:7)\n       at readableAddChunk (_stream_readable.js:176:18)\n       at Socket.Readable.push (_stream_readable.js:134:10)\n       at TCP.onread (net.js:548:20)\n     name: 'error',\n     length: 209,\n     severity: 'ERROR',\n     code: '42883',\n     detail: undefined,\n     hint: 'No operator matches the given name and argument type(s). You might need to add explicit type casts.',\n     position: '246',\n     internalPosition: undefined,\n     internalQuery: undefined,\n     where: undefined,\n     schema: undefined,\n     table: undefined,\n     column: undefined,\n     dataType: undefined,\n     constraint: undefined,\n     file: 'parse_oper.c',\n     line: '722',\n     routine: 'op_error',\n     sql: 'SELECT \"id\", \"asset_name\", \"asset_code\", \"asset_icon\", \"asset_background\", \"asset_add_view\", \"asset_add_script\", \"asset_add_id_regex\", \"date_created\", \"uniqueValue\", \"createdAt\", \"updatedAt\" FROM \"assets\" AS \"assets\" WHERE \"assets\".\"asset_name\" @> \\'%a%\\' LIMIT 10;' },\n  sql: 'SELECT \"id\", \"asset_name\", \"asset_code\", \"asset_icon\", \"asset_background\", \"asset_add_view\", \"asset_add_script\", \"asset_add_id_regex\", \"date_created\", \"uniqueValue\", \"createdAt\", \"updatedAt\" FROM \"assets\" AS \"assets\" WHERE \"assets\".\"asset_name\" @> \\'%a%\\' LIMIT 10;' }\n```\n\n```text\nAssets.findAll({\n        limit: 10,\n        where: {\n            asset_name: {\n                [Op.like]: '%' + request.body.query + '%'\n            }\n        }\n}).then(function(assets){\n    return response.json({\n        msg: 'search results',\n        assets: assets\n    });\n}).catch(function(error){\n    console.log(error);\n});\n```\n\n```text\nlet lookupValue = request.body.query.toLowerCase();\n\nAssets.findAll({\n    limit: 10,\n    where: {\n        asset_name: sequelize.where(sequelize.fn('LOWER', sequelize.col('asset_name')), 'LIKE', '%' + lookupValue + '%')\n    }\n}).then(function(assets){\n    return response.json({\n        msg: 'message',\n        assets: assets\n    });\n}).catch(function(error){\n    console.log(error);\n});\n```\n\n```text\nLOWER\n```\n\n```text\nrequest.body.query\n```\n\n```text\nasset_name\n```\n\n```text\nrequest.body.query\n```\n\n```text\nsequelize.where()\n```\n\n```text\nsequelize.fn()\n```\n\n```text\nsequelize.col()\n```\n\n```text\nfindAll\n```\n\n```text\nfindOne\n```\n\n```text\nsequelize\n```\n\n```text\n[Op.iLike]: `%${request.body.query}%`\n```\n\n```text\n// search case insensitive nodejs usnig sequelize\n\n\n const sequelize = require('sequelize');\n    let search = \"Ajay PRAJAPATI\"; // what ever you right here\n    userModel.findAll({\n        where: {\n            firstname: sequelize.where(sequelize.fn('LOWER', sequelize.col('firstname')), 'LIKE', '%' + search.toLowerCase() + '%')\n        }\n    })\n```\n\n```text\nconst sequelize = require('sequelize');\n\nconst keyword = \"John\";\nUser.findAll({\n    where: {\n        firstName: { [Op.regexp]: keyword };\n    }\n})\n```\n\n========================================\n\nComments:\n- I have updated the answer, now it should be case insensitive.\n- if you're using PG, you can use `[Op.iLike]: `%${request.body.query}%`` and skip the lowercasing cruft.\n- hi @piotrbienias, what can I do when I wanna check if asset_name match with one of this string: 'bac', 'rgr', 'afg', 'rtt'. something like this: if (asset_name.match(/(bac)|(rgr)|(afg)|(rtt)/)) fetch it.\n- How would you do this with multiple columns such as %john% in first_name, last_name & email\n- [Op.like] didnt work for me due to error: OP is not defined. But this works very well: `asset_name: sequelize.where(sequelize.fn('LOWER', sequelize.col('asset_name')), 'LIKE', '%' + lookupValue + '%')`\n- Hey, will definitely try that!\n- Unfortunately, it seems like [Op.iLike] will only work if you're using Postgres sequelize.org/master/manual/model-querying-basics.html","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":227,"estimatedTokens":1724}}11{"id":"stack-16723507","source":"stackoverflow","questionId":16723507,"title":"Get last inserted id Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Get last inserted id Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize and I'm trying to get the last inserted ID in raw query.\n\nMy query is\n\n```\n.query(Sequelize.Utils.format([\"insert into MyTable (field1, field2) values (?,?)\", val1, val2])\n```\n\nThe query is done perfectly, but the result on success event is *null*.\n\nCan someone help?\n\nThanks.\n\nAfter some researches and zillions attempts, I understood how callee object work in sequelizeJs.\n\nplease, correct me if my answer is wrong.\n\nthe callee object needs this structure\n\n```\n{__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }\n```\n\nin this case \"parameterName\" is the field that will store the new ID, sequelize looks for __factory.autoIncrementField to set value of last inserted id into property with its value (value of __factory.autoIncrementField).\n\nso, my call to querys method would be\n\n```\n.query(sequelize.Utils.format(tempInsert), {__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }, {raw: true})\n```\n\nthis will result in object like that\n\n```\n{ __factory: { autoIncrementField: 'parameterName' }, parameterName: newInserted_ID }\n```\n\nthanks for all, and I hope this can help someone.\n\n========================================\n\nTop Answer:\nYou have to add **autoIncrement property** in model definition.\n\n```\nconst Article = sequelize.define('articles', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n }, {},\n {\n createdAt: false,\n updatedAt: false\n });\n```\n\nThen, you can access last inserted id with property in model definition.\n\n```\nArticle.create(article)\n .then(result => console.log(result.id));\n```\n\n========================================\n\nCode:\n```text\n.query(Sequelize.Utils.format([\"insert into MyTable (field1, field2) values (?,?)\", val1, val2])\n```\n\n```text\n{__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }\n```\n\n```text\n.query(sequelize.Utils.format(tempInsert), {__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }, {raw: true})\n```\n\n```text\n{ __factory: { autoIncrementField: 'parameterName' }, parameterName: newInserted_ID }\n```\n\n```text\nvar Sequelize = require(\"sequelize\")\nvar sequelize = new Sequelize('test', 'root', 'root', {dialect: 'mysql'})\n\nvar Page = sequelize.define( 'page', {\n  type  : {type: Sequelize.STRING(20)},\n  order : {type: Sequelize.INTEGER, defaultValue: 1}\n},{\n  timestamps: false,\n  underscored: true\n})\n\nPage.__factory = {autoIncrementField: 'id'}\nPage.id = ''\n\nsequelize.query('INSERT INTO pages SET `type` = ?, `order` = ?, `topic_version_id` = ?', Page, {raw: false}, ['TEXT', 1, 1] ).success(function(page) {\n  console.log(page)\n  Page.find(page.id)\n    .success(function(result){\n      console.log(result)\n    })\n\n})\n```\n\n```text\nconst Article = sequelize.define('articles', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  }, {},\n  {\n   createdAt: false,\n   updatedAt: false\n  });\n```\n\n```text\nArticle.create(article)\n  .then(result => console.log(result.id));\n```\n\n```text\nconst addAuthUser = await authModel.create(\n      { \n          username: username, \n          password: hashedPassword\n      });\n  if (!addAuthUser) {\n      return next(new HttpError('SignUp Failed!', 401));\n  }\n// this last inser id\n  console.log(addAuthUser.id)\n```\n\n========================================\n\nComments:\n- Did you manage to get this working? I've come across the same issue\n- I'm curious, you're setting `raw: false`, but your query is a raw query. Am I missing the purpose of the `raw` property? Could you explain why you did this?\n- so far i remember, `raw: true` will not map result into model.\n- Just getting into Sequeulize. I defined my model with a column: ``` id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }``` Yet the only way I get back the inserted ID is with your method above. This seems strange? Is there a reason this isn't documented anywhere else?\n- Just wanted to mention that now, I am able to get `id` after `save` or `create` when `id` field is defined as `id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true}`. The key part is `autoIncrement`, if you remove it you won't get back `id`.\n- I was missing this. I thought Sequelize will automatically consider primary key as auto increment column. Thanks.\n- Your answer could be improved by adding more information on what the code does and how it helps the OP.","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":155,"estimatedTokens":1118}}12{"id":"stack-55876970","source":"stackoverflow","questionId":55876970,"title":"Sequelize.js : What's the difference between sequelize.define and model.init?","tags":["sequelize.js"],"text":"Title: Sequelize.js : What's the difference between sequelize.define and model.init?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe documentation doesn't explain the difference between sequelize.define and Model.init. All it says is `Internally, sequelize.define calls Model.init`\n\nWhat things do I need to consider when choosing which one to use? What are the main differences between the two and what are the consequences for choosing one over the other? It seems like sequelize.init is the preferred method in the documentation - why is that?\n\n========================================\n\nCode:\n```text\nInternally, sequelize.define calls Model.init\n```\n\n```text\nsequelize.define\n```\n\n```text\nModel.init\n```\n\n```text\nsequelize.define\n```\n\n========================================\n\nComments:\n- The difference is merely syntactic: `Model.init` favors defining your model as a class where as `define` is a method call. The former calls the latter and there are no real functional difference between the two approaches. IMO, define your models as classes and call `init` as this seems to be the favoured approach.\n- Providing `Model.init` just giving you a sensation of OOP as per ECMAScript 2015.\n- But in typescript, both return different types.\n- Sequelize-CLI generates model definitions using .init(), extending Model. I think both work, however the issue I have is that it receives some typescript errors (even if you're not using typescript). The error doesn't break anything but it's very annoying. using define doesn't. I think it depends if you are a functional or OOP programmer.","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":35,"estimatedTokens":399}}13{"id":"stack-25102271","source":"stackoverflow","questionId":25102271,"title":"What goes in the Sequelize \"config file\"?","tags":["node.js","sequelize.js"],"text":"Title: What goes in the Sequelize \"config file\"?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm just starting out with Sequelize in Node.js and finding the documentation really lacking. I have a 'db' module in which I connect to the database via `Sequelize`, and this reads in configuration from an application-wide config file at `./config.json` relative to the root of my project. This is a nested configuration and extremely unlikely to be structured in the way that Sequelize wants a config file for the CLI.\n\nNow I'm trying to use migrations and the documentation makes reference to a \"config file\". I know I can set the path to that config file, but what the heck do I put in it? It's not documented anywhere (that I've seen).\n\n========================================\n\nTop Answer:\nThere are more things you could put into a config file:\n\n```\nvar sequelize = new Sequelize(config.database.dbName, config.database.master.user, config.database.master.password, {\n dialect: config.database.protocol,\n port: config.database.port,\n host: config.database.master.host,\n /* You could setup replication as well\n replication: {\n read: [\n {\n host: config.database.master.host,\n username: config.database.master.host,\n password: config.database.master.password\n },\n {\n host: config.database.master.host,\n username: config.database.master.host,\n password: config.database.master.password\n }\n ],\n write: {\n host: config.database.master.host,\n username: config.database.master.host,\n password: config.database.master.password\n }\n */\n },\n pool: {\n maxConnections: config.database.pool.maxConnections,\n maxIdleTime: config.database.pool.maxIdleTime\n },\n\n logging: false,\n define: {\n underscored: false,\n freezeTableName: false,\n syncOnAssociation: true,\n charset: 'utf8',\n collate: 'utf8_general_ci',\n classMethods: {method1: function() {}},\n instanceMethods: {method2: function() {}},\n timestamps: true\n schema: \"prefix\"\n }\n}),\n```\n\n========================================\n\nCode:\n```text\nSequelize\n```\n\n```text\n./config.json\n```\n\n```text\nvar config = require('./config');\n\nmodule.exports = {\n  database: config.database.name,\n  username: config.database.user,\n  password: config.database.pass,\n  dialect: 'postgres',\n  dialectModulePath: 'pg.js',\n  host: config.database.host,\n  port: config.database.port,\n  pool: config.database.pool\n};\n```\n\n```text\nvar sequelize = new Sequelize(config.database.dbName, config.database.master.user,     config.database.master.password, {\n    dialect: config.database.protocol,\n    port: config.database.port,\n    host: config.database.master.host,\n    /* You could setup replication as well\n    replication: {\n     read: [\n     {\n       host: config.database.master.host,\n       username: config.database.master.host,\n       password: config.database.master.password\n     },\n     {\n       host: config.database.master.host,\n       username: config.database.master.host,\n       password: config.database.master.password\n     }\n     ],\n     write: {\n       host: config.database.master.host,\n       username: config.database.master.host,\n       password: config.database.master.password\n     }\n     */\n    },\n    pool: {\n        maxConnections: config.database.pool.maxConnections,\n        maxIdleTime: config.database.pool.maxIdleTime\n    },\n\n    logging: false,\n    define: {\n        underscored: false,\n        freezeTableName: false,\n        syncOnAssociation: true,\n        charset: 'utf8',\n        collate: 'utf8_general_ci',\n        classMethods: {method1: function() {}},\n        instanceMethods: {method2: function() {}},\n        timestamps: true\n        schema: \"prefix\"\n    }\n}),\n```\n\n```text\noptions.host    string  \noptional\ndefault: 'localhost'\nThe host of the relational database.\n\noptions.port    number  \noptional\nThe port of the relational database.\n\noptions.username    string  \noptional\ndefault: null\nThe username which is used to authenticate against the database.\n\noptions.password    string  \noptional\ndefault: null\nThe password which is used to authenticate against the database.\n\noptions.database    string  \noptional\ndefault: null\nThe name of the database.\n\noptions.dialect string  \noptional\nThe dialect of the database you are connecting to. One of mysql, postgres, sqlite, db2, mariadb and mssql.\n\noptions.dialectModule   string  \noptional\ndefault: null\nIf specified, use this dialect library. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'require(\"pg.js\")' here\n\noptions.dialectModulePath   string  \noptional\ndefault: null\nIf specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify '/path/to/pg.js' here\n\noptions.dialectOptions  object  \noptional\nAn object of additional options, which are passed directly to the connection library\n\noptions.storage string  \noptional\nOnly used by sqlite. Defaults to ':memory:'\n\noptions.protocol    string  \noptional\ndefault: 'tcp'\nThe protocol of the relational database.\n\noptions.define  object  \noptional\ndefault: {}\nDefault options for model definitions. See Model.init.\n\noptions.query   object  \noptional\ndefault: {}\nDefault options for sequelize.query\n\noptions.schema  string  \noptional\ndefault: null\nA schema to use\n\noptions.set object  \noptional\ndefault: {}\nDefault options for sequelize.set\n\noptions.sync    object  \noptional\ndefault: {}\nDefault options for sequelize.sync\n\noptions.timezone    string  \noptional\ndefault: '+00:00'\nThe timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.\n\noptions.clientMinMessages   string | boolean    \noptional\ndefault: 'warning'\n(Deprecated) The PostgreSQL client_min_messages session parameter. Set to false to not override the database's default.\n\noptions.standardConformingStrings   boolean \noptional\ndefault: true\nThe PostgreSQL standard_conforming_strings session parameter. Set to false to not set the option. WARNING: Setting this to false may expose vulnerabilities and is not recommended!\n\noptions.logging Function    \noptional\ndefault: console.log\nA function that gets executed every time Sequelize would log something. Function may receive multiple parameters but only first one is printed by console.log. To print all values use (...msg) => console.log(msg)\n\noptions.benchmark   boolean \noptional\ndefault: false\nPass query execution time in milliseconds as second argument to logging function (options.logging).\n\noptions.omitNull    boolean \noptional\ndefault: false\nA flag that defines if null values should be passed as values to CREATE/UPDATE SQL queries or not.\n\noptions.native  boolean \noptional\ndefault: false\nA flag that defines if native library shall be used or not. Currently only has an effect for postgres\n\noptions.replication boolean \noptional\ndefault: false\nUse read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: host, port, username, password, database\n\noptions.pool    object  \noptional\nsequelize connection pool configuration\n\noptions.pool.max    number  \noptional\ndefault: 5\nMaximum number of connection in pool\n\noptions.pool.min    number  \noptional\ndefault: 0\nMinimum number of connection in pool\n\noptions.pool.idle   number  \noptional\ndefault: 10000\nThe maximum time, in milliseconds, that a connection can be idle before being released.\n\noptions.pool.acquire    number  \noptional\ndefault: 60000\nThe maximum time, in milliseconds, that pool will try to get connection before throwing error\n\noptions.pool.evict  number  \noptional\ndefault: 1000\nThe time interval, in milliseconds, after which sequelize-pool will remove idle connections.\n\noptions.pool.validate   Function    \noptional\nA function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected\n\noptions.pool.maxUses    number  \noptional\ndefault: Infinity\nThe number of times a connection can be used before discarding it for a replacement, used for eventual cluster rebalancing.\n\noptions.quoteIdentifiers    boolean \noptional\ndefault: true\nSet to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!\n\noptions.transactionType string  \noptional\ndefault: 'DEFERRED'\nSet the default transaction type. See Sequelize.Transaction.TYPES for possible options. Sqlite only.\n\noptions.isolationLevel  string  \noptional\nSet the default transaction isolation level. See Sequelize.Transaction.ISOLATION_LEVELS for possible options.\n\noptions.retry   object  \noptional\nSet of flags that control when a query is automatically retried. Accepts all options for retry-as-promised.\n\noptions.retry.match Array   \noptional\nOnly retry a query if the error matches one of these strings.\n\noptions.retry.max   number  \noptional\nHow many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.\n\noptions.typeValidation  boolean \noptional\ndefault: false\nRun built-in type validators on insert and update, and select with where clause, e.g. validate that arguments passed to integer fields are integer-like.\n\noptions.operatorsAliases    object  \noptional\nString based operator alias. Pass object to limit set of aliased operators.\n\noptions.hooks   object  \noptional\nAn object of global hook functions that are called before and after certain lifecycle events. Global hooks will run after any model-specific hooks defined for the same event (See Sequelize.Model.init() for a list). Additionally, beforeConnect(), afterConnect(), beforeDisconnect(), and afterDisconnect() hooks may be defined here.\n\noptions.minifyAliases   boolean \noptional\ndefault: false\nA flag that defines if aliases should be minified (mostly useful to avoid Postgres alias character limit of 64)\n\noptions.logQueryParameters  boolean \noptional\ndefault: false\nA flag that defines if show bind parameters in log.\n```\n\n```text\nthis.config = {\n  database: config.database,\n  username: config.username,\n  password: config.password,\n  host: config.host || this.options.host,\n  port: config.port || this.options.port,\n  pool: this.options.pool,\n  protocol: this.options.protocol,\n  native: this.options.native,\n  ssl: this.options.ssl,\n  replication: this.options.replication,\n  dialectModulePath: this.options.dialectModulePath,\n  keepDefaultTimezone: this.options.keepDefaultTimezone,\n  dialectOptions: this.options.dialectOptions\n};\n```\n\n```text\npool\n```\n\n```text\nlogging\n```\n\n```text\ndefine\n```\n\n```text\noptions\n```\n\n```text\npool\n```\n\n```text\nssl\n```\n\n```text\ndefaultTimezone\n```\n\n========================================\n\nComments:\n- github.com/sequelize/cli/blob/master/docs/README.md seems relevant.\n- So I see the \"config file\" is a js file in your example but I'm following a tutorial that tells me to name it `.sequelizerc`, shouldn't it be `.sequelizerc.js`???\n- @commonSenseCode .sequelizerc.js is not supported by Sequelize, even though its content is written in JavaScript, use .sequelizerc instead\n- Is it possible to store custom settings in there as well?\n- did you set up the define properties?\n- Links provided are not available anymore. In the config, where would the `define` go to set `paranoid: true` and `unserscored: true`\n- Hi @myselfmiqdad here is an updated link. Note this link includes an example which shows how `options.define` is itself an object: sequelize.org/api/v6/class/src/&hellip;\n- I'm trying to make it work with sequelize-cli, i have a `dbconfig.js` which is set up in `.sequelizerc` as `'config': path.resolve('src', 'dbconfig.js'),` and have the `username, password, host, etc` in the config, however, when i set up the `define` attribute, it's not picked up. Would you be familiar with the structure of it?\n- Hi @myselfmiqdad I'm not sure, but please confirm this. Can you paste me the contents of your `dbconfig.js` file? The `username` & `password` is at the *top level*, there should also be `options` property at the *top level*; inside `options` is the `define` property. Inside the `define` property are the `define` configurations...\n- I've created an issue on their GitHub: github.com/sequelize/cli/issues/1139\n- Beautiful issue @myselfmiqdad thanks for sharing","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":397,"estimatedTokens":3217}}14{"id":"stack-45437924","source":"stackoverflow","questionId":45437924,"title":"Drop and create ENUM with sequelize correctly?","tags":["node.js","postgresql","migration","sequelize.js"],"text":"Title: Drop and create ENUM with sequelize correctly?\nTags: node.js, postgresql, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow to correctly drop and then recreate ENUM type with sequelize for Postgres in migrations? For example this migration doesn't drop `enum_Users_status` enum... so any attempts to recreate/change `status` values after they have been once created fail. \n\n```\nmodule.exports = {\n up: function (queryInterface, DataTypes) {\n queryInterface.createTable('Users', {\n //...\n status: {\n type: DataTypes.ENUM,\n values: [\n 'online',\n 'offline',\n ],\n defaultValue: 'online'\n }\n //...\n })\n },\n\n down: function (queryInterface) {\n queryInterface.dropTable('Users')\n },\n}\n```\n\nEventually i did manage to delete the enum type inside `down`, but then `up` migration (which is supposed to create this `status` enum from scratch) fails, saying something like `public.enum_Users_status` enum type doesn't exist..\n\n========================================\n\nTop Answer:\nIf you want to change/edit type enum without losing data. here is my migration code. hopefully it helps.\n\n```\nqueryInterface.changeColumn('table_name', 'column_name', {\n type: Sequelize.TEXT,\n}),\n\n queryInterface.sequelize.query(`\n UPDATE table_name\n SET column_name = CASE\n WHEN column_name = 'OLD_VALUE_1' THEN 'NEW_VALUE_1'\n WHEN column_name = 'OLD_VALUE_2' THEN 'NEW_VALUE_2'\n ELSE column_name\n END\n`),\n\n queryInterface.changeColumn('table_name', 'column_name', {\n type: Sequelize.ENUM('NEW_VALUE_2', 'NEW_VALUE_2'),\n}),\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n    up: function (queryInterface, DataTypes) {\n        queryInterface.createTable('Users', {\n            //...\n            status: {\n                type: DataTypes.ENUM,\n                values: [\n                    'online',\n                    'offline',\n                ],\n                defaultValue: 'online'\n            }\n            //...\n        })\n    },\n\n    down: function (queryInterface) {\n        queryInterface.dropTable('Users')\n    },\n}\n```\n\n```text\nenum_Users_status\n```\n\n```text\nstatus\n```\n\n```text\ndown\n```\n\n```text\nup\n```\n\n```text\nstatus\n```\n\n```text\npublic.enum_Users_status\n```\n\n```js\n'use strict';\n\n/**\n * Since PostgreSQL still does not support remove values from an ENUM,\n * the workaround is to create a new ENUM with the new values and use it\n * to replace the other.\n *\n * @param {String} tableName\n * @param {String} columnName\n * @param {String} defaultValue\n * @param {Array}  newValues\n * @param {Object} queryInterface\n * @param {String} enumName - Optional.\n *\n * @return {Promise}\n */\nmodule.exports = function replaceEnum({\n  tableName,\n  columnName,\n  defaultValue,\n  newValues,\n  queryInterface,\n  enumName = `enum_${tableName}_${columnName}`\n}) {\n  const newEnumName = `${enumName}_new`;\n\n  return queryInterface.sequelize.transaction((t) => {\n    // Create a copy of the type\n    return queryInterface.sequelize.query(`\n      CREATE TYPE ${newEnumName}\n        AS ENUM ('${newValues.join('\\', \\'')}')\n    `, { transaction: t })\n      // Drop default value (ALTER COLUMN cannot cast default values)\n      .then(() => queryInterface.sequelize.query(`\n        ALTER TABLE ${tableName}\n          ALTER COLUMN ${columnName}\n            DROP DEFAULT\n      `, { transaction: t }))\n      // Change column type to the new ENUM TYPE\n      .then(() => queryInterface.sequelize.query(`\n        ALTER TABLE ${tableName}\n          ALTER COLUMN ${columnName}\n            TYPE ${newEnumName}\n            USING (${columnName}::text::${newEnumName})\n      `, { transaction: t }))\n      // Drop old ENUM\n      .then(() => queryInterface.sequelize.query(`\n        DROP TYPE ${enumName}\n      `, { transaction: t }))\n      // Rename new ENUM name\n      .then(() => queryInterface.sequelize.query(`\n        ALTER TYPE ${newEnumName}\n          RENAME TO ${enumName}\n      `, { transaction: t }))\n      .then(() => queryInterface.sequelize.query(`\n        ALTER TABLE ${tableName}\n          ALTER COLUMN ${columnName}\n            SET DEFAULT '${defaultValue}'::${enumName}\n      `, { transaction: t }));\n  });\n}\n```\n\n```js\n'use strict';\n\nconst replaceEnum = require('./utils/replace_enum');\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return replaceEnum({\n      tableName: 'invoices',\n      columnName: 'state',\n      enumName: 'enum_invoices_state',\n      defaultValue: 'created',\n      newValues: ['archived', 'created', 'paid'],\n      queryInterface\n    });\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return replaceEnum({\n      tableName: 'invoices',\n      columnName: 'state',\n      enumName: 'enum_invoices_state',\n      defaultValue: 'draft',\n      newValues: ['archived', 'draft', 'paid', 'sent'],\n      queryInterface\n    });\n  }\n};\n```\n\n```text\nutils/replace_enum.js\n```\n\n```text\nqueryInterface.changeColumn('table_name', 'column_name', {\n  type: Sequelize.TEXT,\n}),\n\n queryInterface.sequelize.query(`\n  UPDATE table_name\n  SET column_name = CASE\n    WHEN column_name = 'OLD_VALUE_1' THEN 'NEW_VALUE_1'\n    WHEN column_name = 'OLD_VALUE_2' THEN 'NEW_VALUE_2'\n    ELSE column_name\n  END\n`),\n\n queryInterface.changeColumn('table_name', 'column_name', {\n  type: Sequelize.ENUM('NEW_VALUE_2', 'NEW_VALUE_2'),\n}),\n```\n\n```text\nmodule.exports = {\n    up: function (queryInterface, DataTypes) {\n        queryInterface.createTable('Users', {\n            //...\n            status: {\n                type: DataTypes.ENUM,\n                values: [\n                    'online',\n                    'offline',\n                ],\n                defaultValue: 'online'\n            }\n            //...\n        })\n    },\n\n    down: function (queryInterface) {\n        return queryInterface.sequelize.transaction(t => {\n            return Promise.all([\n                queryInterface.dropTable('Users'),\n                queryInterface.sequelize.query('DROP TYPE IF EXISTS \"enum_Users_status\";'),\n            ]);\n        });\n    }\n};\n```\n\n```text\ndown\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    // 1. Change the type of the column to string\n    return queryInterface.changeColumn('Users', 'status', {\n      type: Sequelize.STRING,\n    })\n    // 2. Drop the enum\n    .then(() => {\n      const pgEnumDropQuery = queryInterface.QueryGenerator.pgEnumDrop('Users', 'status');\n      return queryInterface.sequelize.query(pgEnumDropQuery);\n    })\n    // 3. Create the enum with the new values\n    .then(() => {\n      return queryInterface.changeColumn('Users', 'status', {\n        type: Sequelize.ENUM,\n        values: [\n          'online',\n          'offline',\n        ],\n        defaultValue: 'online'\n      });\n    })\n  },\n\n  // Here I made the choice to restore older values but it might not work\n  // if rows were inserted with the new enum.\n  // What you want to do then is up to you. Maybe lose the enum and keep\n  // the column as a string.\n  down: (queryInterface, Sequelize) => {\n    // Do as above to restore older enum values\n    return queryInterface.changeColumn('Users', 'status', {\n      type: Sequelize.STRING,\n    }).then(() => {\n      const pgEnumDropQuery = queryInterface.QueryGenerator.pgEnumDrop('Users', 'status');\n      return queryInterface.sequelize.query(pgEnumDropQuery);\n    }).then(() => {\n      return queryInterface.changeColumn('Users', 'status', {\n        type: Sequelize.ENUM,\n        values: [\n          'older',\n          'values',\n        ],\n        defaultValue: 'older'\n      });\n    })\n  },\n}\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    await queryInterface.addColumn(\n      'users',  \n      'status', \n      {\n        type: Sequelize.ENUM,\n        values: [\n          'online',\n          'offline'  \n        ],\n        defaultValue: 'online',\n        allowNull: false,\n      }\n    )   \n  },\n\n  down: async (queryInterface) => {\n    await queryInterface.removeColumn('users', 'status')\n    .then(queryInterface.sequelize.query('DROP TYPE IF EXISTS \"enum_users_status\";'))\n  }\n};\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) =>\n    // transaction in migration reference https://sequelize.org/docs/v6/other-topics/migrations/#migration-skeleton\n    queryInterface.sequelize.transaction(async (transaction) => {\n      // convert enum type to string\n      await queryInterface.changeColumn(\n        'user',\n        'role',\n        {\n          type: Sequelize.STRING()\n        },\n        {\n          transaction\n        }\n      );\n      // drop that enum type\n      await queryInterface.sequelize.query('DROP TYPE IF EXISTS enum_user_role;', {\n        transaction\n      });\n      // again change column type to enum from string\n      await queryInterface.changeColumn(\n        'user',\n        'role',\n        {\n          type: Sequelize.ENUM('Teacher', 'Student', 'Principal', 'Monitor', 'Security')\n        },\n        {\n          transaction\n        }\n      );\n    }),\n\n  down: (queryInterface, Sequelize) =>\n    // using transaction\n    queryInterface.sequelize.transaction(async (transaction) => {\n      await queryInterface.changeColumn(\n        'user',\n        'role',\n        {\n          type: Sequelize.STRING()\n        },\n        {\n          transaction\n        }\n      );\n      await queryInterface.sequelize.query('DROP TYPE IF EXISTS enum_user_role;', {\n        transaction\n      });\n      await queryInterface.changeColumn(\n        'user',\n        'role',\n        {\n          type: Sequelize.ENUM(\n            'Teacher',\n            'Student',\n            'Principal',\n            'Monitor',\n            'Security',\n            'Super Admin',\n            'Volunteers',\n            'Billing',\n            'Admin'\n          )\n        },\n        {\n          transaction\n        }\n      );\n    })\n};\n```\n\n========================================\n\nComments:\n- How do I add an enum without a defaultValue?\n- @Vaulstein you can just omit the `defaultValue` option.\n- Hey @Abel tried that, doesn't work. Will error message\n- @AbelOsorio can you the error and resolutions for that?\n- If you have case sensitive table / column names, remember to use \" \" around the enum name - otherwise you'll get the `type does not exist` error.\n- I think it's better to use 'DROP TYPE IF EXISTS'\n- you are dropping all the table here\n- The other answers focus on how to replace enum. this one is more close to the question.","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":414,"estimatedTokens":2591}}15{"id":"stack-34268597","source":"stackoverflow","questionId":34268597,"title":"sequelize.js - Find by id and return result","tags":["node.js","sequelize.js"],"text":"Title: sequelize.js - Find by id and return result\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a function,\n\n```\nvar findUserDevice = function(userDeviceId){\n\n var device = db.DeviceUser.find({\n where: {\n id: userDeviceId\n }\n }).then(function(device) {\n if (!device) {\n return 'not find';\n }\n return device.dataValues;\n });\n};\n```\n\nbut this function does not return anything...\n\n```\nvar UserDevice = findUserDevice(req.body.deviceUserId);\nconsole.log(UserDevice);// undefined\n```\n\n========================================\n\nTop Answer:\nIt's 2020, `async` & `await` are becoming more popular. You can change your code to:\n\n```\nconst findUserDevice = async function (userDeviceId) {\n const device = await db.DeviceUser.findOne({\n where: {\n id: userDeviceId\n }\n });\n if (device === null) {\n return 'device not found';\n }\n return device.dataValues;\n};\n\n (async () => {\n // ...\n const UserDevice = await findUserDevice(req.body.deviceUserId);\n console.log(UserDevice);\n // ...\n })()\n```\n\nIMHO, the code above is way more readable.\n\n========================================\n\nCode:\n```text\nvar findUserDevice = function(userDeviceId){\n\n    var device = db.DeviceUser.find({\n        where: {\n            id: userDeviceId\n        }\n    }).then(function(device) {\n        if (!device) {\n            return 'not find';\n        }\n        return device.dataValues;\n    });\n};\n```\n\n```text\nvar UserDevice = findUserDevice(req.body.deviceUserId);\nconsole.log(UserDevice);// undefined\n```\n\n```text\nvar findUserDevice = function(userDeviceId){\n    // return the promise itself\n    return db.DeviceUser.find({\n        where: {\n           id: userDeviceId\n        }\n     }).then(function(device) {\n        if (!device) {\n            return 'not find';\n        }\n        return device.dataValues;\n     });\n};\n```\n\n```text\nfindUserDevice(req.body.deviceUserId).then( function(UserDevice) {\n   console.log(UserDevice);\n});\n```\n\n```text\nasync\n```\n\n```text\nsequelize\n```\n\n```text\nvar device = db.DeviceUser.findById(userDeviceId).then(function(device) {\n  if (!device) {\n    return 'not find';\n  }\n  return device.dataValues;\n});\n```\n\n```text\ndevice\n```\n\n```text\ndevice\n```\n\n```text\ndevice.id\n```\n\n```text\nfindById()\n```\n\n```js\nconst findUserDevice = async function (userDeviceId) {\n  const device = await db.DeviceUser.findOne({\n    where: {\n      id: userDeviceId\n    }\n  });\n  if (device === null) {\n    return 'device not found';\n  }\n  return device.dataValues;\n};\n\n (async () => {\n    // ...\n    const UserDevice = await findUserDevice(req.body.deviceUserId);\n    console.log(UserDevice);\n    // ...\n  })()\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\nconst  { customer }  = require('../models');\n\nconst get = async function(req, res){\n    let id = req.params.id;\n\n    [err, singleCustomer] = await to(customer.findByPk(id, { raw : true }));\n\n    return ReS(res, { message :'Obtener cliente: : ', data : JSON.stringify(singleCustomer) });\n}\n```\n\n========================================\n\nComments:\n- A note on Promises from the Sequelize documentation: docs.sequelizejs.com/manual/installation/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":182,"estimatedTokens":778}}16{"id":"stack-29716346","source":"stackoverflow","questionId":29716346,"title":"How to create a TRIGGER in SEQUELIZE (nodeJS)?","tags":["mysql","node.js","triggers","sequelize.js"],"text":"Title: How to create a TRIGGER in SEQUELIZE (nodeJS)?\nTags: mysql, node.js, triggers, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a trigger using sequelize.. the main idea is to create an instance of `CONFIG` after creating a `USER`.\n\n```\n// USER MODEL\nmodule.exports = function(sequelize, DataTypes) { \n var User = sequelize.define('User', {\n name : DataTypes.STRING(255),\n email : DataTypes.STRING(255),\n username : DataTypes.STRING(45),\n password : DataTypes.STRING(100),\n }, {\n classMethods : {\n associate : function(models) {\n User.hasOne(models.Config)\n }\n }\n }); \n return User;\n};\n\n// CONFIG MODEL\nmodule.exports = function(sequelize, DataTypes) {\n var Config = sequelize.define('Config', {\n notifications : DataTypes.INTEGER\n }, {\n classMethods : {\n associate : function(models) {\n Config.belongsTo(models.User)\n }\n }\n });\n\n return Config;\n};\n```\n\nAs you can see, a \"user\" has one \"config\" and a \"config\" belongs to a \"user\", so after a user is created I want to create his config row automatically.\n\nThe goal is to do:\n\n```\nDELIMITER //\nCREATE TRIGGER create_config AFTER INSERT ON user\n FOR EACH ROW\nBEGIN\n insert into config (user_id) values(new.user_id);\nEND; //\nDELIMITER ;\n```\n\nNow, what I do to simulate that is the following:\n\n```\n.then(function(user){\n return dao.Config.create(req.body, user, t);\n})\n```\n\nOnce a User is created I create his configuration like that... it works but is not what I'm searching.\n\nHow would I do it?\n\n========================================\n\nTop Answer:\nA small warning about the answer of Evan: a trigger and a sequelize hook are not the same thing. The trigger lives entirely inside the database, while the sequelize hook lives entirely in JS. Therefore the (after) hooks can only work on the output of the MySQL command, while triggers can use all rows you are inserting, updating or deleting.\n\nThis is especially important if you want to update in bulk. Since an `UPDATE` statement does not return the ids of updated rows, sequelize hooks can only respond to a single update:\n\n```\n// This way the afterUpdate hook is triggered\nconst instance = UserModel.findOne(...);\ninstance.update(...);\n\n// This way the afterBulkUpdate hook is triggered instead,\n// where affected model are not directly available\nUserModel.update({where: {id: 1} });\n```\n\nA trigger defined in the database would respond to both statements. Check the docs to see if you are getting all affected items in the callback.\n\n========================================\n\nCode:\n```text\n// USER MODEL\nmodule.exports = function(sequelize, DataTypes) {    \n    var User = sequelize.define('User', {\n        name        : DataTypes.STRING(255),\n        email       : DataTypes.STRING(255),\n        username    : DataTypes.STRING(45),\n        password    : DataTypes.STRING(100),\n    }, {\n        classMethods : {\n            associate : function(models) {\n                User.hasOne(models.Config)\n            }\n        }\n    });    \n    return User;\n};\n\n// CONFIG MODEL\nmodule.exports = function(sequelize, DataTypes) {\n    var Config = sequelize.define('Config', {\n        notifications   : DataTypes.INTEGER\n    }, {\n        classMethods : {\n            associate : function(models) {\n                Config.belongsTo(models.User)\n            }\n        }\n    });\n\n    return Config;\n};\n```\n\n```text\nDELIMITER //\nCREATE TRIGGER create_config AFTER INSERT ON user\n  FOR EACH ROW\nBEGIN\n    insert into config    (user_id)     values(new.user_id);\nEND; //\nDELIMITER ;\n```\n\n```text\n.then(function(user){\n   return dao.Config.create(req.body, user, t);\n})\n```\n\n```text\nCONFIG\n```\n\n```text\nUSER\n```\n\n```text\nsequelize.query('CREATE TRIGGER create_config AFTER INSERT ON users' +\n  ' FOR EACH ROW' +\n  ' BEGIN' +\n  ' insert into configs (UserId) values(new.id);' +\n  'END;')\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {    \n  var User = sequelize.define('User', {\n    name        : DataTypes.STRING(255),\n    email       : DataTypes.STRING(255),\n    username    : DataTypes.STRING(45),\n    password    : DataTypes.STRING(100),\n  }, {\n    classMethods : {\n      associate : function(models) {\n        User.hasOne(models.Config)\n      }\n    },\n    hooks: {\n      afterCreate: function(user, options) {\n        models.Config.create({\n          UserId: user.id\n        })\n      }\n    }\n  });\n  return User;\n};\n```\n\n```text\nafterCreate\n```\n\n```text\nimport { Sequelize } from \"sequelize\";\n\nconst sequelize = new Sequelize({  host: \"localhost\",\n                                   port: 3306,\n                                   dialect: \"MySQL\",\n                                   username: \"your user name\",\n                                   password: \"your password\",\n                                   database: \"dbname\",\n                                   logging: false,});\n\nsequelize.query('CREATE TRIGGER create_config AFTER INSERT ON users' +\n  ' FOR EACH ROW' +\n  ' BEGIN' +\n  ' insert into configs (UserId) values(new.id);' +\n  'END;')\n```\n\n```text\nawait sequelize.sync()\nawait createTrigger(sequelize, Post, 'insert', `UPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\"`)\nawait createTrigger(sequelize, Post, 'delete', `UPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\"`)\nawait createTrigger(\n  sequelize,\n  Post,\n  'update',\n  `UPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\";\nUPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\"`,\n  {\n    when: 'OLD.\"UserId\" <> NEW.\"UserId\"',\n  }\n)\n```\n\n```text\n// on: lowercase 'insert', 'delete' or 'update'\nasync function createTrigger(sequelize, model, on, action, { after, when, nameExtra } = {}) {\n  if (after === undefined) {\n    after = 'AFTER'\n  }\n  if (nameExtra) {\n    nameExtra = `_${nameExtra})`\n  } else {\n    nameExtra = ''\n  }\n  const oldnew = on === 'delete' ? 'OLD' : 'NEW'\n  const triggerName = `${model.tableName}_${on}${nameExtra}`\n  if (when) {\n    when = `\\n  WHEN (${when})`\n  } else {\n    when = ''\n  }\n  if (sequelize.options.dialect === 'postgres') {\n    const functionName = `${triggerName}_fn`\n    await sequelize.query(`CREATE OR REPLACE FUNCTION \"${functionName}\"()\n  RETURNS TRIGGER\n  LANGUAGE PLPGSQL\n  AS\n$$\nBEGIN\n  ${action};\n  RETURN ${oldnew};\nEND;\n$$\n`)\n    // CREATE OR REPLACE TRIGGER was only added on postgresql 14 so let's be a bit more portable for now:\n    // https://stackoverflow.com/questions/35927365/create-or-replace-trigger-postgres\n    await sequelize.query(`DROP TRIGGER IF EXISTS ${triggerName} ON \"${model.tableName}\"`)\n    await sequelize.query(`CREATE TRIGGER ${triggerName}\n  ${after} ${on.toUpperCase()}\n  ON \"${model.tableName}\"\n  FOR EACH ROW${when}\n  EXECUTE PROCEDURE \"${functionName}\"();\n`)\n  } else if (sequelize.options.dialect === 'sqlite') {\n    await sequelize.query(`\nCREATE TRIGGER IF NOT EXISTS ${triggerName}\n  ${after} ${on.toUpperCase()}\n  ON \"${model.tableName}\"\n  FOR EACH ROW${when}\n  BEGIN\n    ${action};\n  END;\n`)\n  }\n}\n```\n\n```text\nconst path = require('path')\nconst { DataTypes } = require('sequelize')\nconst common = require('./common')\nconst sequelize = common.sequelize(__filename, process.argv[2])\nconst force = process.argv.length <= 3 || process.argv[3] !== '0'\n;(async () => {\n\n// on: lowercase 'insert', 'delete' or 'update'\nasync function createTrigger(sequelize, model, on, action, { after, when, nameExtra } = {}) {\n  if (after === undefined) {\n    after = 'AFTER'\n  }\n  if (nameExtra) {\n    nameExtra = `_${nameExtra})`\n  } else {\n    nameExtra = ''\n  }\n  const oldnew = on === 'delete' ? 'OLD' : 'NEW'\n  const triggerName = `${model.tableName}_${on}${nameExtra}`\n  if (when) {\n    when = `\\n  WHEN (${when})`\n  } else {\n    when = ''\n  }\n  if (sequelize.options.dialect === 'postgres') {\n    const functionName = `${triggerName}_fn`\n    await sequelize.query(`CREATE OR REPLACE FUNCTION \"${functionName}\"()\n  RETURNS TRIGGER\n  LANGUAGE PLPGSQL\n  AS\n$$\nBEGIN\n  ${action};\n  RETURN ${oldnew};\nEND;\n$$\n`)\n    // CREATE OR REPLACE TRIGGER was only added on postgresql 14 so let's be a bit more portable for now:\n    // https://stackoverflow.com/questions/35927365/create-or-replace-trigger-postgres\n    await sequelize.query(`DROP TRIGGER IF EXISTS ${triggerName} ON \"${model.tableName}\"`)\n    await sequelize.query(`CREATE TRIGGER ${triggerName}\n  ${after} ${on.toUpperCase()}\n  ON \"${model.tableName}\"\n  FOR EACH ROW${when}\n  EXECUTE PROCEDURE \"${functionName}\"();\n`)\n  } else if (sequelize.options.dialect === 'sqlite') {\n    await sequelize.query(`\nCREATE TRIGGER IF NOT EXISTS ${triggerName}\n  ${after} ${on.toUpperCase()}\n  ON \"${model.tableName}\"\n  FOR EACH ROW${when}\n  BEGIN\n    ${action};\n  END;\n`)\n  }\n}\n\nconst Post = sequelize.define('Post', {\n  title: { type: DataTypes.STRING },\n});\nconst User = sequelize.define('User', {\n  username: { type: DataTypes.STRING },\n  postCount: { type: DataTypes.INTEGER },\n});\nUser.hasMany(Post)\nPost.belongsTo(User)\nawait sequelize.sync({ force })\nawait createTrigger(sequelize, Post, 'insert', `UPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\"`)\nawait createTrigger(sequelize, Post, 'delete', `UPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\"`)\nawait createTrigger(\n  sequelize,\n  Post,\n  'update',\n  `UPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\";\nUPDATE \"${User.tableName}\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\"`,\n  {\n    when: 'OLD.\"UserId\" <> NEW.\"UserId\"',\n  }\n)\n\nasync function reset() {\n  const user0 = await User.create({ username: 'user0', postCount: 0 });\n  const user1 = await User.create({ username: 'user1', postCount: 0 });\n  await Post.create({ title: 'user0 post0', UserId: user0.id });\n  await Post.create({ title: 'user0 post1', UserId: user0.id });\n  await Post.create({ title: 'user1 post0', UserId: user1.id });\n  return [user0, user1]\n}\nlet rows, user0, user1\n[user0, user1] = await reset()\n\n// Check that the posts created increased postCount for users.\nrows = await User.findAll({ order: [['username', 'ASC']] })\ncommon.assertEqual(rows, [\n  { username: 'user0', postCount: 2 },\n  { username: 'user1', postCount: 1 },\n])\n\n// UPDATE the author of a post and check counts again.\nawait Post.update({ UserId: user1.id }, { where: { title: 'user0 post1' } })\nrows = await User.findAll({ order: [['username', 'ASC']] })\ncommon.assertEqual(rows, [\n  { username: 'user0', postCount: 1 },\n  { username: 'user1', postCount: 2 },\n])\n\n// DELETE some posts.\n\nawait Post.destroy({ where: { title: 'user0 post1' } })\nrows = await User.findAll({ order: [['username', 'ASC']] })\ncommon.assertEqual(rows, [\n  { username: 'user0', postCount: 1 },\n  { username: 'user1', postCount: 1 },\n])\n\nawait Post.destroy({ where: { title: 'user0 post0' } })\nrows = await User.findAll({ order: [['username', 'ASC']] })\ncommon.assertEqual(rows, [\n  { username: 'user0', postCount: 0 },\n  { username: 'user1', postCount: 1 },\n])\n\n})().finally(() => { return sequelize.close() })\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.14.0\",\n    \"sql-formatter\": \"4.0.2\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\nCREATE TRIGGER IF NOT EXISTS Posts_insert\n  AFTER INSERT\n  ON \"Posts\"\n  FOR EACH ROW\n  BEGIN\n    UPDATE \"Users\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\";\n  END;\nCREATE TRIGGER IF NOT EXISTS Posts_delete\n  AFTER DELETE\n  ON \"Posts\"\n  FOR EACH ROW\n  BEGIN\n    UPDATE \"Users\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\";\n  END;\nCREATE TRIGGER IF NOT EXISTS Posts_update\n  AFTER UPDATE\n  ON \"Posts\"\n  FOR EACH ROW\n  WHEN (OLD.\"UserId\" <> NEW.\"UserId\")\n  BEGIN\n    UPDATE \"Users\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\";\nUPDATE \"Users\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\";\n  END;\n```\n\n```text\nCREATE OR REPLACE FUNCTION Posts_insert_fn()\n  RETURNS TRIGGER\n  LANGUAGE PLPGSQL\n  AS\n$$\nBEGIN\n  UPDATE \"Users\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\";\n  RETURN NEW;\nEND;\n$$\nDROP TRIGGER IF EXISTS Posts_insert ON \"Posts\"\nCREATE TRIGGER Posts_insert\n  AFTER INSERT\n  ON \"Posts\"\n  FOR EACH ROW\n  EXECUTE PROCEDURE Posts_insert_fn();\nCREATE OR REPLACE FUNCTION Posts_delete_fn()\n  RETURNS TRIGGER\n  LANGUAGE PLPGSQL\n  AS\n$$\nBEGIN\n  UPDATE \"Users\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\";\n  RETURN NEW;\nEND;\n$$\nDROP TRIGGER IF EXISTS Posts_delete ON \"Posts\"\nCREATE TRIGGER Posts_delete\n  AFTER DELETE\n  ON \"Posts\"\n  FOR EACH ROW\n  EXECUTE PROCEDURE Posts_delete_fn();\nCREATE OR REPLACE FUNCTION Posts_update_fn()\n  RETURNS TRIGGER\n  LANGUAGE PLPGSQL\n  AS\n$$\nBEGIN\n  UPDATE \"Users\" SET \"postCount\" = \"postCount\" - 1 WHERE id = OLD.\"UserId\";\nUPDATE \"Users\" SET \"postCount\" = \"postCount\" + 1 WHERE id = NEW.\"UserId\";\n  RETURN NEW;\nEND;\n$$\nDROP TRIGGER IF EXISTS Posts_update ON \"Posts\"\nCREATE TRIGGER Posts_update\n  AFTER UPDATE\n  ON \"Posts\"\n  FOR EACH ROW\n  WHEN (OLD.\"UserId\" <> NEW.\"UserId\")\n  EXECUTE PROCEDURE Posts_update_fn();\n```\n\n```text\n.sync\n```\n\n```text\nsync({ force\n```\n\n```text\nif\n```\n\n```text\nUser.postCount\n```\n\n```js\n// This way the afterUpdate hook is triggered\nconst instance = UserModel.findOne(...);\ninstance.update(...);\n\n// This way the afterBulkUpdate hook is triggered instead,\n// where affected model are not directly available\nUserModel.update({where: {id: 1} });\n```\n\n```text\nUPDATE\n```\n\n========================================\n\nComments:\n- Excellent, that works with mysqljs too. You can just do `CREATE TRIGGER ...` without trying to change the delimiters as most often shown in examples.","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":528,"estimatedTokens":3427}}17{"id":"stack-10807765","source":"stackoverflow","questionId":10807765,"title":"node.js sequelize: multiple 'where' query conditions","tags":["node.js","sequelize.js"],"text":"Title: node.js sequelize: multiple 'where' query conditions\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do i query a table with multiple conditions?\nHere are the examples both working:\n\n```\nPost.findAll({ where: ['deletedAt IS NULL'] }).success()\n```\n\nand\n\n```\nPost.findAll({ where: {topicId: req.params.id} }).success()\n```\n\nThen, if i need conditions combined, i feel like i need to do something like\n\n```\nPost.findAll({ where: [{topicId: req.params.id}, 'deletedAt IS NULL'] }).success()\n```\n\n, but it doesn't work.\n\nWhat is the syntax the sequelize waits for?\n\nnode debug says:\n\n DEBUG: TypeError: Object # has no method 'replace'\n\nif it matters...\n\n========================================\n\nTop Answer:\nYou can do:\n\n```\nPost.findAll({ where: {deletedAt: null, topicId: req.params.id} })\n```\n\nWhich would be translated to `deletedAt IS NULL`\n\nBTW, if you need `deletedAt NOT IS NULL`, use:\n\n```\nPost.findAll({ where: {deletedAt: {$ne: null}, topicId: req.params.id} })\n```\n\n========================================\n\nCode:\n```text\nPost.findAll({ where: ['deletedAt IS NULL'] }).success()\n```\n\n```text\nPost.findAll({ where: {topicId: req.params.id} }).success()\n```\n\n```text\nPost.findAll({ where: [{topicId: req.params.id}, 'deletedAt IS NULL'] }).success()\n```\n\n```text\nfilters[\"State\"] = {$and: [filters[\"State\"], {$not: this.filterSBM()}] };\n```\n\n```text\n{ $and: [{\"Key1\": \"Value1\"}, {\"Key2\": \"Value2\"}] }\n```\n\n```text\nPost.findAll(\n    { where: [\"topicId = ? AND deletedAt IS NULL\", req.params.id] }\n).success()\n```\n\n```text\nPost.findAll({ where: {deletedAt: null, topicId: req.params.id} })\n```\n\n```text\nPost.findAll({ where: {deletedAt: {$ne: null}, topicId: req.params.id} })\n```\n\n```text\ndeletedAt IS NULL\n```\n\n```text\ndeletedAt NOT IS NULL\n```\n\n```text\nPost.findAll({\n  where: {\n    authorId: 12,\n    status: 'active'\n  }\n}).then(function (data) {\n    res.status(200).json(data)\n            })\n   .catch(function (error) {\n                res.status(500).json(error)\n   });;\n```\n\n```text\nexports.findAll = (req, res) => {\n    const title = req.query.title;\n    const description = req.query.description;\n    Tutorial.findAll({\n            where: {\n                [Op.or]: [{\n                        title: {\n                            [Op.like]: `%${title}%`\n                        }\n                    },\n                    {\n                        description: {\n                            [Op.like]: `%${description}%`\n                        }\n                    }\n                ]\n            }\n        })\n        .then(data => {\n            res.send(data);\n        })\n        .catch(err => {\n            res.status(500).send({\n                message: err.message || \"Some error occurred while retrieving tutorials.\"\n            });\n        });\n\n};\n```\n\n```text\nSELECT `id`, `title`, `description`, `test`, `published`, `createdAt`, `updatedAt` FROM `tests` AS `test` WHERE (`test`.`title` LIKE '%3%' OR `test`.`description` LIKE '%2%');\n```\n\n========================================\n\nComments:\n- Its AND that i needed, and your solution perfectly fits my needs, so thank you.\n- I must say its kinda obvious what u have done there, how could I not have done so myself?) But it feels more like workaround, I'm still curious what would I do if both conditions had parameters? Or if there'd be more conditions? Sequelize manuals doesn't have anything on such cases...\n- Nvm, i just found out that there can be several parameters provided subsequently for '?'s. Thanks again)\n- Please update your answer to check multiple where, show are only showing one condition where as he needs to check number and null.\n- Instead of mentioning `the most recent version of sequelize`, it would be useful if you quote the exact version. When I read your 2015 post in 2020, fairly sure the version you referenced is not `the most recent version` anymore.\n- Reasonable. I also wrote that off the cuff while on the job I had 5 years ago, but I'll bear that in mind.\n- This is the right answer. For some reason, most of the people above provided answers for AND condition. This works in Sequelize 6.","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":155,"estimatedTokens":1032}}18{"id":"stack-42750254","source":"stackoverflow","questionId":42750254,"title":"Promise.all(...).spread is not a function when running promises in parallel","tags":["javascript","node.js","promise","sequelize.js"],"text":"Title: Promise.all(...).spread is not a function when running promises in parallel\nTags: javascript, node.js, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run 2 promises in paralel with sequelize, and then render the results in a .ejs template, but I'm receiving this error:\n\n```\nPromise.all(...).spread is not a function\n```\n\nThis is my code:\n\n```\nvar environment_hash = req.session.passport.user.environment_hash;\nvar Template = require('../models/index').Template;\nvar List = require('../models/index').List;\n\nvar values = { \n where: { environment_hash: environment_hash,\n is_deleted: 0 \n } \n};\n\ntemplate = Template.findAll(values);\nlist = List.findAll(values);\n\nPromise.all([template,list]).spread(function(templates,lists) {\n\n res.render('campaign/create.ejs', {\n templates: templates,\n lists: lists\n });\n\n});\n```\n\nHow can I solve thhis?\n\n========================================\n\nTop Answer:\nYou can write it without non-standard `Bluebird` features and keep less dependencies as well. \n\n```\nPromise.all([template,list])\n .then(function([templates,lists]) {\n };\n```\n\nES6 Destructuring assignment\n\n\r\n\r\n\n```\nPromise.all([\r\n Promise.resolve(1),\r\n Promise.resolve(2),\r\n]).then(([one, two]) => console.log(one, two));\n```\n\n========================================\n\nCode:\n```text\nPromise.all(...).spread is not a function\n```\n\n```text\nvar environment_hash = req.session.passport.user.environment_hash;\nvar Template  = require('../models/index').Template;\nvar List      = require('../models/index').List;\n\nvar values = { \n    where: { environment_hash: environment_hash,\n             is_deleted: 0 \n        }                    \n};\n\ntemplate = Template.findAll(values);\nlist = List.findAll(values);\n\n\nPromise.all([template,list]).spread(function(templates,lists) {\n\n    res.render('campaign/create.ejs', {\n        templates: templates,\n        lists: lists\n    });\n\n});\n```\n\n```text\nvar Promise = require('bluebird');\n```\n\n```text\nPromise.all([template,list]).then(function([templates,lists]) {\n    res.render('campaign/create.ejs', {templates, lists});\n});\n```\n\n```text\n.spread()\n```\n\n```text\n.then(results => {...})\n```\n\n```text\nresults[0]\n```\n\n```text\nresults[1]\n```\n\n```text\n.spread()\n```\n\n```text\n.spread()\n```\n\n```text\nnpm install bluebird\n```\n\n```text\nvar Promise = require(\"bluebird\");\n```\n\n```text\nPromise.all([template,list])\n  .then(function([templates,lists]) {\n  };\n```\n\n```js\nPromise.all([\n  Promise.resolve(1),\n  Promise.resolve(2),\n]).then(([one, two]) => console.log(one, two));\n```\n\n```text\nBluebird\n```\n\n```text\nSequelize.Promise.all(promises).spread(...)\n```\n\n```text\nBluebird\n```\n\n```text\nSequelize.Promise\n```\n\n```text\nBluebird\n```\n\n========================================\n\nComments:\n- `.spread()` is not a standard promise method. It is available in the Bluebird promise library - are you using that? Your code you included does not show that. You can also just use `.then(results => {...})` and access the results as `results[0]` and `results[1]`.\n- Thanks, I didn't know that. I imported BlueBird and it's working now.\n- **`\"I'm trying to run 2 promises in parallel\".`** No you are not because you cannot as JS is single threaded. What you are dealing with is that you don't know which promise will end first.\n- @ankitbug94, but it still can be parallel IO operations.\n- @vp_arth so what? promises are neither going to start at same time nor end at same time and OP mentioned **promise**\n- Based on my prior comment, I posted an answer that offers you three different solutions. The most elegant of which is to use destructing to remove the need for `.spread()` entirely, though I still recommend Bluebird for these reasons: Are there still reasons to use promise libraries like Q or BlueBird now that we have ES6 promises?\n- +1 destructuring assignment , or maybe better to call it \"destructuring to parameters\"\n- Yes, with ES6 we don't need Bluebird spread in most scenarios. We can achieve what it does by just destructuring using then callback.\n- Much better is not to use these specific API. ES6 has so much features for spreading..","metadata":{"transformedAt":"2026-08-18T18:33:34.331Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":181,"estimatedTokens":1022}}19{"id":"stack-49643047","source":"stackoverflow","questionId":49643047,"title":"Update multiple rows in sequelize with different conditions","tags":["javascript","postgresql","sequelize.js"],"text":"Title: Update multiple rows in sequelize with different conditions\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to perform an update command with sequelize on rows in a postgres database. I need to be able to update multiple rows that have different conditions with the same value.\n\nFor example, assume I have a user table that contains the following fields:\n\n- ID\n\n- First Name\n\n- Last Name\n\n- Gender\n\n- Location\n\n- createdAt\n\nAssume, I have 4 records in this table, I want to update records with ID - 1 and 4 with a new location say Nigeria.\n\nSomething like this: `SET field1 = 'foo' WHERE id = 1, SET field1 = 'bar' WHERE id = 2`\n\nHow can I achieve that with sequelize?\n\n========================================\n\nTop Answer:\nYou can update multiple rows following your conditions, and to do that the operators are very helpful.\n\nLook here: http://docs.sequelizejs.com/manual/querying.html (operators)\n\n```\nconst { Op } = Sequelize;\nDisplayMedia.update(\n {\n field: 'bar'\n },\n {\n where: {\n id: {\n [Op.in]: [1, 10, 15, ..] // this will update all the records \n } // with an id from the list\n }\n }\n)\n```\n\nThere is all kinds of operators, including the range operators, or like operator ...etc\n\nAlso one of the important questions when it come to update, is how to update all rows?\n\nNot including `where` results in an error \"**Missing where attribute in the options parameter passed to update**\".\n\nThe answer is in the code bellow: provide a `where` with an **empty object**.\n\n```\nawait DisplayMediaSequence.update({\n default: false\n}, {\n where: {}, // \n}, {\n where: {\n id\n },\n transaction\n});\n```\n\n========================================\n\nCode:\n```text\nSET field1 = 'foo' WHERE id = 1, SET field1 = 'bar' WHERE id = 2\n```\n\n```text\nlet ids = [1,4];\nYour_model.update({ field1 : 'foo' },{ where : { id : ids }});\n```\n\n```text\nYour_model.update({ field1 : 'foo' },{ where : { id : 1 }});\nYour_model.update({ field1 : 'bar' },{ where : { id : 4 }});\n```\n\n```text\nfields1\n```\n\n```text\nid\n```\n\n```text\nfield1\n```\n\n```text\nid\n```\n\n```text\nfield1\n```\n\n```text\nid\n```\n\n```text\nconst { Op } = Sequelize;\nDisplayMedia.update(\n    {\n        field: 'bar'\n    },\n    {\n        where: {\n            id: {\n                [Op.in]: [1, 10, 15, ..]   // this will update all the records \n            }                           // with an id from the list\n        }\n    }\n)\n```\n\n```text\nawait DisplayMediaSequence.update({\n    default: false\n}, {\n    where: {}, // <-- here\n    transaction\n});\nawait DisplayMediaSequence.update({ \n    default: true     <-- after all turned to false, we now set the new default. (that to show a practical expample) -->\n}, {\n    where: {\n        id\n    },\n    transaction\n});\n```\n\n```text\nwhere\n```\n\n```text\nwhere\n```\n\n```text\nconst {idArray,group_id} = params;\n\nfor(const item of idArray){\n\n    const response = await Your_model.findOne({ where:{group_id,user_id:null}, order: [['id', 'DESC']] });\n\n    await response.update({user_id:item});\n}\n```\n\n========================================\n\nComments:\n- Does any DBMS support that SQL syntax? Maybe what you want is `CASE WHEN` as mentioned at: stackoverflow.com/questions/6097815/&hellip; ? That's asked more specifically at: stackoverflow.com/questions/47396796/&hellip; but no one was able to provide a non-literal approach so far.\n- Your requirement is fundamentally not possible in SQL (of what I know. Also, see here response by the author). Sequelize is only an ORM that converts JavaScript code to SQL. I have required that same condition multiple times, but it's not possible in one query. A better solution sometimes is to remove the data to be updated using `Op.in` and create it again using `bulkCreate`.\n- Yes, it does. Thank you.\n- @proton , Glad to know, Thanks , Happy Coding BTW.\n- @VivekDoshi Is there some way we can do this with a single update query.\n- IMO this should be the accepted answer, it directly solves the question asked. Thank You\n- @Sgnl it's not even close to solving the OP question. This answer will update the `field` with the value of bar for all given ids. While, OP asked to update `field` with foo when id = 1 and `field` with bar when id = 2.\n- @RahmatAli Good point there, my answer would require running multiple queries for different values. And i guess the only possible way to do it in sql (postgres, mysql) if i'm not wrong is by using `CASE, WHEN` syntax. And for that what would comes to mind is `Sequelize.literal()` with `case when` inside. I'll test it out first and i will update the answer after. And thanks good point.\n- @MohamedAllal I don't have in-depth knowledge of databases, so I can't say anything about `CASE WHEN`. Many times, I need to bulk update many fields. What's best and fastest works for me is removing the updated fields using `Op.in` and creating new records using `bulkCreate()`. Of course, it does not work everywhere, like if you have foreign keys associated with those records or you are removing, creating a lot so the limit of primary key will reach soon. But, most of the time, it works and is the fastest solution with the smallest number of database calls.","metadata":{"transformedAt":"2026-08-18T18:33:34.332Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":176,"estimatedTokens":1287}}20{"id":"stack-33377673","source":"stackoverflow","questionId":33377673,"title":"Associations in Sequelize migrations","tags":["node.js","associations","database-migration","sequelize.js"],"text":"Title: Associations in Sequelize migrations\nTags: node.js, associations, database-migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy app currently uses the Sequelize `sync()` method to create the database, and I want to change it to use the migrations system.\n\nOne of my model has `belongsTo()` associations with other models, and I don't really know how to make the initial migration code for these associations.\n\nDo I have to manually create the foreign key with SQL queries, or is there some methods available?\n\n========================================\n\nTop Answer:\nAdding this as an answer instead of a comment (not enough rep) for @aryeh-armon answer above. It's the table name that you need to make sure exists rather than the model name. i.e. if your model is named Job and your db table is named Jobs then the migration would look look like this instead. \n\n```\njobId: {\ntype: Sequelize.INTEGER,\nreferences: {\n model: \"Jobs\",\n key: \"id\"\n }\n},\n```\n\n========================================\n\nCode:\n```text\nsync()\n```\n\n```text\nbelongsTo()\n```\n\n```text\nclassMethods: {\n  associate: function(models) {\n    Task.belongsTo(models.User, {\n      onDelete: \"CASCADE\",\n      foreignKey: {\n        allowNull: false\n      }\n    });\n  }\n}\n```\n\n```text\nqueryInterface.addColumn(\n  'user',\n  'group_id',\n  {\n    type: Sequelize.INTEGER,\n    allowNull: true\n  }\n)\n```\n\n```text\nqueryInterface.sequelize.query(\"ALTER TABLE user\n  ADD CONSTRAINT user_group_id_fkey FOREIGN KEY (group_id)\n  REFERENCES group (id) MATCH SIMPLE\n  ON UPDATE CASCADE ON DELETE CASCADE;\");\n```\n\n```text\nsync\n```\n\n```text\nsync\n```\n\n```text\nindex.js\n```\n\n```text\ntask.js\n```\n\n```text\nuser.js\n```\n\n```text\ntask.js\n```\n\n```text\nreadme.md\n```\n\n```text\naddColumn\n```\n\n```text\nuser_id: {\n    type: Sequelize.BIGINT,\n    references: {\n        model: \"users\",\n        key: \"id\"\n    }\n},\n```\n\n```text\njobId: {\ntype: Sequelize.INTEGER,\nreferences: {\n    model: \"Jobs\",\n    key: \"id\"\n  }\n},\n```\n\n========================================\n\nComments:\n- You want to use migrations to create initial database structure or you want to update your current database structure using migrations?\n- I want to create the initial database structure first\n- Hmm ok thanks. I think i'm a bit confused about the differences between the migrations and the sync and when to use them. So if I updated my models using only sync() will it migrate my database correctly?\n- Sync creates a clean database structure based on your current models. If force attribute is set to false it will only create database if it does not already exist. Otherwise it will wipe the whole database each time you restart the server. Migrations scripts are used to change your existing database by operating on already existing structure and data. It is useful in production environment where you want to keep your data between updates.\n- Down voting because question is specifically about migrations (which you need for production) and this answer does not answer that. (But good answer for `sync`).\n- @AJP Thanks for your comment. I updated my answer to contain both cases: initial creation using sync and database migration.\n- @ezrepotein yeah that's what I've doing for the moment. Thanks for updating your answer. Pretty nasty we have to do it this way, the functionality is in there but I'm not quite sure how to pull it out yet. Will post back if I find a nicer solution.\n- @ezpn for some reason, it won't add the on UPDATE and DELETE properties to the foreign key constraint. Any ideas?\n- As of May '17, you can create the foreign key constraint within the migration. See here: github.com/sequelize/cli/issues/239#issuecomment-166564364\n- I agree with everything up until last sentence. You need migrations for production code.\n- Could you elaborate on the possible use case for using migrations to initialize database on production?\n- @ezrepotein sync is fine for db creation obviously just the question title is phrased in the more general (and therefore useful) \"Associations in Sequelize migrations\". I actually prefer using migrations on production though, why not if you do it for your test db too. Then your db setup and update use the same declarative command such as `sequelize db:migrate`, instead of some `if no db, then db:sync, otherwise db:migrate` kinda thing. I think there's a generally accepted minor preference for the former over the later.\n- @ezpn If you use sync() to create your structure, you run into an issue if you ever alter tables via migrations. Example: You create a migration to add column X to table Y. It works...great. A month later a new developer joins the team and runs npm start. He gets an error saying \"Failed to run migration....column X already exists on table Y\". Why is this? Because your sync command took care of the column addition, and now the migration is not needed. Sync() wasn't designed to actually be used. This poor implementation is one of the negatives of using sequelize.\n- Those links you described now turns into spam with redirects to random pages !.\n- @user8969730 thanks! I think the first one is lost, but the second one appears to have a slightly different URL. It's been a long time since I worked on this project, so I could not describe what I did back then, the best I can do is update the link, sorry. And this is maybe outdated, check the comments on the other answers.\n- It's a clarification on aryeh armon's answer (which, I agree, should be a comment) but I don't have enough rep to comment on other user's answers yet.","metadata":{"transformedAt":"2026-08-18T18:33:34.332Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":139,"estimatedTokens":1381}}21{"id":"stack-34120548","source":"stackoverflow","questionId":34120548,"title":"Using BCrypt with Sequelize Model","tags":["node.js","sequelize.js","bcrypt"],"text":"Title: Using BCrypt with Sequelize Model\nTags: node.js, sequelize.js, bcrypt\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use the `bcrypt-nodejs` package with my sequelize model and was tring to a tutorial to incorporate the hashing into my model, but I'm getting an error at `generateHash`. I can't seem to figure out the issue. Is there a better way to incorporate bcrypt?\n\nError:\n\n```\n/Users/user/Desktop/Projects/node/app/app/models/user.js:26\nUser.methods.generateHash = function(password) {\n ^\nTypeError: Cannot set property 'generateHash' of undefined\n at module.exports (/Users/user/Desktop/Projects/node/app/app/models/user.js:26:27)\n at Sequelize.import (/Users/user/Desktop/Projects/node/app/node_modules/sequelize/lib/sequelize.js:641:30)\n```\n\nmodel:\n\n```\nvar bcrypt = require(\"bcrypt-nodejs\");\n\nmodule.exports = function(sequelize, DataTypes) {\n\nvar User = sequelize.define('users', {\n annotation_id: {\n type: DataTypes.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n firstName: {\n type: DataTypes.DATE,\n field: 'first_name'\n },\n lastName: {\n type: DataTypes.DATE,\n field: 'last_name'\n },\n email: DataTypes.STRING,\n password: DataTypes.STRING,\n\n}, {\n freezeTableName: true\n});\n\nUser.methods.generateHash = function(password) {\n return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);\n};\n\nUser.methods.validPassword = function(password) {\n return bcrypt.compareSync(password, this.local.password);\n};\n return User;\n}\n```\n\n========================================\n\nTop Answer:\n**Other alternative:** Use hook and bcrypt async mode\n\n```\nUser.beforeCreate((user, options) => {\n\n return bcrypt.hash(user.password, 10)\n .then(hash => {\n user.password = hash;\n })\n .catch(err => { \n throw new Error(); \n });\n});\n```\n\n========================================\n\nCode:\n```text\n/Users/user/Desktop/Projects/node/app/app/models/user.js:26\nUser.methods.generateHash = function(password) {\n                          ^\nTypeError: Cannot set property 'generateHash' of undefined\n    at module.exports (/Users/user/Desktop/Projects/node/app/app/models/user.js:26:27)\n    at Sequelize.import (/Users/user/Desktop/Projects/node/app/node_modules/sequelize/lib/sequelize.js:641:30)\n```\n\n```text\nvar bcrypt = require(\"bcrypt-nodejs\");\n\nmodule.exports = function(sequelize, DataTypes) {\n\nvar User = sequelize.define('users', {\n    annotation_id: {\n        type: DataTypes.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    firstName: {\n        type: DataTypes.DATE,\n        field: 'first_name'\n    },\n    lastName: {\n        type: DataTypes.DATE,\n        field: 'last_name'\n    },\n    email: DataTypes.STRING,\n    password: DataTypes.STRING,\n\n}, {\n    freezeTableName: true\n});\n\nUser.methods.generateHash = function(password) {\n    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);\n};\n\nUser.methods.validPassword = function(password) {\n    return bcrypt.compareSync(password, this.local.password);\n};\n    return User;\n}\n```\n\n```text\nbcrypt-nodejs\n```\n\n```text\ngenerateHash\n```\n\n```text\nconst bcrypt = require(\"bcrypt\");\n\nmodule.exports = function(sequelize, DataTypes) {\n    const User = sequelize.define('users', {\n        annotation_id: {\n            type: DataTypes.INTEGER,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        firstName: {\n            type: DataTypes.DATE,\n            field: 'first_name'\n        },\n        lastName: {\n            type: DataTypes.DATE,\n            field: 'last_name'\n        },\n        email: DataTypes.STRING,\n        password: DataTypes.STRING\n    }, {\n        freezeTableName: true,\n        instanceMethods: {\n            generateHash(password) {\n                return bcrypt.hash(password, bcrypt.genSaltSync(8));\n            },\n            validPassword(password) {\n                return bcrypt.compare(password, this.password);\n            }\n        }\n    });\n\n    return User;\n}\n```\n\n```text\nsequelize.define\n```\n\n```text\nUser.beforeCreate((user, options) => {\n\n    return bcrypt.hash(user.password, 10)\n        .then(hash => {\n            user.password = hash;\n        })\n        .catch(err => { \n            throw new Error(); \n        });\n});\n```\n\n```text\nhooks: {\n  beforeCreate: (user) => {\n    const salt = bcrypt.genSaltSync();\n    user.password = bcrypt.hashSync(user.password, salt);\n  }\n},\ninstanceMethods: {\n  validPassword: function(password) {\n    return bcrypt.compareSync(password, this.password);\n  }\n}\n```\n\n```text\nUser.prototype.validPassword = function (password) {\n    return bcrypt.compareSync(password, this.password);\n};\n```\n\n```text\nbeforeCreate: async function(user) {\n    const salt = await bcrypt.genSalt(10); //whatever number you want\n    user.password = await bcrypt.hash(user.password, salt);\n}\n\nUser.prototype.validPassword = async function(password) {\n    return await bcrypt.compare(password, this.password);\n}\n```\n\n```text\nUser.findOne({ where: { username: username } }).then(function (user) {\n    if (!user) {\n        res.redirect('/login');\n    } else if (!user.validPassword(password)) {\n        res.redirect('/login');\n    } else {\n        req.session.user = user.dataValues;\n        res.redirect('/dashboard');\n    }\n});\n```\n\n```text\nUser.findOne({ where: { username: username } }).then(async function (user) {\n    if (!user) {\n        res.redirect('/login');\n    } else if (!await user.validPassword(password)) {\n        res.redirect('/login');\n    } else {\n        req.session.user = user.dataValues;\n        res.redirect('/dashboard');\n    }\n});\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\nrequire('dotenv').config();\nconst { Sequelize,DataTypes ,Model} = require(\"sequelize\");\nmodule.exports.Model = Model;\nmodule.exports.DataTypes = DataTypes;\nmodule.exports.sequelize  = new Sequelize(process.env.DB_NAME,process.env.DB_USER_NAME, process.env.DB_PASSWORD, {\n host: process.env.DB_HOST,\n dialect: process.env.DB_DISELECT,\n pool: {\n   max: 1,\n   min: 0,\n   idle: 10000\n },\n //logging: true\n});\n```\n\n```text\nconst { sequelize, DataTypes, Model } = require('../config/db.config');\n  var crypto = require('crypto');\n  class USERS extends Model {\n    validPassword(password) {\n      var hash = crypto.pbkdf2Sync(password,\n        this.SALT, 1000, 64, `sha512`).toString(`hex`);\n      console.log(hash == this.PASSWORD)\n      return this.PASSWORD === hash;\n    }\n  }\n  USERS.init(\n    {\n      ID: {\n        autoIncrement: true,\n        type: DataTypes.BIGINT,\n        allowNull: false,\n        primaryKey: true\n      },\n      MOBILE_NO: {\n        type: DataTypes.BIGINT,\n        allowNull: false,\n        unique: true\n      },\n      PASSWORD: {\n        type: DataTypes.STRING(200),\n        allowNull: false\n      },\n      SALT: {\n        type: DataTypes.STRING(200),\n        allowNull: false\n      }\n    },\n\n    {\n      sequelize,\n      tableName: 'USERS',\n      timestamps: true,\n      hooks: {\n        beforeCreate: (user) => {\n          console.log(user);\n          user.SALT = crypto.randomBytes(16).toString('hex');\n          user.PASSWORD = crypto.pbkdf2Sync(user.PASSWORD, user.SALT,\n            1000, 64, `sha512`).toString(`hex`);\n        },\n      }\n    });\n\n\n  module.exports.USERS = USERS;\n```\n\n```text\nconst { USERS } = require('../../../models/USERS');\nmodule.exports = class authController {\n    static register(req, res) {\n\n        USERS.create({\n            MOBILE_NO: req.body.mobile,\n            PASSWORD: req.body.password,\n            SALT:\"\"\n        }).then(function (data) {\n            res.json(data.toJSON());\n        }).catch((err) => {\n            res.json({\n                error: err.errors[0].message\n            })\n        })\n    }\n    static login(req, res) {\n        var message = [];\n        var success = false;\n        var status = 404;\n        USERS.findOne({\n           where:{\n            MOBILE_NO: req.body.mobile\n           }\n        }).then(function (user) {\n            if (user) {\n                message.push(\"user found\");\n                if(user.validPassword(req.body.password)) {\n                    status=200;\n                    success = true\n                    message.push(\"You are authorised\");\n                }else{\n                    message.push(\"Check Credentials\");\n                }\n            }else{\n                message.push(\"Check Credentials\");\n            }\n           \n            res.json({status,success,message});\n        });\n    }\n}\n```\n\n```js\nconst { Sequelize, DataTypes } = require('sequelize');\nconst useBcrypt = require('sequelize-bcrypt');\n\nconst database = new Sequelize({\n  ...sequelizeConnectionOptions,\n});\n\nconst User = database.define('User', {\n  email: { type: DataTypes.STRING },\n  password: { type: DataTypes.STRING },\n});\n\nuseBcrypt(User);\n```\n\n```js\nUser.create({ email: 'john.doe@example.com', password: 'SuperSecret!' });\n// { id: 1, email: 'john.doe@example.com', password: '$2a$12$VtyL7j5xx6t/GmmAqy53ZuKJ1nwPox5kHLXDaottN9tIQBsEB3EsW' }\n\nconst user = await User.findOne({ where: { email: 'john.doe@example.com' } });\nuser.authenticate('WrongPassword!'); // false\nuser.authenticate('SuperSecret!'); // true\n```\n\n========================================\n\nComments:\n- Just a note: before you deploy this, try and use the native bcrypt module instead of the bcrypt-nodejs module. This will speed the hashing up a lot because it's implemented in C++ instead of JavaScript.\n- bcrypt recommend async mode: github.com/kelektiv/&hellip;\n- Looks like it's important to pay attention to which version of Sequelize you're using here (3 vs 4). In v4 there's a new way to define Instance Methods on the model: docs.sequelizejs.com/manual/tutorial/&hellip;\n- I am reading the sequelize docs and and came here to find about hash stuff and I just saw this post. I have a question. @Louay Alakkad wrote new methods inside sequelize.define options argument but what about getters and setters? On the docs they suggets use set(value) {this.setValue('password', hash(value))} would this be a bad approach related to Louay's one?\n- @nishi In the docs it is mentioned hash(value) but when you try to create a entry in db, it gives error of hash not defined. So you could either use crypto library which is built in module in node js","metadata":{"transformedAt":"2026-08-18T18:33:34.332Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":397,"estimatedTokens":2544}}22{"id":"stack-29518786","source":"stackoverflow","questionId":29518786,"title":"Remove constraints in sequelize migration","tags":["javascript","sql","constraints","sequelize.js"],"text":"Title: Remove constraints in sequelize migration\nTags: javascript, sql, constraints, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm adding a `unique` constraint in a migration via the migrations.changeColumn function.\n\nAdding the constraint works, but since you need to provide a “backwards migration“, removing it the same way does not. It doesn't give any errors when migrating backwards, but again applying the forward migration results in `Possibly unhandled SequelizeDatabaseError: relation \"myAttribute_unique_idx\" already exists`.\n\n(The used database is postgres)\n\n```\nmodule.exports = {\n up: function (migration, DataTypes, done) {\n migration.changeColumn(\n 'Users',\n 'myAttribute',\n {\n type: DataTypes.STRING,\n unique: true // ADDING constraint works\n }\n ).done(done);\n },\n\n down: function (migration, DataTypes, done) {\n migration.changeColumn(\n 'Users',\n 'myAttribute',\n {\n type: DataTypes.STRING,\n unique: false // REMOVING does not\n }\n ).done(done);\n }\n};\n```\n\nI also tried using removeIndex\n\n```\nmigration.removeIndex('Users', 'myAttribute_unique_idx').done(done);\n```\n\nBut it gives the following error when reverting the migration:\n\n```\nPossibly unhandled SequelizeDatabaseError: cannot drop index \"myAttribute_unique_idx\" because constraint myAttribute_unique_idx on table \"Users\" requires it\n```\n\n========================================\n\nTop Answer:\n**Original answer to this question was posted in 2015. As of 2025, this comment is very outdated, please take a look at accepted answer.**\n\nUnfortunately sequelize doesn't have a builtin migration method to remove constraint. That is why before removing key you need to make a raw query.\n\n```\ndown: function (migration, DataTypes) {\n migration.sequelize.query(\n 'ALTER TABLE Users DROP CONSTRAINT myAttribute_unique_idx;'\n );\n migration.removeIndex('Users', 'myAttribute_unique_idx');\n \n return;\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  up: function (migration, DataTypes, done) {\n    migration.changeColumn(\n      'Users',\n      'myAttribute',\n      {\n        type: DataTypes.STRING,\n        unique: true                 // ADDING constraint works\n      }\n    ).done(done);\n  },\n\n  down: function (migration, DataTypes, done) {\n    migration.changeColumn(\n      'Users',\n      'myAttribute',\n      {\n        type: DataTypes.STRING,\n        unique: false                // REMOVING does not\n      }\n    ).done(done);\n  }\n};\n```\n\n```text\nmigration.removeIndex('Users', 'myAttribute_unique_idx').done(done);\n```\n\n```text\nPossibly unhandled SequelizeDatabaseError: cannot drop index \"myAttribute_unique_idx\" because constraint myAttribute_unique_idx on table \"Users\" requires it\n```\n\n```text\nunique\n```\n\n```text\nPossibly unhandled SequelizeDatabaseError: relation \"myAttribute_unique_idx\" already exists\n```\n\n```text\nqueryInterface.removeConstraint(tableName, constraintName)\n```\n\n```text\ndown: function (migration, DataTypes) {\n    return migration.removeIndex('Users', 'myAttribute_unique_idx');\n}\n```\n\n```text\ndown: function (migration, DataTypes) {\n  migration.sequelize.query(\n    'ALTER TABLE Users DROP CONSTRAINT myAttribute_unique_idx;'\n  );\n  migration.removeIndex('Users', 'myAttribute_unique_idx');\n  \n  return;\n}\n```\n\n```text\nremoveConstraint()\n```\n\n```text\nreturn queryInterface.removeConstraint('users', 'users_userId_key', {})\n```\n\n```text\nusers\n```\n\n```text\nusers_userId_key\n```\n\n```text\nattributename_unique_key\n```\n\n```js\nawait queryInterface.removeConstraint(\"Users\",\"myAttribute\" )\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    //remove constraint\n    queryInterface.removeConstraint(\"projects\", \"projects_action_id_fkey\");\n  },\n\n  down: async (queryInterface, Sequelize) => {\n    //re-add a reference example with a raw query\n    queryInterface.sequelize.query(\n    `\n      ALTER TABLE IF EXISTS public.action_executions\n      ADD CONSTRAINT projects_action_id_fkey FOREIGN KEY (action_id)\n      REFERENCES public.actions (id) MATCH SIMPLE\n      ON UPDATE NO ACTION\n      ON DELETE NO ACTION;\n    `\n    );\n  }\n};\n```\n\n```text\nremoveConstraint\n```\n\n========================================\n\nComments:\n- were you able to do it without using sequelize.query.\n- Thank you so much. The docs aren't very clear on this limitation.\n- Yeah, the docs imply you can with `references: null`, but that does not work. This doubly sucks because I cannot find a way to name my constrains, which means my migrations are tightly coupled to a particular version of sequelize. Yuck!\n- Make sure to put the table name in the raw query in double qoutes if the name is not lowercase: `'ALTER TABLE \"Users\" DROP CONSTRAINT myAttribute_unique_idx;'`\n- Updated documentation here\n- doesn't work for me, throws error: can't find constraint with particular name. Even though constraint do exist and below raw query removed it well","metadata":{"transformedAt":"2026-08-18T18:33:34.332Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":192,"estimatedTokens":1218}}23{"id":"stack-53882278","source":"stackoverflow","questionId":53882278,"title":"Sequelize Association called with something that's not a subclass of Sequelize.Model","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize Association called with something that's not a subclass of Sequelize.Model\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm having error \"...called with something that's not a subclass of Sequelize.Model\" when I add association of Sequelize in my model it called error that what I call is not Sequelize Model\n\n```\nE:...\\Projects\\WebApps\\hr1\\hr1\\node_modules\\sequelize\\lib\\associations\\mixin.js:81\n throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\\'s not a subclass of Sequelize.Model');\n ^\n\nError: user_employee_tm.class BelongsTo extends Association {\n constructor(source, target, options) {\n super(source, target, options);\n\n this.associationType = 'BelongsTo';\n this.isSingleAssociation = true;\n this.foreignKeyAttribute = {};\n\n if (this.as) {\n this.isAliased = true;\n this.options.name = {\n singular: this.as\n };\n } else {\n this.as = this.target.options.name.singular;\n this.options.name = this.target.options.name;\n }\n\n if (_.isObject(this.options.foreignKey)) {\n this.foreignKeyAttribute = this.options.foreignKey;\n this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;\n } else if (this.options.foreignKey) {\n this.foreignKey = this.options.foreignKey;\n }\n\n if (!this.foreignKey) {\n this.foreignKey = Utils.camelizeIf(\n [\n Utils.underscoredIf(this.as, this.source.options.underscored),\n this.target.primaryKeyAttribute\n ].join('_'),\n !this.source.options.underscored\n );\n }\n\n this.identifier = this.foreignKey;\n\n if (this.source.rawAttributes[this.identifier]) {\n this.identifierField = this.source.rawAttributes[this.identifier].field || this.identifier;\n }\n\n this.targetKey = this.options.targetKey || this.target.primaryKeyAttribute;\n this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;\n this.targetKeyIsPrimary = this.targetKey === this.target.primaryKeyAttribute;\n\n this.targetIdentifier = this.targetKey;\n this.associationAccessor = this.as;\n this.options.useHooks = options.useHooks;\n\n // Get singular name, trying to uppercase the first letter, unless the model forbids it\n const singular = Utils.uppercaseFirst(this.options.name.singular);\n\n this.accessors = {\n get: 'get' + singular,\n set: 'set' + singular,\n create: 'create' + singular\n };\n }\n\n // the id is in the source table\n injectAttributes() {\n const newAttributes = {};\n\n newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {\n type: this.options.keyType || this.target.rawAttributes[this.targetKey].type,\n allowNull: true\n });\n\n if (this.options.constraints !== false) {\n const source = this.source.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];\n this.options.onDelete = this.options.onDelete || (source.allowNull ? 'SET NULL' : 'NO ACTION');\n this.options.onUpdate = this.options.onUpdate || 'CASCADE';\n }\n\n Helpers.addForeignKeyConstraints(newAttributes[this.foreignKey], this.target, this.source, this.options, this.targetKeyField);\n Utils.mergeDefaults(this.source.rawAttributes, newAttributes);\n\n this.identifierField = this.source.rawAttributes[this.foreignKey].field || this.foreignKey;\n\n this.source.refreshAttributes();\n\n Helpers.checkNamingCollision(this);\n\n return this;\n }\n\n mixin(obj) {\n const methods = ['get', 'set', 'create'];\n\n Helpers.mixinMethods(this, obj, methods);\n }\n\n /**\n * Get the associated instance.\n *\n * @param {Object} [options]\n * @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.\n * @param {String} [options.schema] Apply a schema on the related model\n * @see {@link Model.findOne} for a full explanation of options\n * @return {Promise}\n */\n get(instances, options) {\n const association = this;\n const where = {};\n let Target = association.target;\n let instance;\n\n options = Utils.cloneDeep(options);\n\n if (options.hasOwnProperty('scope')) {\n if (!options.scope) {\n Target = Target.unscoped();\n } else {\n Target = Target.scope(options.scope);\n }\n }\n\n if (options.hasOwnProperty('schema')) {\n Target = Target.schema(options.schema, options.schemaDelimiter);\n }\n\n if (!Array.isArray(instances)) {\n instance = instances;\n instances = undefined;\n }\n\n if (instances) {\n where[association.targetKey] = {\n [Op.in]: instances.map(instance => instance.get(association.foreignKey))\n };\n } else {\n if (association.targetKeyIsPrimary && !options.where) {\n return Target.findByPk(instance.get(association.foreignKey), options);\n } else {\n where[association.targetKey] = instance.get(association.foreignKey);\n options.limit = null;\n }\n }\n\n options.where = options.where ?\n {[Op.and]: [where, options.where]} :\n where;\n\n if (instances) {\n return Target.findAll(options).then(results => {\n const result = {};\n for (const instance of instances) {\n result[instance.get(association.foreignKey, {raw: true})] = null;\n }\n\n for (const instance of results) {\n result[instance.get(association.targetKey, {raw: true})] = instance;\n }\n\n return result;\n });\n }\n\n return Target.findOne(options);\n }\n\n /**\n * Set the associated model.\n *\n * @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.\n * @param {Object} [options] Options passed to `this.save`\n * @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.\n * @return {Promise}\n */\n set(sourceInstance, associatedInstance, options) {\n const association = this;\n\n options = options || {};\n\n let value = associatedInstance;\n if (associatedInstance instanceof association.target) {\n value = associatedInstance[association.targetKey];\n }\n\n sourceInstance.set(association.foreignKey, value);\n\n if (options.save === false) return;\n\n options = _.extend({\n fields: [association.foreignKey],\n allowNull: [association.foreignKey],\n association: true\n }, options);\n\n // passes the changed field to save, so only that field get updated.\n return sourceInstance.save(options);\n }\n\n /**\n * Create a new instance of the associated model and associate it with this.\n *\n * @param {Object} [values]\n * @param {Object} [options] Options passed to `target.create` and setAssociation.\n * @see {@link Model#create} for a full explanation of options\n * @return {Promise}\n */\n create(sourceInstance, values, fieldsOrOptions) {\n const association = this;\n\n const options = {};\n\n if ((fieldsOrOptions || {}).transaction instanceof Transaction) {\n options.transaction = fieldsOrOptions.transaction;\n }\n options.logging = (fieldsOrOptions || {}).logging;\n\n return association.target.create(values, fieldsOrOptions).then(newAssociatedObject =>\n sourceInstance[association.accessors.set](newAssociatedObject, options)\n );\n }\n} called with something that's not a subclass of Sequelize.Model\n at Function. (E:...\\Projects\\WebApps\\hr1\\hr1\\node_modules\\sequelize\\lib\\associations\\mixin.js:81:13)\n at Object. (E:...\\Projects\\WebApps\\hr1\\hr1\\models\\user_employee.js:22:14)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n at Module.load (internal/modules/cjs/loader.js:598:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n at Module.require (internal/modules/cjs/loader.js:636:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at Object. (E:...\\Projects\\WebApps\\hr1\\hr1\\models\\user.js:4:26)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n at Module.load (internal/modules/cjs/loader.js:598:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n at Module.require (internal/modules/cjs/loader.js:636:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at Object. (E:...\\Projects\\WebApps\\hr1\\hr1\\routes\\index.js:4:12)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n at Module.load (internal/modules/cjs/loader.js:598:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n```\n\nHere's my Code for\n\nmodel/User.js\n\n```\nvar bcrypt = require('bcrypt');\nconst sequelize = require('../config/connectionDatabase')\nvar Sequelize = require('sequelize');\nconst UserEmployee = require('../models/user_employee');\n\nvar User = sequelize.define('user_tm', {\n NameFirst: {\n type: Sequelize.STRING\n },\n NameLast: {\n type: Sequelize.STRING\n },\n username: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false\n }\n}, {\n hooks: {\n beforeCreate: (user) => {\n const salt = bcrypt.genSaltSync();\n user.password = bcrypt.hashSync(user.password, salt);\n }\n },\n instanceMethods: {\n validPassword: function(password) {\n return bcrypt.compareSync(password, this.password);\n }\n } \n});\n\nUser.hasOne(UserEmployee, {foreignKey: 'UserID', as: 'User'});\nUser.prototype.validPassword = function (password) {\n return bcrypt.compareSync(password, this.password);\n};\nmodule.exports = User;\n```\n\nmodel/user_employee.js\n\n```\nconst sequelize = require('../config/connectionDatabase');\nvar Sequelize = require('sequelize');\nconst User = require('../models/user');\n\nvar UserEmployee = sequelize.define('user_employee_tm', {\n DateJoin: {\n type: Sequelize.DATE\n },\n UserID: {\n type: Sequelize.INTEGER,\n references: {\n model: User,\n key: \"ID\"\n }\n },\n CompanyID: {\n type: Sequelize.INTEGER\n }\n});\n\n// UserEmployee.hasOne(User, {as: 'User', foreignKey: 'UserID'}); \nUserEmployee.belongsTo(User , {foreignKey: 'ID', as: 'Employee'});\nmodule.exports = UserEmployee;\n```\n\nis there something I missed of? I've try to use this url\nhttps://dreamdevourer.com/example-of-sequelize-associations-in-feathersjs/\n\nfor adding assosicate along with model, but still having the same problem.\n\nMuch thanks for your help\n\n========================================\n\nTop Answer:\nPutting\n`A.hasOne(B)`\nand\n`B.belongsTo(A)` in the same file solved the issue for me.\n\n========================================\n\nCode:\n```text\nE:...\\Projects\\WebApps\\hr1\\hr1\\node_modules\\sequelize\\lib\\associations\\mixin.js:81\n      throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\\'s not a subclass of Sequelize.Model');\n      ^\n\nError: user_employee_tm.class BelongsTo extends Association {\n  constructor(source, target, options) {\n    super(source, target, options);\n\n    this.associationType = 'BelongsTo';\n    this.isSingleAssociation = true;\n    this.foreignKeyAttribute = {};\n\n    if (this.as) {\n      this.isAliased = true;\n      this.options.name = {\n        singular: this.as\n      };\n    } else {\n      this.as = this.target.options.name.singular;\n      this.options.name = this.target.options.name;\n    }\n\n    if (_.isObject(this.options.foreignKey)) {\n      this.foreignKeyAttribute = this.options.foreignKey;\n      this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;\n    } else if (this.options.foreignKey) {\n      this.foreignKey = this.options.foreignKey;\n    }\n\n    if (!this.foreignKey) {\n      this.foreignKey = Utils.camelizeIf(\n        [\n          Utils.underscoredIf(this.as, this.source.options.underscored),\n          this.target.primaryKeyAttribute\n        ].join('_'),\n        !this.source.options.underscored\n      );\n    }\n\n    this.identifier = this.foreignKey;\n\n    if (this.source.rawAttributes[this.identifier]) {\n      this.identifierField = this.source.rawAttributes[this.identifier].field || this.identifier;\n    }\n\n    this.targetKey = this.options.targetKey || this.target.primaryKeyAttribute;\n    this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;\n    this.targetKeyIsPrimary = this.targetKey === this.target.primaryKeyAttribute;\n\n    this.targetIdentifier = this.targetKey;\n    this.associationAccessor = this.as;\n    this.options.useHooks = options.useHooks;\n\n    // Get singular name, trying to uppercase the first letter, unless the model forbids it\n    const singular = Utils.uppercaseFirst(this.options.name.singular);\n\n    this.accessors = {\n      get: 'get' + singular,\n      set: 'set' + singular,\n      create: 'create' + singular\n    };\n  }\n\n  // the id is in the source table\n  injectAttributes() {\n    const newAttributes = {};\n\n    newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {\n      type: this.options.keyType || this.target.rawAttributes[this.targetKey].type,\n      allowNull: true\n    });\n\n    if (this.options.constraints !== false) {\n      const source = this.source.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];\n      this.options.onDelete = this.options.onDelete || (source.allowNull ? 'SET NULL' : 'NO ACTION');\n      this.options.onUpdate = this.options.onUpdate || 'CASCADE';\n    }\n\n    Helpers.addForeignKeyConstraints(newAttributes[this.foreignKey], this.target, this.source, this.options, this.targetKeyField);\n    Utils.mergeDefaults(this.source.rawAttributes, newAttributes);\n\n    this.identifierField = this.source.rawAttributes[this.foreignKey].field || this.foreignKey;\n\n    this.source.refreshAttributes();\n\n    Helpers.checkNamingCollision(this);\n\n    return this;\n  }\n\n  mixin(obj) {\n    const methods = ['get', 'set', 'create'];\n\n    Helpers.mixinMethods(this, obj, methods);\n  }\n\n  /**\n   * Get the associated instance.\n   *\n   * @param {Object} [options]\n   * @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.\n   * @param {String} [options.schema] Apply a schema on the related model\n   * @see {@link Model.findOne} for a full explanation of options\n   * @return {Promise<Model>}\n   */\n  get(instances, options) {\n    const association = this;\n    const where = {};\n    let Target = association.target;\n    let instance;\n\n    options = Utils.cloneDeep(options);\n\n    if (options.hasOwnProperty('scope')) {\n      if (!options.scope) {\n        Target = Target.unscoped();\n      } else {\n        Target = Target.scope(options.scope);\n      }\n    }\n\n    if (options.hasOwnProperty('schema')) {\n      Target = Target.schema(options.schema, options.schemaDelimiter);\n    }\n\n    if (!Array.isArray(instances)) {\n      instance = instances;\n      instances = undefined;\n    }\n\n    if (instances) {\n      where[association.targetKey] = {\n        [Op.in]: instances.map(instance => instance.get(association.foreignKey))\n      };\n    } else {\n      if (association.targetKeyIsPrimary && !options.where) {\n        return Target.findByPk(instance.get(association.foreignKey), options);\n      } else {\n        where[association.targetKey] = instance.get(association.foreignKey);\n        options.limit = null;\n      }\n    }\n\n    options.where = options.where ?\n      {[Op.and]: [where, options.where]} :\n      where;\n\n    if (instances) {\n      return Target.findAll(options).then(results => {\n        const result = {};\n        for (const instance of instances) {\n          result[instance.get(association.foreignKey, {raw: true})] = null;\n        }\n\n        for (const instance of results) {\n          result[instance.get(association.targetKey, {raw: true})] = instance;\n        }\n\n        return result;\n      });\n    }\n\n    return Target.findOne(options);\n  }\n\n  /**\n   * Set the associated model.\n   *\n   * @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.\n   * @param {Object} [options] Options passed to `this.save`\n   * @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.\n   * @return {Promise}\n   */\n  set(sourceInstance, associatedInstance, options) {\n    const association = this;\n\n    options = options || {};\n\n    let value = associatedInstance;\n    if (associatedInstance instanceof association.target) {\n      value = associatedInstance[association.targetKey];\n    }\n\n    sourceInstance.set(association.foreignKey, value);\n\n    if (options.save === false) return;\n\n    options = _.extend({\n      fields: [association.foreignKey],\n      allowNull: [association.foreignKey],\n      association: true\n    }, options);\n\n    // passes the changed field to save, so only that field get updated.\n    return sourceInstance.save(options);\n  }\n\n  /**\n   * Create a new instance of the associated model and associate it with this.\n   *\n   * @param {Object} [values]\n   * @param {Object} [options] Options passed to `target.create` and setAssociation.\n   * @see {@link Model#create}  for a full explanation of options\n   * @return {Promise}\n   */\n  create(sourceInstance, values, fieldsOrOptions) {\n    const association = this;\n\n    const options = {};\n\n    if ((fieldsOrOptions || {}).transaction instanceof Transaction) {\n      options.transaction = fieldsOrOptions.transaction;\n    }\n    options.logging = (fieldsOrOptions || {}).logging;\n\n    return association.target.create(values, fieldsOrOptions).then(newAssociatedObject =>\n      sourceInstance[association.accessors.set](newAssociatedObject, options)\n    );\n  }\n} called with something that's not a subclass of Sequelize.Model\n    at Function.<anonymous> (E:...\\Projects\\WebApps\\hr1\\hr1\\node_modules\\sequelize\\lib\\associations\\mixin.js:81:13)\n    at Object.<anonymous> (E:...\\Projects\\WebApps\\hr1\\hr1\\models\\user_employee.js:22:14)\n    at Module._compile (internal/modules/cjs/loader.js:688:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n    at Module.load (internal/modules/cjs/loader.js:598:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n    at Module.require (internal/modules/cjs/loader.js:636:17)\n    at require (internal/modules/cjs/helpers.js:20:18)\n    at Object.<anonymous> (E:...\\Projects\\WebApps\\hr1\\hr1\\models\\user.js:4:26)\n    at Module._compile (internal/modules/cjs/loader.js:688:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n    at Module.load (internal/modules/cjs/loader.js:598:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n    at Module.require (internal/modules/cjs/loader.js:636:17)\n    at require (internal/modules/cjs/helpers.js:20:18)\n    at Object.<anonymous> (E:...\\Projects\\WebApps\\hr1\\hr1\\routes\\index.js:4:12)\n    at Module._compile (internal/modules/cjs/loader.js:688:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n    at Module.load (internal/modules/cjs/loader.js:598:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n```\n\n```text\nvar bcrypt =  require('bcrypt');\nconst sequelize = require('../config/connectionDatabase')\nvar Sequelize = require('sequelize');\nconst UserEmployee = require('../models/user_employee');\n\nvar User = sequelize.define('user_tm', {\n    NameFirst: {\n        type: Sequelize.STRING\n    },\n    NameLast: {\n        type: Sequelize.STRING\n    },\n    username: {\n        type: Sequelize.STRING,\n        unique: true,\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING,\n        allowNull: false\n    }\n}, {\n    hooks: {\n    beforeCreate: (user) => {\n        const salt = bcrypt.genSaltSync();\n        user.password = bcrypt.hashSync(user.password, salt);\n    }\n    },\n    instanceMethods: {\n    validPassword: function(password) {\n        return bcrypt.compareSync(password, this.password);\n    }\n    }    \n});\n\nUser.hasOne(UserEmployee, {foreignKey: 'UserID', as: 'User'});\nUser.prototype.validPassword = function (password) {\n    return bcrypt.compareSync(password, this.password);\n};\nmodule.exports = User;\n```\n\n```text\nconst sequelize = require('../config/connectionDatabase');\nvar Sequelize = require('sequelize');\nconst User = require('../models/user');\n\nvar UserEmployee = sequelize.define('user_employee_tm', {\n    DateJoin: {\n        type: Sequelize.DATE\n    },\n    UserID: {\n        type: Sequelize.INTEGER,\n        references: {\n            model: User,\n            key: \"ID\"\n        }\n    },\n    CompanyID: {\n        type: Sequelize.INTEGER\n    }\n});\n\n// UserEmployee.hasOne(User, {as: 'User', foreignKey: 'UserID'});  \nUserEmployee.belongsTo(User , {foreignKey: 'ID', as: 'Employee'});\nmodule.exports = UserEmployee;\n```\n\n```text\nconst sequelize = require('../config/connectionDatabase');\nvar Sequelize = require('sequelize');\nconst User = require('../models/user');\nconst Company = require('../models/company');\n\nvar UserEmployee = sequelize.define('user_employee_tm', {\n    DateJoin: {\n        type: Sequelize.DATE\n    },\n    UserID: {\n        type: Sequelize.INTEGER,\n        references: {\n            model: User,\n            key: \"UserID\"\n        }\n    },\n    CompanyID: {\n        type: Sequelize.INTEGER,\n        references: {\n            model: Company,\n            key: \"CompanyID\"\n        }\n    }\n});\nUserEmployee.belongsTo(Company, {as: 'Company', foreignKey: 'CompanyID'});\nUserEmployee.belongsTo(User, {as: 'User', foreignKey: 'UserID'});\nmodule.exports = UserEmployee;\n```\n\n```text\nvar User = sequelize.define('user_tm', {\n  // ... user_tm definition\n});\n\nvar UserEmployee = sequelize.define('user_employee_tm', {\n  // ... user_employee_tm definition\n});\n\nUserEmployee.associate = (models) => {\n  UserEmployee.belongsTo(models.user_tm, {foreignKey: 'ID', as: 'Employee'});\n};\n```\n\n```text\nassociate(models)\n```\n\n```text\nmodels\n```\n\n```text\nModel\n```\n\n```text\nimport\n```\n\n```text\nA.hasOne(B)\n```\n\n```text\nB.belongsTo(A)\n```\n\n```js\n\"use strict\";\nconst { Model } = require(\"sequelize\");\nconst quotation = require(\"./quotation\");\nmodule.exports = (sequelize, DataTypes) => {\n  class Clients extends Model {\n    /**\n     * Helper method for defining associations.\n     * This method is not a part of Sequelize lifecycle.\n     * The `models/index` file will call this method automatically.\n     */\n    static associate(models) {\n      // define association here\n      Clients.hasOne(models.Quotation);\n    }\n  }\n  Clients.init(\n    {\n      firstName: DataTypes.STRING,\n      lastName: DataTypes.STRING,\n      email: DataTypes.STRING,\n      phone: DataTypes.STRING,\n      contactName: DataTypes.STRING,\n      contactPosition: DataTypes.STRING,\n      rncCode: DataTypes.STRING,\n      active: DataTypes.BOOLEAN,\n    },\n    {\n      sequelize,\n      modelName: \"Clients\",\n    }\n  );\n\n  return Clients;\n};\n```\n\n```js\n\"use strict\";\nconst { Model } = require(\"sequelize\");\nconst quotation = require(\"./quotation\");\nmodule.exports = (sequelize, DataTypes) => {\n  class Clients extends Model {\n    /**\n     * Helper method for defining associations.\n     * This method is not a part of Sequelize lifecycle.\n     * The `models/index` file will call this method automatically.\n     */\n    static associate(models) {\n      // define association here\n      Clients.hasOne(models.Quotation);\n    }\n  }\n  Clients.init(\n    {\n      firstName: DataTypes.STRING,\n      lastName: DataTypes.STRING,\n      email: DataTypes.STRING,\n      phone: DataTypes.STRING,\n      contactName: DataTypes.STRING,\n      contactPosition: DataTypes.STRING,\n      rncCode: DataTypes.STRING,\n      active: DataTypes.BOOLEAN,\n    },\n    {\n      sequelize,\n      modelName: \"Clients\",\n    }\n  );\n\n  return Clients;\n};\n```\n\n```text\nimport {Post} from \"./post\";\nimport {Tag} from \"./tag\";\n\nTag.belongsToMany(Post, {\n    through: 'PostTags'\n})\n\nPost.belongsToMany(Tag, {\n    through: 'PostTags'\n})\n```\n\n```text\nassociations\n```\n\n```text\nbelongsTo\n```\n\n```text\nimport './assocations'\n```\n\n```text\nassociations\n```\n\n```js\nconst {Model} = require('sequelize');\n\nmodule.exports = function (sequelize) {\n  class Dog extends Model {}\n\n  setTimeout(() => {\n    Dog.hasMany(sequelize.models.Flea);\n  }, 0);\n\n  return Dog;\n}\n```\n\n```js\nconst {Model} = require('sequelize');\n\nmodule.exports = function (sequelize) {\n  class Flea extends Model {}\n\n  setTimeout(() => {\n    Flea.belongsTo(sequelize.models.Dog);\n  }, 0);\n\n  return Flea;\n}\n```\n\n```js\nconst sequelize = getConnectionSomehow();\n\nconst Dog  = require('./Dog' )(sequelize);\nconst Flea = require('./Flea')(sequelize);\n```\n\n```text\nconst Company = require('./Company'); // you need to remove this line\n    var Employee = sequelize.define('employee', {\n     //define it\n    });\n    module.exports = Employee\n```\n\n```text\nconst Employee = require('./Employee');\n    var Company = sequelize.define('company', {\n     //define it\n    });\n    Company.hasOne(Employee) // this line throws error.\n```\n\n```js\nstatic associate(models) {\n      // define association here\n      console.log(models,'-=====')\n      Category.belongsToMany(models.service, {through: 'serviceCategory'})\n      Category.belongsToMany(models.Job, {through: 'JobCategory'})\n  }\n```\n\n```text\nconst EventReportCategory_EventReport = database.define(\n            \"event_report_category_event_report\",\n            {});\n    \n        EventReport.belongsToMany(EventReportCategory,\n            {\n                through: EventReportCategory_EventReport\n            });\n    \n        EventReportCategory.belongsToMany(EventReport,\n            {\n                through: EventReportCategory_EventReport\n            });\n```\n\n```text\ntypeof Entity\n```\n\n```text\nEntity\n```\n\n```text\nundefined\n```\n\n```text\nEntity\n```\n\n```text\nmodule.export\n```\n\n```text\nmodule.exports\n```\n\n```text\nAssociate\n```\n\n```text\nnew Sequelize(...).sync()\n```\n\n```text\nEventReport\n```\n\n```text\nEventReportCategory\n```\n\n```text\nconst { DataTypes } = require('sequelize');\nconst ContactInfo = require('./ContactInfo');\nconst User = require('./User');\nconst BlogPost = require('./BlogPost');\n\nmodule.exports.associations = (sequelize) => {\n  const user = User(sequelize);\n  const contactInfo = ContactInfo(sequelize);\n  const blogpost = BlogPost(sequelize);\n\n  // Define your associations here\n\n  // One-to-one relationship\n  user.hasOne(contactInfo, {\n    foreignKey: {\n      type: DataTypes.UUID,\n      allowNull: false,\n    },\n  });\n  contactInfo.belongsTo(user);\n\n  // One-to-many relationship\n  user.hasMany(blogpost, {\n    foreignKey: {\n      type: DataTypes.UUID,\n      allowNull: false,\n    },\n  });\n  blogpost.belongsTo(user);\n\n  // Many-to-many relationship\n  user.belongsToMany(user, {\n    as: 'User',\n    foreignKey: 'UserId',\n    through: 'Follow',\n  });\n\n  user.belongsToMany(user, {\n    as: 'Followed',\n    foreignKey: 'FollowedId',\n    through: 'Follow',\n  });\n};\n```\n\n========================================\n\nComments:\n- so i need to put the UserEmployee definition inside User Model File? also, I have another warning { SequelizeEagerLoadingError: user_tm is not associated to user_employee_tm!\n- you need to create the reverse relationship as well.\n- I'd like to add that the case is important too. Make sure the definition name is exactly the same used later.\n- `associate` property doesn't exist in TypeScript :(\n- I can confirm that this approach works... but is this really a good idea? To do this, we have to either (1) put associations (`hasOne`, `belongsTo` etc) into one file separately from model definitions, or (2) put associations and model definitions into one file.\n- If you don't want to deal with having all your models in one file see my answer that does pretty much this but more manageable.\n- What are you referring to with the \"main app file\"? Is that the `index.ts` model file?\n- Update: For those who were confused about the \"main app file\", I am using Express.js and imported it at the top of `src&#47;index.ts` like this: `import '.&#47;db&#47;models&#47;associations';` Seems to be working just fine.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.332Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":1004,"estimatedTokens":7006}}24{"id":"stack-21427501","source":"stackoverflow","questionId":21427501,"title":"How can I see the SQL generated by Sequelize.js?","tags":["node.js","sequelize.js"],"text":"Title: How can I see the SQL generated by Sequelize.js?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to see the SQL commands that are sent to the PostgreSQL server because I need to check if they are correct. In particular, I am interested in the table creation commands.\n\nFor instance, ActiveRecord (Ruby) prints its SQL statements to standard output. Is this possible with Node.js/ActionHero.js and Sequelize.js as well?\n\n========================================\n\nTop Answer:\nAs stated in the log `Error: Please note that find* was refactored and uses only one options object from now on.`. For the latest sequelize version (4) if you want to have the result for only one command:\n\n`User.findAll({where: {...}, logging: console.log})`\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n    logging: console.log\n    logging: function (str) {\n        // do your own logging\n    }\n});\n```\n\n```text\nsequelize.sync({ logging: console.log })\n```\n\n```text\nUser.find(1).on('sql', console.log).then(function(user) {\n  // do whatever you want with the user here\n```\n\n```text\nError: Please note that find* was refactored and uses only one options object from now on.\n```\n\n```text\nUser.findAll({where: {...}, logging: console.log})\n```\n\n```text\nDEBUG=sequelize:sql*\n```\n\n```js\nlogging: console.log,\n```\n\n========================================\n\nComments:\n- Thanks, this is exactly what I want. `DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log` -- what does this mean?\n- Means you should pass a function instead of true.\n- I never ever passed `true`.\n- I'm a bit late to the party, but `console.log` works in mysterious ways. You should be able to avoid the log message using `{ logging: (msg) => console.log(msg) }` or `{ logging: function(msg) { console.log(msg) } }`. (untested so I could be totally wrong)\n- Is there any way I can see the generated query , but the query should not execute ?\n- You now pass in a logger as an option to log a single statement: `User.find(1, { logging: console.log })`\n- Mine just says `.findOne(...).on is not a function` Using sequelize 3.30.4\n- It appears that some of the association mixins do not support the logging option. Specifically, the `get*` on the source of a belongsTo relationship.\n- this also works with native queries: `query(statement, { replacements: { userId: userId, superiorPositions: [ 4, 5, 7 ], departments: [ departmentId ] }, logging: console.log });`\n- this is the correct answer for where logging: console.log should be placed, in sequelize 4.\n- Better one if you need to debug just selected queries! Thank you!\n- how do you disable this? I put this in my env and now it's impossible to remove it after debug.\n- @guest - just redefine the DEBUG variable as nothing. `DEBUG=''`","metadata":{"transformedAt":"2026-08-18T18:33:34.332Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":69,"estimatedTokens":720}}25{"id":"stack-20460270","source":"stackoverflow","questionId":20460270,"title":"How to make join queries using Sequelize on Node.js","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: How to make join queries using Sequelize on Node.js\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize ORM; everything is great and clean, but I had a problem when I use it with `join` queries.\nI have two models: users and posts.\n\n```\nvar User = db.seq.define('User',{\n username: { type: db.Sequelize.STRING},\n email: { type: db.Sequelize.STRING},\n password: { type: db.Sequelize.STRING},\n sex : { type: db.Sequelize.INTEGER},\n day_birth: { type: db.Sequelize.INTEGER},\n month_birth: { type: db.Sequelize.INTEGER},\n year_birth: { type: db.Sequelize.INTEGER}\n\n});\n\nUser.sync().success(function(){\n console.log(\"table created\")\n}).error(function(error){\n console.log(err);\n})\n\nvar Post = db.seq.define(\"Post\",{\n body: { type: db.Sequelize.TEXT },\n user_id: { type: db.Sequelize.INTEGER},\n likes: { type: db.Sequelize.INTEGER, defaultValue: 0 },\n\n});\n\nPost.sync().success(function(){\n console.log(\"table created\")\n}).error(function(error){\n console.log(err);\n})\n```\n\nI want a query that respond with a post with the info of user that made it. In the raw query, I get this:\n\n```\ndb.seq.query('SELECT * FROM posts, users WHERE posts.user_id = users.id ').success(function(rows){\n res.json(rows);\n });\n```\n\nMy question is how can I change the code to use the ORM style instead of the SQL query?\n\n========================================\n\nTop Answer:\nWhile the accepted answer isn't technically wrong, it doesn't answer the original question nor the up question in the comments, which was what I came here looking for. But I figured it out, so here goes.\n\nIf you want to find all Posts that have Users (and only the ones that have users) where the SQL would look like this:\n\n```\nSELECT * FROM posts INNER JOIN users ON posts.user_id = users.id\n```\n\nWhich is semantically the same thing as the OP's original SQL:\n\n```\nSELECT * FROM posts, users WHERE posts.user_id = users.id\n```\n\nthen this is what you want:\n\n```\nPosts.findAll({\n include: [{\n model: User,\n required: true\n }]\n}).then(posts => {\n /* ... */\n});\n```\n\nSetting required to true is the key to producing an inner join. If you want a left outer join (where you get all Posts, regardless of whether there's a user linked) then change required to false, or leave it off since that's the default:\n\n```\nPosts.findAll({\n include: [{\n model: User,\n// required: false\n }]\n}).then(posts => {\n /* ... */\n});\n```\n\nIf you want to find all Posts belonging to users whose birth year is in 1984, you'd want:\n\n```\nPosts.findAll({\n include: [{\n model: User,\n where: {year_birth: 1984}\n }]\n}).then(posts => {\n /* ... */\n});\n```\n\nNote that required is true by default as soon as you add a where clause in.\n\nIf you want all Posts, regardless of whether there's a user attached but if there is a user then only the ones born in 1984, then add the required field back in:\n\n```\nPosts.findAll({\n include: [{\n model: User,\n where: {year_birth: 1984}\n required: false,\n }]\n}).then(posts => {\n /* ... */\n});\n```\n\nIf you want all Posts where the name is \"Sunshine\" and only if it belongs to a user that was born in 1984, you'd do this:\n\n```\nPosts.findAll({\n where: {name: \"Sunshine\"},\n include: [{\n model: User,\n where: {year_birth: 1984}\n }]\n}).then(posts => {\n /* ... */\n});\n```\n\nIf you want all Posts where the name is \"Sunshine\" and only if it belongs to a user that was born in the same year that matches the post_year attribute on the post, you'd do this:\n\n```\nPosts.findAll({\n where: {name: \"Sunshine\"},\n include: [{\n model: User,\n where: [\"year_birth = post_year\"]\n }]\n}).then(posts => {\n /* ... */\n});\n```\n\nI know, it doesn't make sense that somebody would make a post the year they were born, but it's just an example - go with it. :)\n\nI figured this out (mostly) from this doc:\n\n- http://docs.sequelizejs.com/en/latest/docs/models-usage/#eager-loading\n\n========================================\n\nCode:\n```text\nvar User = db.seq.define('User',{\n    username: { type: db.Sequelize.STRING},\n    email: { type: db.Sequelize.STRING},\n    password: { type: db.Sequelize.STRING},\n    sex : { type: db.Sequelize.INTEGER},\n    day_birth: { type: db.Sequelize.INTEGER},\n    month_birth: { type: db.Sequelize.INTEGER},\n    year_birth: { type: db.Sequelize.INTEGER}\n\n});\n\nUser.sync().success(function(){\n    console.log(\"table created\")\n}).error(function(error){\n    console.log(err);\n})\n\n\nvar Post = db.seq.define(\"Post\",{\n    body: { type: db.Sequelize.TEXT },\n    user_id: { type: db.Sequelize.INTEGER},\n    likes: { type: db.Sequelize.INTEGER, defaultValue: 0 },\n\n});\n\nPost.sync().success(function(){\n    console.log(\"table created\")\n}).error(function(error){\n    console.log(err);\n})\n```\n\n```text\ndb.seq.query('SELECT * FROM posts, users WHERE posts.user_id = users.id ').success(function(rows){\n            res.json(rows);\n        });\n```\n\n```text\njoin\n```\n\n```text\nUser.hasMany(Post, {foreignKey: 'user_id'})\nPost.belongsTo(User, {foreignKey: 'user_id'})\n\nPost.find({ where: { ...}, include: [User]})\n```\n\n```text\nSELECT\n  `posts`.*,\n  `users`.`username` AS `users.username`, `users`.`email` AS `users.email`,\n  `users`.`password` AS `users.password`, `users`.`sex` AS `users.sex`,\n  `users`.`day_birth` AS `users.day_birth`,\n  `users`.`month_birth` AS `users.month_birth`,\n  `users`.`year_birth` AS `users.year_birth`, `users`.`id` AS `users.id`,\n  `users`.`createdAt` AS `users.createdAt`,\n  `users`.`updatedAt` AS `users.updatedAt`\nFROM `posts`\n  LEFT OUTER JOIN `users` AS `users` ON `users`.`id` = `posts`.`user_id`;\n```\n\n```text\nModel1.belongsTo(Model2, { as: 'alias' })\n\nModel1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);\n```\n\n```text\nSELECT * FROM posts INNER JOIN users ON posts.user_id = users.id\n```\n\n```text\nSELECT * FROM posts, users WHERE posts.user_id = users.id\n```\n\n```text\nPosts.findAll({\n  include: [{\n    model: User,\n    required: true\n   }]\n}).then(posts => {\n  /* ... */\n});\n```\n\n```text\nPosts.findAll({\n  include: [{\n    model: User,\n//  required: false\n   }]\n}).then(posts => {\n  /* ... */\n});\n```\n\n```text\nPosts.findAll({\n  include: [{\n    model: User,\n    where: {year_birth: 1984}\n   }]\n}).then(posts => {\n  /* ... */\n});\n```\n\n```text\nPosts.findAll({\n  include: [{\n    model: User,\n    where: {year_birth: 1984}\n    required: false,\n   }]\n}).then(posts => {\n  /* ... */\n});\n```\n\n```text\nPosts.findAll({\n  where: {name: \"Sunshine\"},\n  include: [{\n    model: User,\n    where: {year_birth: 1984}\n   }]\n}).then(posts => {\n  /* ... */\n});\n```\n\n```text\nPosts.findAll({\n  where: {name: \"Sunshine\"},\n  include: [{\n    model: User,\n    where: [\"year_birth = post_year\"]\n   }]\n}).then(posts => {\n  /* ... */\n});\n```\n\n```text\nUserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});\nUserMaster.hasMany(UserAccess,{foreignKey : 'userId'});\nvar userData = await UserMaster.findAll({include: [UserAccess]});\n```\n\n```text\nblog1.hasMany(blog2, {foreignKey: 'blog_id'})\nblog2.belongsTo(blog1, {foreignKey: 'blog_id'})\n```\n\n```text\nblog2.find({ where: {blog_id:1}, include: [blog1]})\n```\n\n========================================\n\nComments:\n- Related: stackoverflow.com/questions/22958683/&hellip;\n- What if I want to join only Users who are born in 1984 ? In SQL I would do : `SELECT * FROM posts JOIN users ON users.id = posts.user_id WHERE users.year_birth = 1984`\n- @Iwazaru The answer would be too long to fit in a comment, please open a new question\n- All links are dead not :-(\n- Did that question ever get posted in an answered question?\n- Do we need both of them or one is enough : User.hasMany(Post, {foreignKey: 'user_id'}) Post.belongsTo(User, {foreignKey: 'user_id'})\n- @theptrk I know this is an old post, but I answered both the original question and this extra question in my answer below.\n- @antew When you call `User.hasMany(Post)` you add methods / attributes to the User object, and when you call `Post.belongsTo(User)` you add methods to the Post class. If you're always calling from one direction (ex. User.getPosts()) then you don't need to add anything to the Post object. But it's nice to have the methods on both sides.\n- @antew thanks for the response, i was never able to find the link for the question regarding `SELECT * FROM posts JOIN users ON users.id = posts.user_id WHERE users.year_birth = 1984` but I think i figured it out by using `through` and a `where` object\n- @Ryan, thanks for the clarification. However it's not clear for me, if you meant foreign keys in the database, or methods / attributes in the Sequelize object. Thanks.\n- @theptrk I gave the answer for that exact query in my answer below (I don't see any reason to add a new question).\n- @antew I meant methods / attributes on the Sequelize object.\n- To join using include on a where just do `include[model:db.User,where:{birthyear:1984}}]`. you can filter attributes, too`include[model:db.User,where:{birthyear:1984},attributes:[&zwnj;&#8203;\"username\"]}]`. This wuld be equivalent to `FROM posts JOIN users.usernname on user.id=posts.user_id WHERE users.birthyear=1984`\n- Hi, Is below code block need to define on every query User.hasMany(Post, {foreignKey: 'user_id'}) Post.belongsTo(User, {foreignKey: 'user_id'}) I hope to find a way to generate models by sequelize-auto with foreign keys definition.\n- Where should I put this code? User.hasMany(Post, {foreignKey: 'user_id'}) Post.belongsTo(User, {foreignKey: 'user_id'});\n- @Iwazaru Just add { where: { '$users.birthyear$': 1984 } in your model query to get expected result.\n- so what represents `posts.user_id = users.id` in your sequelize? thanks\n- @hanzichi That the `posts.user_id` column matches the `users.id` column is set up in your sequelize model definition.\n- required false still gave me inner join for some reason\n- Maybe you spelled `required` wrong or put it in the wrong place?\n- what if you only want 1 column from users? example, username but not, id, password, email and so on\n- @JasonG You want the \"attributes\" key. Search for \"attributes\" in this doc: sequelize.org/master/manual/model-querying-basics.html\n- This helped me `SomeTable.hasOne(User, { sourceKey: \"UserId-In-SomeTable\", foreignKey: \"UserId-In-User-Table\" });`\n- and what could happen if it is needed a join on fields different to users.id and posts.user_id?\n- @JoseCabreraZuniga Look at the last example where `year_birth` is being joined with `post_year`.","metadata":{"transformedAt":"2026-08-18T18:33:34.333Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":349,"estimatedTokens":2588}}26{"id":"stack-20386402","source":"stackoverflow","questionId":20386402,"title":"Sequelize Unknown column '*.createdAt' in 'field list'","tags":["node.js","sequelize.js"],"text":"Title: Sequelize Unknown column '*.createdAt' in 'field list'\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting a Unknown column 'userDetails.createdAt' in 'field list'\nWhen trying to fetch with association.\n\nUsing `findAll` without association works fine.\n\nMy code is as follows:\n\n```\nvar userDetails = sequelize.define('userDetails', {\n userId :Sequelize.INTEGER,\n firstName : Sequelize.STRING,\n lastName : Sequelize.STRING,\n birthday : Sequelize.DATE\n});\n\nvar user = sequelize.define('user', {\n email: Sequelize.STRING,\n password: Sequelize.STRING\n});\n\nuser.hasOne(userDetails, {foreignKey: 'userId'});\n\nuser.findAll({include: [userDetails] }).success(function(user) {\n console.log(user)\n});\n```\n\n========================================\n\nTop Answer:\nI got the same error when migrating our project from laravel to featherjs. Tables are having column names created_at, updated_at instead of createdat, updatedat. I had to use field name mapping in Sequelize models as given below\n\n```\nconst users = sequelize.define('users', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true\n },\n createdAt: {\n field: 'created_at',\n type: Sequelize.DATE,\n },\n updatedAt: {\n field: 'updated_at',\n type: Sequelize.DATE,\n },\n ..\n ..\n ..\n ..\n```\n\n========================================\n\nCode:\n```js\nvar userDetails = sequelize.define('userDetails', {\n    userId :Sequelize.INTEGER,\n    firstName : Sequelize.STRING,\n    lastName : Sequelize.STRING,\n    birthday : Sequelize.DATE\n});\n\nvar user = sequelize.define('user', {\n    email: Sequelize.STRING,\n    password: Sequelize.STRING\n});\n\nuser.hasOne(userDetails, {foreignKey: 'userId'});\n\nuser.findAll({include: [userDetails] }).success(function(user) {\n    console.log(user)\n});\n```\n\n```text\nfindAll\n```\n\n```text\nSELECT `users`.*, `userDetails`.`userId` AS `userDetails.userId`,`userDetails`.`firstName` AS `userDetails.firstName`,`userDetails`.`lastName` AS `userDetails.lastName`, `userDetails`.`birthday` AS `userDetails.birthday`, `userDetails`.`id` AS `userDetails.id`, `userDetails`.`createdAt` AS `userDetails.createdAt`, `userDetails`.`updatedAt` AS `userDetails.updatedAt` FROM `users` LEFT OUTER JOIN `userDetails` AS `userDetails` ON `users`.`id` = `userDetails`.`userId`;\n```\n\n```text\nvar userDetails = sequelize.define('userDetails', {\n    userId :Sequelize.INTEGER,\n    firstName : Sequelize.STRING,\n    lastName : Sequelize.STRING,\n    birthday : Sequelize.DATE\n}, {\n    timestamps: false\n});\n```\n\n```text\nvar sequelize = new Sequelize('sequelize_test', 'root', null, {\n    host: \"127.0.0.1\",\n    dialect: 'mysql',\n    define: {\n        timestamps: false\n    }\n});\n```\n\n```text\nSELECT user.*\n```\n\n```text\nconst users = sequelize.define('users', {\n     id: {\n         type: Sequelize.INTEGER,\n         primaryKey: true\n     },\n     createdAt: {\n         field: 'created_at',\n         type: Sequelize.DATE,\n     },\n     updatedAt: {\n         field: 'updated_at',\n         type: Sequelize.DATE,\n     },\n     ..\n     ..\n     ..\n     ..\n```\n\n```text\nCREATE TABLE `users` (\n  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',\n  `name` varchar(30) DEFAULT NULL COMMENT 'user name',\n  `created_at` datetime DEFAULT NULL COMMENT 'created time',\n  `updated_at` datetime DEFAULT NULL COMMENT 'updated time',\n  PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='user';\n```\n\n```text\nconst Project = sequelize.define('project', {\n   title: Sequelize.STRING,\n   description: Sequelize.TEXT\n },{\n   timestamps: false\n })\n```\n\n```text\nconst User = sequelize.define('user', {\n    firstName : Sequelize.STRING,\n    lastName : Sequelize.STRING,\n}, {\n    timestamps: false\n});\n```\n\n```text\ncreatedAt: {\n        allowNull: false,\n        defaultValue: Sequelize.fn('now'),\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        defaultValue: Sequelize.fn('now'),\n        type: Sequelize.DATE\n      }\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Customer = sequelize.define('customer', {\n    name: DataTypes.STRING,\n    email: DataTypes.STRING,\n    phone: DataTypes.TEXT,\n    consider: DataTypes.TEXT,\n    otherQuestion: DataTypes.TEXT\n  }, {})\n  return Customer\n```\n\n```text\nconst sequelize = new Sequelize('postgres://user:pass@url:port/dbname',{ \n    define:{\n        timestamps: false\n    }\n})\n```\n\n```text\nuser\n```\n\n```text\npass\n```\n\n```text\nurl\n```\n\n```text\nport\n```\n\n```text\ndbname\n```\n\n```text\n{\n  timestamps: true,\n}\n```\n\n```text\n{\n  timestamps: true,\n  underscored: true,\n}\n```\n\n========================================\n\nComments:\n- this doesnt make sense because thats not how a sequelize model looks anymore. after the field list is class and instancemethods\n- This is quite annoying. I was having no problem, `timestamps: false` was enough, but suddenly the Sequelize added a` .createdAt` to the SELECT of a specific table, in a foreign key column. Then I needed to include `define: { timestamps: false }` in the Sequelize instantiation and it worked for me.\n- Can you please give some link to the documentation? Because i don't need to find more information.\n- I ended up using: `const sequelize = new Sequelize(`postgres:&#47;&#47;${db.user}:${db.password}@${db.host}:$&zwnj;&#8203;{db.port}&#47;${db.schem&zwnj;&#8203;a}`, { define: { underscored:true, }, &#47;&#47;Solving timestamps problem logging: false, })`","metadata":{"transformedAt":"2026-08-18T18:33:34.333Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":234,"estimatedTokens":1342}}27{"id":"stack-28927836","source":"stackoverflow","questionId":28927836,"title":"Prevent Sequelize from outputting SQL to the console on execution of query?","tags":["node.js","sequelize.js"],"text":"Title: Prevent Sequelize from outputting SQL to the console on execution of query?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a function to retrieve a user's profile.\n\n```\napp.get('/api/user/profile', function (request, response)\n{\n // Create the default error container\n var error = new Error();\n\n var User = db.User;\n User.find({\n where: { emailAddress: request.user.username}\n }).then(function(user)\n {\n if(!user)\n {\n error.status = 500; error.message = \"ERROR_INVALID_USER\"; error.code = 301;\n return next(error);\n }\n\n // Build the profile from the user object\n profile = {\n \"firstName\": user.firstName,\n \"lastName\": user.lastName,\n \"emailAddress\": user.emailAddress\n }\n response.status(200).send(profile);\n });\n});\n```\n\nWhen the \"find\" function is called it displays the select statement on the console where the server was started. \n\n```\nExecuting (default): SELECT `id`, `firstName`, `lastName`, `emailAddress`, `password`, `passwordRecoveryToken`, `passwordRecoveryTokenExpire`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`emailAddress` = 'johndoe@doe.com' LIMIT 1;\n```\n\nIs there a way to get this not to be display? Some flag that I set in a config file somewhere?\n\n========================================\n\nTop Answer:\nIf `config/config.json` file is used then add `\"logging\": false` to the `config.json` in this case under development configuration section.\n\n```\n// file config/config.json\n{\n \"development\": {\n \"username\": \"username\",\n \"password\": \"password\",\n \"database\": \"db_name\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"mysql\",\n \"logging\": false\n },\n \"test\": {\n // ...\n }\n}\n```\n\n========================================\n\nCode:\n```text\napp.get('/api/user/profile', function (request, response)\n{\n  // Create the default error container\n  var error = new Error();\n\n  var User = db.User;\n  User.find({\n    where: { emailAddress: request.user.username}\n  }).then(function(user)\n  {\n    if(!user)\n    {\n      error.status = 500; error.message = \"ERROR_INVALID_USER\"; error.code = 301;\n      return next(error);\n    }\n\n    // Build the profile from the user object\n    profile = {\n      \"firstName\": user.firstName,\n      \"lastName\": user.lastName,\n      \"emailAddress\": user.emailAddress\n    }\n    response.status(200).send(profile);\n  });\n});\n```\n\n```text\nExecuting (default): SELECT `id`, `firstName`, `lastName`, `emailAddress`, `password`, `passwordRecoveryToken`, `passwordRecoveryTokenExpire`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`emailAddress` = 'johndoe@doe.com' LIMIT 1;\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n  \n  // disable logging; default: console.log\n  logging: false\n\n});\n```\n\n```text\nfalse\n```\n\n```text\nlogging\n```\n\n```json\n// file config/config.json\n{\n  \"development\": {\n    \"username\": \"username\",\n    \"password\": \"password\",\n    \"database\": \"db_name\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\",\n    \"logging\": false\n  },\n  \"test\": {\n    // ...\n  }\n}\n```\n\n```text\nconfig/config.json\n```\n\n```text\n\"logging\": false\n```\n\n```text\nconfig.json\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n  logging: winston.debug\n});\n```\n\n```text\nlogging:false\n```\n\n```text\n{\n  \"development\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"logging\" : false,\n    \"database\": \"posts_db_dev\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\",\n    \"operatorsAliases\": false \n  }\n}\n```\n\n```text\nconfig.json\n```\n\n```text\nconst sequelize = new Sequelize(\n        process.env.databaseName,\n        process.env.databaseUser,\n        process.env.password,\n        {\n            host: process.env.databaseHost,\n            dialect: process.env.dialect,\n            \"logging\": false,\n            define: {\n                // Table names won't be pluralized.\n                freezeTableName: true,\n                // All tables won't have \"createdAt\" and \"updatedAt\" Auto fields.\n                timestamps: false\n            }\n        }\n    );\n```\n\n```text\n.env\n```\n\n```text\n// Somewhere your code, turn off the logging\nsequelize.options.logging = false\n\n// Somewhere your code, turn on the logging\nsequelize.options.logging = true\n```\n\n```text\nsequelize\n```\n\n```text\nnew Sequelize(..\n```\n\n```text\nconst sequelize = new Sequelize(\"test\", \"root\", \"root\", {\n  host: \"127.0.0.1\",\n  dialect: \"mysql\",\n  port: \"8889\",\n  connectionLimit: 10,\n  socketPath: \"/Applications/MAMP/tmp/mysql/mysql.sock\",\n  // It will disable logging\n  logging: false\n});\n```\n\n```text\n{\n    'type': process.env.DB_DRIVER,\n    'host': process.env.DB_HOST,\n    'port': process.env.DB_PORT,\n    'username': process.env.DB_USER,\n    'password': process.env.DB_PASS,\n    'database': process.env.DB_NAME,\n    'migrations': [process.env.MIGRATIONS_ENTITIES],\n    'synchronize': false,\n    'logging': process.env.DB_QUERY_LEVEL,\n    'entities': [\n        process.env.ORM_ENTITIES\n    ],\n    'cli': {\n        'migrationsDir': 'migrations'\n     }\n}\n```\n\n```text\ntypeorm\n```\n\n```text\nfalse\n```\n\n```text\nDB_QUERY_LEVEL\n```\n\n```js\nnew Sequelize({\n    host: \"localhost\",\n    database: \"database_name\",\n    dialect: \"mysql\",\n    username: \"root\",\n    password: \"password\",\n    logging: false        // for disable logs\n})\n```\n\n```text\nUser.findAll({ \n    where: { emailAddress: request.user.username},\n    logging: false\n  }).then(function(user)....\n```\n\n========================================\n\nComments:\n- I have a question, suppose i dont want password field returned in findOrCreate () method. How can i do this ?\n- @SunilSharma exclude the attribute, search for `exclude` on this page sequelize.readthedocs.io/en/latest/docs/querying/#attributes\n- you are better off starting a new question than trying to piggyback a new question on an barely related one.\n- Thank you,this is working however it gives a white space for each query executed. Can you please help me..\n- For now, `logging` option should be a function.\n- This doesn't seem to have an effect when using sequelize v4. Anyone found a a resolution?\n- getting 404 error on given webpage\n- Is there a way to bit nicely format SQL queries output on terminal? it looks kinda messy especially with those joins\n- very interesting :) this is actually great.. .I will try\n- people still use MAMP?\n- Yes, for development, if you have another best free option, please let me know, thanks\n- This is what i was looking for but keep in mind that this example is malformed. It should be: User.findAll( { where: { emailAddress: request.user.username}, logging: false}) .then(function(user)....","metadata":{"transformedAt":"2026-08-18T18:33:34.333Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":290,"estimatedTokens":1637}}28{"id":"stack-36259532","source":"stackoverflow","questionId":36259532,"title":"sequelize findAll sort order in nodejs","tags":["node.js","express","sequelize.js"],"text":"Title: sequelize findAll sort order in nodejs\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to output all object list from database with sequelize as and want to get data are sorted out as I added id in where clause.\n\n```\nexports.getStaticCompanies = function () {\n return Company.findAll({\n where: {\n id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]\n },\n attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']\n });\n};\n```\n\nBut the problem is after rendering, all data are sorted out as .\n\n```\n46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....\n```\n\nAs I found, it's neither sorted by id nor name. Please help me how to solve it.\n\n========================================\n\nTop Answer:\nIf you want to sort data either in Ascending or Descending order based on particular column, using `sequlize js`, use the `order` method of `sequlize` as follows\n\n```\n// Will order the specified column by descending order\norder: sequelize.literal('column_name order')\ne.g. order: sequelize.literal('timestamp DESC')\n```\n\n========================================\n\nCode:\n```text\nexports.getStaticCompanies = function () {\n    return Company.findAll({\n        where: {\n            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]\n        },\n        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']\n    });\n};\n```\n\n```text\n46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....\n```\n\n```text\nexports.getStaticCompanies = function () {\n    return Company.findAll({\n        where: {\n            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]\n        }, \n        // Add order conditions here....\n        order: [\n            ['id', 'DESC'],\n            ['name', 'ASC'],\n        ],\n        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']\n    });\n};\n```\n\n```text\norder: [\n      ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order\n],\n```\n\n```text\norder\n```\n\n```text\n.then()\n```\n\n```text\nvar numbers = [2, 20, 23, 9, 53];\nvar orderIWant = [2, 23, 20, 53, 9];\norderIWant.map(x => { return numbers.find(y => { return y === x })});\n```\n\n```text\ncompare_bigger(1,2) => 2\n```\n\n```text\n2,4,11,2,9,0\n```\n\n```text\nfindAll\n```\n\n```text\nnumbers\n```\n\n```text\n[2, 23, 20, 53, 9]\n```\n\n```text\nfindOne\n```\n\n```text\nexports.getStaticCompanies = function () {\n    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]\n    return Company.findAll({\n        where: {\n            id: ids\n        },\n        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],\n        order: sequelize.literal('(' + ids.map(function(id) {\n            return '\"Company\".\"id\" = \\'' + id + '\\'');\n        }).join(', ') + ') DESC')\n    });\n};\n```\n\n```text\n[...] ORDER BY (\"Company\".\"id\"='46128', \"Company\".\"id\"='2865', \"Company\".\"id\"='49569', [...])\n```\n\n```text\nCompany.findAll({\n    where: {id : {$in : companyIds}},\n    order: sequelize.literal(\"FIELD(company.id,\"+companyIds.join(',')+\")\")\n})\n```\n\n```text\norder by FIELD(id, ...)\n```\n\n```text\n// Will order the specified column by descending order\norder: sequelize.literal('column_name order')\ne.g. order: sequelize.literal('timestamp DESC')\n```\n\n```text\nsequlize js\n```\n\n```text\norder\n```\n\n```text\nsequlize\n```\n\n```text\nconst arr = [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680];\nconst ord = [sequelize.literal(`ARRAY_POSITION(ARRAY[${arr}]::integer[], \"id\")`)];\n\nreturn Company.findAll({\n    where: {\n        id: arr\n    },\n    attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],\n    order: ord,\n});\n```\n\n```text\ncase \nwhen id=46128 then 0\nwhen id=2865 then 1\nwhen id=49569 then 2\nend as order_field\n\nand order by order_field.\n```\n\n```text\nexports.readAll = (req, res) => {\n  console.log(\"Inside ReadAll Data method\");\n  let data;\n  if (!req.body) {\n    data = CompanyModel.findAll({  order: [[sequelize.literal('\"updatedAt\"'), 'DESC']]});\n  } else {\n    data = CompanyModel.findAll({  order: [[sequelize.literal('\"updatedAt\"'), 'DESC']]});\n  }\n  data\n    .then((data) => {\n      res.send(\n        data\n      );\n    })\n    .catch((err) => {\n      res.status(500).send({\n        message: err.message || \"Some error occurred while retrieving data.\",\n      });\n    });\n};\n```\n\n```text\nInside ReadAll Data method\n\nExecuting (default): SELECT \"company_name\", \"company_id\", \"on_record\", \"createdAt\", \"updatedAt\" FROM \"companies\" AS \"company\" ORDER BY \"updatedAt\" DESC;\n```\n\n```text\nupdatedAt\n```\n\n```text\nconst ids = [\n'f01a057e-5646-4527-a219-336804317246', \n'ee900087-4910-42b4-a559-06aea7b4e250', \n'b363f116-1fc5-473a-aed7-0ceea9beb14d'\n];\n\nconst idsFormat = `'${ids.join(\"','\")}'`;\n\nconst order = [sequelize.literal(`ARRAY_POSITION(ARRAY[${idsFormat}]::uuid[], \"<insert_table_name>\".\"id\")`)];\n```\n\n========================================\n\nComments:\n- I want to order like that by `46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680`.\n- Hmmm. You won't be able to do that (as far as I know)! You'll have to look into sorting the objects once you've received them in the .then() promise? Why do you need to order them in this specific range?! Is there a order clause that could maybe do it for you? @ppshein\n- I tried to do the same with a table associated with another, It did not worked. How can we do this with association @james111\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.333Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":238,"estimatedTokens":1444}}29{"id":"stack-8158244","source":"stackoverflow","questionId":8158244,"title":"How to update a record using sequelize for node?","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: How to update a record using sequelize for node?\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm creating a RESTful API with NodeJS, express, express-resource, and Sequelize that is used to manage datasets stored in a MySQL database.\n\nI'm trying to figure out how to properly update a record using Sequelize.\n\nI create a model:\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n return sequelize.define('Locale', {\n id: {\n type: DataTypes.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n locale: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n validate: {\n len: 2\n }\n },\n visible: {\n type: DataTypes.BOOLEAN,\n defaultValue: 1\n }\n })\n}\n```\n\nThen, in my resource controller, I define an update action.\n\nIn here I want to be able to update the record where the id matches a `req.params` variable.\n\nFirst I build a model and then I use the `updateAttributes` method to update the record.\n\n```\nconst Sequelize = require('sequelize')\nconst { dbconfig } = require('../config.js')\n\n// Initialize database connection\nconst sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password)\n\n// Locale model\nconst Locales = sequelize.import(__dirname + './models/Locale')\n\n// Create schema if necessary\nLocales.sync()\n\n/**\n * PUT /locale/:id\n */\n\nexports.update = function (req, res) {\n if (req.body.name) {\n const loc = Locales.build()\n\n loc.updateAttributes({\n locale: req.body.name\n })\n .on('success', id => {\n res.json({\n success: true\n }, 200)\n })\n .on('failure', error => {\n throw new Error(error)\n })\n }\n else\n throw new Error('Data not provided')\n}\n```\n\nNow, this does not actually produce an update query as I would expect.\n\nInstead, an insert query is executed:\n\n```\nINSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)\nVALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)\n```\n\nSo my question is: What is the proper way to update a record using Sequelize ORM?\n\n========================================\n\nTop Answer:\nSince version 2.0.0 you need to wrap your **where** clause in a `where` property:\n\n```\nProject.update(\n { title: 'a very different title now' },\n { where: { _id: 1 } }\n)\n .success(result =>\n handleResult(result)\n )\n .error(err =>\n handleError(err)\n )\n```\n\n### Update 2016-03-09\n\nThe latest version actually doesn't use `success` and `error` anymore but instead uses `then`-able promises.\n\nSo the upper code will look as follows:\n\n```\nProject.update(\n { title: 'a very different title now' },\n { where: { _id: 1 } }\n)\n .then(result =>\n handleResult(result)\n )\n .catch(err =>\n handleError(err)\n )\n```\n\n### Using async/await\n\n```\ntry {\n const result = await Project.update(\n { title: 'a very different title now' },\n { where: { _id: 1 } }\n )\n handleResult(result)\n} catch (err) {\n handleError(err)\n}\n```\n\nSee links: docs Link and API Link\n\n========================================\n\nCode:\n```text\nmodule.exports = function (sequelize, DataTypes) {\n  return sequelize.define('Locale', {\n    id: {\n      type: DataTypes.INTEGER,\n      autoIncrement: true,\n      primaryKey: true\n    },\n    locale: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true,\n      validate: {\n        len: 2\n      }\n    },\n    visible: {\n      type: DataTypes.BOOLEAN,\n      defaultValue: 1\n    }\n  })\n}\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst { dbconfig } = require('../config.js')\n\n// Initialize database connection\nconst sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password)\n\n// Locale model\nconst Locales = sequelize.import(__dirname + './models/Locale')\n\n// Create schema if necessary\nLocales.sync()\n\n\n/**\n * PUT /locale/:id\n */\n\nexports.update = function (req, res) {\n  if (req.body.name) {\n    const loc = Locales.build()\n\n    loc.updateAttributes({\n      locale: req.body.name\n    })\n      .on('success', id => {\n        res.json({\n          success: true\n        }, 200)\n      })\n      .on('failure', error => {\n        throw new Error(error)\n      })\n  }\n  else\n    throw new Error('Data not provided')\n}\n```\n\n```text\nINSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)\nVALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)\n```\n\n```text\nreq.params\n```\n\n```text\nupdateAttributes\n```\n\n```text\nProject.find({ where: { title: 'aProject' } })\n  .on('success', function (project) {\n    // Check if record exists in db\n    if (project) {\n      project.update({\n        title: 'a very different title now'\n      })\n      .success(function () {})\n    }\n  })\n```\n\n```text\nProject.update(\n\n  // Set Attribute values \n        { title:'a very different title now' },\n\n  // Where clause / criteria \n         { _id : 1 }     \n\n ).success(function() { \n\n     console.log(\"Project with id =1 updated successfully!\");\n\n }).error(function(err) { \n\n     console.log(\"Project update failed !\");\n     //handle error here\n\n });\n```\n\n```text\nProject.update(\n  { title: 'a very different title now' },\n  { where: { _id: 1 } }\n)\n  .success(result =>\n    handleResult(result)\n  )\n  .error(err =>\n    handleError(err)\n  )\n```\n\n```text\nProject.update(\n  { title: 'a very different title now' },\n  { where: { _id: 1 } }\n)\n  .then(result =>\n    handleResult(result)\n  )\n  .catch(err =>\n    handleError(err)\n  )\n```\n\n```text\ntry {\n  const result = await Project.update(\n    { title: 'a very different title now' },\n    { where: { _id: 1 } }\n  )\n  handleResult(result)\n} catch (err) {\n  handleError(err)\n}\n```\n\n```text\nwhere\n```\n\n```text\nsuccess\n```\n\n```text\nerror\n```\n\n```text\nthen\n```\n\n```text\nProject.update(\n      { title: 'a very different title no' } /* set attributes' value */, \n      { where: { _id : 1 }} /* where criteria */\n).then(function(affectedRows) {\nProject.findAll().then(function(Projects) {\n     console.log(Projects) \n})\n```\n\n```text\nUPDATE ... WHERE\n```\n\n```text\nProject.update(\n\n    // Set Attribute values \n    {\n        title: 'a very different title now'\n    },\n\n    // Where clause / criteria \n    {\n        _id: 1\n    }\n\n).then(function() {\n\n    console.log(\"Project with id =1 updated successfully!\");\n\n}).catch(function(e) {\n    console.log(\"Project update failed !\");\n})\n```\n\n```text\n.complete()\n```\n\n```text\nProject.update(\n    // Set Attribute values \n    { title:'a very different title now' },\n  // Where clause / criteria \n     { _id : 1 }     \n  ).then(function(result) { \n\n //it returns an array as [affectedCount, affectedRows]\n\n  })\n```\n\n```text\nProject.update(\n    // Values to update\n    {\n        title:  'a very different title now'\n    },\n    { // Clause\n        where: \n        {\n            id: 1\n        }\n    }\n).then(count => {\n    console.log('Rows updated ' + count);\n});\n```\n\n```text\nconst title = \"title goes here\";\nconst id = 1;\n\n    try{\n    const result = await Project.update(\n          { title },\n          { where: { id } }\n        )\n    }.catch(err => console.log(err));\n```\n\n```text\ntry{\n  const result = await Project.update(\n    { title: \"Updated Title\" }, //what going to be updated\n    { where: { id: 1 }} // where clause\n  )  \n} catch (error) {\n  // error handling\n}\n```\n\n```text\nProject.update(\n    { title: \"Updated Title\" }, //what going to be updated\n    { where: { id: 1 }} // where clause\n)\n.then(result => {\n  // code with result\n})\n.catch(error => {\n  // error handling\n})\n```\n\n```text\nconst sequelizeModel = require(\"../models/sequelizeModel\");\n    const id = req.params.id;\n            sequelizeModel.findAll(id)\n            .then((result)=>{\n                result.name = updatedName;\n                result.lastname = updatedLastname;\n                result.price = updatedPrice;\n                result.tele = updatedTele;\n                return result.save()\n            })\n            .then((result)=>{\n                    console.log(\"the data was Updated\");\n                })\n            .catch((err)=>{\n                console.log(\"Error : \",err)\n            });\n```\n\n```text\nconst id = req.params.id;\n            const name = req.body.name;\n            const lastname = req.body.lastname;\n            const tele = req.body.tele;\n            const price = req.body.price;\n    StudentWork.update(\n        {\n            name        : name,\n            lastname    : lastname,\n            tele        : tele,\n            price       : price\n        },\n        {returning: true, where: {id: id} }\n      )\n            .then((result)=>{\n                console.log(\"data was Updated\");\n                res.redirect('/');\n            })\n    .catch((err)=>{\n        console.log(\"Error : \",err)\n    });\n```\n\n```text\nresult.feild = updatedField\n```\n\n```text\nSequlizeModel.findOne({where: {id: 'some-id'}})\n.then(record => {\n  \n  if (!record) {\n    throw new Error('No record found')\n  }\n\n  console.log(`retrieved record ${JSON.stringify(record,null,2)}`) \n\n  let values = {\n    registered : true,\n    email: 'some@email.com',\n    name: 'Joe Blogs'\n  }\n  \n  record.update(values).then( updatedRecord => {\n    console.log(`updated record ${JSON.stringify(updatedRecord,null,2)}`)\n    // login into your DB and confirm update\n  })\n\n})\n.catch((error) => {\n  // do seomthing with the error\n  throw new Error(error)\n})\n```\n\n```text\nModel.update()\n```\n\n```text\nInstance.update()\n```\n\n```text\nModel.findOne()\n```\n\n```text\nModel.findByPkId()\n```\n\n```text\nInstance.update()\n```\n\n```text\nsequelize@5.21.3\n```\n\n```text\nUser.increment(\"field\", {by: 1, where: {id: 1});\n```\n\n```text\nconst objectToUpdate = {\ntitle: 'Hello World',\ndescription: 'Hello World'\n}\n\nmodels.Locale.update(objectToUpdate, { where: { id: 2}})\n```\n\n```text\nmodels.Locale.update({ title: 'Hello World'}, { where: { id: 2}})\n```\n\n```text\nconst objectToUpdate = {\ntitle: 'Hello World',\ndescription: 'Hello World'\n}\n\nmodels.Locale.findAll({ where: { title: 'Hello World'}}).then((result) => {\n   if(result){\n   // Result is array because we have used findAll. We can use findOne as well if you want one row and update that.\n        result[0].set(objectToUpdate);\n        result[0].save(); // This is a promise\n}\n})\n```\n\n```text\nmodels.sequelize.transaction((tx) => {\n    models.Locale.update(objectToUpdate, { transaction: tx, where: {id: 2}});\n})\n```\n\n```text\neditLocale: async (req, res) => {\n\n    sequelize.sequelize.transaction(async (t1) => {\n\n        if (!req.body.id) {\n            logger.warn(error.MANDATORY_FIELDS);\n            return res.status(500).send(error.MANDATORY_FIELDS);\n        }\n\n        let id = req.body.id;\n\n        let checkLocale= await sequelize.Locale.findOne({\n            where: {\n                id : req.body.id\n            }\n        });\n\n        checkLocale = checkLocale.get();\n        if (checkLocale ) {\n            let Locale= await sequelize.Locale.update(req.body, {\n                where: {\n                    id: id\n                }\n            });\n\n            let result = error.OK;\n            result.data = Locale;\n\n            logger.info(result);\n            return res.status(200).send(result);\n        }\n        else {\n            logger.warn(error.DATA_NOT_FOUND);\n            return res.status(404).send(error.DATA_NOT_FOUND);\n        }\n    }).catch(function (err) {\n        logger.error(err);\n        return res.status(500).send(error.SERVER_ERROR);\n    });\n},\n```\n\n```text\nsequelize.js\n```\n\n```text\nnode.js\n```\n\n```text\ntransaction\n```\n\n```text\nModel.findOne({\n    where: {\n      condtions\n    }\n  }).then( j => {\n    return j.update({\n      field you want to update\n    }).then( r => {\n      return res.status(200).json({msg: 'succesfully updated'});\n    }).catch(e => {\n      return res.status(400).json({msg: 'error ' +e});\n    })\n  }).catch( e => {\n    return res.status(400).json({msg: 'error ' +e});\n  });\n```\n\n```text\ntry{ \n    await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})\n}\ncatch(err){\n    console.log(err)\n}\n```\n\n```text\nModel.update\n```\n\n```text\nmodels.users.update({req.body},\n{where:{ id:1}}\n)\n```\n\n```text\nvar whereStatement = {};\n\n  whereStatement.id = req.userId;\n\n  if (whereStatement) {\n    User.findOne({\n      where: whereStatement\n    })\n      .then(user => {\n\n        if (user) {\n          \n          var updateuserdetails = {\n            email: req.body.email,\n            mobile: req.body.mobile,\n            status: req.body.status,\n            user_type_id: req.body.user_type_id\n          };\n\n          user.update(\n            updateuserdetails\n          )\n            .then(function () {\n              res.status(200).send({ message: 'Success...' });\n            })\n            .catch(err => {\n              res.status(500).send({ message: err.message });\n            });\n        }\n\n        \n      })\n```\n\n```text\nconst approveUser = asyncHandler(async (req, res) => {\n\n  var userID = parseInt(req.params.id);\n\n  const user = await User.findByPk(userID);\n\n  if (!user) throw new Error('No record found');\n\n  const result = await user.update({ isValid: !user.isValid });\n\n  if (result) {\n    res.status(201).json({\n      result,\n    });\n  } else {\n    res.status(400);\n    throw new Error('Invalid data');\n  }\n});\n```\n\n```text\nlet data = await UserModel.update(body, {\n  where: {\n    id:id,\n  },\n  individualHooks: true,\n});\n```\n\n```text\nUserModel\n```\n\n```text\nconst localeName = req.body.name;\nconst localeId = req.body.id;\n\nconst locale = await Locale.findOne({ where: { id: localeId } });\nif (locale) {\n    locale.name = localeName;\n    await locale.save();\n}\n```\n\n```text\nawait Locale.update({ name: localeName }, {\n  where: {\n    id: localeId\n  }\n});\n```\n\n========================================\n\nComments:\n- This works, however I did have to change `.success` to `.then`\n- Should it be `Project.findOne(` ?\n- Old question but relevant if searching today (as I did). As of Sequelize 5, the correct way to find the record is with `findByPk(req.params.id)` which returns an instance.\n- This should not be recommended, it sends 2 queries where it could be done by single query. Please check other answers below.\n- will this run validation too?\n- From what I've read in the API docs this is the preferred method.\n- It has actually been deprecated. See the official API Reference for Model.\n- Here are the docs as of the time of this comment—they've moved to ReadTheDocs.\n- As mentioned, this notation is deprecated since 2.0.0. Please also refer to this answer: stackoverflow.com/a/26303473/831499\n- Docs moved to: sequelize.readthedocs.org/en/latest/api/model/&hellip;\n- You have more upvotes than the first thread answer, i think it should be moved to the first answer of these answers thread. Cheers.\n- This sould be the accepted answer. This way you can only set some fields, and you can specify the criteria. Thank you very much :)\n- This should be the top answer.\n- Not working in 2019: Unhandled rejection Error: Invalid value [Function]\n- Working fine with Sequelize 6.6.2 (June 2021).\n- Works well well with Sequelize 6.21.4 (Aug 2022)\n- model.update(data, { where: {id: 1} }); is still working in 202 v6.x as per the answer from @kube\n- The problem, again, is that this would require two SQL transactions (select and update) instead of one (update).\n- I think it would throw an error, because the property \"where\" is outside of the brackets\n- I'd avoid 1 way. There are: a) no reason to do 2 requests instead of 1; b) in some cases there could be a race\n- The 1st way can open a breach to dirt updates, you need to use a transaction or use the 2nd option.","metadata":{"transformedAt":"2026-08-18T18:33:34.333Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":52,"totalLines":758,"estimatedTokens":3877}}30{"id":"stack-8402597","source":"stackoverflow","questionId":8402597,"title":"Sequelize.js delete query?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize.js delete query?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to write a delete/deleteAll query like findAll?\n\nFor example I want to do something like this (assuming MyModel is a Sequelize model...):\n\n```\nMyModel.deleteAll({ where: ['some_field != ?', something] })\n .on('success', function() { /* ... */ });\n```\n\n========================================\n\nTop Answer:\nI've searched deep into the code, step by step into the following files:\n\nhttps://github.com/sdepold/sequelize/blob/master/test/Model/destroy.js\n\nhttps://github.com/sdepold/sequelize/blob/master/lib/model.js#L140\n\nhttps://github.com/sdepold/sequelize/blob/master/lib/query-interface.js#L207-217\n\nhttps://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js\n\nWhat I found:\n\nThere isn't a deleteAll method, there's a destroy() method you can call on a record, for example:\n\n```\nProject.find(123).on('success', function(project) {\n project.destroy().on('success', function(u) {\n if (u && u.deletedAt) {\n // successfully deleted the project\n }\n })\n})\n```\n\n========================================\n\nCode:\n```text\nMyModel.deleteAll({ where: ['some_field != ?', something] })\n    .on('success', function() { /* ... */ });\n```\n\n```text\nModel.destroy({\n    where: {\n        // criteria\n    }\n})\n```\n\n```text\nProject.find(123).on('success', function(project) {\n  project.destroy().on('success', function(u) {\n    if (u && u.deletedAt) {\n      // successfully deleted the project\n    }\n  })\n})\n```\n\n```text\n// Delete the user with id=4\nUser.findAndDelete(4,function(error,result){\n  // all done\n});\n\n// Delete all users with type === 'suspended'\nUser.findAndDelete({\n  type: 'suspended'\n},function(error,result){\n  // all done\n});\n```\n\n```text\n/**\n * Retrieve models which match `where`, then delete them\n */\nfunction findAndDelete (where,callback) {\n\n    // Handle *where* argument which is specified as an integer\n    if (_.isFinite(+where)) {\n        where = {\n            id: where\n        };\n    }\n\n    Model.findAll({\n        where:where\n    }).success(function(collection) {\n        if (collection) {\n            if (_.isArray(collection)) {\n                Model.deleteAll(collection, callback);\n            }\n            else {\n                collection.destroy().\n                success(_.unprefix(callback)).\n                error(callback);\n            }\n        }\n        else {\n            callback(null,collection);\n        }\n    }).error(callback);\n}\n\n/**\n * Delete all `models` using the query chainer\n */\ndeleteAll: function (models) {\n    var chainer = new Sequelize.Utils.QueryChainer();\n    _.each(models,function(m,index) {\n        chainer.add(m.destroy());\n    });\n    return chainer.run();\n}\n```\n\n```text\nUser.destroy('`name` LIKE \"J%\"').success(function() {\n    // We just deleted all rows that have a name starting with \"J\"\n})\n```\n\n```text\nModel.destroy({\n   where: {\n      id: 123 //this will be your id that you want to delete\n   }\n}).then(function(rowDeleted){ // rowDeleted will return number of rows deleted\n  if(rowDeleted === 1){\n     console.log('Deleted successfully');\n   }\n}, function(err){\n    console.log(err); \n});\n```\n\n```text\nfunction (req,res) {    \n        model.destroy({\n            where: {\n                id: req.params.id\n            }\n        })\n        .then(function (deletedRecord) {\n            if(deletedRecord === 1){\n                res.status(200).json({message:\"Deleted successfully\"});          \n            }\n            else\n            {\n                res.status(404).json({message:\"record not found\"})\n            }\n        })\n        .catch(function (error){\n            res.status(500).json(error);\n        });\n```\n\n```text\nasync deleteProduct(id) {\n\n        if (!id) {\n            return {msg: 'No Id specified..', payload: 1};\n        }\n\n        try {\n            return !!await products.destroy({\n                where: {\n                    id: id\n                }\n            });\n        } catch (e) {\n            return false;\n        }\n\n    }\n```\n\n```text\n!!\n```\n\n```text\nconst StudentSequelize = require(\"../models/studientSequelize\");\nconst StudentWork = StudentSequelize.Student;\n\nconst id = req.params.id;\n    StudentWork.findByPk(id) // here i fetch result by ID sequelize V. 5\n    .then( resultToDelete=>{\n        resultToDelete.destroy(id); // when i find the result i deleted it by destroy function\n    })\n    .then( resultAfterDestroy=>{\n        console.log(\"Deleted :\",resultAfterDestroy);\n    })\n    .catch(err=> console.log(err));\n```\n\n```text\nModel.destroy({\n    truncate: true,\n})\n```\n\n```text\ndeleteMyModel: async (req, res) => {\n\n    sequelize.sequelize.transaction(async (t1) => {\n\n        if (!req.body.id) {\n            return res.status(500).send(error.MANDATORY_FIELDS);\n        }\n\n        let feature = await sequelize.MyModel.findOne({\n            where: {\n                id: req.body.id\n            }\n        })\n\n        if (feature) {\n            let feature = await sequelize.MyModel.destroy({\n                where: {\n                    id: req.body.id\n                }\n            });\n\n            let result = error.OK;\n            result.data = MyModel;\n            return res.status(200).send(result);\n\n        } else {\n            return res.status(404).send(error.DATA_NOT_FOUND);\n        }\n    }).catch(function (err) {\n        return res.status(500).send(error.SERVER_ERROR);\n    });\n}\n```\n\n```js\nModel.destroy({\n  where: {\n    some_field: {\n      //any selection operation\n      // for example [Op.lte]:new Date()\n    }\n  }\n}).then(result => {\n  //some operation\n}).catch(error => {\n  console.log(error)\n})\n```\n\n```text\ndelete()\n```\n\n```text\ndestroy()\n```\n\n```text\nexports.deleteSponsor = async (req, res) => {\n  try {\n```\n\n```text\nconst { userId } = req.body;\n    const { eventId } = req.body;\n    const { sponsorId } = req.body;\n```\n\n```text\nif (!sponsorId)\n      return res\n        .status(422)\n        .send({ message: \"Missing Sponsor id in parameters\" });\n`checking in db too`\n\n    const sponsorDetails = await Sponsor.findAll({\n      where: { [Op.or]: [{ id: sponsorId }] },\n    });\n\n    if (sponsorDetails.length === 0) {\n      return res.status(422).send({ message: \"Sponsor id not exist\" });\n    } else {\n      await Sponsor.destroy({\n```\n\n```text\nwhere: {\n          id: sponsorId,\n          userId: userId,\n          eventId: eventId,\n        }\n      });\n      return res\n        .status(201)\n        .send({ message: \"Sponsor deleted successfully\" });\n    }\n  } catch (err) {\n    console.log(err);\n    customGenericException(err, res);\n  }\n};\n```\n\n```text\nusing conditions like userid,eventid and sponsorid\n```\n\n```text\nchecking exist or not\n```\n\n```text\nwhere clause as per your requirements you can change\n```\n\n```text\ngeneral_category.destroy({ truncate: true, where: {} })\n```\n\n```text\n// Delete everyone named \"Jane\"\nawait User.destroy({\n  where: {\n    firstName: \"Jane\"\n  }\n});\n```\n\n```text\n// Truncate the table\nawait User.destroy({\n  truncate: true\n});\n```\n\n========================================\n\nComments:\n- Yeah, I knew about the destroy method, but unfortunately it's only for one record. I guess I'll have to write my own deleteAll method. Thanks!\n- Really weird that this doesn't exist. Maybe you can write it yourself and submit a pull request to sequelize. I'm sure other people could really use it.\n- Feel free to submit a pull request or to open an issue in the github repository :)\n- destroy() isn't in the documentation on sequelizejs.com, in case anyone else was here looking for that like I was\n- I've got an \"TypeError: Cannot call method 'hasOwnProperty' of null \" error when trying to delete using the destroy() method. Does anyone know what could it be?\n- Your links are all returning 404s for me. Am I the only one?\n- @OrwellHindenberg No it's happening to me too.\n- Those links referred to an old version of Sequelize, they are probably of no use if you're using a current version\n- For reference, this is defined in lib/model.js, and you don't have to use a string. You can use any sort of `where` object (e.g. `{someId: 123}`).\n- It's a pretty old question so at the time I guess Sequelize didn't have a destroy method surprisingly\n- Fair enough; though because this is the first search result on Google, and people are also discouraged from asking questions that have already been asked it seems like the accepted answer should get updated... but that's probably more of a site wide issue.\n- I'm wondering sequelize documentation doesn't give, this much pretty easy coding sample... Any one can understand this. Thank you ncksllvn. You save my time...\n- How do you handle if the id is an invalid id?\n- shouldn't rowDeleted be 1 when checking for successful deletion of one row?\n- This no longer works like that. Return is the row ID affected / not the count of rows affected.\n- Shouldn't you use catch to catch the error instead of callback?\n- Shouldn't you add `transaction: t1` into the options of `findOne`, and `destroy` functions?","metadata":{"transformedAt":"2026-08-18T18:33:34.333Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":367,"estimatedTokens":2261}}31{"id":"stack-8039932","source":"stackoverflow","questionId":8039932,"title":"Specifying specific fields with Sequelize (NodeJS) instead of *","tags":["mysql","node.js","sequelize.js"],"text":"Title: Specifying specific fields with Sequelize (NodeJS) instead of *\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAlright so I have a project in NodeJS where I'm utilizing Sequelize for a MySQL ORM. The thing works fantastically however I'm trying to figure out if there is a way to specify what fields are being returned on a query basis or if there's even a way just to do a .query() somewhere. \n\nFor example in our user database there can be ridiculous amounts of records and columns. In this case I need to return three columns only so it would be faster to get just those columns. However, Sequelize just queries the table for everything \"*\" to fulfill the full object model as much as possible. This is the functionality I'd like to bypass in this particular area of the application.\n\n========================================\n\nTop Answer:\nTry this in **new** version\n\n```\ntemplate.findAll({\n where: {\n user_id: req.params.user_id \n },\n attributes: ['id', 'template_name'], \n}).then(function (list) {\n res.status(200).json(list);\n})\n```\n\n========================================\n\nCode:\n```text\nconst projects = await Project.findAll({\n   attributes: ['name', 'age']\n});\n```\n\n```text\nprojectInstance.update({ name: 'NewProjectName' })\n```\n\n```text\nattributes\n```\n\n```text\nfindAll()\n```\n\n```text\ninclude\n```\n\n```text\nexclude\n```\n\n```text\nupdate()\n```\n\n```text\ntemplate.findAll({\n    where: {\n        user_id: req.params.user_id \n    },\n    attributes: ['id', 'template_name'], \n}).then(function (list) {\n    res.status(200).json(list);\n})\n```\n\n```text\nProject.findAll({\n  attributes: ['id', ['name', 'project_name']],\n  where: {id: req.params.id}\n})\n.then(function(projects) {\n  res.json(projects);\n})\n```\n\n```text\nSELECT id, name AS project_name FROM projects WHERE id = ...;\n```\n\n```text\nModel.findAll({\n  attributes: { include: ['id'] }\n});\n\nModel.findAll({\n  attributes: { exclude: ['createdAt'] }\n});\n```\n\n```text\ninclude\n```\n\n```text\nexclude\n```\n\n========================================\n\nComments:\n- oh wow, there is now documentation about it :-/ lame. alessioalex is right.\n- Hey can you please check the links, they seems to be broken\n- I find this answer confusing. Why `attributes`, an array, says `&#47;&#47;object`? Something similar occurs with `where`, it says `&#47;&#47;array` but if looks like a single value (`number` or `string`).\n- @Camilo oops never mind, ignore the comment. it can be array, nested array or object. for more detail, you can have look sequelize.org/master/manual/model-querying-basics.html","metadata":{"transformedAt":"2026-08-18T18:33:34.333Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":108,"estimatedTokens":640}}32{"id":"stack-21961818","source":"stackoverflow","questionId":21961818,"title":"Sequelize, convert entity to plain object","tags":["node.js","sequelize.js"],"text":"Title: Sequelize, convert entity to plain object\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm not very familiar with javascript, and stunning, because i can't add new property, to object, that fetched from database using ORM names Sequelize.js.\n\nTo avoid this, i use this hack:\n\n```\ndb.Sensors.findAll({\n where: {\n nodeid: node.nodeid\n }\n}).success(function (sensors) {\n var nodedata = JSON.parse(JSON.stringify(node)); // this is my trick\n nodedata.sensors = sensors;\n nodesensors.push(nodedata);\n response.json(nodesensors);\n});\n```\n\nSo, what normally way to add new properties to object.\n\nIf it can help, i use sequelize-postgres version 2.0.x.\n\n**upd. console.log(node):**\n\n```\n{ dataValues: \n { nodeid: 'NodeId',\n name: 'NameHere',\n altname: 'Test9',\n longname: '',\n latitude: 30,\n longitude: -10,\n networkid: 'NetworkId',\n farmid: '5',\n lastheard: Mon Dec 09 2013 04:04:40 GMT+0300 (FET),\n id: 9,\n createdAt: Tue Dec 03 2013 01:29:09 GMT+0300 (FET),\n updatedAt: Sun Feb 23 2014 01:07:14 GMT+0300 (FET) },\n __options: \n { timestamps: true,\n createdAt: 'createdAt',\n updatedAt: 'updatedAt',\n deletedAt: 'deletedAt',\n touchedAt: 'touchedAt',\n instanceMethods: {},\n classMethods: {},\n validate: {},\n freezeTableName: false,\n underscored: false,\n syncOnAssociation: true,\n paranoid: false,\n whereCollection: { farmid: 5, networkid: 'NetworkId' },\n schema: null,\n schemaDelimiter: '',\n language: 'en',\n defaultScope: null,\n scopes: null,\n hooks: { beforeCreate: [], afterCreate: [] },\n omitNull: false,\n hasPrimaryKeys: false },\n hasPrimaryKeys: false,\n selectedValues: \n { nodeid: 'NodeId',\n name: 'NameHere',\n longname: '',\n latitude: 30,\n longitude: -110,\n networkid: 'NetworkId',\n farmid: '5',\n lastheard: Mon Dec 09 2013 04:04:40 GMT+0300 (FET),\n id: 9,\n createdAt: Tue Dec 03 2013 01:29:09 GMT+0300 (FET),\n updatedAt: Sun Feb 23 2014 01:07:14 GMT+0300 (FET),\n altname: 'Test9' },\n __eagerlyLoadedAssociations: [],\n isDirty: false,\n isNewRecord: false,\n daoFactoryName: 'Nodes',\n daoFactory: \n { options: \n { timestamps: true,\n createdAt: 'createdAt',\n updatedAt: 'updatedAt',\n deletedAt: 'deletedAt',\n touchedAt: 'touchedAt',\n instanceMethods: {},\n classMethods: {},\n validate: {},\n freezeTableName: false,\n underscored: false,\n syncOnAssociation: true,\n paranoid: false,\n whereCollection: [Object],\n schema: null,\n schemaDelimiter: '',\n language: 'en',\n defaultScope: null,\n scopes: null,\n hooks: [Object],\n omitNull: false,\n hasPrimaryKeys: false },\n name: 'Nodes',\n tableName: 'Nodes',\n rawAttributes: \n { nodeid: [Object],\n name: [Object],\n altname: [Object],\n longname: [Object],\n latitude: [Object],\n longitude: [Object],\n networkid: [Object],\n farmid: [Object],\n lastheard: [Object],\n id: [Object],\n createdAt: [Object],\n updatedAt: [Object] },\n daoFactoryManager: { daos: [Object], sequelize: [Object] },\n associations: {},\n scopeObj: {},\n primaryKeys: {},\n primaryKeyCount: 0,\n hasPrimaryKeys: false,\n autoIncrementField: 'id',\n DAO: { [Function] super_: [Function] } } }\n```\n\nI think next, what you think will be: \"Ok, that is easy, just add your property to dataValues.\"\n\n```\nnode.selectedValues.sensors = sensors;\nnode.dataValues.sensors = sensors;\n```\n\nI add this lines, and this don't work\n\n========================================\n\nTop Answer:\nyou can use the query options `{raw: true}` to return the raw result. Your query should like follows:\n\n```\ndb.Sensors.findAll({\n where: {\n nodeid: node.nodeid\n },\n raw: true,\n})\n```\n\nalso if you have associations with `include` that gets flattened. So, we can use another parameter `nest:true`\n\n```\ndb.Sensors.findAll({\n where: {\n nodeid: node.nodeid\n },\n raw: true,\n nest: true,\n})\n```\n\nhttps://i.sstatic.net/EPZFd.png\n\n========================================\n\nCode:\n```text\ndb.Sensors.findAll({\n    where: {\n        nodeid: node.nodeid\n    }\n}).success(function (sensors) {\n        var nodedata = JSON.parse(JSON.stringify(node)); // this is my trick\n        nodedata.sensors = sensors;\n        nodesensors.push(nodedata);\n        response.json(nodesensors);\n});\n```\n\n```text\n{ dataValues: \n   { nodeid: 'NodeId',\n     name: 'NameHere',\n     altname: 'Test9',\n     longname: '',\n     latitude: 30,\n     longitude: -10,\n     networkid: 'NetworkId',\n     farmid: '5',\n     lastheard: Mon Dec 09 2013 04:04:40 GMT+0300 (FET),\n     id: 9,\n     createdAt: Tue Dec 03 2013 01:29:09 GMT+0300 (FET),\n     updatedAt: Sun Feb 23 2014 01:07:14 GMT+0300 (FET) },\n  __options: \n   { timestamps: true,\n     createdAt: 'createdAt',\n     updatedAt: 'updatedAt',\n     deletedAt: 'deletedAt',\n     touchedAt: 'touchedAt',\n     instanceMethods: {},\n     classMethods: {},\n     validate: {},\n     freezeTableName: false,\n     underscored: false,\n     syncOnAssociation: true,\n     paranoid: false,\n     whereCollection: { farmid: 5, networkid: 'NetworkId' },\n     schema: null,\n     schemaDelimiter: '',\n     language: 'en',\n     defaultScope: null,\n     scopes: null,\n     hooks: { beforeCreate: [], afterCreate: [] },\n     omitNull: false,\n     hasPrimaryKeys: false },\n  hasPrimaryKeys: false,\n  selectedValues: \n   { nodeid: 'NodeId',\n     name: 'NameHere',\n     longname: '',\n     latitude: 30,\n     longitude: -110,\n     networkid: 'NetworkId',\n     farmid: '5',\n     lastheard: Mon Dec 09 2013 04:04:40 GMT+0300 (FET),\n     id: 9,\n     createdAt: Tue Dec 03 2013 01:29:09 GMT+0300 (FET),\n     updatedAt: Sun Feb 23 2014 01:07:14 GMT+0300 (FET),\n     altname: 'Test9' },\n  __eagerlyLoadedAssociations: [],\n  isDirty: false,\n  isNewRecord: false,\n  daoFactoryName: 'Nodes',\n  daoFactory: \n   { options: \n      { timestamps: true,\n        createdAt: 'createdAt',\n        updatedAt: 'updatedAt',\n        deletedAt: 'deletedAt',\n        touchedAt: 'touchedAt',\n        instanceMethods: {},\n        classMethods: {},\n        validate: {},\n        freezeTableName: false,\n        underscored: false,\n        syncOnAssociation: true,\n        paranoid: false,\n        whereCollection: [Object],\n        schema: null,\n        schemaDelimiter: '',\n        language: 'en',\n        defaultScope: null,\n        scopes: null,\n        hooks: [Object],\n        omitNull: false,\n        hasPrimaryKeys: false },\n     name: 'Nodes',\n     tableName: 'Nodes',\n     rawAttributes: \n      { nodeid: [Object],\n        name: [Object],\n        altname: [Object],\n        longname: [Object],\n        latitude: [Object],\n        longitude: [Object],\n        networkid: [Object],\n        farmid: [Object],\n        lastheard: [Object],\n        id: [Object],\n        createdAt: [Object],\n        updatedAt: [Object] },\n     daoFactoryManager: { daos: [Object], sequelize: [Object] },\n     associations: {},\n     scopeObj: {},\n     primaryKeys: {},\n     primaryKeyCount: 0,\n     hasPrimaryKeys: false,\n     autoIncrementField: 'id',\n     DAO: { [Function] super_: [Function] } } }\n```\n\n```text\nnode.selectedValues.sensors = sensors;\nnode.dataValues.sensors = sensors;\n```\n\n```text\ndb.Sensors.findAll({\n  where: {\n    nodeid: node.nodeid\n  }\n}).success(function (sensors) {\n  var nodedata = node.values;\n\n  nodedata.sensors = sensors.map(function(sensor){ return sensor.values });\n  // or\n  nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });\n\n  nodesensors.push(nodedata);\n  response.json(nodesensors);\n});\n```\n\n```text\nsensors\n```\n\n```text\nnode\n```\n\n```text\ninclude\n```\n\n```text\nvalues\n```\n\n```text\nnodedata.sensors = sensors\n```\n\n```text\ndb.Sensors.findAll({\n  where: {\n    nodeid: node.nodeid\n  },\n  raw: true,\n})\n```\n\n```js\ndb.Sensors.findAll({\n  where: {\n    nodeid: node.nodeid\n  },\n  raw: true,\n  nest: true,\n})\n```\n\n```text\n{raw: true}\n```\n\n```text\ninclude\n```\n\n```text\nnest:true\n```\n\n```text\nvar nodedata = node.get({ plain: true });\n```\n\n```text\n.values\n```\n\n```text\n.get()\n```\n\n```text\ndb.Sensors.findAll({\n    where: {\n        nodeid: node.nodeid\n    }\n}).success((sensors) => {\n    const nodeData = sensors.map((node) => node.get({ plain: true }));\n});\n```\n\n```text\n.values()\n```\n\n```text\n{ raw: true }\n```\n\n```text\n.get()\n```\n\n```text\n.get()\n```\n\n```text\nvar results = [{},{},...]; //your result data returned from sequelize query\nvar jsonString = JSON.stringify(results); //convert to string to remove the sequelize specific meta data\n\nvar obj = JSON.parse(jsonString); //to make plain json\n// do whatever you want to do with obj as plain json\n```\n\n```text\ndb.Sensors.findAll({\n    where: {\n        nodeid: node.nodeid\n    },\n    raw : true // <----------- Magic is here\n}).success(function (sensors) {\n        console.log(sensors);\n});\n```\n\n```text\ndb.Sensors.findAll({\n    where: {\n        nodeid: node.nodeid\n    },\n    include : [\n        { model : someModel }\n    ]\n    raw : true , // <----------- Magic is here\n    nest : true // <----------- Magic is here\n}).success(function (sensors) {\n        console.log(sensors);\n});\n```\n\n```text\nconst toPlain = response => {\n  const flattenDataValues = ({ dataValues }) => {\n    const flattenedObject = {};\n\n    Object.keys(dataValues).forEach(key => {\n      const dataValue = dataValues[key];\n\n      if (\n        Array.isArray(dataValue) &&\n        dataValue[0] &&\n        dataValue[0].dataValues &&\n        typeof dataValue[0].dataValues === 'object'\n      ) {\n        flattenedObject[key] = dataValues[key].map(flattenDataValues);\n      } else if (dataValue && dataValue.dataValues && typeof dataValue.dataValues === 'object') {\n        flattenedObject[key] = flattenDataValues(dataValues[key]);\n      } else {\n        flattenedObject[key] = dataValues[key];\n      }\n    });\n\n    return flattenedObject;\n  };\n\n  return Array.isArray(response) ? response.map(flattenDataValues) : flattenDataValues(response);\n};\n```\n\n```text\nconst toPlain = response => {\n  const flattenDataValues = ({ dataValues }) =>\n    _.mapValues(dataValues, value => (\n      _.isArray(value) && _.isObject(value[0]) && _.isObject(value[0].dataValues)\n        ? _.map(value, flattenDataValues)\n        : _.isObject(value) && _.isObject(value.dataValues)\n          ? flattenDataValues(value)\n          : value\n    ));\n\n  return _.isArray(response) ? _.map(response, flattenDataValues) : flattenDataValues(response);\n};\n```\n\n```text\nconst res = await User.findAll({\n  include: [{\n    model: Company,\n    as: 'companies',\n    include: [{\n      model: Member,\n      as: 'member',\n    }],\n  }],\n});\n\nconst plain = toPlain(res);\n\n// 'plain' now contains simple db object without any getters/setters with following structure:\n// [{\n//   id: 123,\n//   name: 'John',\n//   companies: [{\n//     id: 234,\n//     name: 'Google',\n//     members: [{\n//       id: 345,\n//       name: 'Paul',\n//     }]\n//   }]\n// }]\n```\n\n```text\nsequelize\n```\n\n```text\ndb.Sensors\n    .findAll({\n        where: { nodeid: node.nodeid }\n     })\n    .map(el => el.get({ plain: true }))\n    .then((rows)=>{\n        response.json( rows )\n     });\n```\n\n```text\ndb.model.findAll({\n  raw : true ,\n  nest : true\n})\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {query:{raw:true}})\n```\n\n```text\nconst sensors = JSON.parse(JSON.stringify(await \n    db.Sensors.findAll({\n    where: {\n        nodeid: node.nodeid\n    }\n})))\n```\n\n```text\nconst camelcaseKeys = require('camelcase-keys');\n\nconst initMixins = Sequelize => {\n    // Convert model to plain object and camelcase keys for response\n    Sequelize.Model.prototype.toPlainObject = function({ camelcase = false } = {}) {\n        const plain = this.get({ plain: true });\n        if (camelcase) {\n            return camelcaseKeys(plain, { deep: true });\n        } else {\n            return plain;\n        }\n    };\n};\n\nmodule.exports = {\n    initMixins,\n};\n// usage\nconst userModel = await UserModel.findOne();\nconsole.log(userModel.toPlainObject());\n```\n\n========================================\n\nComments:\n- Thank you, all i need: node.values :)\n- \"raw: true\" will somehow flattens array injected by associated models. The only work around I found so far is to configs = JSON.parse(JSON.stringify(configs));\n- That's simple and better approach than accepted answer. thanks\n- @SoichiHayashi Actually, its the reverse when you think about it... ;) Without raw: true, Sequelize somehow unflattens the result into objects. The results from the sql query are already flattened. I've found it useful a few times to get a flat result... +1 for this answer.\n- @SoichiHayashi to get raw but nested result, you can use `nest: true` along with `raw: true`.\n- any idea how to pass the `raw:true` as a global setting, so there is no need to pass it to every query? Thanks\n- If you have array of association(such as hasMany), try toJSON, it actually returns object instead of string.\n- Note that `raw: true` will also ignore any `virtual` columns\n- Correct me if I'm wrong - but I don't think this will work with an array of rows? For example with .findAndcount you'd have to .map the result rows and return .get on each to get what you need.\n- Probably easier to just run JSON.stringify or res.json (if you're working within express).\n- @backdesk - haven't tried it on an array - but from the docs it looks like it should return the same thing.\n- Using `.get()` won't convert included associations, use `.get({ plain: true })` instead. Thanks for mentioning the suggestion from the docs.\n- Also useful if you already performed the query and thus can't issue `raw: true`\n- Best answer so far.\n- This worked for me! Though I don't know if 'get' is a JavaScript or a Sequelize function. Please enlighten me. Thanks\n- @antew It's a method on an object returned from the database - it's part of the sequelize library, not a native javascript function.\n- Took me ages to get to this working! Thank you. Was so difficult because I have a lot of nested includes, which is also a bug. So I have to do multiple queries, and I couldn't because of this!!!\n- So simple, yet powerfully works and keeps the model logic. I don't know how efficient it is, but it was good enough for me. You can short it to something like: let res = JSON.parse(JSON.stringify(result));\n- This answer very useful, use native functionality provided by sequleize, in my case when i send more than one row in socket, stack overflow error happened.\n- If you have an array of child data, you will get wrong results. So, if posted query returns only one `sensors` with an array of child `someModel`, you will get an `array` of `sensors` with one `someModel` in each.\n- `raw` result also omits all `VIRTUAL` property values.\n- Thanks! The toPlain works as expected and solved my issue as well.\n- This is neat, but it's no good if you override any of your model's toJSON methods. I do this quite a lot to either remove or convert the createdAt/updatedAt values. So far the only thing that has worked properly for me is JSON.parse(JSON.stringify(response)).\n- Your answer gave me a nudge to look deeper into Model's doc and toJSON. After fixing a custom getter in my model definition, `toJSON` worked well for me, so had no need for a custom implementation like yours.\n- I believe this is the only working solution. `get({plain:true})` adds all non requested fields with undefined. `{raw:true, nest:true}` does not deal with 1:n nested associations well.\n- Thanks this was the best solution for my use cast, just `results = results.map(el => el.get({ plain: true }))`\n- I was searching for `get({ plain: true })`. Thanks!\n- it doesn't work propery for one to many association its better to use .map(obj => obj.get({ plain: true }))\n- actually i am talking about db.model.findOne and one to many association.\n- watch out, that doesn't give you json. it gives you plain objects.\n- brother it remove one to many relation\n- it is invalid when we use associate concept\n- So - how does this work when you are doing an upsert?!\n- this answer is working for association also .. plus 1 added","metadata":{"transformedAt":"2026-08-18T18:33:34.334Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":598,"estimatedTokens":3943}}33{"id":"stack-21883484","source":"stackoverflow","questionId":21883484,"title":"How to use an include with attributes with sequelize?","tags":["node.js","orm","sequelize.js","relationship"],"text":"Title: How to use an include with attributes with sequelize?\nTags: node.js, orm, sequelize.js, relationship\nSource: Stack Overflow\n\nQuestion:\nAny idea how to use an include with attributes (when you need to include only specific fields of the included table) with sequelize?\n\nCurrently I have this (but it doesn't work as expected):\n\n```\nvar attributes = ['id', 'name', 'bar.version', ['bar.last_modified', 'changed']];\nfoo.findAll({\n where : where,\n attributes : attributes,\n include : [bar]\n}).success(function (result) { ...\n```\n\n========================================\n\nTop Answer:\nWe can do something like that for exclude or include specific attribute with sequelize in Node.js.\n\n```\nPayment.findAll({\n where: {\n DairyId: req.query.dairyid\n },\n attributes: {\n exclude: ['createdAt', 'updatedAt']\n },\n include: {\n model: Customer,\n attributes:['customerName', 'phoneNumber']\n }\n})\n```\n\n========================================\n\nCode:\n```text\nvar attributes = ['id', 'name', 'bar.version', ['bar.last_modified', 'changed']];\nfoo.findAll({\n    where      : where,\n    attributes : attributes,\n    include    : [bar]\n}).success(function (result) { ...\n```\n\n```text\nfoo.findAll({\n    where      : where,\n    attributes : attributes,\n    include    : [{ model: bar, attributes: attributes}]\n}).success(function (result) {\n```\n\n```text\nPayment.findAll({\n    where: {\n        DairyId: req.query.dairyid\n    },\n    attributes: {\n        exclude: ['createdAt', 'updatedAt']\n    },\n    include: {\n        model: Customer,\n        attributes:['customerName', 'phoneNumber']\n    }\n})\n```\n\n```text\nModel.find().select('attr1 attr2 attr3')\n```\n\n```text\nCourse.findAll({where: {\n         status:responseCode.STATUS_ACTIVE\n     }, attributes:['id','course_title','course_slug','age_group','image','class_duration','no_of_classes','is_course_upcoming'],\n     order:[['is_sorting','ASC']],\n    include:{model:Section,attributes:['id','title','course_id','start_date','end_date']},\n}).then(course_detail =>{\n    result(null,course_detail);\n}).catch(err =>{\n    console.log(err)\n});\n```\n\n========================================\n\nComments:\n- This is for mongoose, right?\n- Yes it is mongoose","metadata":{"transformedAt":"2026-08-18T18:33:34.334Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":95,"estimatedTokens":545}}34{"id":"stack-29233896","source":"stackoverflow","questionId":29233896,"title":"sequelize table without column 'id'","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: sequelize table without column 'id'\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following sequelize definition of a table:\n\n```\nAcademyModule = sequelize.define('academy_module', {\n academy_id: DataTypes.INTEGER,\n module_id: DataTypes.INTEGER,\n module_module_type_id: DataTypes.INTEGER,\n sort_number: DataTypes.INTEGER,\n requirements_id: DataTypes.INTEGER\n }, {\n freezeTableName: true\n});\n```\n\nAs you can see there is not an `id` column in this table. However when I try to insert it still tries the following sql:\n\n```\nINSERT INTO `academy_module` (`id`,`academy_id`,`module_id`,`sort_number`) VALUES (DEFAULT,'3',5,1);\n```\n\nHow can I disable the `id` function it clearly has?\n\n========================================\n\nTop Answer:\nIf you want to completely disable the primary key for the table, you can use `Model.removeAttribute`. Be warned that this could cause problems in the future, as Sequelize is an ORM and joins will need extra setup.\n\n```\nconst AcademyModule = sequelize.define('academy_module', {\n academy_id: DataTypes.INTEGER,\n module_id: DataTypes.INTEGER,\n module_module_type_id: DataTypes.INTEGER,\n sort_number: DataTypes.INTEGER,\n requirements_id: DataTypes.INTEGER\n}, {\n freezeTableName: true\n});\nAcademyModule.removeAttribute('id');\n```\n\n========================================\n\nCode:\n```text\nAcademyModule = sequelize.define('academy_module', {\n        academy_id: DataTypes.INTEGER,\n        module_id: DataTypes.INTEGER,\n        module_module_type_id: DataTypes.INTEGER,\n        sort_number: DataTypes.INTEGER,\n        requirements_id: DataTypes.INTEGER\n    }, {\n        freezeTableName: true\n});\n```\n\n```text\nINSERT INTO `academy_module` (`id`,`academy_id`,`module_id`,`sort_number`) VALUES (DEFAULT,'3',5,1);\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nAcademyModule = sequelize.define('academy_module', {\n    academy_id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true\n    },\n    module_id: DataTypes.INTEGER,\n    module_module_type_id: DataTypes.INTEGER,\n    sort_number: DataTypes.INTEGER,\n    requirements_id: DataTypes.INTEGER\n}, {\n    freezeTableName: true\n});\n```\n\n```text\nprimaryKey\n```\n\n```text\nid\n```\n\n```text\nprimaryKey: true\n```\n\n```text\nconst AcademyModule = sequelize.define('academy_module', {\n    academy_id: DataTypes.INTEGER,\n    module_id: DataTypes.INTEGER,\n    module_module_type_id: DataTypes.INTEGER,\n    sort_number: DataTypes.INTEGER,\n    requirements_id: DataTypes.INTEGER\n}, {\n    freezeTableName: true\n});\nAcademyModule.removeAttribute('id');\n```\n\n```text\nModel.removeAttribute\n```\n\n```text\nAcademyModule = sequelize.define('academy_module', {\n    academy_id: DataTypes.INTEGER,\n    module_id: DataTypes.INTEGER,\n    module_module_type_id: DataTypes.INTEGER,\n    sort_number: DataTypes.INTEGER,\n    requirements_id: DataTypes.INTEGER\n}, {\n    freezeTableName: true\n});\nAcademyModule.removeAttribute('id');\n```\n\n```text\nacademy_id\n```\n\n```text\nmodule_id\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  class follow extends Model {\n    /**\n     * Helper method for defining associations.\n     * This method is not a part of Sequelize lifecycle.\n     * The `models/index` file will call this method automatically.\n     */\n    static associate(models) {\n      // define association here\n    }\n  }\n  follow.init({\n    follower_id: DataTypes.INTEGER,\n    followee_id: DataTypes.INTEGER\n  }, {\n    sequelize,\n    modelName: 'follows',\n  });\n\n  follow.removeAttribute(\"id\");\n\n  return follow;\n};\n```\n\n========================================\n\nComments:\n- What if both module_id and academy_id is a primaryKey?\n- A table can only have one primary key, unless you create a compound primary key. I'm not sure if Sequelize supports this.\n- Disregard the above, Sequelize does support this. Just add `primaryKey: true` to the columns you want to use as a primary key.\n- how to delare primary key using sequelize-cli like something like this sequelize model:create --name MyUsera --attributes first_name:Integer:primaryKey: true,last_name:string,bio:text\n- Why is this even regarded as an answer? The question was very clearly \"How can i disable the `id` function it clearly has?\" and this answer tries to answer it with \"If you want you can change the name of the primary key\". What??\n- Maybe you should read the answer as: 'Your tables MUST have a primary key, so it cannot be disabled, but you can change the name/definition of it'. Not sure whether it's actually impossible to completely disable it though.\n- According to sequelize configurtion, one can define which of the existing/defined fields will be the `id` (you can set multiple filds as `primaryKey: true`) and if you have just no id on your table, then sequelize legazy documentation says you can just remove it with `Model.removeAttribute('id');` and you will have a table (model) without primary key.\n- Setting a primaryKey to another column didn't work for me. In the end, only `Model.removeAttribute('id')` solved the problem of getting Sequelize to work with a table without an `id`\n- how to delare custome primary key using sequelize-cli like something like this sequelize model:create --name MyUsera --attributes first_name:Integer:primaryKey: true,last_name:string,bio:text\n- This was back in 2015 and I can't figure out what is going on. How do I build the relationships with a compound key??\n- OP has asked for \"How can I disable the id function it clearly has?\" this is clearly the wrong answer.\n- You're right. OP would have marked this as an answer if this was the direct unblocking solution. This extends the right answer for cases where the primary key is composite. You clearly have not read the solution Ben Fortune provided.\n- That is, unless you want to join to a non-primary key column with a unique index","metadata":{"transformedAt":"2026-08-18T18:33:34.334Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":179,"estimatedTokens":1453}}35{"id":"stack-12487416","source":"stackoverflow","questionId":12487416,"title":"How to organize a node app that uses sequelize?","tags":["node.js","express","sequelize.js"],"text":"Title: How to organize a node app that uses sequelize?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am looking for an example nodejs app that uses the sequelize ORM.\n\nMy main concern is that it seems next to impossible to define your models in separate js files if those models have complex relationships to one another because of require() dependency loops. Maybe people define all their models in one file that is very very long?\n\nI am mainly interested in how the models are defined and use through out the app. I would like to have some validation that what i am doing on my own is the \"good\" way to do things.\n\n========================================\n\nTop Answer:\nSequelizeJS has a article on their website which solves this problem. \n\n*Link is broken, but you can find the working sample project here and browse it. See edited answer above to see why this is a better solution.*\n\nExtract from article:\n\nmodels/index.js\n\nThe idea of this file is to configure a connection to the database and to collect all Model definitions. Once everything is in place, we will call the method associated on each of the Models. This method can be used to associate the Model with others.\n\n```\nvar fs = require('fs')\n , path = require('path')\n , Sequelize = require('sequelize')\n , lodash = require('lodash')\n , sequelize = new Sequelize('sequelize_test', 'root', null)\n , db = {} \n\n fs.readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf('.') !== 0) && (file !== 'index.js')\n })\n .forEach(function(file) {\n var model = sequelize.import(path.join(__dirname, file))\n db[model.name] = model\n })\n\n Object.keys(db).forEach(function(modelName) {\n if (db[modelName].options.hasOwnProperty('associate')) {\n db[modelName].options.associate(db)\n }\n })\n\n module.exports = lodash.extend({\n sequelize: sequelize,\n Sequelize: Sequelize\n }, db)\n```\n\n========================================\n\nCode:\n```text\nrequire\n```\n\n```text\nrequire\n```\n\n```text\nreaddirSync\n```\n\n```text\nbelongsToMany\n```\n\n```text\nthrough\n```\n\n```text\nbelongsTo\n```\n\n```text\nfetch\n```\n\n```text\nsave\n```\n\n```text\ndelete\n```\n\n```text\nsequelize.import\n```\n\n```text\nvar fs        = require('fs')\n        , path      = require('path')\n        , Sequelize = require('sequelize')\n        , lodash    = require('lodash')\n        , sequelize = new Sequelize('sequelize_test', 'root', null)\n        , db        = {} \n\n      fs.readdirSync(__dirname)\n        .filter(function(file) {\n          return (file.indexOf('.') !== 0) && (file !== 'index.js')\n        })\n        .forEach(function(file) {\n          var model = sequelize.import(path.join(__dirname, file))\n          db[model.name] = model\n        })\n\n      Object.keys(db).forEach(function(modelName) {\n        if (db[modelName].options.hasOwnProperty('associate')) {\n          db[modelName].options.associate(db)\n        }\n      })\n\n      module.exports = lodash.extend({\n        sequelize: sequelize,\n        Sequelize: Sequelize\n      }, db)\n```\n\n```text\nvar Config = require('../config/config');\n\n var fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar _ = require('lodash');\nvar sequelize;\nvar db = {};\n\nvar dbName, dbUsername, dbPassword, dbPort, dbHost;\n// set above vars\n\nvar sequelize = new Sequelize(dbName, dbUsername, dbPassword, {\ndialect: 'postgres', protocol: 'postgres', port: dbPort, logging: false, host: dbHost,\n  define: {\n    classMethods: {\n        db: function () {\n                    return db;\n        },\n        Sequelize: function () {\n                    return Sequelize;\n        }\n\n    }\n  }\n});\n\n\nfs.readdirSync(__dirname).filter(function(file) {\n   return (file.indexOf('.') !== 0) && (file !== 'index.js');\n}).forEach(function(file) {\n  var model = sequelize.import(path.join(__dirname, file));\n  db[model.name] = model;\n});\n\nObject.keys(db).forEach(function(modelName) {\n  if ('associate' in db[modelName]) {\n      db[modelName].associate(db);\n  }\n});\n\nmodule.exports = _.extend({\n  sequelize: sequelize,\n  Sequelize: Sequelize\n}, db);\n```\n\n```text\nvar classMethods = {\n  createFromParams: function (userParams) {\n    var user = this.build(userParams);\n\n    return this.db().PromoCode.find({where: {name: user.promoCode}}).then(function (code) {\n        user.credits += code.credits;\n                return user.save();\n    });\n  }\n\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define(\"User\", {\n  userId: DataTypes.STRING,\n}, {  tableName: 'users',\n    classMethods: classMethods\n });\n};\n```\n\n```text\nvar orm = require('sequelize-connect');\n\norm.discover = [\"/my/model/path/1\", \"/path/to/models/2\"];      // 1 to n paths can be specified here\norm.connect(db, user, passwd, options);                        // initialize the sequelize connection and models\n```\n\n```text\nvar orm       = require('sequelize-connect');\nvar sequelize = orm.sequelize;\nvar Sequelize = orm.Sequelize;\nvar models    = orm.models;\nvar User      = models.User;\n```\n\n```js\n'use strict';\nconst getRole   = require('../helpers/getRole')\nconst library   = require('../helpers/library')\nconst Op        = require('sequelize').Op\n\nmodule.exports = (sequelize, DataTypes) => {\n  var User = sequelize.define('User', {\n    AdminId: DataTypes.INTEGER,\n    name: {\n      type: DataTypes.STRING,\n      validate: {\n        notEmpty: {\n          args: true,\n          msg: 'Name must be filled !!'\n        },\n      }\n    },\n    email: {\n      type: DataTypes.STRING,\n      validate: {\n        notEmpty: {\n          args: true,\n          msg: 'Email must be filled !!'\n        },\n        isUnique: function(value, next) {\n          User.findAll({\n            where:{\n              email: value,\n              id: { [Op.ne]: this.id, }\n            }\n          })\n          .then(function(user) {\n            if (user.length == 0) {\n              next()\n            } else {\n              next('Email already used !!')\n            }\n          })\n          .catch(function(err) {\n            next(err)\n          })\n        }\n      }\n    },\n    password: {\n      type: DataTypes.STRING,\n      validate: {\n        notEmpty: {\n          args: true,\n          msg: 'Password must be filled !!'\n        },\n        len: {\n          args: [6, 255],\n          msg: 'Password at least 6 characters !!'\n        }\n      }\n    },\n    role: {\n      type: DataTypes.INTEGER,\n      validate: {\n        customValidation: function(value, next) {\n          if (value == '') {\n            next('Please choose a role !!')\n          } else {\n            next()\n          }\n        }\n      }\n    },\n    gender: {\n      type: DataTypes.INTEGER,\n      validate: {\n        notEmpty: {\n          args: true,\n          msg: 'Gender must be filled !!'\n        },\n      }\n    },\n    handphone: {\n      type: DataTypes.STRING,\n      validate: {\n        notEmpty: {\n          args: true,\n          msg: 'Mobile no. must be filled !!'\n        },\n      }\n    },\n    address: DataTypes.TEXT,\n    photo: DataTypes.STRING,\n    reset_token: DataTypes.STRING,\n    reset_expired: DataTypes.DATE,\n    status: DataTypes.INTEGER\n  }, {\n    hooks: {\n      beforeCreate: (user, options) => {\n        user.password = library.encrypt(user.password)\n      },\n      beforeUpdate: (user, options) => {\n        user.password = library.encrypt(user.password)\n      }\n    }\n  });\n\n  User.prototype.check_password = function (userPassword, callback) {\n    if (library.comparePassword(userPassword, this.password)) {\n      callback(true)\n    }else{\n      callback(false)\n    }\n  }\n\n  User.prototype.getRole = function() {\n    return getRole(this.role)\n  }\n\n  User.associate = function(models) {\n    User.hasMany(models.Request)\n  }\n\n  return User;\n};\n```\n\n```text\nimport { DataTypes } from 'sequelize';\nimport { sequelize } from '../database.js';\n\nexport const User = sequelize.define(\"user\",{\n    uid:{\n      type:DataTypes.STRING,\n      allowNull:false,\n      unique: true\n    },\n    email:{\n      type:DataTypes.STRING,\n      allowNull:true\n    },\n    firstName:{\n      type:DataTypes.STRING,\n      allowNull:true\n    },\n    lastName:{\n      type:DataTypes.STRING,\n      allowNull:true\n    },\n    companyWebsite:{\n      type:DataTypes.STRING,\n      allowNull:true\n    },\n    domain:{\n      type:DataTypes.STRING,\n      allowNull:true\n    },\n    hsPortalId:{\n      type:DataTypes.INTEGER,\n      allowNull:true\n    },\n    integrations:{\n      type:DataTypes.STRING\n    },\n    brandedKeywords : {\n      type:DataTypes.STRING\n    },\n    companyName: {\n      type:DataTypes.STRING\n    },\n    companyStreet:{\n      type:DataTypes.STRING\n    },\n    companyZip:{\n      type:DataTypes.STRING\n    },\n    companyCountry:{\n      type:DataTypes.STRING\n    },\n    vatId:{\n      type:DataTypes.STRING\n    },\n    brand:{\n      type:DataTypes.STRING\n    },\n    markets:{\n      type:DataTypes.JSON\n    },\n    niche : {\n      type:DataTypes.JSON\n    }\n  \n  },{schema:\"api\"})\n```\n\n```text\nimport { Billing } from './billing.model.js';\nimport { Competitor } from './competitors.model.js';\nimport { DemoAccount } from './demo.model.js';\nimport { Notification } from './notification.model.js';\nimport { Product } from './products.model.js';\nimport { Reseller } from './resellers.model.js';\nimport {Reseller_User} from './reseller_user.model.js'\nimport { Tag } from './tags.model.js';\nimport {User} from './user.model.js'\n\nReseller.belongsToMany(User, { through: Reseller_User });\nUser.belongsToMany(Reseller, { through: Reseller_User });\n\n// this will create a UserId column on your Product table\n// https://www.youtube.com/watch?v=HJGWu0cZUe8 40min\nUser.hasMany(Product,{onDelete: 'CASCADE',})\nProduct.belongsTo(User)\n\nUser.hasOne(DemoAccount,{onDelete: 'CASCADE',})\nDemoAccount.belongsTo(User)\n\nUser.hasMany(Billing,{onDelete: 'CASCADE',})\nBilling.belongsTo(User)\n\nUser.hasMany(Tag,{onDelete: 'CASCADE',})\nTag.belongsTo(User)\n\nUser.hasMany(Competitor,{onDelete: 'CASCADE'})\nCompetitor.belongsTo(User)\n\nUser.hasMany(Notification,{onDelete: 'CASCADE'})\nNotification.belongsTo(User)\n\n\nUser.sync().then(\n    () => console.log(\"Sync complete\")\n);\n\nReseller.sync().then(\n() => console.log(\"Sync complete\")\n);\n\nReseller_User.sync().then(\n() => console.log(\"Sync complete\")\n);\n\nProduct.sync().then(\n() => console.log(\"Product Sync complete\")\n);\n\nCompetitor.sync().then(\n() => console.log(\"Competitor Sync complete\")\n);\n\nNotification.sync().then(\n() => console.log(\"Competitor Sync complete\")\n);\n\nBilling.sync().then(\n() => console.log(\"Billing Sync complete\")\n);\n\nTag.sync().then(\n() => console.log(\"Tag Sync complete\")\n);\n\nDemoAccount.sync()\n\nexport { User, Reseller, Product, Competitor, Notification, DemoAccount, Billing, Tag };\n\n// DemoAccount.sync({force:true}).then(\n//   () => console.log(\"Sync complete\")\n// );\n```\n\n```text\nuser.model.js\n```\n\n```text\nmodels/user.model.js\n```\n\n```text\nindex.js\n```\n\n```text\nmodels/index.js\n```\n\n```text\nindex.js\n```\n\n```text\ndatabase.js\n```\n\n```text\napp.js\n```\n\n```text\nmodels/user.model.js\n```\n\n```text\nmodels/index.js\n```\n\n========================================\n\nComments:\n- I added an example that may will help someone github.com/shaishab/sequelize-express-example\n- I have written an article about our solution: medium.com/@ismayilkhayredinov/&hellip;\n- Also, I was under the impression that all `require`d modules in node were in a sense singletons because the code in them is executed once and then cached, so that next time you require them you are getting a a cached object reference. Is this not the whole picture?\n- @mkoryak, you are right - all commonjs modules in node are effectively singletons, as the returned value is cached after the first execution. nodejs.org/api/modules.html#modules_caching\n- So, the example could be simplified by removing the singleton tricky part and just put module.exports = new OrmClass(). I'll try it out, thanks for your feedback :)\n- Just in case anyone had the headache I had, I'll save you. I had issues with the code listed in the github article that centered around paths. I had to add a . to the require (like this: var object = require('.' + modelsPath + \"/\" + name);) and also put a return if name.indexOf('DS_Store') > -1 in the forEach in the init function (yay OSX). Hope that helps.\n- as @jinglesthula mentioned - there are some changes/bugs in the sample for loading files withing directory (especially if it's nested somewhere else). I would also add the ability to pass options to the relations, as they are very important (like the name of the foreign key, if it's allowed to be null, etc.)\n- It moved again, here is the updated link: github.com/sequelize/express-example/blob/master/&hellip;\n- These are valid points, but I would rather avoid reimplementing `fetch`, `save`, `delete` etc. outside of `Sequelize` given that the framework already provides the means. It is nicer, but less convenient to have a separate fetching layer. At the same time, you could probably add a fetching abstraction layer around Sequelize but then the solution is more complicated, for an arguable win.\n- this tutorial be very helpfuL: sequelize+express example\n- @mvbl-fst You've just described a DAO layer. Let's say you have some users in an SQL DB and different users on the filesystem. You should have two DAOs which abstract how to get each of them, then a business layer which concatenates the users together (maybe even adapts some properties) and passes them back to your route (the presentation layer).\n- does this work with circular dependencies? For example when model A has a FK to model B and model be has a FK to model A\n- link is not valid\n- This is the way that Sequelize recommends doing it. I would accept this as the correct answer.\n- Just fixed the broken link and added explanation to the selected question why it's not ok :)\n- This is good, but you can't use a model from another model's instance methods, or perhaps I missed something.\n- The page doesn't exist any more\n- Here's the working link: sequelize.readthedocs.org/en/1.7.0/articles/express\n- If you see my answer below, I've created a package which handles this so people don't have to keep reimplementing this in their code. npmjs.com/package/sequelize-connect\n- @mlkmt you can! Since you have access to the `sequelize` variable in your model file, you can access your other model with `sequelize.models.modelName`.\n- it's not a very good practice to use sync io operations at runtime; am i the only one seeing this? i wouldn't recommend this solution. one alternative (albeit an expensive one, in terms of performance) is to use a proxy around the DB instance, that delegates function invocations to the relevant model (via DI).\n- please working link as above both links are not working.\n- I found a link in the wayback machine, which kind of works, although the CSS is busted. Still, it might give you an idea. web.archive.org/web/20141129235215/http://&hellip;\n- Is this answer still valid? the commented code above is what I am refering too. The links are dead but the link to this github.com/sequelize/express-example does not match the code above so I am curious what the correct way is?\n- +1 for that prototype classMethod that returns the db. Exactly the idea I was looking for to be able to load classMethods during define but also be able to reference any Model in a ClassMethod (i.e. for including relationships)\n- Linking to an article helps a bit. Quoting some docs is better. Showing a code snippet is great.... But actually building a library that solves the problem and putting it up on NPM is **fantastic** and deserves more love! +1 and will star your project.","metadata":{"transformedAt":"2026-08-18T18:33:34.334Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":543,"estimatedTokens":3892}}36{"id":"stack-38524938","source":"stackoverflow","questionId":38524938,"title":"Sequelize - update record, and return result","tags":["javascript","sequelize.js"],"text":"Title: Sequelize - update record, and return result\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize with MySQL. For example if I do:\n\n```\nmodels.People.update({OwnerId: peopleInfo.newuser},\n {where: {id: peopleInfo.scenario.id}})\n .then(function (result) {\n response(result).code(200);\n\n }).catch(function (err) {\n request.server.log(['error'], err.stack);\n ).code(200);\n });\n```\n\nI am not getting information back if the people model was succesfully updated or not. Variable result is just an array with one element, 0=1\n\nHow can I know for certain that the record was updated or not.\n\n========================================\n\nTop Answer:\nYou can just find the item and update its properties and then save it. \nThe save() results in a UPDATE query to the db\n\n```\nconst job = await Job.findOne({where: {id, ownerId: req.user.id}});\nif (!job) {\n throw Error(`Job not updated. id: ${id}`);\n}\n\njob.name = input.name;\njob.payload = input.payload;\nawait job.save();\n```\n\nOn Postgres:\n\n```\nExecuting (default): UPDATE \"jobs\" SET \"payload\"=$1,\"updatedAt\"=$2 WHERE \"id\" = $3\n```\n\n========================================\n\nCode:\n```text\nmodels.People.update({OwnerId: peopleInfo.newuser},\n        {where: {id: peopleInfo.scenario.id}})\n        .then(function (result) {\n            response(result).code(200);\n\n        }).catch(function (err) {\n        request.server.log(['error'], err.stack);\n       ).code(200);\n    });\n```\n\n```text\ndb.connections.update({\n  user: data.username,\n  chatroomID: data.chatroomID\n}, {\n  where: { socketID: socket.id },\n  returning: true,\n  plain: true\n})\n.then(function (result) {\n  console.log(result);   \n  // result = [x] or [x, y]\n  // [x] if you're not using Postgres\n  // [x, y] if you are using Postgres\n});\n```\n\n```text\nx\n```\n\n```text\ny\n```\n\n```text\noptions.returning\n```\n\n```text\ntrue\n```\n\n```text\nresult[1].dataValues\n```\n\n```text\nreturning: true\n```\n\n```text\nplain: true\n```\n\n```text\nmodels.People.update({OwnerId: peopleInfo.newuser},\n    {where: {id: peopleInfo.scenario.id}})\n    .then(() => {return models.People.findById(peopleInfo.scenario.id)})\n    .then((user) => response(user).code(200))\n    .catch((err) => {\n         request.server.log(['error'], err.stack);\n      });\n```\n\n```text\nconst asyncFunction = async function(req, res) {\n    try {\n        //update \n        const updatePeople = await models.People.update({OwnerId: peopleInfo.newuser},\n                                    {where: {id: peopleInfo.scenario.id}})\n        if (!updatePeople) throw ('Error while Updating');\n        // fetch updated data\n        const returnUpdatedPerson =  await models.People.findById(peopleInfo.scenario.id)\n        if(!returnUpdatedPerson) throw ('Error while Fetching Data');\n        res(user).code(200);\n    } catch (error) {\n        res.send(error)\n    }\n}\n```\n\n```text\nconst job = await Job.findOne({where: {id, ownerId: req.user.id}});\nif (!job) {\n    throw Error(`Job not updated. id: ${id}`);\n}\n\njob.name = input.name;\njob.payload = input.payload;\nawait job.save();\n```\n\n```text\nExecuting (default): UPDATE \"jobs\" SET \"payload\"=$1,\"updatedAt\"=$2 WHERE \"id\" = $3\n```\n\n```text\ntry {\n    const result = await MODELNAME.update(req.body, {\n      where: { id: req.params.id },\n      returning: true\n    });\n    if (!result) HANDLEERROR()\n    const data = result[1][0].get();\n\n    res.status(200).json({ success: true, data });\n  } catch (error) {\n    HANDLEERROR()\n  }\n```\n\n```text\nlet person = await models.People.findByPk(peopleInfo.scenario.id);\nif (!person) {\n  // Here you can handle the case when a person is not found\n  // For example, I return a \"Not Found\" message and a 404 status code\n}\nperson = await person.update({ OwnerId: peopleInfo.newuser });\nresponse(person).code(200);\n```\n\n```text\nfindByPk\n```\n\n```text\nupdate\n```\n\n```text\nreturn new Promise(function(resolve, reject) {\nUser.update({\n        subject: params.firstName, body: params.lastName, status: params.status\n    },{\n        returning:true,\n        where: {id:id }                             \n    }).then(function(){\n        let response = User.findById(params.userId);                      \n        resolve(response);\n    });\n```\n\n```text\nconst instance = await Model.findOne({\n  where: {\n    'id': objectId\n  }\n});\n\nif (instance && instance.dataValues) {\n  instance.set('name', objectName);\n  return await instance.save(); // promise rejection (primary key violation…) might be thrown here\n} else {\n  throw new Error(`No Model was found for the id ${objectId}`);\n}\n```\n\n========================================\n\nComments:\n- So it seems the only way is to call find immediately after the update?\n- anyway you should use find function.\n- you can call `find` function first, then do update with this object without using `where`\n- if you're using PostgreSQL you can define `returning` option to `true` that returns affected rows\n- I am using MySQL. I will test it with. Thanks for reply\n- I was not able to make it work with MySql. I guess this is only Postgresql feature :(\n- Also, despite what the docs say, I get `undefined` as the first parameter and the *number of affected rows* as the second parameter (using sqlite). To fix this I did `result = result.filter(Boolean);` before processing anything.\n- Is there a way to specify returned columns? I'm working with Postgress\n- what does mean x in \"[x, y] if you are using Postgres\" ?\n- @stackdave `x` would be the number of affected rows, while `y` is the actual affected rows (only supported in postgres with options.returning true.)\n- @nickang thanks, I'm working with postgress and options.returning true, with .update i get always x null, and y the record data, with .create i get directly y record data, no x!, it's possible to unify return [x, y] to .create and .update sequelize methods? and i missed a config maybe? because x is always null in .update\n- @stackdave That's weird. Could it be that you're missing a curly brace somewhere, causing your first and second params into `update` to be messed up? I'm not sure what the return value for `x` will be if no rows are being updated (should be 0 or null). Try digging into the docs for `.update()` - docs.sequelizejs.com/manual/tutorial/instances.html\n- The \"plain\" option seems to not be supported for the update statement (sequelize.readthedocs.io/en/latest/api/model/&hellip;)\n- As docs say: it returns the affected rows (only for postgres)\n- It seems that plain: true is deprecated. you can use save() instead. Look at my answer below.\n- it is not working for mysql , is there a way around\n- This definitely worked, but the `data[0].data.Values api` is wonky. BTW I am on Sequelize 6.12\n- in here stable v6 , there is no save operation , its only on after create , not update , sequelize.org/docs/v6/core-concepts/model-querying-basics/&hellip; so how to solve then ?\n- This is the cleanest solution that works universally. Thanks.\n- This needs 2 queries instead of 1\n- so there is no one way for mysql ? we must be re-fetch instead of update can be detect if the data is alr exist on db , all of comment what i thought is seem to be twice query for mysql.\n- its not solve still undefined because the question is mysql , your code just replace `person` to update query where its undefined of affect and result is `[ 1 ]`. still looking for best code, no need re-fetch data after update data.","metadata":{"transformedAt":"2026-08-18T18:33:34.334Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":234,"estimatedTokens":1841}}37{"id":"stack-35445849","source":"stackoverflow","questionId":35445849,"title":"Sequelize findOne latest entry","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize findOne latest entry\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to find the latest entry in a table. What is the best way to do this? The table has Sequelize's default `createdAt` field.\n\n========================================\n\nTop Answer:\n```\nmodel.findOne({\n where: { key },\n order: [ [ 'createdAt', 'DESC' ]],\n});\n```\n\n========================================\n\nCode:\n```text\ncreatedAt\n```\n\n```text\nYourModel.findAll({\n  limit: 1,\n  where: {\n    //your where conditions, or without them if you need ANY entry\n  },\n  order: [ [ 'createdAt', 'DESC' ]]\n}).then(function(entries){\n  //only difference is that you get users list limited to 1\n  //entries[0]\n});\n```\n\n```text\nfindOne\n```\n\n```text\nfindAll\n```\n\n```text\nfindAll\n```\n\n```text\nmodel.findOne({\n    where: { key },\n    order: [ [ 'createdAt', 'DESC' ]],\n});\n```\n\n```text\nmodel.findOne({\norder: [ [ 'id', 'DESC' ]],\n});\n```\n\n========================================\n\nComments:\n- I think you mean `createdAt`, not `id` on line 6. Submitted an edit: stackoverflow.com/suggested-edits/2345804\n- Usually id is auto increment. Therefore the highest value of id means the last added entry. But yes you could use `createdAt`.\n- If you are sure that you prefer createdAt, I will accept your edit.\n- And what? `findOne` returns an object and `findAll` returns an array! It is a huge difference!\n- Yes that is true. And I think that I pointed it in code sample. I wrote there : \" //only difference is that you get users list limited to 1\". In my opinion it is clear info that you get list/array. But if you still think that this should be stronger pointed I will do it.\n- @Noah this could be obvious but just to clarify the thing about using createdAt vs id, they aren't the same, normally your id field will be indexed since it is the primary key, createdAt is not indexed in most of cases, this has impact on the query time due to you're using \"order by\"\n- Basically, since `id` is auto increment, both fields, `id` and `createdAt` can do the job, if you have to choose, probably the `id` will do it faster\n- @Polak Strictly speaking, I'd prefer `createdAt` unless you (a) can prove it's faster (which, since datetimes are integers under the hood, isn't guaranteed!) and (b) have a need, because sorting by `createdAt` is much clearer than by ID -- if you're sorting by the date something was `createdAt`, you're obviously looking for chronological order. In contrast, `id` is a bit less clear.\n- @NicHartley, yeah, I agree with you if assuming id and createdAt were both already indexed, of course createdAt is clearer but as I told before, createdAt is normally an audit field not indexed and there's a trade off choosing between being clearer by adding a new index in your database vs reusing the primary key, maintaining only one index which won't slow down inserts/deletes performance and also saves disk space, to sumarize, just wanted to explain that depending on the situation, one option might be better than the other\n- @syzm why would someone order results when there is only one result being returned by your method and what if you don't have the key ? In most cases we don't have access to keys of latest entries.\n- @MuhammadFaizanUlHaq because ordering it by the createdAt is what is determining the latest entry.\n- I also think this is a better answer than the original post as it utilizes the correct Sequelize method, requires less parameters, and doesn't need to be unwrapped from an array. I also think @VinceBowdren 's request for more context is invalid as there is no context in the original question warranting any explanation.\n- to find the latest entry without knowing the key, just omit the `where` parameter entirely\n- @szym do I need to set key or is this useable as is? Kinda guessing key is suppose to be a field that exists on the model?\n- This is the correct answer. Everyone using `createdAt` risk the chance of getting the wrong object because ISO8601 dates in sequelize is second precise. If you have 2 objects created the same second, it's possible it will find and return the wrong one. If you're using an incremental ID, it's guaranteed to be in order.\n- unless you are using UUID :)\n- You are assuming that `id` is a sequential number here which isn't necessary in every case. It wouldn't work when it's a non-number or not sequential.","metadata":{"transformedAt":"2026-08-18T18:33:34.334Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":82,"estimatedTokens":1095}}38{"id":"stack-20695062","source":"stackoverflow","questionId":20695062,"title":"Sequelize OR condition object","tags":["node.js","sequelize.js"],"text":"Title: Sequelize OR condition object\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nBy creating object like this\n\n```\nvar condition=\n{\n where:\n {\n LastName:\"Doe\",\n FirstName:[\"John\",\"Jane\"],\n Age:{\n gt:18\n }\n } \n}\n```\n\nand pass it in\n\n```\nStudent.findAll(condition)\n.success(function(students){\n\n})\n```\n\nIt could beautifully generate SQL like this\n\n```\n\"SELECT * FROM Student WHERE LastName='Doe' AND FirstName in (\"John\",\"Jane\") AND Age>18\"\n```\n\nHowever, It is all 'AND' condition, how could I generate 'OR' condition by creating a condition object?\n\n========================================\n\nTop Answer:\nString based operators will be deprecated in the future (You've probably seen the warning in console).\n\nGetting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.\n\n```\nPost.findAll({\n where: {\n [Op.or]: [{authorId: 12}, {authorId: 13}]\n }\n});\n// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;\n\nPost.findAll({\n where: {\n authorId: {\n [Op.or]: [12, 13]\n }\n }\n});\n// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;\n```\n\n========================================\n\nCode:\n```text\nvar condition=\n{\n  where:\n  {\n     LastName:\"Doe\",\n     FirstName:[\"John\",\"Jane\"],\n     Age:{\n       gt:18\n     }\n  }    \n}\n```\n\n```text\nStudent.findAll(condition)\n.success(function(students){\n\n})\n```\n\n```text\n\"SELECT * FROM Student WHERE LastName='Doe' AND FirstName in (\"John\",\"Jane\") AND Age>18\"\n```\n\n```text\nwhere: {\n    LastName: \"Doe\",\n    $or: [\n        {\n            FirstName: \n            {\n                $eq: \"John\"\n            }\n        }, \n        {\n            FirstName: \n            {\n                $eq: \"Jane\"\n            }\n        }, \n        {\n            Age: \n            {\n                $gt: 18\n            }\n        }\n    ]\n}\n```\n\n```text\nWHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)\n```\n\n```text\n$or\n```\n\n```text\n[Sequelize.db.Op.or]\n```\n\n```text\nvar condition = {\n  where: Sequelize.and(\n    { name: 'a project' },\n    Sequelize.or(\n      { id: [1,2,3] },\n      { id: { lt: 10 } }\n    )\n  )\n};\n```\n\n```text\nSequelize.or\n```\n\n```text\nSequelize.or\n```\n\n```text\n$or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)\n```\n\n```text\nPost.findAll({\n  where: {\n    [Op.or]: [{authorId: 12}, {authorId: 13}]\n  }\n});\n// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;\n\nPost.findAll({\n  where: {\n    authorId: {\n      [Op.or]: [12, 13]\n    }\n  }\n});\n// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;\n```\n\n```text\nSELECT * FROM Student WHERE LastName='Doe' \nAND (FirstName = \"John\" or FirstName = \"Jane\") AND Age BETWEEN 18 AND 24\n```\n\n```text\nconst Op = require('Sequelize').Op;\n\nvar r = await to (Student.findAll(\n{\n  where: {\n    LastName: \"Doe\",\n    FirstName: {\n      [Op.or]: [\"John\", \"Jane\"]\n    },\n    Age: {\n      // [Op.gt]: 18\n      [Op.between]: [18, 24]\n    }\n  }\n}\n));\n```\n\n```text\n$\n```\n\n```text\n$and\n```\n\n```text\n$or\n```\n\n```text\n{freezeTableName: true}\n```\n\n```text\nvar condition = \n{ \n  [Op.or]: [ \n   { \n     LastName: {\n      [Op.eq]: \"Doe\"\n      },\n    },\n   { \n     FirstName: {\n      [Op.or]: [\"John\", \"Jane\"]\n      }\n   },\n   {\n      Age:{\n        [Op.gt]: 18\n      }\n    }\n ]\n}\n```\n\n```text\nconst Op = require('Sequelize').Op\n```\n\n```text\nStudent.findAll(condition)\n.success(function(students){ \n//\n})\n```\n\n```text\n\"SELECT * FROM Student WHERE LastName='Doe' OR FirstName in (\"John\",\"Jane\") OR Age>18\"\n```\n\n```text\nwhere: {\n          [Op.or]: [\n            {\n              id: {\n                [Op.in]: recordId,\n              },\n            }, {\n              id: {\n                [Op.eq]: recordId,\n              },\n            },\n          ],\n        },\n```\n\n```text\n// where email = 'xyz@mail.com' AND (( firstname = 'first' OR lastname = 'last' ) AND age > 18)\n```\n\n```text\n[Op.and]: [\n    {\n        \"email\": { [Op.eq]: 'xyz@mail.com' }\n        // OR \"email\": 'xyz@mail.com'\n    },\n    {\n        [Op.and]: [\n            {\n                [Op.or]: [\n                    {\n                        \"firstname\": \"first\"\n                    },\n                    {\n                        \"lastname\": \"last\"\n                    }\n                ]\n            },\n            {\n                \"age\": { [Op.gt]: 18 }\n            }]\n    }\n]\n```\n\n```js\nlet options: FindOptions<any> = {}\nlet where: WhereOptions = [];\n\nwhere.push({filedZ: 10});\n\nif (query.search) {\n        let tmp: WhereOptions = {\n          [Op.or]: [\n            {\n              [Op.and]: {\n                filedX: { [Op.like]: `%${query.search}%` },\n              },\n            },\n            {\n              [Op.and]: {\n                filedY: { [Op.like]: `%${query.search}%` },\n              },\n            },\n          ],\n        };\n        where.push(tmp)\n}\n\n\noptions.where = where;\n\nawait some.findAndCountAll(options);\n```\n\n```js\nlet options: FindOptions<any> = {}\nlet where: WhereOptions = [];\n\nwhere.push({filedZ: 10});\n\nif (query.search) {\n        let tmp: WhereOptions = {\n          [Op.or]: [\n            {\n              [Op.and]: {\n                filedX: { [Op.like]: `%${query.search}%` },\n              },\n            },\n            {\n              [Op.and]: {\n                filedY: { [Op.like]: `%${query.search}%` },\n              },\n            },\n          ],\n        };\n        where.push(tmp)\n}\n\n\noptions.where = where;\n\nawait some.findAndCountAll(options);\n```\n\n========================================\n\nComments:\n- i've seen 3 ways or operator being used... `where: { $or : [ {attr:val}, {attr:val}] }` , `where : { $or : { attr:val, attr2:val} }` , `where: { attr: { $or: [val, val] } }`\n- This should be `$or: { ... }`. Note, the `[` and `]` should become `{` and `}`\n- I prefer this way before the and/or functional way @evanhadfield suggested since it's neater.\n- how would i do the following in sequelize? ...where (A or B) and (C or D)\n- Use `[Op.or]` now from sequelize, `const { Op } = require('sequelize')`, instead of `$or`, as your key for sequelize 5+. They changed them to symbols.\n- Looks like the syntax has changed; this format no longer works (Sequelize 6.6.5 on my system). From their docs: sequelize.org/master/manual/&hellip;\n- i've seen 3 way or operator being used... ` where: { $or : [ {attr:val}, {attr:val}] } ` , ` where : { $or : { attr:val, attr2:val} } ` , ` where: { attr: { $or: [val, val] } } `\n- Thanks a ton! You saved my life bro. I was getting error for ('Sequelize/type'), your detailed answer with import did help me.\n- It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.","metadata":{"transformedAt":"2026-08-18T18:33:34.334Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":366,"estimatedTokens":1665}}39{"id":"stack-33357567","source":"stackoverflow","questionId":33357567,"title":"ECONNREFUSED for Postgres on nodeJS with dockers","tags":["node.js","postgresql","docker","sequelize.js"],"text":"Title: ECONNREFUSED for Postgres on nodeJS with dockers\nTags: node.js, postgresql, docker, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm building an app running on NodeJS using postgresql.\nI'm using SequelizeJS as ORM.\nTo avoid using real postgres daemon and having nodejs on my own device, i'm using containers with docker-compose.\n\nwhen I run `docker-compose up`\nit starts the pg database\n\n```\ndatabase system is ready to accept connections\n```\n\nand the nodejs server.\nbut the server can't connect to database.\n\n```\nError: connect ECONNREFUSED 127.0.01:5432\n```\n\nIf I try to run the server without using containers (with real nodejs and postgresd on my machine) it works.\n\nBut I want it to work correctly with containers. I don't understand what i'm doing wrong.\n\nhere is the `docker-compose.yml` file\n\n```\nweb:\n image: node\n command: npm start\n ports:\n - \"8000:4242\"\n links:\n - db\n working_dir: /src\n environment:\n SEQ_DB: mydatabase\n SEQ_USER: username\n SEQ_PW: pgpassword\n PORT: 4242\n DATABASE_URL: postgres://username:pgpassword@127.0.0.1:5432/mydatabase\n volumes:\n - ./:/src\ndb:\n image: postgres\n ports:\n - \"5432:5432\"\n environment:\n POSTGRES_USER: username\n POSTGRES_PASSWORD: pgpassword\n```\n\nCould someone help me please?\n\n(someone who likes docker :) )\n\n========================================\n\nTop Answer:\nFor further readers, if you're using `Docker desktop for Mac` use `host.docker.internal` instead of `localhost` or `127.0.0.1` as it's suggested in the doc. I came across same `connection refused...` problem. Backend `api-service` couldn't connect to `postgres` using `localhost/127.0.0.1`. Below is my docker-compose.yml and environment variables as a reference:\n\n```\nversion: \"2\"\n\nservices:\n api:\n container_name: \"be\"\n image: :latest\n ports:\n - \"8000:8000\"\n environment:\n DB_HOST: host.docker.internal\n DB_USER: \n DB_PASS: \n networks: \n - mynw\n\n db:\n container_name: \"psql\"\n image: postgres\n ports:\n - \"5432:5432\"\n environment:\n POSTGRES_DB: \n POSTGRES_USER: \n POSTGRES_PASS: \n volumes:\n - ~/dbdata:/var/lib/postgresql/data\n networks:\n - mynw\n```\n\n========================================\n\nCode:\n```text\ndatabase system is ready to accept connections\n```\n\n```text\nError: connect ECONNREFUSED 127.0.01:5432\n```\n\n```text\nweb:\n  image: node\n  command: npm start\n  ports:\n    - \"8000:4242\"\n  links:\n    - db\n  working_dir: /src\n  environment:\n    SEQ_DB: mydatabase\n    SEQ_USER: username\n    SEQ_PW: pgpassword\n    PORT: 4242\n    DATABASE_URL: postgres://username:pgpassword@127.0.0.1:5432/mydatabase\n  volumes:\n    - ./:/src\ndb:\n  image: postgres\n  ports:\n  - \"5432:5432\"\n  environment:\n    POSTGRES_USER: username\n    POSTGRES_PASSWORD: pgpassword\n```\n\n```text\ndocker-compose up\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nDATABASE_URL: postgres://username:pgpassword@127.0.0.1:5432/mydatabase\n```\n\n```text\nDATABASE_URL: postgres://username:pgpassword@db:5432/mydatabase\n```\n\n```text\nDATABASE_URL\n```\n\n```text\n127.0.0.1\n```\n\n```text\nlocalhost\n```\n\n```text\nweb\n```\n\n```text\ndb\n```\n\n```text\ndocker0\n```\n\n```text\ndocker-compose\n```\n\n```text\n127.0.0.1\n```\n\n```text\nCONTAINER_NAME\n```\n\n```text\ndb\n```\n\n```text\nweb\n```\n\n```text\n/etc/hosts\n```\n\n```text\ndb\n```\n\n```text\ndb\n```\n\n```text\nDB_HOST=<POSTGRES_SERVICE_NAME> #in your case \"db\" from docker-compose file.\n```\n\n```text\nversion: \"2\"\n\nservices:\n  api:\n    container_name: \"be\"\n    image: <image_name>:latest\n    ports:\n      - \"8000:8000\"\n    environment:\n      DB_HOST: host.docker.internal\n      DB_USER: <your_user>\n      DB_PASS: <your_pass>\n    networks: \n      - mynw\n\n  db:\n    container_name: \"psql\"\n    image: postgres\n    ports:\n      - \"5432:5432\"\n    environment:\n      POSTGRES_DB: <your_postgres_db_name>\n      POSTGRES_USER: <your_postgres_user>\n      POSTGRES_PASS: <your_postgres_pass>\n    volumes:\n      - ~/dbdata:/var/lib/postgresql/data\n    networks:\n      - mynw\n```\n\n```text\nDocker desktop for Mac\n```\n\n```text\nhost.docker.internal\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nconnection refused...\n```\n\n```text\napi-service\n```\n\n```text\npostgres\n```\n\n```text\nlocalhost/127.0.0.1\n```\n\n```js\nconst pool = new Pool({\n    user: 'postgres',\n    host: 'localhost',\n    database: 'users',\n    password: 'password',\n    port: 5432,\n})\n```\n\n```js\nconst pool = new Pool({\n    user: 'postgres',\n    host: 'postgresdb',\n    database: 'users',\n    password: 'password',\n    port: 5432,\n})\n```\n\n```text\nconst pgPool = new Pool(pgConfig);\nconst pgPoolWrapper = {\n    async connect() {\n        for (let nRetry = 1; ; nRetry++) {\n            try {\n                const client = await pgPool.connect();\n                if (nRetry > 1) {\n                    console.info('Now successfully connected to Postgres');\n                }\n                return client;\n            } catch (e) {\n                if (e.toString().includes('ECONNREFUSED') && nRetry < 5) {\n                    console.info('ECONNREFUSED connecting to Postgres, ' +\n                        'maybe container is not ready yet, will retry ' + nRetry);\n                    // Wait 1 second\n                    await new Promise(resolve => setTimeout(resolve, 1000));\n                } else {\n                    throw e;\n                }\n            }\n        }\n    }\n};\n```\n\n```text\nPgPool.connect()\n```\n\n```text\nversion: \"3\"\nservices:\n    web:\n      image: node\n      command: npm start\n      ports:\n         - \"8000:4242\"\n      # links:\n      #   - db\n      working_dir: /src\n      environment:\n        SEQ_DB: mydatabase\n        SEQ_USER: username\n        SEQ_PW: pgpassword\n        PORT: 4242\n        # DATABASE_URL: postgres://username:pgpassword@127.0.0.1:5432/mydatabase\n        DATABASE_URL: \"postgres://username:pgpassword@db:5432/mydatabase\"\n      volumes:\n          - ./:/src\n    db:\n      image: postgres\n      ports:\n          - \"5432:5432\"\n      environment:\n        POSTGRES_USER: username\n        POSTGRES_PASSWORD: pgpassword\n```\n\n```text\nweb\n```\n\n```text\ndb\n```\n\n```text\nweb\n```\n\n```text\ndb\n```\n\n```text\nweb\n```\n\n```text\npostgres://db:5432\n```\n\n```text\nHOST_PORT\n```\n\n```text\nCONTAINER_PORT\n```\n\n```text\ndb\n```\n\n```text\nHOST_PORT\n```\n\n```text\n8001\n```\n\n```text\n5432\n```\n\n```text\nCONTAINER_PORT\n```\n\n```text\nHOST_PORT\n```\n\n```text\nweb\n```\n\n```text\ndb\n```\n\n```text\npostgres://db:5432\n```\n\n```text\npostgres://{DOCKER_IP}:8001\n```\n\n```text\nDATABASE_URL\n```\n\n```text\npostgres://username:pgpassword@db:5432/mydatabase\n```\n\n```text\ndb:\nimage: postgres:14.1-alpine\ncontainer_name: doca_db\nports:\n  - \"54320:5432\" <---------- HERE\nenvironment:\n  POSTGRES_USER: user\n  POSTGRES_PASSWORD: password\nvolumes: \n  - psql:/var/lib/postgresql/data:Z\n```\n\n```text\ndb:\nimage: postgres:14.1-alpine\ncontainer_name: doca_db\nports:\n  - \"5432:5432\"\nenvironment:\n  POSTGRES_USER: user\n  POSTGRES_PASSWORD: password\nvolumes: \n  - psql:/var/lib/postgresql/data:Z\n```\n\n```text\ndocker compose up --build\n```\n\n```text\ndocker compose up\n```\n\n```text\n--build\n```\n\n```text\n--build\n```\n\n========================================\n\nComments:\n- this article mentions \"boot2docker ip\" command, seems useful here? andreagrandi.it/2015/02/21/&hellip;\n- seems to make a difference as to which host OS you are on\n- i am a noob/beginner with postgres/node. where exactly do i need to do the change?\n- @nerdess `DATABASE_URL` is in the question's `docker-compose.yml` - that's what needs changing. You reference it in your application code with `process.env['DATABASE_URL']`.\n- What if, on a Windows 10 machine, your Node app is running in Docker, but your Postgres is not?\n- @Andy changing that I get `Error: getaddrinfo ENOTFOUND db db:5432`\n- @Dani Did you modified the `docker-compose.yml` or another file?\n- Adding the `database container name` from `docker-compose.yml` as port worked for me as well. `localhost` is indeed not used when app is running on `Docker` environment. Thanks for your support.\n- For those of you who encountered the same issue that @Dani mentioned, make sure that your environment variables are configured corrently. For me, I'd misconfigured my Dockerfile so that Docker couldn't resolve the hostname\n- `docker compose build` helped my issue. `docker compose` doesn't rebuild your `Dockerfile` by default. See github.com/docker/compose/issues/1487. I was running an old build with `127.0.0.1` hardcoded.\n- The best answer out there. Maybe remember about adding container_name: in docker compose new versions to each container to be sure.\n- This also applies to having trouble connecting from the web front end container to the API container. Once I switched the API URL in my `.env.local` to `http:&#47;&#47;api:3333` things started working again.\n- Wow, thanks for the answer.. It worked like a charm\n- Been bagging my head against this for ages trying all manner of suggestions, this finally got my migrations working. Thank you.\n- I'm using Mac and I've been looking for this answer for almost two hours across internet, and it makes the things done, thanks!\n- Literally nothing worked until I tried this and it instantly worked! Thank You!!!!\n- For people coming to this error from Stephen Grider course of Docker, use this after PGClient connection in the server's index.js file. It works\n- Can't believe i was hours trying to find the problem and this was the perfect answear, Thank you so much\n- `ports:` aren't used for connections between containers and changing this shouldn't make a difference for the setup shown in the question, where both the application and the database are in containers.\n- While this is generally useful advice, it's not directly related to the problem described in the question. In particular, if the only thing you're changing is the `DATABASE_URL` environment variable in the Compose file, you're not changing the image contents at all and it doesn't matter if you rebuild.","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":62,"totalLines":495,"estimatedTokens":2445}}40{"id":"stack-29798357","source":"stackoverflow","questionId":29798357,"title":"Sequelize Where statement with date","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize Where statement with date\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize as my backend ORM. Now I wish to do some `WHERE` operations on a Date.\n\nMore specifically, I want to get all data where a date is between now and 7 days ago.\n\nThe problem is that the documentation does not specify which operations you can do on `Datatypes.DATE`\n\nCan anyone point me in the right direction?\n\n========================================\n\nTop Answer:\nI had to import the Operators symbols from sequelize and use like so.\n\n```\nconst { Op } = require('sequelize')\n\nmodel.findAll({\n where: {\n start_datetime: {\n [Op.gte]: moment().subtract(7, 'days').toDate()\n }\n }\n})\n```\n\nAccording to the docs, for security reasons this is considered best practise.\n\nSee http://docs.sequelizejs.com/manual/tutorial/querying.html for more info.\n\n Using Sequelize without any aliases improves security. Some frameworks\n automatically parse user input into js objects and if you fail to\n sanitize your input it might be possible to inject an Object with\n string operators to Sequelize.\n\n \n (...)\n\n \n For better security it is highly advised to use Sequelize.Op and not\n depend on any string alias at all. You can limit alias your\n application will need by setting operatorsAliases option, remember to\n sanitize user input especially when you are directly passing them to\n Sequelize methods.\n\n========================================\n\nCode:\n```text\nWHERE\n```\n\n```text\nDatatypes.DATE\n```\n\n```text\nmodel.findAll({\n  where: {\n    start_datetime: {\n      $gte: moment().subtract(7, 'days').toDate()\n    }\n  }\n})\n```\n\n```text\nconst { Op } = require('sequelize')\n\nmodel.findAll({\n  where: {\n    start_datetime: {\n      [Op.gte]: moment().subtract(7, 'days').toDate()\n    }\n  }\n})\n```\n\n```text\n$gt\n```\n\n```text\n$lt\n```\n\n```text\n$gte\n```\n\n```text\n$lte\n```\n\n```text\nOp\n```\n\n```text\nSymbol\n```\n\n```text\nconst { Op } = require('sequelize')\n\nmodel.findAll({\n  where: {\n    start_datetime: {\n      [Op.gte]: moment().subtract(7, 'days').toDate()\n    }\n  }\n})\n```\n\n```text\nmodel.findAll({\n  where: {\n    start_datetime: {\n      $gte: Sequelize.literal('NOW() - INTERVAL \\'7d\\''),\n    }\n  }\n})\n```\n\n```text\nSequelize.literal()\n```\n\n```text\nconst sevenDaysAgo = new Date(new Date().setDate(new Date().getDate() - 7));\nmodels.instagram.findAll({\n  where: {\n    my_date: {\n      $gt: sevenDaysAgo,\n      $lt: new Date(),\n    },\n  },\n});\n```\n\n```text\nconst sevenDaysFromNow = new Date(new Date().setDate(new Date().getDate() + 7));\nmodels.instagram.findAll({\n  where: {\n    my_date: {\n      $gt: new Date(),\n      $lt: sevenDaysFromNow,\n    },\n  },\n});\n```\n\n```text\nmoment.js\n```\n\n```text\n$gt\n```\n\n```text\n$gte\n```\n\n```text\n$gt\n```\n\n```text\n$gte\n```\n\n```text\n$lte\n```\n\n```text\n$lt\n```\n\n```text\n$gt\n```\n\n```text\n[Sequelize.Op.gt]\n```\n\n```text\n$gt\n```\n\n```text\nconst sevenDaysFromNowResults = await db.ModelName.findAll({\n      where: {\n        createdAt: {\n          [Sequelize.Op.gte]: new Date(new Date() - (7 * 24 * 60 * 60 * 1000)) // seven days ago\n        }\n      }\n    })\n```\n\n```text\n(days * 24hrs * 60mins * 60secs * 1000ms)\n```\n\n========================================\n\nComments:\n- So have you tried $lt: (new Date ()) and $gt : (...) replace ... with time now - 7 days\n- do note that this will not work from Sequelize 5... you can check out the breaking changes from Sequelize due to string based operators being insecure .. you should instead use [Op.gte] as per other comment\n- Or `db.Sequelize.Op` if you just import db\n- HI, instead using moment().subtract(7, 'days').toDate(), i need to use column name createdDate . is that possible?\n- Welcome to Stack Overflow ! To further improve the quality of your answer, keep in mind that links to other websites can become unavailable, and thus it is strongly advised that you copy the relevant info from the external documentation as a citation in the body of your answer.\n- This is the new standard for Sequelize.\n- There is a warning syntax error at or near \\\"\\\"7d\\\"\\\"\"\n- Could it be that you have double `\"` both escaped?\n- Change 'NOW() to \"NOW() and end with \" (double quote) then the \\' can be just a '\n- thank you i was scrolling and scrollin hoping for a non moment.js solution :) this need more upvotes\n- Upvoted. There seems to be no compelling reason to use `moment`. sequelize.org/v5/manual/querying.html now gives a non-moment example: `{ createdAt: { [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000) }`","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":224,"estimatedTokens":1122}}41{"id":"stack-46380563","source":"stackoverflow","questionId":46380563,"title":"Get only dataValues from Sequelize ORM","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: Get only dataValues from Sequelize ORM\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI'm using the sequelize ORM to fetch data from a PSQL DB. However, when I retrieve something, a whole bunch of data is given. The only data I want is inside 'dataValues'. Of course, I can use object.dataValues. But, is there any other good solutions?\n\nI'm using Sequelize 4.10\n\n========================================\n\nTop Answer:\nYes you can\n\n```\nModel.findAll({\n raw: true,\n //Other parameters\n});\n```\n\nwould return just the data and not the model instance\n\n========================================\n\nCode:\n```text\nModel.findAll({\n raw: true,\n //Other parameters\n});\n```\n\n```text\nModel.findById(1).then(data => {\n  console.log(data.get({ plain: true }));\n});\n```\n\n```text\nModel.findById(1).then(data => {\n  console.log(data.toJSON());\n});\n```\n\n```text\n.toJSON\n```\n\n```text\nconst users = await db.users.findAll({})\n   .map(el => el.get({ plain: true })) // add this line to code\n```\n\n```text\nconst users = await User.findAll({\n    attributes: [\"id\"], \n    where: {} // Your filters here\n}).map(u => u.get(\"id\")) // [1,2,3]\n```\n\n```text\nconst users = await User.findAll({\n    attributes: [\"id\"], \n    where: {} // Your filters here\n})\nconst userIds = JSON.stringify(users)) // [1,2,3]\n```\n\n```text\nelement.get({ plain: true })\n```\n\n```text\nlet rows = await database.Book.findAll(options);\n    rows = JSON.stringify(rows);\n    rows = JSON.parse(rows);\n```\n\n```text\nconst query = await myQuery(id);\nconst record = query.toJSON();\n```\n\n```text\n.toJSON\n```\n\n========================================\n\nComments:\n- Can I apply that to all queries globally?\n- Please not this does not work with eager loading nested entities.\n- To apply to all queries, use `var sequelize = new Sequelize('database', 'username', 'password', {query:{raw:true}})` as mentioned in stackoverflow.com/a/26228558/1802726.\n- While i'm writing this comment this answer has 55 upvotes, then why it is in last thread ?, it must be on top list. I think Stack Overflow need to change it's algorithm.\n- You should have some disclaimer while picking raw\n- This works on JS, but on typescript, the following error will trigger: \"error TS2551: Property 'dataValues' does not exist on type 'Model'. Did you mean 'getDataValue'?\" For this cases Masoud Tavakkoli answer solve the problem.\n- I like the `data.get` answer you gave, it's almost exactly what I want. But do you know if there's a way that one could specify the `data.get` (or the `plain:true`, or anything else, really) part in the `find`'s options? E.g. instead of doing what you did, rather something like `Model.findOne({ plain:true, ... }).then(...)` ? Because the way I see it, if you're only going to filter out the data you want *inside* the `.then()`, you might as well save yourself some time and just do `data.dataValues` instead of `data.get(...)`.\n- @PrintlnParams See Shivam's answer for details on that, if you want to do that globally see this answer stackoverflow.com/a/26228558/3803506 The method I described is more if you want to use the object for instance methods, etc but you want to encapsulate the implementation details before passing on the values, or for logging. `data.dataValues` works as well but be careful of mutability, also keep in mind that `dataValues` is sequelize's internal implementation which may change.","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":99,"estimatedTokens":847}}42{"id":"stack-21066755","source":"stackoverflow","questionId":21066755,"title":"How does sequelize.sync() work, specifically the force option?","tags":["sequelize.js"],"text":"Title: How does sequelize.sync() work, specifically the force option?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhat does the force option on sequelize.sync() do?\n\n```\nsequelize.sync({\n force: true\n});\n```\n\nSpecifically, I am interested in knowing what force: false does? Will it not sync the schema with the database?\n\nAre there any formal docs for sequelize? I could only find examples inside the docs.\n\n========================================\n\nTop Answer:\nThe OP was asking what `force: false` does, which is what I wanted to know too, so here's the rest.\n\n**The major takeaway, for me, was that the individual fields aren't synced (which is what I was hoping for, coming from the Waterline ORM). Meaning, if you have `force: false` and the table exists, any field additions/modifications/deletions you have won't be executed.**\n\n- `beforeSync` hooks are run\n\n- table is dropped if `force: true`\n\n- table is created with `if not exists`\n\n- indexes are added if necessary\n\n- `afterSync` hooks are run\n\nHere's the current code from the github repo for reference:\n\n**`lib.model.js`**\n\n```\nModel.prototype.sync = function(options) {\n options = options || {};\n options.hooks = options.hooks === undefined ? true : !!options.hooks;\n options = Utils._.extend({}, this.options, options);\n\n var self = this\n , attributes = this.tableAttributes;\n\n return Promise.try(function () {\n if (options.hooks) {\n return self.runHooks('beforeSync', options);\n }\n }).then(function () {\n if (options.force) {\n return self.drop(options);\n }\n }).then(function () {\n return self.QueryInterface.createTable(self.getTableName(options), attributes, options, self);\n }).then(function () {\n return self.QueryInterface.showIndex(self.getTableName(options), options);\n }).then(function (indexes) {\n // Assign an auto-generated name to indexes which are not named by the user\n self.options.indexes = self.QueryInterface.nameIndexes(self.options.indexes, self.tableName);\n\n indexes = _.filter(self.options.indexes, function (item1) {\n return !_.some(indexes, function (item2) {\n return item1.name === item2.name;\n });\n });\n\n return Promise.map(indexes, function (index) {\n return self.QueryInterface.addIndex(self.getTableName(options), _.assign({logging: options.logging, benchmark: options.benchmark}, index), self.tableName);\n });\n }).then(function () {\n if (options.hooks) {\n return self.runHooks('afterSync', options);\n }\n }).return(this);\n};\n```\n\n========================================\n\nCode:\n```text\nsequelize.sync({\n    force: true\n});\n```\n\n```text\nforce: true\n```\n\n```text\nDROP TABLE IF EXISTS\n```\n\n```js\nModel.prototype.sync = function(options) {\n  options = options || {};\n  options.hooks = options.hooks === undefined ? true : !!options.hooks;\n  options = Utils._.extend({}, this.options, options);\n\n  var self = this\n    , attributes = this.tableAttributes;\n\n  return Promise.try(function () {\n    if (options.hooks) {\n      return self.runHooks('beforeSync', options);\n    }\n  }).then(function () {\n    if (options.force) {\n      return self.drop(options);\n    }\n  }).then(function () {\n    return self.QueryInterface.createTable(self.getTableName(options), attributes, options, self);\n  }).then(function () {\n    return self.QueryInterface.showIndex(self.getTableName(options), options);\n  }).then(function (indexes) {\n    // Assign an auto-generated name to indexes which are not named by the user\n    self.options.indexes = self.QueryInterface.nameIndexes(self.options.indexes, self.tableName);\n\n    indexes = _.filter(self.options.indexes, function (item1) {\n      return !_.some(indexes, function (item2) {\n        return item1.name === item2.name;\n      });\n    });\n\n    return Promise.map(indexes, function (index) {\n      return self.QueryInterface.addIndex(self.getTableName(options), _.assign({logging: options.logging, benchmark: options.benchmark}, index), self.tableName);\n    });\n  }).then(function () {\n    if (options.hooks) {\n      return self.runHooks('afterSync', options);\n    }\n  }).return(this);\n};\n```\n\n```text\nforce: false\n```\n\n```text\nforce: false\n```\n\n```text\nbeforeSync\n```\n\n```text\nforce: true\n```\n\n```text\nif not exists\n```\n\n```text\nafterSync\n```\n\n```text\nlib.model.js\n```\n\n```text\nconst { Sequelize, DataTypes } = require('sequelize');\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'tmp.sqlite',\n});\n(async () => {\nconst IntegerNames = sequelize.define('IntegerNames', {\n  value: { type: DataTypes.INTEGER, },\n  name: { type: DataTypes.STRING, },\n}, {});\n//await IntegerNames.sync({force: true})\nawait IntegerNames.create({value: 2, name: 'two'});\nawait sequelize.close();\n})();\n```\n\n```text\nnpm install sequelize@6.5.1 sqlite3@5.0.2.\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS `IntegerNames`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `IntegerNames` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `value` INTEGER, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`IntegerNames`)\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4);\n```\n\n```text\nExecuting (default): CREATE TABLE IF NOT EXISTS `IntegerNames` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `value` INTEGER, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`IntegerNames`)\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4);\n```\n\n```text\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4);\n```\n\n```text\nconst assert = require('assert')\nconst { Sequelize, DataTypes } = require('sequelize');\n\nfunction getSequelize() {\n  if (process.argv[2] === 'p') {\n    return new Sequelize('tmp', undefined, undefined, {\n      dialect: 'postgres',\n      host: '/var/run/postgresql',\n    })\n  } else {\n    return new Sequelize({\n      dialect: 'sqlite',\n      storage: 'tmp.sqlite',\n    })\n  }\n}\n\n(async () => {\n{\n  const sequelize = getSequelize()\n  const IntegerNames = sequelize.define('IntegerNames', {\n    value: { type: DataTypes.INTEGER, },\n    name: { type: DataTypes.STRING, },\n  }, {});\n  await IntegerNames.sync({force: true})\n  await IntegerNames.create({value: 2, name: 'two'});\n  await IntegerNames.create({value: 3, name: 'three'});\n  await sequelize.close();\n}\n\n// Alter by adding column.\n{\n  const sequelize = getSequelize()\n  const IntegerNames = sequelize.define('IntegerNames', {\n    value: { type: DataTypes.INTEGER, },\n    name: { type: DataTypes.STRING, },\n    nameEs: { type: DataTypes.STRING, },\n  }, {});\n  await IntegerNames.sync({\n    alter: true,\n    force: false,\n  })\n  await IntegerNames.create({value: 5, name: 'five' , nameEs: 'cinco'});\n  await IntegerNames.create({value: 7, name: 'seven', nameEs: 'siete'});\n  const integerNames = await IntegerNames.findAll({\n    order: [['value', 'ASC']],\n  });\n  assert(integerNames[0].value  === 2);\n  assert(integerNames[0].name   === 'two');\n  assert(integerNames[0].nameEs === null);\n  assert(integerNames[1].name   === 'three');\n  assert(integerNames[1].nameEs === null);\n  assert(integerNames[2].name   === 'five');\n  assert(integerNames[2].nameEs === 'cinco');\n  assert(integerNames[3].name   === 'seven');\n  assert(integerNames[3].nameEs === 'siete');\n  await sequelize.close();\n}\n})();\n```\n\n```text\nSequelizeDatabaseError: SQLITE_ERROR: table IntegerNames has no column named nameEs\n```\n\n```text\nExecuting (default): ALTER TABLE \"public\".\"IntegerNames\" ADD COLUMN \"nameEs\" VARCHAR(255);\nExecuting (default): ALTER TABLE \"IntegerNames\" ALTER COLUMN \"value\" DROP NOT NULL;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"value\" DROP DEFAULT;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"value\" TYPE INTEGER;\nExecuting (default): ALTER TABLE \"IntegerNames\" ALTER COLUMN \"name\" DROP NOT NULL;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"name\" DROP DEFAULT;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"name\" TYPE VARCHAR(255);\nExecuting (default): ALTER TABLE \"IntegerNames\" ALTER COLUMN \"createdAt\" SET NOT NULL;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"createdAt\" DROP DEFAULT;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"createdAt\" TYPE TIMESTAMP WITH TIME ZONE;\nExecuting (default): ALTER TABLE \"IntegerNames\" ALTER COLUMN \"updatedAt\" SET NOT NULL;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"updatedAt\" DROP DEFAULT;ALTER TABLE \"IntegerNames\" ALTER COLUMN \"updatedAt\" TYPE TIMESTAMP WITH TIME ZONE;\n```\n\n```text\nExecuting (default): CREATE TABLE IF NOT EXISTS `IntegerNames_backup` (`id` INTEGER PRIMARY KEY, `value` INTEGER, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `nameEs` VARCHAR(255));\nExecuting (default): INSERT INTO `IntegerNames_backup` SELECT `id`, `value`, `name`, `createdAt`, `updatedAt`, `nameEs` FROM `IntegerNames`;\nExecuting (default): DROP TABLE `IntegerNames`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `IntegerNames` (`id` INTEGER PRIMARY KEY, `value` INTEGER, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `nameEs` VARCHAR(255));\n```\n\n```text\nforce: false\n```\n\n```text\nDROP\n```\n\n```text\nforce\n```\n\n```text\nforce: false\n```\n\n```text\nIF NOT EXISTS\n```\n\n```text\nCREATE TABLE IF NOT EXISTS\n```\n\n```text\nforce: true\n```\n\n```text\nCREATE TABLE IF NOT EXISTS\n```\n\n```text\nalter: true, force: false\n```\n\n```text\nforce: true\n```\n\n```text\nalter: true\n```\n\n```text\nforce: false\n```\n\n```text\nIntegerNames_backup\n```\n\n```text\nalter: true\n```\n\n```text\nALTER\n```\n\n```text\nALTER\n```\n\n```text\nALTER\n```\n\n```text\nalter\n```\n\n```text\nalter: true\n```\n\n```text\nNOT NULL\n```\n\n```text\nsequelize.sync({ force: false, alter: true })\n```\n\n========================================\n\nComments:\n- Additionally: if you change the table name (that already exist) of an Entity, the table stays with data, and another table with the new name is created.\n- This is not answering the question. The question asks what `force: false` does, not what `force: true` does.\n- I call sequelize.sync({force: false}), but still the tables are re-created. Why is this?\n- Link is dead. That's the reason why (stand-alone) links in answers should be avoided.\n- In February 2022, this is the most elaborate and descriptive answer.\n- There is more to check at: sequelize.org/docs/v7/models/model-synchronization","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":379,"estimatedTokens":2594}}43{"id":"stack-23929098","source":"stackoverflow","questionId":23929098,"title":"Is multiple delete available in sequelize?","tags":["node.js","sequelize.js"],"text":"Title: Is multiple delete available in sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a multiple contentIds.\n\n```\nMode.findAll({\n where: {\n id: contentIds\n }\n })\n```\n\nAfter finding all how can I Delete multiple rows from a table.\n\nOr tell me other options to delete multiple records with a single query.\n\n========================================\n\nTop Answer:\nIf you want to delete ALL models of a specific type, you can use: \n\n```\nModel.destroy({where: {}}).then(function () {});\n```\n\nThis will delete all records of type 'Model' from database.\nTested with mysql;\n\n========================================\n\nCode:\n```text\nMode.findAll({\n    where: {\n     id: contentIds\n   }\n  })\n```\n\n```text\nModel.destroy({ where: { id: [1,2,3,4] }})\n```\n\n```js\nModel.destroy({\n  where: {\n    id: contentIds\n  }\n});\n```\n\n```text\nModel.destroy({where: {}}).then(function () {});\n```\n\n```text\nModel.destroy({\n    where: {}\n}).then(function(){\n    console.log('destroy all data');\n    res.redirect('/');\n})\n```\n\n```text\ndeleted_at\n```\n\n```text\nforce: true\n```\n\n```text\nModel.destroy({})\n```\n\n========================================\n\nComments:\n- I am having mysql database. is this work on mysql ??\n- @SpunkyLive this does work in mySQL. I am on sequelize 2.0.3.\n- @Nikolay, your answer is actually more correct using the variable contentIds. Updated docs for anyone still interested in a mass delete: sequelize.readthedocs.org/en/latest/docs/instances/&hellip;\n- @js_gandalf cool, although others should keep in mind that you `cannot truncate a table referenced in a foreign key constraint`, as I ran into on one of my tables. ;)\n- The original link is dead, it seems that part has been reworked and there is no section for bulk delete in the guides anymore. I have linked the relevant API page instead.\n- api docs link not working\n- how to do for multiple column check id, somecolumn ?\n- Might be worthy to consider the paranoid option: stackoverflow.com/a/62226425/5157706\n- The original link is dead, it seems that part has been reworked and there is no section for bulk delete in the guides anymore. I have linked the relevant API page instead.\n- Url is not working throwing 404\n- Working url: sequelize.org/api/v6/class/src/&hellip;\n- Came here looking for a way to delete ALL records of a specific type. This worked perfectly!\n- `await Model.destroy({where: {}})`\n- Please read this how-to-answer for providing quality answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":96,"estimatedTokens":612}}44{"id":"stack-36262912","source":"stackoverflow","questionId":36262912,"title":"Where condition for joined table in Sequelize ORM","tags":["javascript","sql","postgresql","orm","sequelize.js"],"text":"Title: Where condition for joined table in Sequelize ORM\nTags: javascript, sql, postgresql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to get query like this with sequelize ORM: \n\n```\nSELECT \"A\".*, \nFROM \"A\" \nLEFT OUTER JOIN \"B\" ON \"A\".\"bId\" = \"B\".\"id\"\nLEFT OUTER JOIN \"C\" ON \"A\".\"cId\" = \"C\".\"id\"\nWHERE (\"B\".\"userId\" = '100'\n OR \"C\".\"userId\" = '100')\n```\n\nThe problem is that sequelise not letting me to reference \"B\" or \"C\" table in where clause. Following code\n\n```\nA.findAll({\n include: [{\n model: B,\n where: {\n userId: 100\n },\n required: false\n\n }, {\n model: C,\n where: {\n userId: 100\n },\n required: false\n }]\n]\n```\n\ngives me\n\n```\nSELECT \"A\".*, \nFROM \"A\" \nLEFT OUTER JOIN \"B\" ON \"A\".\"bId\" = \"B\".\"id\" AND \"B\".\"userId\" = 100\nLEFT OUTER JOIN \"C\" ON \"A\".\"cId\" = \"C\".\"id\" AND \"C\".\"userId\" = 100\n```\n\nwhich is completely different query, and result of\n\n```\nA.findAll({\n where: {\n $or: [\n {'\"B\".\"userId\"' : 100},\n {'\"C\".\"userId\"' : 100}\n ]\n },\n include: [{\n model: B,\n required: false\n\n }, {\n model: C,\n required: false\n }]\n]\n```\n\nis no even a valid query:\n\n```\nSELECT \"A\".*, \nFROM \"A\" \nLEFT OUTER JOIN \"B\" ON \"A\".\"bId\" = \"B\".\"id\"\nLEFT OUTER JOIN \"C\" ON \"A\".\"cId\" = \"C\".\"id\"\nWHERE (\"A\".\"B.userId\" = '100'\n OR \"A\".\"C.userId\" = '100')\n```\n\nIs first query even possible with sequelize, or I should just stick to raw queries?\n\n========================================\n\nTop Answer:\nAdd the where condition in the include, along with join.\n\n```\n{\n model: C,\n where: {\n id: 1\n }\n }\n```\n\n========================================\n\nCode:\n```text\nSELECT \"A\".*,      \nFROM \"A\" \nLEFT OUTER JOIN \"B\" ON \"A\".\"bId\" = \"B\".\"id\"\nLEFT OUTER JOIN \"C\" ON \"A\".\"cId\" = \"C\".\"id\"\nWHERE (\"B\".\"userId\" = '100'\n       OR \"C\".\"userId\" = '100')\n```\n\n```text\nA.findAll({\n    include: [{\n        model: B,\n        where: {\n            userId: 100\n        },\n        required: false\n\n    }, {\n        model: C,\n        where: {\n            userId: 100\n        },\n        required: false\n    }]\n]\n```\n\n```text\nSELECT \"A\".*,      \nFROM \"A\" \nLEFT OUTER JOIN \"B\" ON \"A\".\"bId\" = \"B\".\"id\" AND \"B\".\"userId\" = 100\nLEFT OUTER JOIN \"C\" ON \"A\".\"cId\" = \"C\".\"id\" AND \"C\".\"userId\" = 100\n```\n\n```text\nA.findAll({\n    where: {\n        $or: [\n            {'\"B\".\"userId\"' : 100},\n            {'\"C\".\"userId\"' : 100}\n        ]\n    },\n    include: [{\n        model: B,\n        required: false\n\n    }, {\n        model: C,\n        required: false\n    }]\n]\n```\n\n```text\nSELECT \"A\".*,      \nFROM \"A\" \nLEFT OUTER JOIN \"B\" ON \"A\".\"bId\" = \"B\".\"id\"\nLEFT OUTER JOIN \"C\" ON \"A\".\"cId\" = \"C\".\"id\"\nWHERE (\"A\".\"B.userId\" = '100'\n       OR \"A\".\"C.userId\" = '100')\n```\n\n```text\nA.findAll({\n    where: {\n        $or: [\n            {'$B.userId$' : 100},\n            {'$C.userId$' : 100}\n        ]\n    },\n    include: [{\n        model: B,\n        required: false\n\n    }, {\n        model: C,\n        required: false\n    }]\n});\n```\n\n```text\n$$\n```\n\n```text\n{\n       model: C,\n       where: {\n        id: 1\n       }\n   }\n```\n\n```text\nA.findAll({\n    where: {\n        $or: [\n            sequelize.where(sequelize.col('B.userId'), 100),\n            sequelize.where(sequelize.col('C.userId'), 100),\n        ]\n    },\n});\n```\n\n```text\nsequelize.where(sequelize.col(\n```\n\n```text\ncol\n```\n\n```text\n$$\n```\n\n```text\ncol\n```\n\n```text\nwhere: {}\n```\n\n```text\nsequelize.where\n```\n\n========================================\n\nComments:\n- very useful question!\n- Updating (Jan Aagaard Meier)'s answer, add `subQuery=false` option to work with limit and offset\n- `subQuery: false` on the top config object fixed it for me. Instead of each join being a subquery and have its own nested where, it ran all the joins, then added the where's to the end. Very cool option. How did you ever find this? I can't find it anywhere in the docs.\n- It all fails if I add another include, that is `{required: true}`. Then sequelize makes subquery with INNER JOIN in it and puts WHERE clause within. Therefore that generates an invalid query. SELECT \"A\".*, FROM (SELECT * FROM \"A\" INNER JOIN \"D\" ON \"A\".\"dId\" = \"D\".\"id\" WHERE (\"A\".\"B.userId\" = '100' OR \"A\".\"C.userId\" = '100') ) as \"A\" LEFT OUTER JOIN \"B\" ON \"A\".\"bId\" = \"B\".\"id\" LEFT OUTER JOIN \"C\" ON \"A\".\"cId\" = \"C\".\"id\" Any suggestions how to solve this?\n- Is this $$ syntax documented somewhere?\n- @xb1itz Any luck solving the problem with a second join? I am running into this as well.\n- Documented here: docs.sequelizejs.com/manual/tutorial/&hellip; under \"Top level where with eagerly loaded models\"\n- Works as-is, but breaks if I try to add `limit`.\n- @Jan Aagaard Meier i want to use condition where like var whereStatement = {}; if (status){ whereStatement.status = status; } if(condition){ whereStatement.'$B.userId$' = 100 } its not working, any help\n- not working for me `missing FROM-clause entry for table ...`\n- @BradDecker Here is the the updated documentation link (has been moved) sequelize.org/master/manual/&hellip;\n- This comment, just to update link for $$ docs sequelize.org/docs/v6/advanced-association-concepts/&hellip;\n- Make sure to add `required: true` here if you want to use it as an \"AND\" filter","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":243,"estimatedTokens":1270}}45{"id":"stack-43115151","source":"stackoverflow","questionId":43115151,"title":"Sequelize query to find all records that falls in between date range","tags":["mysql","sequelize.js"],"text":"Title: Sequelize query to find all records that falls in between date range\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a model with columns:\n\n```\nfrom: { type: Sequelize.DATE }\nto: { type: Sequelize.DATE }\n```\n\nI want to query all records whose either `from` OR `to` falls in between the date ranges: `[startDate, endDate]`\n\nI tried something like:\n\n```\nconst where = {\n $or: [{\n from: {\n $lte: startDate,\n $gte: endDate,\n },\n to: {\n $lte: startDate,\n $gte: endDate,\n },\n }],\n};\n```\n\nSomething like:\n\n```\nSELECT * from MyTable WHERE (startDate <= from <= endDate) OR (startDate <= to <= endDate\n```\n\n========================================\n\nTop Answer:\nTry this condition. What I think you are asking will do so.\n\n**For a new version of Sequelize:**\n\n```\nconst where = {\n [Op.or]: [{\n from: {\n [Op.between]: [startDate, endDate]\n }\n }, {\n to: {\n [Op.between]: [startDate, endDate]\n }\n }]\n};\n```\n\n**OR as your code structure:**\n\n```\nconst where = {\n $or: [{\n from: {\n $between: [startDate, endDate]\n }\n }, {\n to: {\n $between: [startDate, endDate]\n }\n }]\n};\n```\n\nFor more information, you can this Sequelize official documentation.\n\n========================================\n\nCode:\n```text\nfrom: { type: Sequelize.DATE }\nto: { type: Sequelize.DATE }\n```\n\n```text\nconst where = {\n    $or: [{\n        from: {\n            $lte: startDate,\n            $gte: endDate,\n        },\n        to: {\n            $lte: startDate,\n            $gte: endDate,\n        },\n    }],\n};\n```\n\n```text\nSELECT * from MyTable WHERE (startDate <= from <= endDate) OR (startDate <= to <= endDate\n```\n\n```text\nfrom\n```\n\n```text\nto\n```\n\n```text\n[startDate, endDate]\n```\n\n```javascript\n// Here startDate and endDate are Date objects\nconst where = {\n    from: {\n        $between: [startDate, endDate]\n    }\n};\n```\n\n```text\nbetween\n```\n\n```text\n(startDate <= from AND from <= endDate)\n```\n\n```text\nconst where = {\n    [Op.or]: [{\n        from: {\n            [Op.between]: [startDate, endDate]\n        }\n    }, {\n        to: {\n            [Op.between]: [startDate, endDate]\n        }\n    }]\n};\n```\n\n```text\nconst where = {\n    $or: [{\n        from: {\n            $between: [startDate, endDate]\n        }\n    }, {\n        to: {\n            $between: [startDate, endDate]\n        }\n    }]\n};\n```\n\n```text\nconst { Op } = require('sequelize');\n```\n\n```text\nconst startedDate = new Date(\"2020-12-12 00:00:00\");\nconst endDate = new Date(\"2020-12-26 00:00:00\");\n```\n\n```text\ntable.findAll({where : {\"fieldOfYourDate\" : {[Op.between] : [startedDate , endDate ]}}})\n.then((result) =>  res.status(200).json({data : result}))\n.catch((error) =>  res.status(404).json({errorInfo: error}))\n```\n\n```js\nconst where = {\n  \"date_field\": {\n    [Op.and]: {\n      [Op.gte]: startOfDateRange,\n      [Op.lte]: endOfDateRange\n    }\n  }\n}\n```\n\n```text\n[Op.between]\n```\n\n```text\nOp.between\n```\n\n```text\nBETWEEN\n```\n\n========================================\n\nComments:\n- What is the problem? Do you get any error? What is the SQL generated by this query?\n- it's because your query is wrong. `from: { $gte: startDate, $lte:endDate }`\n- $between is boundary exclusive? Does it include if `from === startDate || from === endDate`\n- @ShankarRegmi `Between` comparison in MYSQL is **inclusive** . For more dev.mysql.com/doc/refman/5.7/en/&hellip;\n- I don't think this is correct. If the `from` date is *before* the start date, the `to` date could still be between start and end. If the goal is to check for an *overlapping time period*, it's necessary to check that `to` is *before* start *and* that `from` is *after* end.\n- Why would you need both start and end date for both the from and to positions?\n- @CecilRodriguez Need to check if any of the date from separate two field found between those dates. And also he specifically asked for that in the question.\n- It's giving `Types of property '[Op.between]' are incompatible.` error, below one solves that issue stackoverflow.com/a/60987727/5134215 Putting here just in case anyone trying to solve same issue","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":209,"estimatedTokens":1005}}46{"id":"stack-46357533","source":"stackoverflow","questionId":46357533,"title":"How to Add, Delete new Columns in Sequelize CLI","tags":["node.js","sequelize.js","psql","sequelize-cli"],"text":"Title: How to Add, Delete new Columns in Sequelize CLI\nTags: node.js, sequelize.js, psql, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI've just started using Sequelize and Sequelize CLI\n\nSince it's a development time, there are a frequent addition and deletion of columns. What the best the method to add a new column to an existing model?\n\nFor example, I want to a new column '**completed**' to **Todo** model. I'll add this column to models/todo.js. Whats the next step?\n\nI tried `sequelize db:migrate`\n\nnot working: *\"No migrations were executed, database schema was already up to date.\"*\n\n========================================\n\nTop Answer:\nIf you want to add multiple columns to the same table, wrap everything in a `Promise.all()` and put the columns you'd like to add within an array:\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return Promise.all([\n queryInterface.addColumn(\n 'tableName',\n 'columnName1',\n {\n type: Sequelize.STRING\n }\n ),\n queryInterface.addColumn(\n 'tableName',\n 'columnName2',\n {\n type: Sequelize.STRING\n }\n ),\n ]);\n },\n\n down: (queryInterface, Sequelize) => {\n return Promise.all([\n queryInterface.removeColumn('tableName', 'columnName1'),\n queryInterface.removeColumn('tableName', 'columnName2')\n ]);\n }\n};\n```\n\nYou can have any column type supported by sequelize https://sequelize.readthedocs.io/en/2.0/api/datatypes/\n\n========================================\n\nCode:\n```text\nsequelize db:migrate\n```\n\n```text\n$ sequelize migration:create --name name_of_your_migration\n```\n\n```text\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n    // logic for transforming into the new state\n    return queryInterface.addColumn(\n      'Todo',\n      'completed',\n     Sequelize.BOOLEAN\n    );\n\n  },\n\n  down: function(queryInterface, Sequelize) {\n    // logic for reverting the changes\n    return queryInterface.removeColumn(\n      'Todo',\n      'completed'\n    );\n  }\n}\n```\n\n```text\n$ sequelize db:migrate\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return Promise.all([\n      queryInterface.addColumn(\n        'tableName',\n        'columnName1',\n        {\n          type: Sequelize.STRING\n        }\n      ),\n      queryInterface.addColumn(\n        'tableName',\n        'columnName2',\n        {\n          type: Sequelize.STRING\n        }\n      ),\n    ]);\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return Promise.all([\n      queryInterface.removeColumn('tableName', 'columnName1'),\n      queryInterface.removeColumn('tableName', 'columnName2')\n    ]);\n  }\n};\n```\n\n```text\nPromise.all()\n```\n\n```text\nmodule.exports = {\n/**\n   * @typedef {import('sequelize').Sequelize} Sequelize\n   * @typedef {import('sequelize').QueryInterface} QueryInterface\n   */\n\n  /**\n   * @param {QueryInterface} queryInterface\n   * @param {Sequelize} Sequelize\n   * @returns\n   */\n  up: function(queryInterface, Sequelize) {\n    // logic for transforming into the new state\n    return queryInterface.addColumn(\n      'Todo',\n      'completed',\n     Sequelize.BOOLEAN\n    );\n\n  },\n\n  down: function(queryInterface, Sequelize) {\n    // logic for reverting the changes\n    return queryInterface.removeColumn(\n      'Todo',\n      'completed'\n    );\n  }\n}\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n    async up(queryInterface, Sequelize) {\n        const transaction = await queryInterface.sequelize.transaction();\n        try {\n            await queryInterface.addColumn(\n                'Todo',\n                'completed',\n                {\n                    type: Sequelize.STRING,\n                },\n                { transaction }\n            );\n\n            await queryInterface.addIndex(\n                'Todo',\n                {\n                    fields: ['completed'],\n                    unique: true,\n                },\n                { transaction }\n            );\n\n            await transaction.commit();\n        } catch (err) {\n            await transaction.rollback();\n            throw err;\n        }\n    },\n\n    async down(queryInterface, Sequelize) {\n        const transaction = await queryInterface.sequelize.transaction();\n        try {\n            await queryInterface.removeColumn(\n                'Todo',\n                'completed',\n                { transaction }\n            );\n\n            await transaction.commit();\n        } catch (err) {\n            await transaction.rollback();\n            throw err;\n        }\n    }\n};\n```\n\n```text\nmodule.exports = {\n    up: (queryInterface, Sequelize) => {\n        return queryInterface.sequelize.transaction((t) => {\n            return Promise.all([\n                queryInterface.addColumn('table_name', 'field_one_name', {\n                    type: Sequelize.STRING\n                }, { transaction: t }),\n                queryInterface.addColumn('table_name', 'field_two_name', {\n                    type: Sequelize.STRING,\n                }, { transaction: t })\n            ])\n        })\n    },\n\n    down: (queryInterface, Sequelize) => {\n        return queryInterface.sequelize.transaction((t) => {\n            return Promise.all([\n                queryInterface.removeColumn('table_name', 'field_one_name', { transaction: t }),\n                queryInterface.removeColumn('table_name', 'field_two_name', { transaction: t })\n            ])\n        })\n    }\n};\n```\n\n```text\nsequelize migration:generate --name custom_name_describing_your_migration\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  // result_description\n  up: async (queryInterface, Sequelize) => {\n    let tableName = 'yourTableName';\n    let columnName1 = 'columnName1';\n    let columnName2 = 'columnName1';\n    return Promise.all([\n      queryInterface.describeTable(tableName)\n        .then(tableDefinition => {\n          if (tableDefinition.columnName1) return Promise.resolve();\n\n          return queryInterface.addColumn(\n            tableName,\n            columnName1,\n            {\n              type: Sequelize.INTEGER,\n              allowNull: false\n            }\n          );\n        }),\n      queryInterface.describeTable(tableName)\n        .then(tableDefinition => {\n          if (tableDefinition.columnName2) return Promise.resolve();\n\n          return queryInterface.addColumn(\n            tableName,\n            columnName2,\n            {\n              type: Sequelize.STRING,\n              allowNull: false\n            }\n          );\n        })\n    ]);\n  },\n\n  down: (queryInterface, Sequelize) => {\n\n    let tableName = 'TestList';\n    let columnName1 = 'totalScore';\n    let columnName2 = 'resultDescription';\n    return Promise.all([\n      queryInterface.describeTable(tableName)\n        .then(tableDefinition => {\n          if (tableDefinition.columnName1) return Promise.resolve();\n          return queryInterface.removeColumn(tableName, columnName1)\n        }),\n      queryInterface.describeTable(tableName)\n        .then(tableDefinition => {\n          if (tableDefinition.columnName1) return Promise.resolve();\n          return queryInterface.removeColumn(tableName, columnName2)\n        }),\n    ]);\n  }\n};\n```\n\n```text\nUserModel.sync({ alter: true })\n```\n\n```text\nUserModel.sync({ force: true })\n```\n\n========================================\n\nComments:\n- Is there any documentation for this?\n- Thanks. What if I want to add multiple columns?\n- Also which docs should I prefer? docs.sequelizejs.com or sequelize.readthedocs.io ??\n- For 1. You just add multiple `addColumn` statements in the `up` function and then the corresponding `removeColumn`s in the `down` function.\n- For 2. I'd say sequelize.readthedocs.io/en/v3. It comes straight from the source code repository.\n- Thanks. Note that you have to specify the name of the new migration with --name parameter.\n- Should I manually add the new column to the already existing model file before or after the migration command? Or does sequelize add it automatically?\n- @Hans, sequelize doesn't touch the model file. So you should update the model class after the migration is done.\n- how to add default value ? like default must be true.. what option do we provide\n- Also, it will be better to wrap a promise using a transaction. You can find an example here: docs.sequelizejs.com/manual/migrations.html#migration-skelet&zwnj;&#8203;on\n- @Pter You can use transactions and column changes, but mysql 5.7 does not allow column changes as part of a transaction.\n- that's awesome!\n- hi @NS23, what extension are you using?\n- @JohnReyFlores there is no need for any extension. You can read article in link to better understand type safety with jsdoc “Type Safe JavaScript with JSDoc” by TruckJS medium.com/@trukrs/type-safe-javascript-with-jsdoc-7a2a63209&zwnj;&#8203;b76\n- GREAT I didn't know about this incredible usefull feature!! thank you\n- why do you manually rollback? you can get ride of the try/catch, when an error comes it will automatically rollback\n- Upvoting for giving a direct link to the migrations part of the doc.\n- @Gavin creating migration, adding new columns to this migration and then running migration will also add the columns to model as well?\n- @MKJ it will not add columns to the model. If you generate a new migration for a new table and give it attributes, it would then generate the model with the given attributes (columns)","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":329,"estimatedTokens":2319}}47{"id":"stack-18304504","source":"stackoverflow","questionId":18304504,"title":"Create or Update Sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: Create or Update Sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize in my Nodejs project and I found a problem that I'm having a hard time to solve.\nBasically I have a cron that gets an array of objects from a server than inserts it on my database as a object ( for this case, cartoons ). But if I already have one of the objects, I have to update it.\n\nBasically I have a array of objects and a could use the BulkCreate() method. But as the Cron starts again, it doesn't solve it so I was needing some sort of update with an upsert true flag. And the main issue: I must have a callback that fires just once after all these creates or updates. Does anyone have an idea of how can I do that? Iterate over an array of object.. creating or updating it and then getting a single callback after?\n\nThanks for the attention\n\n========================================\n\nTop Answer:\nYou can use upsert\nIt's way easier.\n\nAn example from this answer:\n\n```\nconst [record, created] = await Model.upsert(\n { id: 1, name: 'foo' }, // Record to upsert\n { returning: true } // Return upserted record\n);\n```\n\nAnd an example from the documentation (note `{returning: true}` is the default value, so can be omitted):\n\n```\nconst [instance, created] = await MyModel.upsert({});\n```\n\nInsert or update a single row. An update will be executed if a row which matches the supplied values on **either the primary key or a unique key is found**. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.\n\nImplementation details:\n\n- **MySQL** - Implemented with `ON DUPLICATE KEY UPDATE`\n\n- **PostgreSQL** - Implemented with `ON CONFLICT DO UPDATE`. If update data contains PK field, then PK is selected as the default conflict key. Otherwise first unique constraint/index will be selected, which can satisfy conflict key requirements.\n\n- **SQLite** - Implemented with `ON CONFLICT DO UPDATE`\n\n- **MSSQL** - Implemented as a single query using `MERGE` and `WHEN (NOT) MATCHED THEN`\n\n========================================\n\nCode:\n```text\nfunction upsert(values, condition) {\n    return Model\n        .findOne({ where: condition })\n        .then(function(obj) {\n            // update\n            if(obj)\n                return obj.update(values);\n            // insert\n            return Model.create(values);\n        })\n}\n```\n\n```text\nupsert({ first_name: 'Taku' }, { id: 1234 }).then(function(result){\n    res.status(200).send({success: true});\n});\n```\n\n```text\nwhere\n```\n\n```text\nnew Sequelize.Utils.CustomEventEmitter(function(emitter) {\n    if(data.id){\n        Model.update(data, {id: data.id })\n        .success(function(){\n            emitter.emit('success', data.id );\n        }).error(function(error){\n            emitter.emit('error', error );\n        });\n    } else {\n        Model.build(data).save().success(function(d){\n            emitter.emit('success', d.id );\n        }).error(function(error){\n            emitter.emit('error', error );\n        });\n    }\n}).success(function(data_id){\n    // Your callback stuff here\n}).error(function(error){\n   // error stuff here\n}).run();  // kick off the queries\n```\n\n```text\nasync.auto({\n   getInstance : function(cb) {\n      Model.findOrCreate({\n        attribute : value,\n        ...\n      }).complete(function(err, result) {\n        if (err) {\n          cb(null, false);\n        } else {\n          cb(null, result);\n        }\n      });\n    },\n    updateInstance : ['getInstance', function(cb, result) {\n      if (!result || !result.getInstance) {\n        cb(null, false);\n      } else {\n        result.getInstance.updateAttributes({\n           attribute : value,\n           ...\n        }, ['attribute', ...]).complete(function(err, result) {\n          if (err) {\n            cb(null, false);\n          } else {\n            cb(null, result);\n          }\n        });\n       }\n      }]\n     }, function(err, allResults) {\n       if (err || !allResults || !allResults.updateInstance) {\n         // job not done\n       } else {\n         // job done\n     });\n});\n```\n\n```text\nfindOrCreate\n```\n\n```text\nupdate\n```\n\n```text\nvar updateOrCreate = function (model, where, newItem, onCreate, onUpdate, onError) {\n    // First try to find the record\n    model.findOne({where: where}).then(function (foundItem) {\n        if (!foundItem) {\n            // Item not found, create a new one\n            model.create(newItem)\n                .then(onCreate)\n                .catch(onError);\n        } else {\n            // Found an item, update it\n            model.update(newItem, {where: where})\n                .then(onUpdate)\n                .catch(onError);\n            ;\n        }\n    }).catch(onError);\n}\nupdateOrCreate(\n    models.NewsItem, {title: 'sometitle1'}, {title: 'sometitle'},\n    function () {\n        console.log('created');\n    },\n    function () {\n        console.log('updated');\n    },\n    console.log);\n```\n\n```text\nconst [record, created] = await Model.upsert(\n  { id: 1, name: 'foo' }, // Record to upsert\n  { returning: true }     // Return upserted record\n);\n```\n\n```text\nconst [instance, created] = await MyModel.upsert({});\n```\n\n```text\n{returning: true}\n```\n\n```text\nON DUPLICATE KEY UPDATE\n```\n\n```text\nON CONFLICT DO UPDATE\n```\n\n```text\nON CONFLICT DO UPDATE\n```\n\n```text\nMERGE\n```\n\n```text\nWHEN  (NOT) MATCHED THEN\n```\n\n```text\nvar Promise = require('promise');\nvar PushToken = require(\"../models\").PushToken;\n\nvar createOrUpdatePushToken = function (deviceID, pushToken) {\n  return new Promise(function (fulfill, reject) {\n    PushToken\n      .findOrCreate({\n        where: {\n          deviceID: deviceID\n        }, defaults: {\n          pushToken: pushToken\n        }\n      })\n      .spread(function (foundOrCreatedPushToken, created) {\n        if (created) {\n          fulfill(foundOrCreatedPushToken);\n        } else {\n          foundOrCreatedPushToken\n            .update({\n              pushToken: pushToken\n            })\n            .then(function (updatedPushToken) {\n              fulfill(updatedPushToken);\n            })\n            .catch(function (err) {\n              reject(err);\n            });\n        }\n      });\n  });\n};\n```\n\n```text\nasync function updateOrCreate (model, where, newItem) {\n    // First try to find the record\n   const foundItem = await model.findOne({where});\n   if (!foundItem) {\n        // Item not found, create a new one\n        const item = await model.create(newItem)\n        return  {item, created: true};\n    }\n    // Found an item, update it\n    const item = await model.update(newItem, {where});\n    return {item, created: false};\n}\n```\n\n```text\nfunction updateOrCreate (model, where, newItem) {\n    // First try to find the record\n    return model\n    .findOne({where: where})\n    .then(function (foundItem) {\n        if (!foundItem) {\n            // Item not found, create a new one\n            return model\n                .create(newItem)\n                .then(function (item) { return  {item: item, created: true}; })\n        }\n         // Found an item, update it\n        return model\n            .update(newItem, {where: where})\n            .then(function (item) { return {item: item, created: false} }) ;\n    }\n}\n```\n\n```text\nupdateOrCreate(models.NewsItem, {slug: 'sometitle1'}, {title: 'Hello World'})\n    .then(function(result) {\n        result.item;  // the model\n        result.created; // bool, if a new item was created.\n    });\n```\n\n```text\nupdateOrCreate(models.NewsItem, {slug: 'sometitle1'}, {title: 'Hello World'})\n    .then(..)\n    .catch(function(err){});\n```\n\n```text\nUser.upsert({ a: 'a', b: 'b', username: 'john' })\n```\n\n```text\nit('works with upsert on id', function() {\n    return this.User.upsert({ id: 42, username: 'john' }).then(created => {\n        if (dialect === 'sqlite') {\n            expect(created).to.be.undefined;\n        } else {\n            expect(created).to.be.ok;\n        }\n\n        this.clock.tick(1000);\n        return this.User.upsert({ id: 42, username: 'doe' });\n    }).then(created => {\n        if (dialect === 'sqlite') {\n            expect(created).to.be.undefined;\n        } else {\n            expect(created).not.to.be.ok;\n        }\n\n        return this.User.findByPk(42);\n    }).then(user => {\n        expect(user.createdAt).to.be.ok;\n        expect(user.username).to.equal('doe');\n        expect(user.updatedAt).to.be.afterTime(user.createdAt);\n    });\n});\n```\n\n```text\nupsert\n```\n\n```text\nMySQL\n```\n\n```text\nPostgreSQL\n```\n\n```text\nSQLite\n```\n\n```text\nMSSQL\n```\n\n========================================\n\nComments:\n- I was hoping for some upset option on the Update from Sequelize but it seems out of the road map. I'll try this. Thanks!\n- Hint: Use promise chaining for error handling and save 50% of your code :)\n- how to use it for parent child relationship? how to upsert child table?\n- Use upsert, but if it performed an insert, you'll then need to then get the inserted object :( - stackoverflow.com/a/29071422/48348\n- @IanGrainger - not anymore! stackoverflow.com/a/50301416/107277\n- The link is broken the current API documentation for `upsert`: sequelize.org/api/v6/class/src/&hellip;\n- return Model.create({...values, ...condition})\n- When working with high frequency data, not being atomic causes repetition of data to happen! Otherwise, an elegant solution!\n- Comment: I noticed taht update() .. does not return the database object. So if you need it you may fetch it one more time.\n- It will find a match on a unique or primary key column\n- I really liked the way answered the question. Kudos","metadata":{"transformedAt":"2026-08-18T18:33:34.335Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":354,"estimatedTokens":2418}}48{"id":"stack-41577597","source":"stackoverflow","questionId":41577597,"title":"sequelize \"findbyid\" is not a function but apparently \"findAll\" is","tags":["node.js","orm","sequelize.js"],"text":"Title: sequelize \"findbyid\" is not a function but apparently \"findAll\" is\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am getting a very strange problem with sequelize, When I try to call the function findAll it works fine (same for create and destroy), but when I try to call function \"findById\", it throws \"findById is not a function\" (same for \"FindOne\").\n\n```\n//works fine\nvar gammes = models.gamme.findAll().then(function(gammes) {\n res.render('admin/gammes/gestion_gamme',{\n layout: 'admin/layouts/structure' ,\n gammes : gammes,\n js: \"gammes\"\n });\n });\n\n// throws models.gamme.findById is not a function\nmodels.gamme.findById(req.params.id).then(function(gamme) {\n gamme.update({\n nom: req.body.nom\n }).then(function () {\n res.redirect(\"/gammes\");\n })\n });\n```\n\nGamme.js model\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n \"use strict\";\n var gamme = sequelize.define('gamme', {\n id_gamme: {\n type: DataTypes.INTEGER.UNSIGNED,\n autoIncrement: true,\n primaryKey: true\n },\n nom: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n classMethods: {},\n timestamps: false\n });\n return gamme;\n};\n```\n\n========================================\n\nTop Answer:\nthe team of sequelize was deleting this function and replced it by a new function is \n\n findByPk\n\nlike this \n\n```\n// search for known ids\nProject.findByPk(123).then(project => {\n // project will be an instance of Project and stores the content of the table entry\n // with id 123. if such an entry is not defined you will get null\n})\n```\n\n========================================\n\nCode:\n```text\n//works fine\nvar gammes = models.gamme.findAll().then(function(gammes) {\n        res.render('admin/gammes/gestion_gamme',{\n            layout: 'admin/layouts/structure' ,\n            gammes : gammes,\n            js: \"gammes\"\n        });\n    });\n\n// throws models.gamme.findById is not a function\nmodels.gamme.findById(req.params.id).then(function(gamme) {\n        gamme.update({\n            nom: req.body.nom\n        }).then(function () {\n            res.redirect(\"/gammes\");\n        })\n    });\n```\n\n```text\nmodule.exports = function (sequelize, DataTypes) {\n    \"use strict\";\n    var gamme = sequelize.define('gamme', {\n        id_gamme: {\n            type: DataTypes.INTEGER.UNSIGNED,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        nom: {\n            type: DataTypes.STRING,\n            allowNull: false\n        }\n    }, {\n        classMethods: {},\n        timestamps: false\n    });\n    return gamme;\n};\n```\n\n```text\n// search for known ids\nProject.findByPk(123).then(project => {\n  // project will be an instance of Project and stores the content of the table entry\n  // with id 123. if such an entry is not defined you will get null\n})\n```\n\n```text\nQuestion.findByPk(question_id).then(question => {\n            return res.status(200).json({\n                question: question\n           });\n}).catch(err => {\n     console.log(err);\n});\n```\n\n========================================\n\nComments:\n- Can you let us know the sequelize version you are using\n- github.com/sequelize/sequelize/wiki/Upgrade-from-2.0-to-3.0\n- thanks a lot ! I was consulting the documentation of sequelize 2, but the installed version was 1.7\n- what leads you to believe that the OP is using v5? do you see the comment about the installed version being v1.7?\n- Well I just upgraded from Sequelize 4.33.2 to 5.8.6 and this fixed my issue.\n- i try in sequelize version 6.13.0 , findByPk() will working fine","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":138,"estimatedTokens":875}}49{"id":"stack-28116187","source":"stackoverflow","questionId":28116187,"title":"Unique constraint on sequelize column","tags":["javascript","node.js","sequelize.js"],"text":"Title: Unique constraint on sequelize column\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing NodeJS and Sequelize 2.0, I'm writing a migration to create a new table. In addition to the primary key, I want to mark a second column to be enforced as unique. I can't find anything about this in the documentation.\n\n```\nmigration.createTable('data', {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n key: {\n // needs to be unique\n type: DataTypes.UUID,\n allowNull: false\n }\n})\n .then(function () {\n done();\n });\n```\n\n========================================\n\nCode:\n```text\nmigration.createTable('data', {\n    id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    key: {\n        // needs to be unique\n        type: DataTypes.UUID,\n        allowNull: false\n    }\n})\n    .then(function () {\n        done();\n    });\n```\n\n```text\nkey: {\n    // needs to be unique\n    type: DataTypes.UUID,\n    allowNull: false,\n    unique: true\n}\n```\n\n========================================\n\nComments:\n- Ok. Now I feel like an idiot for not just trying that. Thanks. :)\n- @Yuri do you know where there are docs on Sequelize constraints?\n- I'm still able to insert duplicate rows into my SQLite database with this using `upsert`. Any ideas why?\n- @JamesKlein probably because you're not defining the unique on the .sync()\n- Following up two years later - how would you find this out from the docs, or without asking on SO?\n- @DonnyP not 100% sure but at the time, I may have just quickly looked it up in the source code.\n- @DonP The documentation for Sequelize is pretty bad. As far as I can tell, there's no reference that shows every column option. The return values of most methods are documented only as \"Promise.\" I'm going to cut a lot of slack for anyone whose needs are not addressed by that mess.\n- `unique` is not listed in sequelizejs' doc for attribute validation. Don't understand why such a commonly used feature is not even mentioned in the doc.\n- New to the party but I am feeling your pain ... the docs I've read stop at `attributes: Object`.\n- check this: sequelize.org/master/class/lib/&hellip;\n- as of now it's mentioned here: sequelize.org/master/manual/validations-and-constraints.html\n- Maybe those docs require a PR @user938363 ?","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":70,"estimatedTokens":585}}50{"id":"stack-42870374","source":"stackoverflow","questionId":42870374,"title":"Node.js 7 how to use sequelize transaction with async / await?","tags":["transactions","sequelize.js"],"text":"Title: Node.js 7 how to use sequelize transaction with async / await?\nTags: transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nNode.js 7 and up already support async/await syntax. How should I use async/await with sequelize transactions?\n\n========================================\n\nTop Answer:\nThe accepted answer is an \"unmanaged transaction\", which requires you to call `commit` and `rollback` explicitly. For anyone who wants a \"managed transaction\", this is what it would look like:\n\n```\ntry {\n // Result is whatever you returned inside the transaction\n let result = await sequelize.transaction( async (t) => {\n // step 1\n await Model.destroy({where: {id: id}, transaction: t});\n\n // step 2\n return await Model.create({}, {transaction: t});\n });\n\n // In this case, an instance of Model\n console.log(result);\n} catch (err) {\n // Rollback transaction if any errors were encountered\n console.log(err);\n}\n```\n\nTo rollback, just throw an error inside the transaction function:\n\n```\ntry {\n // Result is whatever you returned inside the transaction\n let result = await sequelize.transaction( async (t) => {\n // step 1\n await Model.destroy({where: {id:id}, transaction: t});\n\n // Cause rollback\n if( false ){\n throw new Error('Rollback initiated');\n }\n\n // step 2\n return await Model.create({}, {transaction: t});\n });\n\n // In this case, an instance of Model\n console.log(result);\n} catch (err) {\n // Rollback transaction if any errors were encountered\n console.log(err);\n}\n```\n\nIf any code that throws an error inside the transaction block, the rollback is automatically triggered.\n\n========================================\n\nCode:\n```js\nlet transaction;    \n\ntry {\n  // get transaction\n  transaction = await sequelize.transaction();\n\n  // step 1\n  await Model.destroy({ where: {id}, transaction });\n\n  // step 2\n  await Model.create({}, { transaction });\n\n  // step 3\n  await Model.update({}, { where: { id }, transaction });\n\n  // commit\n  await transaction.commit();\n\n} catch (err) {\n  // Rollback transaction only if the transaction object is defined\n  if (transaction) await transaction.rollback();\n}\n```\n\n```text\nawait Model.destroy({where: {id}, transaction});\n```\n\n```text\nawait sequelize.transaction( async t=>{\n  const user = User.create( { name: \"Alex\", pwd: \"2dwe3dcd\" }, { transaction: t} )\n  const group = Group.findOne( { name: \"Admins\", transaction: t} )\n  // etc.\n})\n```\n\n```js\ntry {\n    // Result is whatever you returned inside the transaction\n    let result = await sequelize.transaction( async (t) => {\n        // step 1\n        await Model.destroy({where: {id: id}, transaction: t});\n\n        // step 2\n        return await Model.create({}, {transaction: t});\n    });\n\n    // In this case, an instance of Model\n    console.log(result);\n} catch (err) {\n    // Rollback transaction if any errors were encountered\n    console.log(err);\n}\n```\n\n```js\ntry {\n    // Result is whatever you returned inside the transaction\n    let result = await sequelize.transaction( async (t) => {\n        // step 1\n        await Model.destroy({where: {id:id}, transaction: t});\n\n        // Cause rollback\n        if( false ){\n            throw new Error('Rollback initiated');\n        }\n\n        // step 2\n        return await Model.create({}, {transaction: t});\n    });\n\n    // In this case, an instance of Model\n    console.log(result);\n} catch (err) {\n    // Rollback transaction if any errors were encountered\n    console.log(err);\n}\n```\n\n```text\ncommit\n```\n\n```text\nrollback\n```\n\n```text\nasync () => {\n  let t;\n\n  try {\n    t = await sequelize.transaction({ autocommit: true});\n\n    let _user = await User.create({}, {t});\n\n    let _userInfo = await UserInfo.create({}, {t});\n\n    t.afterCommit((t) => {\n      _user.setUserInfo(_userInfo);\n      // other logic\n    });\n  } catch (err) {\n    throw err;\n  }\n}\n```\n\n```js\nimport { Sequelize } from \"sequelize\";\nimport { createNamespace } from \"cls-hooked\"; // npm i cls-hooked\n\nconst cls = createNamespace(\"transaction-namespace\"); // any string\nSequelize.useCLS(cls);\n\nconst sequelize = new Sequelize(...);\n```\n\n```js\nconst removeUser = async (id) => {\n    await sequelize.transaction(async () => { // no need `async (tx)`\n        await removeUserClasses(id);\n        await User.destroy({ where: { id } }); // will auto receive `tx`\n    });\n}\n\nconst removeUserClasses = async (userId) => {\n    await UserClass.destroy({ where: { userId } }); // also receive the same transaction object as this function was called inside `sequelize.transaction()`\n    await somethingElse(); // all queries inside this function also receive `tx`\n}\n```\n\n```js\nif (useCLS && this.sequelize.constructor._cls) {\n    this.sequelize.constructor._cls.set('transaction', this);\n}\n```\n\n```js\nif (options.transaction === undefined && Sequelize._cls) {\n    options.transaction = Sequelize._cls.get('transaction');\n}\n```\n\n```text\ncontinuation-passing\n```\n\n```text\ngithub.com/sequelize\n```\n\n```js\nconst transaction = await sequelize.transaction({ autocommit: false });\n    try {\n      await Model.create(data, {transaction})\n    } catch (e) {\n      if (transaction) await transaction.rollback();\n      next(e);\n      response.status(500).json({ error: e });\n    }\n\n    if (transaction) {\n      await transaction.commit();\n    }\n```\n\n========================================\n\nComments:\n- This doesn't work. `t` in this case is a Promise and not the transaction object.\n- @Pier, await waits the sequelize.transaction() and then get the result of it. the t is not the promise, it is the result of promise.\n- I can't seem to get await to work when I'm doing a .findOne() command. Does it work with this?\n- user7403683 you are a champion... I will forever remember your name!\n- What if `transaction = await sequelize.transaction();` fails? Then `transaction.rollback()` will throw an error. Do we need to check whether .rollback is available on transaction in catch block?\n- @Kunal, there should be an \"if (transaction)...\" clause. I submitted a change request to the code example for peer review.\n- it is not working in my case untill i pass transaction as key:value. eg in above solution, {transaction:transaction} is working. I am using sequelize version 5.19.2\n- No need of try, catch ?\n- Thank you very much, I have been looking for this solution for a while. Didn't realize you could await `sequelize.transaction`.\n- @hellowill89 - you can check the documentation of a given function. If it returns a Promise, then you can use await.\n- `Property 'transaction' does not exist on type 'typeof import(\"&#47;Users&#47;mac&#47;Projects&#47;myinvoice-be&#47;node_modules&#47;sequel&zwnj;&#8203;ize&#47;types&#47;index\")'. Did you mean 'Transaction'?ts(2551)` I have imported sequelize from `import sequelize from 'sequelize';`\n- A nice answer for completeness i suppose but I don't know why I would want the indirection of throwing an error to rollback rather than explicitly just stating it. Maybe if you do it enough times its better but I prefer the explicit version myself.\n- @JoelM its because thats the only way to rollback in a managed transaction. There is no transaction.rollback.\n- Thank you so much for posting an example using CLS. Clean.","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":247,"estimatedTokens":1793}}51{"id":"stack-34565360","source":"stackoverflow","questionId":34565360,"title":"Difference between HasOne and BelongsTo in Sequelize ORM","tags":["node.js","orm","sequelize.js"],"text":"Title: Difference between HasOne and BelongsTo in Sequelize ORM\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am developing a sails.js app with sequelize ORM. I am a little confused as to when BelongsTo and HasOne need to be used.\n\nThe documentation states that :\n\n**BelongsTo** associations are associations where the foreign key for the\none-to-one relation exists on the source model.\n\n**HasOne** associations are associations where the foreign key for the\none-to-one relation exists on the target model.\n\nIs there any other difference apart from the the place where these are specified? Does the behavior still continue to be the same in either cases?\n\n========================================\n\nTop Answer:\nI agree with Krzysztof Sztompka about the difference between:\n\n```\nMan.hasOne(RightArm);\nRightArm.belongsTo(Man);\n```\n\nI'd like to answer Yangjun Wang's question:\n\n So in this case, should I use either `Man.hasOne(RightArm);` or\n `RightArm.belongsTo(Man);`? Or use them both?\n\nIt is true that the `Man.hasOne(RightArm);` relation and the `RightArm.belongsTo(Man);` one do the same thing - each of these relations will add the foreign key `manId` to the `RightArm` table.\n\nFrom the perspective of the physical database layer, these methods do the same thing, and it makes no difference for our database which exact method we will use.\n\nSo, what's the difference? The main difference lays on the ORM's layer (in our case it is Sequalize ORM, but the logic below applies to Laravel's Eloquent ORM or even to Ruby's Active Record ORM).\n\nUsing the `Man.hasOne(RightArm);` relation, we will be able to populate the man's `RightArm` using the `Man` model. If this is enough for our application, we can stop with it and do not add the `RightArm.belongsTo(Man);` relation to the `RightArm` model. \n\nBut what if we need to get the `RightArm`'s owner? We won't be able to do this using the `RightArm` model without defining the `RightArm.belongsTo(Man);` relation on the `RightArm` model.\n\nOne more example will be the `User` and the `Phone` models. Defining the `User.hasOne(Phone)` relation, we will be able to populate our `User`'s `Phone`. Without defining the `Phone.belongsTo(User)` relation, we won't be able to populate our `Phone`'s owner (e.g. our `User`). If we define the `Phone.belongsTo(User)` relation, we will be able to get our `Phone`'s owner.\n\nSo, here we have the main difference: if we want to be able to populate data from both models, we need to define the relations (`hasOne` and `belongsTo`) on both of them. If it is enough for us to get only, for example, `User`'s `Phone`, but not `Phone`'s `User`, we can define only `User.hasOne(Phone)` relation on the `User` model.\n\nThe logic above applies to all the ORMs that have `hasOne` and `belongsTo` relations.\n\nI hope this clarifies your understanding.\n\n========================================\n\nCode:\n```text\nMan.hasOne(RightArm);      // ManId in RigthArm\nRightArm.belongsTo(Man);   // ManId in RigthArm\n```\n\n```text\nMan.hasOne(RightArm);\nRightArm.belongsTo(Man);\n```\n\n```text\nMan.hasOne(RightArm);\n```\n\n```text\nRightArm.belongsTo(Man);\n```\n\n```text\nMan.hasOne(RightArm);\n```\n\n```text\nRightArm.belongsTo(Man);\n```\n\n```text\nmanId\n```\n\n```text\nRightArm\n```\n\n```text\nMan.hasOne(RightArm);\n```\n\n```text\nRightArm\n```\n\n```text\nMan\n```\n\n```text\nRightArm.belongsTo(Man);\n```\n\n```text\nRightArm\n```\n\n```text\nRightArm\n```\n\n```text\nRightArm\n```\n\n```text\nRightArm.belongsTo(Man);\n```\n\n```text\nRightArm\n```\n\n```text\nUser\n```\n\n```text\nPhone\n```\n\n```text\nUser.hasOne(Phone)\n```\n\n```text\nUser\n```\n\n```text\nPhone\n```\n\n```text\nPhone.belongsTo(User)\n```\n\n```text\nPhone\n```\n\n```text\nUser\n```\n\n```text\nPhone.belongsTo(User)\n```\n\n```text\nPhone\n```\n\n```text\nhasOne\n```\n\n```text\nbelongsTo\n```\n\n```text\nUser\n```\n\n```text\nPhone\n```\n\n```text\nPhone\n```\n\n```text\nUser\n```\n\n```text\nUser.hasOne(Phone)\n```\n\n```text\nUser\n```\n\n```text\nhasOne\n```\n\n```text\nbelongsTo\n```\n\n```js\nProject.hasMany(Task);\n```\n\n```js\nconst project = await Project.create({...});\n\n// Here, addTask exists in project instance as a \n// consequence of Project.hasMany(Task); statement \nproject.addTasks([task1, task2]);\n```\n\n```js\nTask.belongsTo(Project);\n```\n\n```js\nconst proj = await Project.findByPk(...);\nconst task1 = await Task.create({...});\n\n...\n\n// Here, setProject exists in task instance as a \n// consequence of Task.belongsTo(Project); statement \ntask1.setProject(proj);\n```\n\n```js\n// All the instances of Project model will have utility methods\nProject.hasMany(Task);\n\n// All the instances of Task model will have utility methods\nTask.belongsTo(Project);\n\nconst project = await Project.create(...);\nconst task1 = await Task.create(...);\nconst task2 = await Task.create(...);\n\n...\n\n// as a consequence of Project.hasMany(Task), this can be done:\nproject.addTask(task1);\n\n...\n\n// as a consequence of Task.belongsTo(Project), this can be done:\ntask2.setProject(project);\n```\n\n```text\nProject\n```\n\n```text\nProject\n```\n\n```text\naddTask\n```\n\n```text\nsetTask\n```\n\n```text\ntasks\n```\n\n```text\nprojects\n```\n\n```text\nProject.hasMany(Task);\n```\n\n```text\ntasks\n```\n\n```text\nprojects\n```\n\n```text\naddTasks\n```\n\n```text\nproject\n```\n\n```text\nTask.belongsTo(Project);\n```\n\n```text\ntask\n```\n\n```text\nProject.hasMany(Task);\n```\n\n```text\nProject\n```\n\n```text\nTask\n```\n\n```text\nTask.belongsTo(Project);\n```\n\n```text\nTask\n```\n\n```text\nProject\n```\n\n```text\nhasOne\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsToMany\n```\n\n```text\nProject\n```\n\n```text\nTask\n```\n\n```text\ntasks\n```\n\n```text\nprojects\n```\n\n```text\nclass User extends Model {\n  static associate(models) {}\n}\n\nUser.init(\n  {\n    username: DataTypes.STRING(25),\n    password: DataTypes.STRING(50)\n  }\n)\n```\n\n```text\nclass Staff extends Model {\n   static associate(models) {}\n{\n    \n   Staff.init(\n     {\n       permissions: DataTypes.ARRAY(DataTypes.STRING),\n       roleType: DataTypes.STRING(20),\n     }\n   )\n```\n\n```text\nuser: {\n  type: DataTypes.INTEGER,\n  references: {\n    model: User,\n    key: 'userId'\n  }\n}\n```\n\n```text\nhasOne()\n```\n\n```text\nbelongsTo()\n```\n\n```text\nStaff.belongsTo(User)\n```\n\n```text\nUser.hasOne(Staff)\n```\n\n========================================\n\nComments:\n- So in this case, should I use either `Man.hasOne(RightArm);` or `RightArm.belongsTo(Man);`? Or use them both?\n- In most cases I would use them both\n- I think @KrzysztofSztompka wants to say is: Depending on each case he could use or either hasOne or belongsTo considering the semantic. But there's no point to set for instance: `Man.hasOne(RightArm); RightArm.belongsTo(Man);` Because they do the same thing which is set a foreign key to RighArm.\n- @YangjunWang, please, see my answer below.\n- Oh man, the inverse is hilarious.\n- Can we just use `belongsTo` on both models or it will not work? Also – how to properly define migrations? Should we just add column (e.g. `user_id`) on the Phone's model?","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":76,"totalLines":421,"estimatedTokens":1723}}52{"id":"stack-20290815","source":"stackoverflow","questionId":20290815,"title":"belongsTo vs hasMany in Sequelize.js","tags":["sql","node.js","orm","sequelize.js"],"text":"Title: belongsTo vs hasMany in Sequelize.js\nTags: sql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhat's the difference between `B.belongsTo(A)` and `A.hasMany(B)`\n\n```\nArtist = sequelize.define('Artist', {});\nAlbum = sequelize.define('Albums', {});\n\nAlbum.belongsTo(Artist, foreignKey: 'album_belongsl_artist');\nArtist.hasMany(Album, foreignKey: 'artist_hasmany_albums');\n```\n\nif it in both cases creates the depended tables in `Album`?\n\n========================================\n\nCode:\n```text\nArtist = sequelize.define('Artist', {});\nAlbum = sequelize.define('Albums', {});\n\nAlbum.belongsTo(Artist, foreignKey: 'album_belongsl_artist');\nArtist.hasMany(Album, foreignKey: 'artist_hasmany_albums');\n```\n\n```text\nB.belongsTo(A)\n```\n\n```text\nA.hasMany(B)\n```\n\n```text\nAlbum\n```\n\n```text\nCREATE TABLE IF NOT EXISTS `Albums` (`id` INTEGER NOT NULL auto_increment , `album_belongsl_artist` INTEGER, `artist_hasmany_albums` INTEGER, PRIMARY KEY (`id`))\n```\n\n```text\nAlbum.belongsTo(Artist, {foreignKey: 'artist_id'});\nArtist.hasMany(Album,{ foreignKey: 'artist_id'});\n```\n\n```text\nCREATE TABLE IF NOT EXISTS `Albums` (`id` INTEGER NOT NULL auto_increment, `artist_id` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;\n```\n\n```text\nAlbum.belongsTo(Artist)\n```\n\n```text\nalbum.getArtist()\n```\n\n```text\nArtist.hasMany(Album)\n```\n\n```text\nartist.getAlbums()\n```\n\n```text\nAlbum.belongsTo(Artist)\n```\n\n```text\nforeignKey\n```\n\n========================================\n\nComments:\n- I'm having a similar issue and I'm just wondering how to get the relation reversely working. I fetched an Artist and call getAlbums on it, which works fine. But then when I use one Album item from result I've and execute `getArtists` on it it's returning just `null`. How can that be solved? Because the method `getArtist` is provided by sequelize.\n- @Bernhard You probably need to use the `include` option in the find function call, to specify which model's relations to eagerly load.\n- after an hour trawling the docs trying to work out how to do this, your code helped a great deal! got a nice two-way 1:m association now. yay!\n- how to implement simple `one-to many` relation. `db.File.hasMany(db.Like, {foreignKey: 'file_id'})` it's giving me error :`ER_BAD_FIELD_ERROR: Unknown column 'upload_file_tab.file_name' in 'on clause'`\n- @UmairAhmed it is best to ask this as a separate question\n- Is it possible to add both relations? Or will this cause any conflicts?\n- Shouldn't it be like this; note `foreignKey` value is **artist_id** (vs **album_id**): `Album.belongsTo(Artist, {foreignKey: 'artist_id'});` just like the Sequelize documentation has `City.belongsTo(Country, {foreignKey: 'countryCode' })`. In other words, the function `belongsTo` is ... 1) called *on* the model/table which adds a *referencing* column (i.e. the source; Album , or City) 2) called *with* the model/table which has the *referenced* ID (Artist, or Country) 3) called with the `foreignKey` , the name of the column pointing from #1 to #2 (artist_id, countryCode)\n- shouldn't both statements have foreignKey: 'artist_id' ? as 1 artist has many albums and the idea is that the FKs are the same\n- so in any case putting both belongsTo and hasMany would enable internal methods from Sequelize but the resulting table would be the same with one of them, is this correct?\n- Yes, both foreign keys should be `artist_id`. The answer itself states \"the foreignKey should be the same\". sequelize.org/master/manual/&hellip;. This mistake was overlooked, the pair of associations' foreign keys have to the same name for it to work. Both should be `artist_id` instead of both being `album_id` because the parent artist hasMany child albums, FK is stored with the child.\n- Both were originally artist_id until the post was edited incorrectly. I've submitted a new edit (pending review) to undo that.\n- why is this thing overly complicated? why cant you just say table B has a foreign key to table A instead of doing all this hasMany belongsTo stuff","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":92,"estimatedTokens":1000}}53{"id":"stack-29995116","source":"stackoverflow","questionId":29995116,"title":"Ordering results of eager-loaded nested models in Node Sequelize","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Ordering results of eager-loaded nested models in Node Sequelize\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a complex set of associated models. The models are associated using join tables, each with an attribute called 'order'. I need to be able to query the parent model 'Page' and include the associated models, and sort those associations by the field 'order'.\n\nThe following is having no effect on the results' sort order:\n\n```\ndb.Page.findAll({\n include: [{\n model: db.Gallery,\n order: ['order', 'DESC'],\n include: [{\n model: db.Artwork,\n order: ['order', 'DESC']\n }]\n }],\n})\n```\n\n========================================\n\nTop Answer:\nIf you also use 'as' and let's say you want to order by 'createdDate' , the query looks like this: \n\n```\nDbCategoryModel.findAll({\n include: [\n {\n model: DBSubcategory,\n as: 'subcategory',\n include: [\n {\n model: DBProduct,\n as: 'product',\n }\n ],\n }\n ],\n order: [\n [\n {model: DBSubcategory, as: 'subcategory'},\n {model: DBProduct, as: 'product'},\n 'createdDate',\n 'DESC'\n ]\n ]\n})\n```\n\n========================================\n\nCode:\n```text\ndb.Page.findAll({\n  include: [{\n    model: db.Gallery,\n    order: ['order', 'DESC'],\n    include: [{\n      model: db.Artwork,\n      order: ['order', 'DESC']\n    }]\n  }],\n})\n```\n\n```text\ndb.Page.findAll({\n  include: [{\n    model: db.Gallery\n    include: [{\n      model: db.Artwork\n    }]\n  }],\n  order: [\n    // sort by the 'order' column in Gallery model, in descending order.\n\n    [ db.Gallery, 'order', 'DESC' ], \n\n\n    // then sort by the 'order' column in the nested Artwork model in a descending order.\n    // you need to specify the nested model's parent first.\n    // in this case, the parent model is Gallery, and the nested model is Artwork\n\n    [ db.Gallery, db.ArtWork, 'order', 'DESC' ]\n  ]\n})\n```\n\n```text\nDbCategoryModel.findAll({\n    include: [\n        {\n            model: DBSubcategory,\n            as: 'subcategory',\n            include: [\n                {\n                    model: DBProduct,\n                    as: 'product',\n                }\n            ],\n        }\n    ],\n    order: [\n        [\n            {model: DBSubcategory, as: 'subcategory'},\n            {model: DBProduct, as: 'product'},\n            'createdDate',\n            'DESC'\n        ]\n    ]\n})\n```\n\n```text\norder: [\n[ db.Sequelize.col('order'), 'DESC'],    /*If you want to order by page module as well you can add this line*/\n[ db.Gallery, db.ArtWork, 'order', 'DESC' ]\n]\n```\n\n```text\nlet getdata = await categories_recipes.findAll({   \n                    order:[ \n                        [{model: recipes, as: 'recipesdetails'},'id', 'DESC'] // change your column name like (id and created_at)\n                    ],\n                    include:[{\n                        model:recipes, as : \"recipesdetails\",\n                        include:[{\n                            model:recipe_images, as: \"recipesimages\",\n                        }],\n                        where:{\n                            user_id:data.id\n                        },\n                        required: true,\n                    }]\n                })\n```\n\n```text\ndb.Page.findAll({\n  include: [{\n    model: db.Gallery\n    include: [{\n      model: db.Artwork\n    }]\n  }],\n  order: [\n    [ sequelize.col('Gallery.order', 'DESC' ], \n    [ sequelize.col('Gallery.Artwork.order', 'DESC' ]\n  ]\n})\n```\n\n```text\nu0WithComments = await User.findOne({\n    where: { id: u0.id },\n    order: [[\n      'Comments', 'body', 'DESC'\n    ]],\n    limit: 1,\n    subQuery: false,\n    include: [{\n      model: Comment,\n    }],\n  })\n```\n\n```text\nsequelize.col\n```\n\n```text\norder:\n```\n\n```text\n.col\n```\n\n```text\nlimit:\n```\n\n```text\nsubQuery: false\n```\n\n```text\n// Failed:\norder: ['column1', 'column2', 'column3', 'DESC'],\n```\n\n```text\n// Worked:\norder: [['column1', 'ASC'], ['column2', 'DESC'], ['colum3', 'DESC']],\n```\n\n```text\ninclude: [{\n  model: db.Artwork,\n  order: [['order', 'DESC']]\n}]\n```\n\n```text\norder\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  class Category extends Model {\n    static associate(models) {\n      Category.belongsTo(models.Restaurant, {\n        foreignKey: { name: 'restaurant_id', type: DataTypes.UUID },\n        as: 'restaurant',\n      })\n      Category.hasMany(models.Dish, {\n        onDelete: 'CASCADE',\n        onUpdate: 'CASCADE',\n        foreignKey: { name: 'category_id', type: DataTypes.UUID },\n        as: 'dishes',\n      })\n    }\n  }\n....\nmodule.exports = (sequelize, DataTypes) => {\n  class Dish extends Model {\n    static associate(models) {\n      Dish.belongsTo(models.Category, {\n        foreignKey: { name: 'category_id', type: DataTypes.UUID },\n        as: 'category',\n      })\n      Dish.hasMany(models.Picture, {\n        onDelete: 'CASCADE',\n        foreignKey: { name: 'dish_id', type: DataTypes.UUID },\n        as: 'pictures',\n      })\n    }\n  }\n....\n```\n\n```text\ncategories = await Category.findAll({\n      where,\n      attributes: ['id', 'name', 'description', 'active', 'display_order'],\n      include: [\n        {\n          model: Dish,\n          as: 'dishes',\n          attributes: [\n            'id',\n            'name',\n            'description',\n            'active',\n            'display_order',\n            'price',\n            'previous_price',\n          ],\n          include: [\n            {\n              model: Picture,\n              as: 'pictures',\n              attributes: ['id', 'source'],\n            },\n          ],\n        },\n      ],\n      order: [\n        ['display_order', 'ASC'],\n        [{ model: Dish, as: 'dishes' }, 'display_order', 'ASC'],\n      ],\n    })\n```\n\n========================================\n\nComments:\n- Annoying naming of your example fields. Firstly, both the models are being ordered on a field with the same name. That name is the same as the operation.\n- And to think I've been screwing this up for the last year.\n- order: [ [db.Sequelize.col('order'), 'DESC'], // for page table [ db.Gallery, 'order', 'DESC' ], [ db.Gallery, db.ArtWork, 'order', 'DESC' ] ]\n- I want to kiss you\n- what if I want to order the artwork results within the page? adding 'order' in the include of the `Artwork` does not seem to have any effect on the order of the included results\n- This helped me, I had to add `order` in main table, instead of my include block. I already had 1 order added, adding another order in same array worked well. My final include in main table: `order: [[\"id\", \"desc\"], [IncludedModel, \"id\", \"asc\"],],`\n- Also adding order directly in include worked for me `order: [[\"id\", \"asc\"]],`\n- Should this work with foreign keys aswell? I'm getting Unhandled rejection TypeError: Converting circular structure to JSON at Object.stringify (native) at Object.QueryGenerator.quote (/Users/kristoffer/web/fitch/node_modules/sequelize/lib/dial&zwnj;&#8203;ects/abstract/query-&zwnj;&#8203;generator.js:869:76)\n- Yes, it works, in the example \"stackoverflow.com/questions/38145702/&hellip;\", using my models declaration, just use the following code: User.findAll({ raw: 'true', include: [ { model: UserAttribute, as: \"UserAttribute\" } ], order: [ [ { model: UserAttribute, as: 'UserAttribute' }, 'userId', 'DESC' ] ] }) .then((users) => { console.log('users', users) process.exit() })\n- This worked perfectly for me. Thanks so much for this answer. It's 7 years already and still actively helping\n- Although this code may answer the question, providing additional context regarding *why* and/or *how* it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.\n- It orders only eager loading, not the querying module.\n- Is there a missing closing bracket in `sequelize.col('Gallery.Artwork.order', 'DESC'`?","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":294,"estimatedTokens":1937}}54{"id":"stack-10060265","source":"stackoverflow","questionId":10060265,"title":"Sequelize: how to import definitions from an existing database","tags":["node.js","sequelize.js"],"text":"Title: Sequelize: how to import definitions from an existing database\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAm I required to handwrite the model definitions for Sequelize even if I'm working off of an existing database.\n\nIf it's not required, then how does one go about using Sequelize with an existing database?\n\nI've already defined the database's schema in Doctrine, so I'd rather not have to write another set of model definitions again.\n\n========================================\n\nTop Answer:\nThis project aims to create Sequelize models from existing schema https://github.com/sequelize/sequelize-auto\n\n### Sequelize-Auto\n\nA tool to automatically generate models for `SequelizeJS` via the command line.\n\n### Install:\n\n```\nnpm install -g sequelize-auto\n```\n\n### Usage:\n\n```\nsequelize-auto -h -d -u -x [password] -p [port] --dialect [dialect] -c [/path/to/config] -o [/path/to/models]\n```\n\n### Options:\n\n```\n-h, --host IP/Hostname for the database. [required]\n -d, --database Database name. [required]\n -u, --user Username for database. [required]\n -x, --pass Password for database.\n -p, --port Port number for database.\n -c, --config JSON file for sending additional options to the Sequelize object.\n -o, --output What directory to place the models.\n -e, --dialect The dialect/engine that you're using: postgres, mysql, sqlite\n```\n\n**Example**\n\n```\nsequelize-auto -o \"./models\" -d sequelize_auto_test -h localhost -u daniel -p 5432 -x my_password -e postgres\n```\n\nProduces a file/files such as **`./models/Users.js`** which looks like this:\n\n```\n/* jshint indent: 2 */\n\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('Users', {\n username: {\n type: DataTypes.STRING,\n allowNull: true,\n defaultValue: null\n },\n touchedAt: {\n type: DataTypes.DATE,\n allowNull: true,\n defaultValue: null\n },\n aNumber: {\n type: DataTypes.INTEGER,\n allowNull: true,\n defaultValue: null\n },\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n createdAt: {\n type: DataTypes.DATE,\n allowNull: false,\n defaultValue: null\n },\n updatedAt: {\n type: DataTypes.DATE,\n allowNull: false,\n defaultValue: null\n }\n });\n};\n```\n\nWhich makes it easy for you to simply **`Sequelize.import`** it.\n\n========================================\n\nCode:\n```text\nnpm install -g sequelize-auto\n```\n\n```text\nsequelize-auto -h <host> -d <database> -u <user> -x [password] -p [port]  --dialect [dialect] -c [/path/to/config] -o [/path/to/models]\n```\n\n```text\n-h, --host      IP/Hostname for the database.                                      [required]\n  -d, --database  Database name.                                                     [required]\n  -u, --user      Username for database.                                             [required]\n  -x, --pass      Password for database.\n  -p, --port      Port number for database.\n  -c, --config    JSON file for sending additional options to the Sequelize object.\n  -o, --output    What directory to place the models.\n  -e, --dialect   The dialect/engine that you're using: postgres, mysql, sqlite\n```\n\n```text\nsequelize-auto -o \"./models\" -d sequelize_auto_test -h localhost -u daniel -p 5432 -x my_password -e postgres\n```\n\n```text\n/* jshint indent: 2 */\n\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('Users', {\n    username: {\n      type: DataTypes.STRING,\n      allowNull: true,\n      defaultValue: null\n    },\n    touchedAt: {\n      type: DataTypes.DATE,\n      allowNull: true,\n      defaultValue: null\n    },\n    aNumber: {\n      type: DataTypes.INTEGER,\n      allowNull: true,\n      defaultValue: null\n    },\n    id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true\n    },\n    createdAt: {\n      type: DataTypes.DATE,\n      allowNull: false,\n      defaultValue: null\n    },\n    updatedAt: {\n      type: DataTypes.DATE,\n      allowNull: false,\n      defaultValue: null\n    }\n  });\n};\n```\n\n```text\nSequelizeJS\n```\n\n```text\n./models/Users.js\n```\n\n```text\nSequelize.import\n```\n\n========================================\n\nComments:\n- Thanks for the quick response. If I find the time I might try to add a module to this project to export the schema from a MySQL Workbench file, since that's the point of origin for most of my projects. github.com/johmue/mysql-workbench-schema-exporter\n- One major note about sequelize-auto project: it **DID NOT** support importing **associations** YET (as of May 2016). So, you should define them \"manually\", in code. But definitely its much easier when you have basic database structure already imported!\n- @deksden how to add the assosiations\n- @Jegan : here is dedicated article in documentation - docs.sequelizejs.com/en/v3/docs/associations","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":176,"estimatedTokens":1169}}55{"id":"stack-19341975","source":"stackoverflow","questionId":19341975,"title":"Heroku + Node: Cannot find module error","tags":["javascript","git","node.js","heroku","sequelize.js"],"text":"Title: Heroku + Node: Cannot find module error\nTags: javascript, git, node.js, heroku, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy Node app is running fine locally, but has run into an error when deploying to Heroku. The app uses Sequelize in a `/models` folder, which contains `index.js`, `Company.js` and `Users.js`. Locally, I am able to import the models using the following code in `/models/index.js`:\n\n```\n// load models\nvar models = [\n 'Company',\n 'User'\n];\nmodels.forEach(function(model) {\n module.exports[model] = sequelize.import(__dirname + '/' + model);\n});\n```\n\nThis works fine, however, when I deploy to Heroku the app crashes with the following error:\n\n```\nError: Cannot find module '/app/models/Company'\n at Function.Module._resolveFilename (module.js:338:15)\n at Function.Module._load (module.js:280:25)\n at Module.require (module.js:364:17)\n at require (module.js:380:17)\n at module.exports.Sequelize.import (/app/node_modules/sequelize/lib/sequelize.js:219:24)\n at module.exports.sequelize (/app/models/index.js:60:43)\n at Array.forEach (native)\n at Object. (/app/models/index.js:59:8)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\nProcess exited with status 8\n```\n\nInitially I thought it was due to case sensitivity (local mac vs heroku linux), but I moved the file, made a git commit, and then moved back and committed again to ensure `Company.js` is capitalized in the git repository. This didn't solve the problem and I'm not sure what the issue could be.\n\n========================================\n\nTop Answer:\nI can't see the exact fix, but you can figure it out yourself by running `heroku run bash` to log into a Heroku instance, then run `node` to enter a REPL, and try requiring the paths directly.\n\n========================================\n\nCode:\n```text\n// load models\nvar models = [\n  'Company',\n  'User'\n];\nmodels.forEach(function(model) {\n  module.exports[model] = sequelize.import(__dirname + '/' + model);\n});\n```\n\n```text\nError: Cannot find module '/app/models/Company'\n   at Function.Module._resolveFilename (module.js:338:15)\n   at Function.Module._load (module.js:280:25)\n   at Module.require (module.js:364:17)\n   at require (module.js:380:17)\n   at module.exports.Sequelize.import (/app/node_modules/sequelize/lib/sequelize.js:219:24)\n   at module.exports.sequelize (/app/models/index.js:60:43)\n   at Array.forEach (native)\n   at Object.<anonymous> (/app/models/index.js:59:8)\n   at Module._compile (module.js:456:26)\n   at Object.Module._extensions..js (module.js:474:10)\nProcess exited with status 8\n```\n\n```text\n/models\n```\n\n```text\nindex.js\n```\n\n```text\nCompany.js\n```\n\n```text\nUsers.js\n```\n\n```text\n/models/index.js\n```\n\n```text\nCompany.js\n```\n\n```text\nheroku run bash\n```\n\n```text\n/models\n```\n\n```text\nUser.js\n```\n\n```text\nCompany.js\n```\n\n```text\nUser.js\n```\n\n```text\nCompany.js\n```\n\n```text\nuser.js\n```\n\n```text\nUser.js\n```\n\n```text\ncompany.js\n```\n\n```text\nCompany.js\n```\n\n```text\nheroku run bash\n```\n\n```text\nnode\n```\n\n```sh\n$ heroku config:set NODE_MODULES_CACHE=false\n```\n\n```text\nmodule.js\n```\n\n```text\nModule.js\n```\n\n```text\nconst Product = require('../models/product');\n```\n\n```text\n'../models/Product'\n```\n\n```text\ngit mv\n```\n\n```text\nif (process.env.NODE_ENV !== \"production\") {\n  require(\"dotenv\").config();\n}\n```\n\n```text\nrequire(\"dotenv\").config()\n```\n\n```text\ndevDependency\n```\n\n========================================\n\nComments:\n- Thanks for this helpful debugging tip which enabled me to fix the issue.\n- I never knew you could look at your heroku file structure - this has been a life saver - Thanks!!!\n- still valid in 2021\n- What key words in REPL should I type?\n- I had this same problem and had been trying to figure it out for the longest time. Thank you and than @dankohn!\n- YOU SIR ARE A FREAKING LEGEND. Had this wrong in the (auto generated) package.json file with „server.js“ instead of „Server.js“.\n- Bravo, this was just the ticket for me and my \"Tools\"/\"tools\" folder\n- Wow - Thank you - had no idea what was going on - I had misnamed my models User file with lower case user.js on my initial push to heroku and even though I corrected it later on - the file stayed lower case\n- this worked for me too I checked with Heroku run bash and my file was somehow capital and locally it was lowercase. thanks a lot\n- maybe usefull to say that you can always check with heroku run bash if the naming of the files is like expected\n- Thank you so much. I was importing a module with camel case when the file was not actually capitalized that way. My Mac did not complain - though it should have.\n- This didn't work for me. If you are working on MacOS and changed the case of a file's name, the only solution that worked for me is the first one, i.e. rename the file into a temporary name that differs not only by the letter's case, and then change it back... Thought it's worth mentioning to save others the time of testing this (BTW cache is a good thing, and I wouldn't waive it that easily)\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":198,"estimatedTokens":1377}}56{"id":"stack-40952058","source":"stackoverflow","questionId":40952058,"title":"Sequelize: Destroy/Delete all records in the table","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize: Destroy/Delete all records in the table\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Mocha for Unit tests.\n\nWhen testing begins, I would like to delete all the previous records in a table. \n\nWhat I have tried:\n\n```\ndb.User.destroy({ force: true }).then(() => {\n}).then(() => done());\n\ndb.User.destroy(\n {where: undefined},\n {truncate: false}\n).then(() => {\n return \n}).then(() => done());\n\ndb.User.destroy({}).then(() => {\n return db.User.bulkCreate(users)\n}).then(() => done());\n```\n\nI keep getting the following error:\n\n```\nError: Missing where or truncate attribute in the options parameter of model.destroy.\n```\n\nHow do I delete/destroy all the records in a table?\n\n========================================\n\nTop Answer:\nI was able to solve this problem with the code:\n\n```\ntable.sync({ force: true });\n```\n\nThis is a safer solution than the one proposed in maheshiv's answer.\n\n========================================\n\nCode:\n```text\ndb.User.destroy({ force: true }).then(() => {\n}).then(() => done());\n\n\ndb.User.destroy(\n    {where: undefined},\n    {truncate: false}\n).then(() => {\n    return \n}).then(() => done());\n\n\ndb.User.destroy({}).then(() => {\n    return db.User.bulkCreate(users)\n}).then(() => done());\n```\n\n```text\nError: Missing where or truncate attribute in the options parameter of model.destroy.\n```\n\n```text\ndb.User.destroy({\n  where: {},\n  truncate: true\n})\n```\n\n```text\ntable.sync({ force: true });\n```\n\n```text\ndb.User.truncate()\n```\n\n========================================\n\nComments:\n- @Coxer it isn't. You will receive an `UnhandledPromiseRejectionWarning: Error: Missing where or truncate attribute in the options parameter of model.destroy` error\n- you don't need where option. `db.User.destroy({ truncate: true })` it's ok\n- `truncate: true` may not work if you have foreign key constraints in place. In that case, you can simply remove that clause.\n- here is safer solution.\n- I did that only `users.destroy({ where: {} })` and it works\n- this is a better solution if you want to reset the whole table and ids will count from 1 again, I found this answer is the safest answer for the testing purposes\n- Thank u it helped me a lot while development b2c service","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":96,"estimatedTokens":561}}57{"id":"stack-49161055","source":"stackoverflow","questionId":49161055,"title":"Should Sequelize migrations update model files?","tags":["sequelize.js","sequelize-cli"],"text":"Title: Should Sequelize migrations update model files?\nTags: sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nAre Sequelize migrations supposed to keep your model files in line with your database?\n\nI used the sequelize cli to bootstrap a simple project and create a model `node_modules/.bin/sequelize model:generate --name User --attributes email:string`. I migrated this with no issue. \n\nThen I created the following migration file to add a notNull constraint to the user email attribute.\n\n**updateEmail migration**\n\n```\nconst models = require(\"../models\")\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.changeColumn(models.User.tableName, 'email',{\n type: Sequelize.STRING,\n allowNull: false,\n });\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.changeColumn(models.User.tableName, 'email',{\n type: Sequelize.STRING,\n });\n },\n};\n```\n\nThe database schema updated to add the constraint but the model file did not. Is there a way to automatically update the model files as you make migrations?\n\n========================================\n\nCode:\n```text\nconst models = require(\"../models\")\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n      return queryInterface.changeColumn(models.User.tableName, 'email',{\n        type: Sequelize.STRING,\n        allowNull: false,\n      });\n    },\n\n  down: (queryInterface, Sequelize) => {\n      return queryInterface.changeColumn(models.User.tableName, 'email',{\n        type: Sequelize.STRING,\n      });\n    },\n};\n```\n\n```text\nnode_modules/.bin/sequelize model:generate --name User --attributes email:string\n```\n\n```text\nsequelize model:create\n```\n\n```text\nsequelize-cli\n```\n\n```text\nSequelize\n```\n\n```text\nsequelize-cli\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":75,"estimatedTokens":435}}58{"id":"stack-18838433","source":"stackoverflow","questionId":18838433,"title":"Sequelize find based on association","tags":["node.js","sequelize.js"],"text":"Title: Sequelize find based on association\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow would I use Sequelize to find all people where a column in the relation satisfies a condition?\n\nAn example would be to find all Books whose author's last name is 'Hitchcock'. The book schema contains a hasOne relation with the Author's table.\n\nEdit: I understand how this could be done with a raw SQL query, but looking for another approach\n\n========================================\n\nTop Answer:\nIn the newest version of Sequilize (5.9.0) the method proposed by @c.hill does not work.\n\nNow you need to do the following:\n\n```\nreturn Book.findAll({\n where: {\n '$Authors.lastName$': 'Testerson'\n },\n include: [\n {model: Author, as: Author.tableName}\n ]\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n    var Author = sequelize.define('Author', {\n\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        firstName: {\n            type: DataTypes.STRING\n        },\n        lastName: {\n            type: DataTypes.STRING\n        }\n\n    })\n\n    var Book = sequelize.define('Book', {\n\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        title: {\n            type: DataTypes.STRING\n        }\n\n    })\n\n    var firstAuthor;\n    var secondAuthor;\n\n    Author.hasMany(Book)\n    Book.belongsTo(Author)\n\n    Author.sync({ force: true })\n        .then(function() {\n            return Book.sync({ force: true });\n        })\n        .then(function() {\n            return Author.create({firstName: 'Test', lastName: 'Testerson'});\n        })\n        .then(function(author1) {\n            firstAuthor=author1;\n            return Author.create({firstName: 'The Invisible', lastName: 'Hand'});\n        })\n        .then(function(author2) {\n            secondAuthor=author2\n            return Book.create({AuthorId: firstAuthor.id, title: 'A simple book'});\n        })\n        .then(function() {\n            return Book.create({AuthorId: firstAuthor.id, title: 'Another book'});\n        })\n        .then(function() {\n            return Book.create({AuthorId: secondAuthor.id, title: 'Some other book'});\n        })\n        .then(function() {\n            // This is the part you're after.\n            return Book.findAll({\n                where: {\n                   'Authors.lastName': 'Testerson'\n                },\n                include: [\n                    {model: Author, as: Author.tableName}\n                ]\n            });\n        })\n        .then(function(books) { \n            console.log('There are ' + books.length + ' books by Test Testerson')\n        });\n  }\n```\n\n```text\nBooks\n```\n\n```text\nAuthor\n```\n\n```text\nfindAll\n```\n\n```js\nreturn Book.findAll({\n    where: {\n        '$Authors.lastName$': 'Testerson'\n    },\n    include: [\n        {model: Author, as: Author.tableName}\n    ]\n});\n```\n\n```js\nUser.findAll({\n  where: {\n    '$Instruments.size$': { [Op.ne]: 'small' }\n  },\n  include: [{\n    model: Tool,\n    as: 'Instruments'\n  }]\n});\n```\n\n```sql\nSELECT\n  `user`.`id`,\n  `user`.`name`,\n  `Instruments`.`id` AS `Instruments.id`,\n  `Instruments`.`name` AS `Instruments.name`,\n  `Instruments`.`size` AS `Instruments.size`,\n  `Instruments`.`userId` AS `Instruments.userId`\nFROM `users` AS `user`\nLEFT OUTER JOIN `tools` AS `Instruments` ON\n  `user`.`id` = `Instruments`.`userId`\nWHERE `Instruments`.`size` != 'small';\n```\n\n```js\n// Inner where, with default `required: true`\nawait User.findAll({\n  include: {\n    model: Tool,\n    as: 'Instruments',\n    where: {\n      size: { [Op.ne]: 'small' }\n    }\n  }\n});\n\n// Inner where, `required: false`\nawait User.findAll({\n  include: {\n    model: Tool,\n    as: 'Instruments',\n    where: {\n      size: { [Op.ne]: 'small' }\n    },\n    required: false\n  }\n});\n\n// Top-level where, with default `required: false`\nawait User.findAll({\n  where: {\n    '$Instruments.size$': { [Op.ne]: 'small' }\n  },\n  include: {\n    model: Tool,\n    as: 'Instruments'\n  }\n});\n\n// Top-level where, `required: true`\nawait User.findAll({\n  where: {\n    '$Instruments.size$': { [Op.ne]: 'small' }\n  },\n  include: {\n    model: Tool,\n    as: 'Instruments',\n    required: true\n  }\n});\n```\n\n```sql\n-- Inner where, with default `required: true`\nSELECT [...] FROM `users` AS `user`\nINNER JOIN `tools` AS `Instruments` ON\n  `user`.`id` = `Instruments`.`userId`\n  AND `Instruments`.`size` != 'small';\n\n-- Inner where, `required: false`\nSELECT [...] FROM `users` AS `user`\nLEFT OUTER JOIN `tools` AS `Instruments` ON\n  `user`.`id` = `Instruments`.`userId`\n  AND `Instruments`.`size` != 'small';\n\n-- Top-level where, with default `required: false`\nSELECT [...] FROM `users` AS `user`\nLEFT OUTER JOIN `tools` AS `Instruments` ON\n  `user`.`id` = `Instruments`.`userId`\nWHERE `Instruments`.`size` != 'small';\n\n-- Top-level where, `required: true`\nSELECT [...] FROM `users` AS `user`\nINNER JOIN `tools` AS `Instruments` ON\n  `user`.`id` = `Instruments`.`userId`\nWHERE `Instruments`.`size` != 'small';\n```\n\n========================================\n\nComments:\n- This did not work for me, I think as of sequelize 2.0, the where clause must be placed in the include array member, such as `include: [{model:..., where:...}]`\n- Nevertheless, the answer gave me hope that this is somehow possible so I pursued to finding a solution :)\n- I can confirm that as of Sequelize 2.0 the `where` clause must be inside the `include`, just like: `include: [ { model: ..}, where: { 'Author.lastName: 'Testerson' }]`\n- @AndreyPopov, but how in this case to find Books by title or by Author.lastName?\n- `Book.findAll({ include: [ model: Author, where: { 'lastName': 'Testerson' } ] });` Should be working fine.. :)\n- Is it better practise to keep all models in one file? Like above? Or put them in separate files? @AndreyPopov\n- I would strongly recommend putting models in different files. Then just load all files in a directory and they will self-initialize :) Otherwise you'll get pretty doomed after a while (thousands of lines in one file)\n- As some others commented before, the query doesn't work with `where:{'Authors.lastName': 'Testerson'}` outside `include`, as in this answer. Sequelize compiles it as `[...] AND `Authors.lastName` = 'Testerson' [...]`.\n- How would this work if the relationship was a many to many? `Author.belongsToMany(Book)` `Book.belongsToMany(Author)` A second table (something like \"BookAuthor\") gets created, and syntax like `where: { 'Authors.lastName': 'Testerson' }` doesn't seem to work anymore...\n- you don't need the Authors inside the where clause: `{ 'lastName': 'Testerson' }`\n- putting `where` inside `include` builds a query like this: `LEFT OUTER JOIN Authors ON Books.authorId = Authors.id AND Authors.lastName = 'Testerson'`, and the result is quite different from `LEFT OUTER JOIN Authors ON Books.authorId = Authors.id ... WHERE Authors.lastName = 'Testerson'`. I'm not sure how to achieve the latter query with sequelize.\n- how to use the same way when having many to many relations since you have an external table instead of columns to test on ?\n- Where do I find the documentation for this?\n- I didn't find any documentation, but this worked like a charm!\n- @lordvcs Here: sequelize.org/master/manual/&hellip;\n- I miss good old plain SQL when it takes me 2 hours to accomplish this with Sequelize\n- pagination does not work in this","metadata":{"transformedAt":"2026-08-18T18:33:34.336Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":253,"estimatedTokens":1889}}59{"id":"stack-42195348","source":"stackoverflow","questionId":42195348,"title":"How to define unique index on multiple columns in sequelize","tags":["mysql","sequelize.js"],"text":"Title: How to define unique index on multiple columns in sequelize\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do I define a unique index on a combination of columns in sequelize. For example I want to add a unique index on user_id, count and name. \n\n```\nvar Tag = sequelize.define('Tag', {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n user_id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n },\n count: {\n type: DataTypes.INTEGER(11),\n allowNull: true\n },\n name: {\n type: DataTypes.STRING,\n allowNull: true,\n })\n```\n\n========================================\n\nTop Answer:\nI have same issue to applied composite unique constraint to multiple\n columns but nothing work with Mysql, Sequelize(4.10.2) and NodeJs\n 8.9.4 finally I fixed through following code.\n\n```\nqueryInterface.createTable('actions', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n system_id: {\n type: Sequelize.STRING,\n unique: 'actions_unique',\n },\n rule_id: {\n type: Sequelize.STRING,\n unique: 'actions_unique',\n },\n plan_id: {\n type: Sequelize.INTEGER,\n unique: 'actions_unique',\n }\n}, {\n uniqueKeys: {\n actions_unique: {\n fields: ['system_id', 'rule_id', 'plan_id']\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nvar Tag = sequelize.define('Tag', {\n        id: {\n            type: DataTypes.INTEGER(11),\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        user_id: {\n            type: DataTypes.INTEGER(11),\n            allowNull: false,\n        },\n        count: {\n            type: DataTypes.INTEGER(11),\n            allowNull: true\n        },\n        name: {\n            type: DataTypes.STRING,\n            allowNull: true,\n        })\n```\n\n```text\nvar Tag = sequelize.define('Tag', {\n    id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    user_id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n    },\n    count: {\n        type: DataTypes.INTEGER(11),\n        allowNull: true\n    },\n    name: {\n        type: DataTypes.STRING,\n        allowNull: true,\n    }\n},\n{\n    indexes: [\n        {\n            unique: true,\n            fields: ['user_id', 'count', 'name']\n        }\n    ]\n});\n```\n\n```text\nvar Tag = sequelize.define('Tag', {\n    id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    user_id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        unique: 'uniqueTag',\n    },\n    count: {\n        type: DataTypes.INTEGER(11),\n        allowNull: true,\n        unique: 'uniqueTag',\n    },\n    name: {\n        type: DataTypes.STRING,\n        allowNull: true,\n        unique: 'uniqueTag',\n    }\n});\n```\n\n```text\nqueryInterface.createTable('actions', {\n  id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n  },\n  system_id: {\n      type: Sequelize.STRING,\n      unique: 'actions_unique',\n  },\n  rule_id: {\n      type: Sequelize.STRING,\n      unique: 'actions_unique',\n  },\n  plan_id: {\n      type: Sequelize.INTEGER,\n      unique: 'actions_unique',\n  }\n}, {\n  uniqueKeys: {\n      actions_unique: {\n          fields: ['system_id', 'rule_id', 'plan_id']\n      }\n  }\n});\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('Model', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      fieldOne: {\n        type: Sequelize.INTEGER,\n        unique: 'uniqueTag',\n        allowNull: false,\n        references: {\n          model: 'Model1',\n          key: 'id'\n        },\n        onUpdate: 'cascade',\n        onDelete: 'cascade'\n      },\n      fieldsTwo: {\n        type: Sequelize.INTEGER,\n        unique: 'uniqueTag',\n        allowNull: false,\n        references: {\n          model: 'Model2',\n          key: 'id'\n        },\n        onUpdate: 'cascade',\n        onDelete: 'cascade'\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    })\n    .then(function() {\n      return queryInterface.sequelize.query(\n        'ALTER TABLE `UserFriends` ADD UNIQUE `unique_index`(`fieldOne`, `fieldTwo`)'\n      );\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable('Model');\n  }\n};\n```\n\n```js\nmodule.exports = (sequelize, DataTypes) => {\n  const Tag = sequelize.define(\n    \"Tag\",\n    {\n      name: { type: DataTypes.STRING, unique: true },\n      nVideos: DataTypes.INTEGER\n    },\n    {\n      indexes: [\n        {\n          unique: true,\n          fields: [\"name\"]\n        }\n      ]\n    }\n  );\n\n  return Tag;\n};\n```\n\n```js\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable(\n      \"Tags\",\n      {\n        id: {\n          allowNull: false,\n          autoIncrement: true,\n          primaryKey: true,\n          type: Sequelize.INTEGER\n        },\n        name: {\n          type: Sequelize.STRING,\n          unique: \"unique_tag\"\n        },\n        nVideos: { type: Sequelize.INTEGER },\n        createdAt: {\n          allowNull: false,\n          type: Sequelize.DATE\n        },\n        updatedAt: {\n          allowNull: false,\n          type: Sequelize.DATE\n        }\n      },\n      {\n        uniqueKeys: {\n          unique_tag: {\n            customIndex: true,\n            fields: [\"name\"]\n          }\n        }\n      }\n    );\n  },\n  down: queryInterface => {\n    return queryInterface.dropTable(\"Tags\");\n  }\n};\n```\n\n```text\nmodule.exports = function (sequelize: any, DataTypes: any) {\nreturn sequelize.define('muln_user_goals_transaction', {\n    id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n    },\n    name: {\n        type: DataTypes.STRING(),\n        allowNull: false,\n    },\n    email: {\n        type: DataTypes.STRING(),\n        allowNull: false,\n    },\n    phone: {\n        type: DataTypes.STRING(),\n        allowNull: false,\n    },\n    amount: {\n        type: DataTypes.INTEGER(8),\n        allowNull: false\n    },\n    deleted: {\n        type: DataTypes.BOOLEAN,\n        defaultValue: false,\n    },\n}, {\n    tableName: 'muln_user_goals_transaction',\n    timestamps: false,\n    indexes: [\n        {\n            name: 'unique_index',\n            unique: true,\n            fields: ['name', 'email', 'phone', 'amount', 'deleted']\n        }\n    ],\n    defaultScope: {\n        where: {\n            deleted: false\n        }\n    }\n});\n};\n```\n\n========================================\n\nComments:\n- This doesn't work for me. Neither do any of the answers below. I'm trying to run a query equivalent to this: `CREATE TABLE scores (id INT PRIMARY KEY NOT NULL, oppId INT NOT NULL, oppType TEXT NOT NULL, tree TEXT NOT NULL, version INT NOT NULL, score JSON NOT NULL, CONSTRAINT uniq_scores UNIQUE(oppId, oppType, tree, version));`. When I use the unique indexes with sequelize I'm still able to create two rows with the same values in those columns. Anyone else have these issues?\n- @clu it because only process in sequelize itself\n- Must not be used now. Will not work with `alter: true` option in sync...\n- Hi @RahmatAli didn't understand where I used `alter: true`\n- You can use `alter: true` in the `sync` function of the `sequelize`. So, when the `sequelize` syncs the `models` with database, `sequelize` alters the database columns with the changed columns from models. It is recommended to use the `unique` attribute through `indexes`. Else, there will be some error if you use it with `alter: true` in `sync` function. Please refer to the document for more about `alter` attribute: link\n- This should be the accepted answer. Calling sync is bad for keeping a migration trail.\n- Also, for me just mentioning `unique: 'actions_unique'` for the columns I wanted to be in composite unique rule worked. Didn't add the `uniqueKeys` option.\n- Can confirm that with MySQL 5.7 and Sequelize 5.21.2 just mentioning unique tags on the corresponding fields don't do a thing; only `uniqueKeys` seem to work. Checked by running migrations with and without the thing, then checking mySQL with 'show create table'.\n- Geez. Works for postgres as well.\n- got error `SequelizeDatabaseError: syntax error at or near \"`\"` fixed by using `'ALTER TABLE \"UserFriends\" ADD UNIQUE (\"fieldOne\", \"fieldTwo\")'`\n- @Sandeep you are a savior. tried so many options, only this worked for me. Big Thank you.\n- Could not get this to work with these versions.. \"sequelize\": \"^6.3.5\", \"sequelize-hierarchy\": \"git+github.com/jsanta/sequelize-hierarchy.git\"\n- All I needed was to know that you can add `'deleted'` to the index, in case you are handling soft delete. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:34.337Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":355,"estimatedTokens":2236}}60{"id":"stack-48124949","source":"stackoverflow","questionId":48124949,"title":"Nodejs sequelize bulk upsert","tags":["node.js","sequelize.js"],"text":"Title: Nodejs sequelize bulk upsert\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way of doing bulk upsert in sequelize. Also, can I specify which keys to use for checking for duplicates? \n\nI tried following but it didn't work:\n\n```\nEmployee.bulkCreate(data, {\n updateOnDuplicate: true\n});\n```\n\nBulk creation works fine though. Above statement always creates new entries in the DB.\n\n========================================\n\nTop Answer:\n### Update (Sequelize >= 6)\n\nSequelize 6.x added support for all UPSERTs on all dialects, so @followtest52's answer is valid for PostgreSQL too.\n\n### Original (Sequelize Since PostgreSQL is not supported by the answer, the \"\"\"\"best\"\"\"\" alternative using Sequelize is doing a manual query with the `ON CONFLICT` statement. Example (Typescript):\n\n```\nconst values: Array> = [\n [1, 'Apple', 'Red', 'Yummy'],\n [2, 'Kiwi', 'Green', 'Yuck'],\n]\n\nconst query = 'INSERT INTO fruits (id, name, color, flavor) VALUES ' +\n values.map(_ => { return '(?)' }).join(',') +\n ' ON CONFLICT (id) DO UPDATE SET flavor = excluded.flavor;'\n\nsequelize.query({ query, values }, { type: sequelize.QueryTypes.INSERT })\n```\n\nThis would build a query like:\n\n```\nINSERT INTO \n fruits (id, name, color, flavor)\nVALUES \n (1, 'Apple', 'Red', 'Yummy'),\n (2, 'Kiwi', 'Green', 'Yuck')\nON CONFLICT (id) DO UPDATE SET \n flavor = excluded.flavor;\n```\n\nSuffice to say, this is not an ideal solution to have to manually build queries, since it defeats the purpose of using sequelize, but if it's one-off query that you don't desperately need, you could use this method.\n\n========================================\n\nCode:\n```text\nEmployee.bulkCreate(data, {\n    updateOnDuplicate: true\n});\n```\n\n```text\nEmployee.bulkCreate(dataArray, \n    {\n        fields:[\"id\", \"name\", \"address\"] ,\n        updateOnDuplicate: [\"name\"] \n    } )\n```\n\n```text\nbulkCreate\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\ndataArray\n```\n\n```text\nconst values: Array<Array<number | string>> = [\n    [1, 'Apple', 'Red', 'Yummy'],\n    [2, 'Kiwi', 'Green', 'Yuck'],\n]\n\nconst query = 'INSERT INTO fruits (id, name, color, flavor) VALUES ' +\n     values.map(_ => { return '(?)' }).join(',') +\n     ' ON CONFLICT (id) DO UPDATE SET flavor = excluded.flavor;'\n\nsequelize.query({ query, values }, { type: sequelize.QueryTypes.INSERT })\n```\n\n```text\nINSERT INTO \n    fruits (id, name, color, flavor)\nVALUES \n    (1, 'Apple', 'Red', 'Yummy'),\n    (2, 'Kiwi', 'Green', 'Yuck')\nON CONFLICT (id) DO UPDATE SET \n    flavor = excluded.flavor;\n```\n\n```text\nON CONFLICT\n```\n\n```text\nif (Array.isArray(options.updateOnDuplicate) && options.updateOnDuplicate.length) {\n    options.updateOnDuplicate = _.intersection(\n        _.without(Object.keys(model.tableAttributes), createdAtAttr),\n        options.updateOnDuplicate\n    );\n} else {\n    return Promise.reject(new Error('updateOnDuplicate option only supports non-empty array.'));\n}\n```\n\n```text\nEmployee.bulkCreate(data, {\n    updateOnDuplicate: ['employeeName', 'employeeAge'],\n});\n```\n\n```text\nmodels.Employee.bulkCreate(items, {\n    returning: ['employeeId'],\n    ignoreDuplicates: true\n  })\n```\n\n```js\nconst bulkUpsertIntoTable = async ({ bulkUpsertableData }) => {\n  try {\n    /* eslint-disable */\n   // id column will automatically be incremented if you have set it to auto-increment\n   const query = `INSERT INTO \"Table\" (\"non_id_attr1\", \"non_id_attr2\", \"non_id_attr3\",\"createdAt\", \"updatedAt\") VALUES ${bulkUpsertableData\n    .map((_) => \"(?)\")\n    .join(\n      \",\"\n    )} ON CONFLICT (\"non_id_attr1\",\"non_id_attr2\") DO UPDATE SET \"non_id_attr1\"=excluded.\"non_id_attr1\", \"non_id_attr2\"=excluded.\"non_id_attr2\", \"non_id_attr3\"=excluded.\"non_id_attr3\",  \"updatedAt\"=excluded.\"updatedAt\" RETURNING \"id\",\"non_id_attr1\",\"non_id_attr2\",\"non_id_attr3\",\"createdAt\",\"updatedAt\";`;\n    /* eslint-enable */\n\n    return await models.sequelize.query(query, {\n      replacements: bulkUpsertableData,//------> dont forget to pass your data here\n      type: models.Sequelize.QueryTypes.INSERT,\n      // transaction:t -----> if required to be done in transaction\n    });\n  } catch (error) {\n    console.error(\"Bulk Upserting into Table:\", error);\n    throw error;\n  }\n};\n```\n\n```js\n// with reference to above wrapper function\nconst bulkUpsertableData = Object.keys(myObjectData).map(type => [\n      myObjectData[type],// -----> non_id_attr1\n      type, // -----> non_id_attr2\n      someOtherRandomValue, // -----> non_id_attr3\n      new Date(), // -----> created_at\n      new Date(), // -----> updated_at\n]);\n\n// response will have all the raw attributes mentioned in RETURNING clause\nconst upsertedTableResponse = await bulkUpsertIntoTable({ bulkUpsertableData });\n```\n\n```text\nbulkUpsert\n```\n\n```text\nbulkCreate\n```\n\n```text\nupdateOnDuplicates\n```\n\n```text\nbulkUpsertableData\n```\n\n```text\nArray<Array> ie:- [[]]\n```\n\n```text\nexport const bulkUpsert = async <T extends Model<T>, K extends keyof T>(\n  items: Partial<T>[],\n  model: ModelCtor<T>,\n  conflictKeys: K[],\n  excludeFromUpdate: K[] = [],\n): Promise<[number, number]> => {\n  if (!items.length) {\n    return [0, 0];\n  }\n\n  const { tableName, sequelize, name } = model;\n  if (!sequelize) {\n    throw new Error(`Sequelize not initialized on ${name}?`);\n  }\n\n  const sample = items[0];\n  const fields = Object.keys(sample) as K[];\n  const createFields = `(\"${fields.join(`\",\"`)}\")`;\n  const updateFields = fields\n    .filter((field) => ![...excludeFromUpdate, ...conflictKeys].includes(field))\n    .map((field) => `\"${field}\"=EXCLUDED.\"${field}\"`)\n    .join(', ');\n  const values = items.map(dataToSql(sequelize)).join(',');\n  const onConflict = `ON CONFLICT (\"${conflictKeys.join(`\",\"`)}\")`;\n  const returning = `\"${fields.join('\",\"')}\"`;\n\n  const query = `INSERT INTO \"${tableName}\" ${createFields} VALUES ${values} ${onConflict} DO UPDATE SET ${updateFields} RETURNING ${returning};`;\n\n  return sequelize.query(query, {\n    replacements: items,\n    type: QueryTypes.INSERT,\n  });\n};\n\nconst valueToSql = (sequelize: Sequelize) => (\n  value: string | number | boolean | null | Date | string[] | Record<string, unknown>,\n): string => {\n  if (value === null) {\n    return 'null';\n  }\n\n  if (typeof value === 'boolean') {\n    return value ? 'true' : 'false';\n  }\n\n  if (typeof value !== 'object' || value instanceof Date) {\n    return sequelize.escape(value);\n  }\n\n  return sequelize.escape(JSON.stringify(value));\n};\n\n\nconst dataToSql = <T extends Node<T>>(sequelize: Sequelize) => (data: Partial<T>): string =>\n  `(${Object.values(data).map(valueToSql(sequelize)).join(',')})`;\n```\n\n```text\n/**\n *\n * @param {*} data Raw JSON data\n * @param {*} model Sequalize model\n * @param {*} fields Columns thare need to be inserted/update.If none passed, it will extract fields from the data.\n * @returns response consists of data with type of action(upsert/create) performed for each record.\n */\nexport const bulkUpert = (data, model, fields = undefined) => {\n  console.log(\"****Bulk insertion started****\");\n  if (!data.length) {\n    return [0, 0];\n  }\n  const { name, primaryKeyAttributes } = model;\n\n  console.log(name, primaryKeyAttributes, fields);\n\n  if (!sequelize) {\n    throw new Error(`Sequalize not initialized on ${name}`);\n  }\n\n  const extractFields = fields ? fields : Object.keys(data[0]);\n  const createFields = extractFields.join(\", \");\n  const values = data.map(dataToSql()).join(\", \");\n\n  const query = `MERGE INTO\n    [${name}]\n    WITH(HOLDLOCK)\n    AS [targetTable]\n    USING (\n        VALUES ${values}\n    )\n    AS [sourceTable]\n    (\n      ${createFields}\n    ) ON\n    ${getPrimaryQueryString(primaryKeyAttributes)}\n    WHEN MATCHED THEN\n        UPDATE SET\n            ${getUpdateFieldsString(extractFields)}\n    WHEN NOT MATCHED THEN\n        INSERT (\n              ${createFields}\n            )\n        VALUES\n            (\n                ${getInsertValuesString(extractFields)}\n            )\n    OUTPUT $action, INSERTED.*;`;\n  return sequelize.query(query);\n};\n\nconst valueToSQL = () => (value) => {\n  if (value === null) {\n    return \"null\";\n  }\n\n  if (typeof value === \"boolean\") {\n    return value ? \"true\" : \"false\";\n  }\n\n  if (typeof value !== \"object\" || value instanceof Date) {\n    return sequelize.escape(value);\n  }\n\n  return sequelize.escape(JSON.stringify(value));\n};\n\nconst getPrimaryQueryString = (primaryKeyAttributes) => {\n  let string = \"\";\n  for (let i = 0; i < primaryKeyAttributes.length; i++) {\n    string += `[targetTable].[${primaryKeyAttributes[i]}] = [sourceTable].[${primaryKeyAttributes[i]}]`;\n    if (i != primaryKeyAttributes.length - 1) {\n      string += \" AND\";\n    }\n  }\n  return string;\n};\n\nconst getUpdateFieldsString = (fields) => {\n  let string = \"\";\n  for (let i = 0; i < fields.length; i++) {\n    string += `[targetTable].[${fields[i]}] = [sourceTable].[${fields[i]}]`;\n    if (i != fields.length - 1) {\n      string += \", \";\n    }\n  }\n  return string;\n};\n\nconst getInsertValuesString = (fields) => {\n  let string = \"\";\n  for (let i = 0; i < fields.length; i++) {\n    string += `[sourceTable].[${fields[i]}]`;\n    if (i != fields.length - 1) {\n      string += \", \";\n    }\n  }\n  return string;\n};\n\nconst dataToSql = () => (data) =>\n  `(${Object.values(data).map(valueToSQL()).join(\",\")})`;\n```\n\n```text\nEmployee.bulkCreate(dataArray, \n    {\n        upsertKeys:[\"id\"] ,\n        updateOnDuplicate: [\"name\"] \n    } )\n```\n\n```text\nqueryInterface.bulkInsert\n```\n\n```text\nupsertKeys\n```\n\n```text\n@Table({ modelName: 'transaction' })\nexport class TransactionModel extends Model {\n\n\n  @Column({\n    type: DataType.INTEGER,\n    allowNull: false,\n    autoIncrement: true,\n    unique: true,\n    primaryKey: true,\n  })\n  override id: number;\n\n  @Column(DataType.DATE)\n  override createdAt: string;\n\n  @Column(DataType.STRING)\n  contractAddress: string;\n\n  @Column(DataType.INTEGER)\n  cumulativeGasUsed: number;\n\n  @Column(DataType.STRING)\n  from: string;\n\n  @Column(DataType.INTEGER)\n  gasUsed: number;\n\n  @Column(DataType.INTEGER)\n  effectiveGasPrice: number;\n\n\n  @Column(DataType.TEXT)\n  logsBloom: string;\n\n  @Column(DataType.BOOLEAN)\n  status: boolean;\n\n  @Column(DataType.STRING)\n  to: string;\n\n  @Unique\n  @Column(DataType.STRING)\n  hash: string;           // <---------------------- Required Unique column\n}\n```\n\n```text\n@Table({ modelName: 'transaction' })\nexport class TransactionModel extends Model {\n\n  @Unique\n  @Column(DataType.STRING)\n  hash: string;           // <---------------------- Required Unique column\n\n  @Column({\n    type: DataType.INTEGER,\n    allowNull: false,\n    autoIncrement: true,\n    unique: true,\n    primaryKey: true,\n  })\n  override id: number;\n\n  @Column(DataType.DATE)\n  override createdAt: string;\n\n  @Column(DataType.STRING)\n  contractAddress: string;\n\n  @Column(DataType.INTEGER)\n  cumulativeGasUsed: number;\n\n  @Column(DataType.STRING)\n  from: string;\n\n  @Column(DataType.INTEGER)\n  gasUsed: number;\n\n  @Column(DataType.INTEGER)\n  effectiveGasPrice: number;\n\n\n  @Column(DataType.TEXT)\n  logsBloom: string;\n\n  @Column(DataType.BOOLEAN)\n  status: boolean;\n\n  @Column(DataType.STRING)\n  to: string;\n}\n```\n\n```text\nseqeulize\n```\n\n```text\nsequlize-typescript\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\nunique\n```\n\n```text\nunique\n```\n\n```text\nmodel\n```\n\n```text\n// Version: 6.17.0\n// yarn add sequelize@6.17.0\n//\n\nconst _ = require('lodash');\nconst { Sequelize, Model, Utils, QueryTypes, QueryError } = require('sequelize');\n\n// --------------------------------------------------------------\n// --------------------------------------------------------------\nconst __defProp = Object.defineProperty;\nconst __defProps = Object.defineProperties;\nconst __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nconst __getOwnPropSymbols = Object.getOwnPropertySymbols;\nconst __hasOwnProp = Object.prototype.hasOwnProperty;\nconst __propIsEnum = Object.prototype.propertyIsEnumerable;\nconst __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nconst __spreadValues = (a, b) => {\n  for (let prop in b || (b = {}))\n    if (__hasOwnProp.call(b, prop))\n      __defNormalProp(a, prop, b[prop]);\n  if (__getOwnPropSymbols)\n    for (let prop of __getOwnPropSymbols(b)) {\n      if (__propIsEnum.call(b, prop))\n        __defNormalProp(a, prop, b[prop]);\n    }\n  return a;\n};\nconst __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\n// --------------------------------------------------------------\n// --------------------------------------------------------------\n\n/**\n * \n * @param {Model} model Instance of Sequelize model\n * @param {Object} options Similar to options of findAll function.\n * @param {Boolean} removeSemicolon to remove the semicolon at the end of query. It is useful when using to build query for UNION ALL\n * @returns {String} SQL SELECT query\n */\nasync function buildFindAllSQL(model, options, { removeSemicolon = false }) {\n  if (options !== void 0 && !_.isPlainObject(options)) {\n    throw new QueryError(\"The argument passed to findAll must be an options object, use findByPk if you wish to pass a single primary key value\");\n  }\n  if (options !== void 0 && options.attributes) {\n    if (!Array.isArray(options.attributes) && !_.isPlainObject(options.attributes)) {\n      throw new QueryError(\"The attributes option must be an array of column names or an object\");\n    }\n  }\n  model.warnOnInvalidOptions(options, Object.keys(model.rawAttributes));\n  const tableNames = {};\n  tableNames[model.getTableName(options)] = true;\n  options = Utils.cloneDeep(options);\n  _.defaults(options, { hooks: true });\n  options.rejectOnEmpty = Object.prototype.hasOwnProperty.call(options, \"rejectOnEmpty\") ? options.rejectOnEmpty : model.options.rejectOnEmpty;\n  model._injectScope(options);\n  if (options.hooks) {\n    await model.runHooks(\"beforeFind\", options);\n  }\n  model._conformIncludes(options, model);\n  model._expandAttributes(options);\n  model._expandIncludeAll(options);\n  if (options.hooks) {\n    await model.runHooks(\"beforeFindAfterExpandIncludeAll\", options);\n  }\n  options.originalAttributes = model._injectDependentVirtualAttributes(options.attributes);\n  if (options.include) {\n    options.hasJoin = true;\n    model._validateIncludedElements(options, tableNames);\n    if (options.attributes && !options.raw && model.primaryKeyAttribute && !options.attributes.includes(model.primaryKeyAttribute) && (!options.group || !options.hasSingleAssociation || options.hasMultiAssociation)) {\n      options.attributes = [model.primaryKeyAttribute].concat(options.attributes);\n    }\n  }\n  if (!options.attributes) {\n    options.attributes = Object.keys(model.rawAttributes);\n    options.originalAttributes = model._injectDependentVirtualAttributes(options.attributes);\n  }\n  model.options.whereCollection = options.where || null;\n  Utils.mapFinderOptions(options, model);\n  options = model._paranoidClause(model, options);\n  if (options.hooks) {\n    await model.runHooks(\"beforeFindAfterOptions\", options);\n  }\n  const selectOptions = __spreadProps(__spreadValues({}, options), { tableNames: Object.keys(tableNames) });\n\n  // This function based-on the code from findAll function of the Model class.\n  // In the findAll function, the model.queryInterface.select function will be called.\n  // Inside the select function of the QueryInterface class will define the way to build SELECT query.\n  const sql = model.sequelize.queryInterface.queryGenerator.selectQuery(model.getTableName(selectOptions), { ...selectOptions, type: QueryTypes.SELECT, model }, model);\n\n  if (removeSemicolon) {\n    const lastChar = sql.slice(sql.length - 1);\n    if (lastChar === ';') {\n      return sql.slice(0, -1)\n    }\n  }\n\n  return sql;\n}\n\n/**\n * \n * @param {Array<Object>} items List data object need to be parsed / mapped.\n * @param {Model} model Instance of Sequelize model\n * @param {Array<String>} fields List of columns' name\n * @returns {Array<Object>}\n */\nfunction mapValues(items, { model, fields }) {\n  const records = _.cloneDeep(items);\n  //\n  const fieldMappedAttributes = {};\n  for (const attr in model.tableAttributes) {\n    fieldMappedAttributes[model.rawAttributes[attr].field || attr] = model.rawAttributes[attr];\n  }\n  //\n  const fieldValueHashes = records.map(values => {\n    const out = Utils.mapValueFieldNames(values, fields, model);\n    for (const key of model._virtualAttributes) {\n      delete out[key];\n    }\n    return out;\n  });\n  //\n  const tuples = []\n  for (const fieldValueHash of fieldValueHashes) {\n    const values = fields.map(key => {\n      return model.sequelize.queryInterface.queryGenerator.escape(fieldValueHash[key], fieldMappedAttributes[key], { context: 'INSERT' });\n    });\n    tuples.push(`(${values.join(',')})`);\n  }\n  //\n  return tuples;\n}\n\n/**\n * \n * @param {Array<Object>} items List data object need to be inserted / updated\n * @param {Model} model Instance of Sequelize model\n * @returns {String} SQL INSERT query\n */\nasync function buildBulkUpsertSQL(items = [], {\n  model,\n  conflictKeys = [],\n  excludeFromUpdate = [],\n  conflictWhere = [],\n  returning = false,\n  logging = false,\n}) {\n\n  if (!items.length) {\n    return null;\n  }\n\n  const { tableName, sequelize } = model;\n\n  const sample = items[0];\n  const fields = Object.keys(sample);\n  const createFields = `(\"${fields.join(`\",\"`)}\")`;\n  const updateFields = fields\n    .filter((field) => ![...excludeFromUpdate, ...conflictKeys].includes(field))\n    .map((field) => `\"${field}\"=EXCLUDED.${field}`)\n    .join(', ');\n  //\n  const tuples = mapValues(_.cloneDeep(items), { model, fields });\n  const values = tuples.join(',');\n  //\n  const onConflict = `ON CONFLICT (\"${conflictKeys.join(`\",\"`)}\")`;\n  const returningFields = `\"${fields.join('\",\"')}\"`;\n\n  // const updateWhere = Object.keys(conflictWhere).length > 0 ? `WHERE ${Object.keys(conflictWhere).map(key => `\"${tableName}\".\"${key}\" ${conflictWhere[key]}`).join(',')}` : '';\n\n  const updateWhere = conflictWhere.length > 0 ? `WHERE ${conflictWhere.join(',')}` : '';\n\n  let query = `INSERT INTO \"${tableName}\" ${createFields} VALUES ${values}`;\n\n  if (conflictKeys.length > 0) {\n    query = `${query} ${onConflict} DO UPDATE SET ${updateFields} ${updateWhere}`;\n  }\n\n  if (returning === true) {\n    query = `${query} RETURNING ${returningFields}`;\n  }\n\n  query += ';';\n\n  if (typeof logging === 'function') {\n    logging('---------------------------------------');\n    logging(query);\n    logging('---------------------------------------');\n  }\n\n  return query;\n}\n\n/**\n * \n * @param {Array<Object>} items List data object need to be inserted / updated\n * @param {Model} model Instance of Sequelize model\n * @returns {Array} Result of sequelize.query function\n */\nasync function bulkUpsert(items = [], {\n  model,\n  conflictKeys = [],\n  excludeFromUpdate = [],\n  conflictWhere = [],\n  transaction = null,\n  logging = false\n}) {\n\n  if (!items.length) {\n    return [0, 0];\n  }\n\n  const query = await buildBulkUpsertSQL(items, { model, conflictKeys, excludeFromUpdate, conflictWhere, logging });\n\n  if (!query) {\n    return [0, 0];\n  }\n\n  const { sequelize } = model;\n\n  const options = {\n    type: sequelize.QueryTypes.INSERT,\n    // logging,\n  };\n\n  if (transaction) {\n    options[transaction] = transaction;\n  }\n\n  return sequelize.query(query, options);\n}\n\n// --------------------------------------------------------------\n\nmodule.exports = {\n  buildFindAllSQL,\n  buildBulkUpsertSQL,\n  bulkUpsert,\n  mapValues,\n};\n```\n\n========================================\n\nComments:\n- Thanks followtest52, bingo :)\n- Unfortunately, the documentation says that this option is supported only by mysql =(\n- if you set a boolean true like: `updateOnDuplicate: true` all attributes will be updated if changed.\n- Now Postgres supported also - \"Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL, MariaDB & Postgres >= 9.5). By default, all fields are updated.\"\n- Worth mentioning: the field `updatedAt` which is usually automagically updated by sequelize will *not* get updated unless it's explicitly passed via `updateOnDuplicate`\n- A note: if your table has uniq indexes, this solution won't work. A PR is in progress: github.com/sequelize/sequelize/pull/12516\n- \"By default, all fields are updated.\" so does that mean you could leave the option out and it would do an upsert by default?\n- This accepted answer doesn't work in all cases. It doesn't work with unique composite indexes yet.\n- SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 \"sequelize\": \"^6.6.5\"\n- can you more explain how to retrive status its create is true / false i mean state of execution is create or update .\n- Do not forget to mark the field as unique `@Unique decorator in case of sequelize-typescript` otherwise this code will try to use primary key instead of `name`. Postgres 14.1\n- Just stumbled upon this, if anyone comes here looking out for more info, Make sure you have a column that has unique Index. Sometimes primary key is something you can't use. eg. id, name and age here you can have index on id but for data insertion you can't use it to find duplicate so just make name as unique index and it will work.\n- Do not forget to mark the field as unique `@Unique decorator in case of sequelize-typescript` otherwise this code will try to use primary key instead of `name`. Postgres 14.1\n- items should be an array of objects with the same fields your model has\n- Your update will work for situations when you don't need to update values. It is a nice way in postgres to say \"if this doesn't exist, make it ... but if it does exist, don't change anything about it.\" I can use this for part of my problem now. But I still need to (a) update row fields on \"duplicates\" and then create those rows if they do not exist. Trying to avoid raw SQL.\n- did you try this updateOnDuplicate: ['employeeName', 'employeeAge'] it works on my table\n- That's so weird it's working for you. I am using heroku postgres with the latest version of sequelize. When I use Page.bulkCreate(data.pages, { returning: true, updateOnDuplicate: ['id'] }), it will create new instances, but it won't update the old ones.\n- what is your sequelize version\n- Let us continue this discussion in chat.\n- I get this error `there is no unique or exclusion constraint matching the ON CONFLICT specification` in a model that has a primary key of `id` and 4 other attributes that have a unique constraint. Anybody else has run into this?\n- Thanks @Yedhin for this answer I will post a more generic solution based on your code.\n- How do I actually use the composite indexes and specify what keys I want to use to determine duplicates? It looks like there's an attribute called `upsertKeys` you can pass `bulkCreate`, is that correct? I was looking here github.com/sequelize/sequelize/pull/13345/commits/&hellip;\n- Also is `updateOnDuplicate` supposed to be an array still? That's what the docs say but I thought it was supposed to be a boolean","metadata":{"transformedAt":"2026-08-18T18:33:34.337Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":761,"estimatedTokens":5770}}61{"id":"stack-46694157","source":"stackoverflow","questionId":46694157,"title":"Dialect needs to be explicitly supplied as of v4.0.0","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Dialect needs to be explicitly supplied as of v4.0.0\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have been working on a NodeJS project which uses PostgreSQL database. \nI am trying to implement migration to the database. Also, using Sequelize. After setting up the migration folder and config, it throws error while running db:migrate\n\nThe error is:\n\"Dialect needs to be explicitly supplied as of v4.0.0\"\n\n========================================\n\nTop Answer:\nI was facing this error, as it turns out, because of typescipt's transformation/compilation.\n\nA little background: I am using sequelize in a typescript project. And the database config file was in a `database.ts` file.\n\n```\nconst config = {\n development: {\n username: env.PG_USERNAME,\n password: env.PG_PASSWORD,\n database: 'sample_db',\n host: env.PG_HOST,\n port: env.PG_PORT,\n dialect: 'postgres',\n },\n test: {\n username: env.PG_USERNAME,\n password: env.PG_PASSWORD,\n database: 'sample_db',\n host: env.PG_HOST,\n port: env.PG_PORT,\n dialect: 'postgres',\n },\n production: {\n username: env.PG_USERNAME,\n password: env.PG_PASSWORD,\n database: 'sample_db',\n host: env.PG_HOST,\n port: env.PG_PORT,\n dialect: 'postgres',\n },\n};\n\nexport default config;\n```\n\nIn `.sequelizerc` file, I was pointing to the transpiled version of the `database.ts` file i.e. the `dist/config/database.js` file. As shown below:\n\n```\nconst path = require('path');\n\nmodule.exports = {\n env: process.env.NODE_ENV || 'development',\n config: path.resolve('dist', 'config', 'database.js'),\n ...\n};\n```\n\nBut after inspecting the transpiled version of the `database.ts` file, i noticed that the config was exported as:\n\n```\nmodule.exports.default = config\n```\n\nBut `sequelize` is expecting the config to be at `module.exports`.\n\nSo, I modified the `database.ts` file by appending this one line to the end of the file and that resolved it for me.\n\n```\n...\n\nmodule.exports = config;\n```\n\n========================================\n\nCode:\n```text\n{\n local: {\n  username: 'root',\n  password: null,\n  database: 'database_dev',\n  host: '127.0.0.1',\n  dialect: 'postgres'\n  },\n development: {\n  username: 'root',\n  password: null,\n  database: 'database_dev',\n  host: '127.0.0.1',\n  dialect: 'postgres'\n  },\n  test: {\n  username: 'root',\n  password: null,\n  database: 'database_test',\n  host: '127.0.0.1',\n  dialect: 'postgres'\n },\n production: {\n  username: 'root',\n  password: null,\n  database: 'database',\n  host: '127.0.0.1',\n  dialect: 'postgres'\n }\n}\n```\n\n```text\nNODE_ENV\n```\n\n```text\necho $NODE_ENV\n```\n\n```text\nexport NODE_ENV=development\n```\n\n```text\nlocal\n```\n\n```json\n{\n  development: {\n    username: 'root',\n    password: null,\n    database: 'database_development',\n    host: '127.0.0.1',\n    dialect: 'mysql'\n  },\n  test: {\n    username: 'root',\n    password: null,\n    database: 'database_test',\n    host: '127.0.0.1',\n    dialect: 'mysql'\n  },\n  production: {\n    username: 'root',\n    password: null,\n    database: 'database_production',\n    host: '127.0.0.1',\n    dialect: 'mysql'\n  }\n}\n```\n\n```text\nexport DATABASE_URL=<your-db-url>\n```\n\n```text\nnpm server\n```\n\n```text\ntitle: {\n    type: Sequelize,\n    allowNull: false,\n  },\n```\n\n```text\ntitle: {\n    type: Sequelize.STRING,\n    allowNull: false,\n  },\n```\n\n```text\nconst Sequelize = require('sequelize');\n// Option 1: Passing parameters separately\nconst sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */\n});\n```\n\n```text\nmiddle_name: {\n    type: Sequelize.Sequelize,\n    allowNull: false,\n}\n```\n\n```text\nmiddle_name: {\n    type: Sequelize.STRING,\n    allowNull: false,\n}\n```\n\n```text\nmodule.exports = {\n  production: {\n    database: process.env.DB_PROD_DATABASE,\n    username: process.env.DB_PROD_USERNAME,\n    password: process.env.DB_PROD_PASSWORD,\n    options: {\n      host: process.env.DB_PROD_HOST,\n      port: process.env.DB_PROD_PORT,\n      dialect: 'postgres',\n      define: {\n        paranoid: true,\n        timestamp: true,\n        freezeTableName: true,\n        underscored: false\n      }\n    }\n  },\n  development: {\n    database: process.env.DB_DEV_DATABASE || 'database_name',\n    username: process.env.DB_DEV_USERNAME || 'user_name', \n    password: process.env.DB_DEV_PASSWORD || 'pass', \n    host: process.env.DB_DEV_HOST || 'localhost',\n    port: process.env.DB_DEV_PORT || 5432,\n    dialect: 'postgres',\n    define: {\n      paranoid: true,\n      timestamp: true,\n      freezeTableName: true,\n      underscored: false\n    }\n  }\n}\n```\n\n```text\nmodule.exports = {\n  production: {\n    database: process.env.DB_PROD_DATABASE,\n    username: process.env.DB_PROD_USERNAME,\n    password: process.env.DB_PROD_PASSWORD,\n    options: {\n      host: process.env.DB_PROD_HOST,\n      port: process.env.DB_PROD_PORT,\n      dialect: 'postgres',\n      define: {\n        paranoid: true,\n        timestamp: true,\n        freezeTableName: true,\n        underscored: false\n      }\n    }\n  },\n  development: {\n    database: 'database_name',\n    username: 'user_name', \n    password: 'pass', \n    host: 'localhost',\n    port: 5432,\n    dialect: 'postgres',\n    define: {\n      paranoid: true,\n      timestamp: true,\n      freezeTableName: true,\n      underscored: false\n    }\n  }\n}\n```\n\n```text\nprocess.env.DB_DEV_DATABASE || 'database_name'\n```\n\n```text\nvar Sequilize=require('sequelize');\nvar connection =new Sequilize('db_name','root_user_name','password_for_rootUser',{\n    host:'localhost',\n    dialect:'mysql'|'mariadb'|'sqlite'|'postgress'|'mssql',\n    pool:{\n        max:5,\n        min:0,\n        idle:10000\n    },\n//for sqlite only\nstorage:path/to/database.sqlite\n\n\n});\n\n\nvar Article=connection.define('tableName',{\n    title:Sequilize.STRING, // your cloumn name with data type\n    body:Sequilize.TEXT    // your cloumn name with data type\n});\n\nconnection.sync();\n```\n\n```text\nmodule.exports = {\n  development: {\n    dialect: process.env.DB_DIALECT,\n    username: process.env.DB_USER,\n    password: process.env.DB_PASS,\n    database: process.env.DB_NAME_DEVELOPMENT,\n    host: process.env.DB_HOST,\n    port: process.env.DB_PORT,\n  },\n  test: {\n    dialect: process.env.DB_DIALECT,\n    username: process.env.DB_USER,\n    password: process.env.DB_PASS,\n    database: process.env.DB_NAME_DEVELOPMENT,\n    host: process.env.DB_HOST,\n    port: process.env.DB_PORT,\n  },\n  production: {\n    dialect: process.env.DB_DIALECT,\n    username: process.env.DB_USER,\n    password: process.env.DB_PASS,\n    database: process.env.DB_NAME_DEVELOPMENT,\n    host: process.env.DB_HOST,\n    port: process.env.DB_PORT,\n  },\n};\n```\n\n```text\nexport const = {}\n```\n\n```text\nmodule.exports\n```\n\n```text\nconst main = require('./main');\n\nmodule.exports = {\n  development: { // this was set to `current` in my case, and it was causing the error\n    username: main.db.user,\n    password: main.db.password,\n    database: main.db.name,\n    host: main.db.host,\n    port: main.db.port || 3306,\n    dialect: 'mysql'\n  }\n};\n```\n\n```text\nconfig.js\n```\n\n```text\ncurrent\n```\n\n```text\ndevelopment\n```\n\n```text\nexport NODE_ENV=development; npx sequelize db:migrate\n```\n\n```text\nDB_CONNECTION\n```\n\n```text\n.env\n```\n\n```text\ncd src; node app.js\n```\n\n```text\nnode src/app.js\n```\n\n```js\nconst config = {\n    development: {\n        username: env.PG_USERNAME,\n        password: env.PG_PASSWORD,\n        database: 'sample_db',\n        host: env.PG_HOST,\n        port: env.PG_PORT,\n        dialect: 'postgres',\n    },\n    test: {\n        username: env.PG_USERNAME,\n        password: env.PG_PASSWORD,\n        database: 'sample_db',\n        host: env.PG_HOST,\n        port: env.PG_PORT,\n        dialect: 'postgres',\n    },\n    production: {\n        username: env.PG_USERNAME,\n        password: env.PG_PASSWORD,\n        database: 'sample_db',\n        host: env.PG_HOST,\n        port: env.PG_PORT,\n        dialect: 'postgres',\n    },\n};\n\nexport default config;\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n    env: process.env.NODE_ENV || 'development',\n    config: path.resolve('dist', 'config', 'database.js'),\n    ...\n};\n```\n\n```text\nmodule.exports.default = config\n```\n\n```text\n...\n\nmodule.exports = config;\n```\n\n```text\ndatabase.ts\n```\n\n```text\n.sequelizerc\n```\n\n```text\ndatabase.ts\n```\n\n```text\ndist/config/database.js\n```\n\n```text\ndatabase.ts\n```\n\n```text\nsequelize\n```\n\n```text\nmodule.exports\n```\n\n```text\ndatabase.ts\n```\n\n```text\nconfig: any = {\n        \"development\": {\n        \"username\": dbUser,\n        \"password\": dbPassword,\n    ...\n    module.exports = config\n```\n\n```text\nconst path = require('path');\n    module.exports = {\n        'config': path.resolve('./dist', 'src/config/config.js')\n    };\n```\n\n```text\nmodule.exports = config\n```\n\n```text\nimport dotenv from 'dotenv'\ndotenv.config()\n```\n\n```text\nmodule.exports = {\n  'config': path.resolve('config', 'sequelize.js'),\n  'models-path': path.resolve('src', 'models'),\n  'seeders-path': path.resolve('src', 'seeders'),\n  'migrations-path': path.resolve('src', 'migrations')\n};\n```\n\n```text\nimport dotenv from 'dotenv'\ndotenv.config()\n\nexport default {\n    development: {\n        username: process.env.DB_USER,\n        password: process.env.DB_PASSWORD,\n        database: process.env.DB_DATABASE,\n        host: process.env.DB_HOST,\n        port: process.env.DB_PORT,\n        dialect: process.env.DB_DIALECT,\n        dialectOptions: {\n            bigNumberStrings: true\n        }\n    },\n    test: {\n        username: process.env.DB_USER,\n        password: process.env.DB_PASSWORD,\n        database: process.env.DB_DATABASE,\n        host: process.env.DB_HOST,\n        port: process.env.DB_PORT,\n        dialect: process.env.DB_DIALECT,\n    },\n    production: {\n        username: process.env.DB_USER,\n        password: process.env.DB_PASSWORD,\n        database: process.env.DB_DATABASE,\n        host: process.env.DB_HOST,\n        port: process.env.DB_PORT,\n        dialect: process.env.DB_DIALECT,\n        dialectOptions: {\n            bigNumberStrings: true,\n        }\n    }\n};\n```\n\n```text\n{\n    \"type\": \"module\",\n    ...\n}\n```\n\n```text\n{\n    \"compilerOptions\": {\n        \"module\": \"ESNext\",\n                ...\n        }\n}\n```\n\n```text\nexport default configDB;\n```\n\n```text\nexport function connectDB(database, dialect, logging = false) {\n  const connectionConfig = {\n    server: process.env[`LOCAL_${dialect.toUpperCase()}_SERVER`],\n    database: database,\n    username: process.env[`LOCAL_${dialect.toUpperCase()}_USERNAME`],\n    password: process.env[`LOCAL_${dialect.toUpperCase()}_PASSWORD`],\n    host: process.env[`LOCAL_${dialect.toUpperCase()}_HOST`],\n    port: process.env[`LOCAL_${dialect.toUpperCase()}_PORT`],\n    dialect: `${dialect.toLowerCase()}`,\n    logging: logging,\n  }\n  return new Sequelize(connectionConfig)\n}\n```\n\n```bash\nnpx sequelize-cli db:migrate --env development\n```\n\n```text\nconst path = require('path');\nrequire('dotenv').config({ path: path.resolve(__dirname, '../../.env') });\n```\n\n```text\nDB_USERNAME=your_username\nDB_PASSWORD=your_password\nDB_NAME=your_db_name\nDB_HOST=localhost //if you are running on local machine\nDB_DIALECT=postgres //change according to your dialect\nDB_PORT=5432  //optional\n```\n\n```text\n../../.env\n```\n\n```js\nmodule.exports = {\n  development: {\n    username: 'root',\n    password: null,\n    storage: 'dev.sqlite',\n    seederStorage: \"\",\n    database: path.resolve('./', 'dev.sqlite'),\n    \"mode\": SqliteDialect.OPEN_READWRITE | SqliteDialect.OPEN_CREATE | SqliteDialect.OPEN_FULLMUTEX,\n    // host: '127.0.0.1',\n    port: 5432,\n    pool: {\n      max: 5,\n      min: 0,\n      acquire: 30000,\n      idle: 10000\n    },\n    retry: {\n      match: [\n        /SQLITE_BUSY/,\n        Sequelize.ConnectionError,\n      ],\n      max: 3,\n    },\n    dialect: 'sqlite',\n    dialectOptions: {\n      bigNumberStrings: true,\n    },\n  },\n  test: {\n    // ...\n  },\n  production: {\n    // ...\n  },\n};\n```\n\n```js\nlet dbConfig;\nif (buildFlag === 'production') {\n  dbConfig = configFile.production;\n}\nelse if (buildFlag === 'test') {\n  dbConfig = configFile.test;\n}\nelse {\n  dbConfig = configFile.development;\n}\n\n// was this... const sequelize = new Sequelize(dbConfig);\n\n// below works...\nconst sequelize = new Sequelize({...dbConfig, dialect: 'sqlite'});\n```\n\n========================================\n\nComments:\n- // with uri const sequelize = new Sequelize('postgres://localhost:5432/db_name')\n- Where do I find this config file? I install sequelize from npm in a node.js project and I don't know where it is\n- @Mitro: If you are using the Sequelize CLI, I *think* it generates those files for you. Either way, take a look at the docs here: docs.sequelizejs.com/manual/tutorial/migrations.html These should help explain the files that you will need in order to run migrations. If you're still having trouble, try opening a new question.\n- set export NODE_ENV=development this needs to be set in ~/.zshrc or ~/.bashrc in case of linux\n- alternatively you can use **--env** to specify an entry from config, `npx sequelize-cli db:migrate:status --config \"config.json\" --env \"development\"`\n- yes, same for me is important to verify the name, i was using stage and my env was staging, so thanks to this solution i realized what was happening.\n- You can not enter that as a command, you should be more clear and please update your answer.\n- This was my issue as well. I was using PM2 to manage an app and I (lazily) started the app via console by scolling through previous command strings - but I wasn't in the app's root directory when I executed the pm2 start command and this was the error I received even though the path to the app in the command string was absolute.\n- This worked for me. I was setting my env as production in many ways, but only after I added --env in the commands, it worked completely fine","metadata":{"transformedAt":"2026-08-18T18:33:34.337Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":57,"totalLines":664,"estimatedTokens":3451}}62{"id":"stack-26228499","source":"stackoverflow","questionId":26228499,"title":"Setting all queries to raw = true sequelize","tags":["node.js","orm","sequelize.js"],"text":"Title: Setting all queries to raw = true sequelize\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI really like using sequelize as my ORM for my node application, but right now, I am kind of irritated when they are passing DAO objects by default when you query. How can I set the raw option to true all the time?\n\n========================================\n\nTop Answer:\nFor create you can use this:\n\n```\nModel.create(modelObject)\n.then((resultEntity) => {\n const dataObj = resultEntity.get({plain:true})\n}\n```\n\nCheck this out: Set raw = true on Sequelize Model.create\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {query:{raw:true}})\n```\n\n```text\nModel.create(modelObject)\n.then((resultEntity) => {\n    const dataObj = resultEntity.get({plain:true})\n}\n```\n\n========================================\n\nComments:\n- your title says : set raw = true, and your question asks how to set raw= false...\n- Wow, that was very helpful, I have one problem though, when I use create, there are still DAO objects, the query raw: true helped when I used find but it won't affect when I use create. Sample code: `Model.create({name: 'test'}, {options: raw: true})`\n- try : `Modelgroup.create(test, {raw: true})`\n- github.com/sequelize/sequelize/wiki/&hellip;\n- You edited your comment... `Model.create({name: 'test'}, {raw: true})` should work\n- well, the question : \"Setting all queries to raw = true\" is answered, maybe ask a specific question for the Model.create(). are you sure `Model.create({name: 'test'}, {raw: true})` doesn't work?\n- Just be careful to note that this bypasses sequelize modal transformations. E.g TINYINT will be returned as 0/1 with raw as opposed to true/false","metadata":{"transformedAt":"2026-08-18T18:33:34.337Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":45,"estimatedTokens":442}}63{"id":"stack-64449464","source":"stackoverflow","questionId":64449464,"title":"Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import when attempting to start Nodejs App locally","tags":["javascript","node.js","express","heroku","sequelize.js"],"text":"Title: Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import when attempting to start Nodejs App locally\nTags: javascript, node.js, express, heroku, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm caught in a bit of a loop trying to deploy my app to Heroku. My import statements (e.g. `import cors from 'cors'`) seem to prevent the app from launching in production, due to the \"Cannot Load ES6 Modules in Common JS\" error. Locally it runs just fine.\n\nHowever, when I attempt to resolve the above error by adding `\"type\": \"module\"` to my `package.json` I get a whole new set of errors and the app will no longer run locally. I *believe* this error is due to the way I'm initializing sequelize and associated models but I am unsure. I'd like to resolve this error but need a hand with new syntax for the imports... I think.\n\nError, `package.json` and `index.js` include below.\n\n**Error Text**\n\n```\n[nodemon] starting `babel-node src/index.js`\ninternal/process/esm_loader.js:74\n internalBinding('errors').triggerUncaughtException(\n ^\n\nError [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/Users/jeff/Clients/Bummer/Code/Server/src/models' is not supported resolving ES modules imported from /Users/jeff/Clients/Bummer/Code/Server/src/index.js\n at finalizeResolution (internal/modules/esm/resolve.js:272:17)\n at moduleResolve (internal/modules/esm/resolve.js:699:10)\n at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)\n at Loader.resolve (internal/modules/esm/loader.js:85:40)\n at Loader.getModuleJob (internal/modules/esm/loader.js:229:28)\n at ModuleWrap. (internal/modules/esm/module_job.js:51:40)\n at link (internal/modules/esm/module_job.js:50:36) {\n code: 'ERR_UNSUPPORTED_DIR_IMPORT',\n url: 'file:///Users/jeff/Clients/Bummer/Code/Server/src/models'\n}\n[nodemon] app crashed - waiting for file changes before starting...\n```\n\n**Package.JSON**\n\n```\n{\n \"name\": \"bummer\",\n \"type\": \"module\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"start\": \"node src/index.js\",\n \"dev\": \"nodemon --exec babel-node src/index.js\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"@babel/core\": \"^7.9.6\",\n \"@babel/node\": \"^7.8.7\",\n \"@babel/preset-env\": \"^7.9.6\",\n \"nodemon\": \"^2.0.4\",\n \"sequelize-cli\": \"^6.2.0\"\n },\n \"dependencies\": {\n \"cookie-parser\": \"^1.4.5\",\n \"cors\": \"^2.8.5\",\n \"dotenv\": \"^8.2.0\",\n \"express\": \"^4.17.1\",\n \"pg\": \"^8.2.1\",\n \"querystring\": \"^0.2.0\",\n \"request\": \"^2.88.2\",\n \"sequelize\": \"^6.3.5\",\n \"sequelize-auto-migrations\": \"^1.0.3\",\n \"uuid\": \"^8.0.0\"\n }\n}\n```\n\n**Index.js**\n\n```\nimport cors from 'cors';\nimport express from 'express';\nimport models, { sequelize } from './models';\n// import routes from './routes';\n\n//Initiaze Express\nconst app = express();\nconst routes = require('./routes');\n\n//Helpers for Spotify oAuth\nconst cookieParser = require('cookie-parser')\n\n// Include Middleware\napp.use(express.static(__dirname + '/public'))\n .use(cors())\n .use(cookieParser())\n .use(express.json())\n .use(express.urlencoded({ extended: true }))\n require('dotenv').config()\n\n \n\n// Include all Models\napp.use((req, res, next) => {\n req.context = {\n models,\n };\n next();\n});\n\n// Load Routes from Router Index\napp.use('/', routes);\n\nsequelize.sync().then(() => {\n app.listen(process.env.PORT, () => {\n console.log(`Example app listening on port ${process.env.PORT}!`)\n });\n});\n```\n\nThoughts or pointers? Thank you!\n\n========================================\n\nTop Answer:\n### Explicitly, point to your main file (usually `index.js`). E. g.\n\n```\nimport ... from './models' // ❌\nimport ... from './models/index.js' // ✅\n```\n\n### Alternative way (see the below UPDATE for Node.js v19+ and the newer one for Node.js 20.8+):\n\nUse `--experimental-specifier-resolution=node` flag. For example:\n\n```\nnode --experimental-specifier-resolution=node main.js\n```\n\nSee:\nhttps://nodejs.org/api/esm.html#esm_customizing_esm_specifier_resolution_algorithm\n\n### UPDATE (Node.js v19+):\n\nNode.js has removed the `--experimental-specifier-resolution` flag. Its functionality can now be achieved via **custom loaders**.\n\nhttps://nodejs.org/en/blog/announcements/v19-release-announce/#custom-esm-resolution-adjustments\n\nThe simplest **loader** (that only appends `.js` extension if needed) is something like:\n\n```\nimport {isBuiltin} from 'node:module'\n\n// noinspection JSUnusedGlobalSymbols\nexport const resolve = (specifier, context, nextResolve) => // This function can be `async` too\n nextResolve(isBuiltin(specifier) || specifier.endsWith('.js') ? specifier : `${specifier}.js`, context)\n```\n\nName it `loader.js` (or `loader.mjs` if you don't set yet `\"type\": \"module\"` in your `package.json`).\n\nThen if you run your script (e.g. `./some-script.js`) using this loader:\n\n```\nnode --loader ./loader.js some-script.js\n```\n\nthe `import`s within `some-script.js` (and the files imported in it) can omit `.js` extension.\n\nSee more complex examples: https://github.com/nodejs/loaders-test\n\n### UPDATE (Node.js v20.8+): `register()`/`--import`\n\nUsing **`register()`** function (from built-in `node:module` package) and then **`--import`** flag (instead of `--loader`).\n\nThere is a `ts-loader` example, in my other answer, using `ts-node/esm` (from `ts-node` library):\n\n```\nimport {register} from 'node:module'\nimport {pathToFileURL} from 'node:url'\n\nregister('ts-node/esm', pathToFileURL('./'))\n```\n\nAnd then:\n\n```\nnode --import ./ts-loader.js my-script.ts\n```\n\nThat has some cons that I mentioned there (specially in `import`s inside your file/files).\n\nPlus **another perfect ts-loader solution using esbuild** that you can see it there.\n\nThey're both originally for executing TypeScript files using Node.js. But **they both work for the purpose of current question, too**. It means you can execute your `models/index.js` (or `models/index.ts`), by:\n\n```\nnode --import ./ts-loader.js models\n```\n\nor (using the second perfect solution):\n\n```\nnode --import ./register-ts-loader.js models\n```\n\nAlso, using it, you can execute `js`/`ts` files **w/o extension** + **running `ts` files with `js` extension** (as you can `import` `ts` files in another `ts` file, using `js` extension). With the second perfect solution, you can enjoy these features recursively for `import`s inside your file/files. Plus supporting `jsx`/`tsx`!\n\n### UPDATE\n\nInstall and use `tsx` package:\n\n```\nnode --import tsx some-script.js\n```\n\nor simpler:\n\n```\ntsx some-script.js\n```\n\nIt supports `.ts`, `.tsx`, and `.jsx` too.\n\nhttps://tsx.is/#about-the-project:\n\n***tsx* is designed to simplify your TypeScript experience.** It enhances Node.js with TypeScript support in both CommonJS and ESM modes, allowing you to switch between them seamlessly. It also supports `tsconfig.json` paths and includes a Watch mode to make development even easier.\n\nSee also: https://nodejs.org/en/learn/typescript/run#running-typescript-code-with-tsx\n\n========================================\n\nCode:\n```text\n[nodemon] starting `babel-node src/index.js`\ninternal/process/esm_loader.js:74\n    internalBinding('errors').triggerUncaughtException(\n                              ^\n\nError [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/Users/jeff/Clients/Bummer/Code/Server/src/models' is not supported resolving ES modules imported from /Users/jeff/Clients/Bummer/Code/Server/src/index.js\n    at finalizeResolution (internal/modules/esm/resolve.js:272:17)\n    at moduleResolve (internal/modules/esm/resolve.js:699:10)\n    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)\n    at Loader.resolve (internal/modules/esm/loader.js:85:40)\n    at Loader.getModuleJob (internal/modules/esm/loader.js:229:28)\n    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:51:40)\n    at link (internal/modules/esm/module_job.js:50:36) {\n  code: 'ERR_UNSUPPORTED_DIR_IMPORT',\n  url: 'file:///Users/jeff/Clients/Bummer/Code/Server/src/models'\n}\n[nodemon] app crashed - waiting for file changes before starting...\n```\n\n```text\n{\n  \"name\": \"bummer\",\n  \"type\": \"module\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"start\": \"node src/index.js\",\n    \"dev\": \"nodemon --exec babel-node src/index.js\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.9.6\",\n    \"@babel/node\": \"^7.8.7\",\n    \"@babel/preset-env\": \"^7.9.6\",\n    \"nodemon\": \"^2.0.4\",\n    \"sequelize-cli\": \"^6.2.0\"\n  },\n  \"dependencies\": {\n    \"cookie-parser\": \"^1.4.5\",\n    \"cors\": \"^2.8.5\",\n    \"dotenv\": \"^8.2.0\",\n    \"express\": \"^4.17.1\",\n    \"pg\": \"^8.2.1\",\n    \"querystring\": \"^0.2.0\",\n    \"request\": \"^2.88.2\",\n    \"sequelize\": \"^6.3.5\",\n    \"sequelize-auto-migrations\": \"^1.0.3\",\n    \"uuid\": \"^8.0.0\"\n  }\n}\n```\n\n```text\nimport cors from 'cors';\nimport express from 'express';\nimport models, { sequelize } from './models';\n// import routes from './routes';\n\n//Initiaze Express\nconst app = express();\nconst routes = require('./routes');\n\n\n//Helpers for Spotify oAuth\nconst cookieParser = require('cookie-parser')\n\n\n// Include Middleware\napp.use(express.static(__dirname + '/public'))\n   .use(cors())\n   .use(cookieParser())\n   .use(express.json())\n   .use(express.urlencoded({ extended: true }))\n   require('dotenv').config()\n\n   \n\n// Include all Models\napp.use((req, res, next) => {\n  req.context = {\n    models,\n  };\n  next();\n});\n\n\n\n// Load Routes from Router Index\napp.use('/', routes);\n\nsequelize.sync().then(() => {\n  app.listen(process.env.PORT, () => {\n    console.log(`Example app listening on port ${process.env.PORT}!`)\n  });\n});\n```\n\n```text\nimport cors from 'cors'\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nindex.js\n```\n\n```text\nscripts\": {\n    \"start\": \"node --experimental-specifier-resolution=node index\",\n    ...\n},\n```\n\n```text\n--experimental-specifier-resolution=node\n```\n\n```text\nstart\n```\n\n```text\npackage.json\n```\n\n```js\n\"scripts\": {\n  \"start\": \"node --experimental-specifier-resolution=node src/index\"\n}\n```\n\n```text\npackage.json\n```\n\n```js\nimport ... from './models'          // ❌\nimport ... from './models/index.js' // ✅\n```\n\n```bash\nnode --experimental-specifier-resolution=node main.js\n```\n\n```js\nimport {isBuiltin} from 'node:module'\n\n// noinspection JSUnusedGlobalSymbols\nexport const resolve = (specifier, context, nextResolve) => // This function can be `async` too\n  nextResolve(isBuiltin(specifier) || specifier.endsWith('.js') ? specifier : `${specifier}.js`, context)\n```\n\n```bash\nnode --loader ./loader.js some-script.js\n```\n\n```js\nimport {register} from 'node:module'\nimport {pathToFileURL} from 'node:url'\n\nregister('ts-node/esm', pathToFileURL('./'))\n```\n\n```bash\nnode --import ./ts-loader.js my-script.ts\n```\n\n```bash\nnode --import ./ts-loader.js models\n```\n\n```bash\nnode --import ./register-ts-loader.js models\n```\n\n```text\nnode --import tsx some-script.js\n```\n\n```text\ntsx some-script.js\n```\n\n```text\nindex.js\n```\n\n```text\n--experimental-specifier-resolution=node\n```\n\n```text\n--experimental-specifier-resolution\n```\n\n```text\n.js\n```\n\n```text\nloader.js\n```\n\n```text\nloader.mjs\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\n./some-script.js\n```\n\n```text\nimport\n```\n\n```text\nsome-script.js\n```\n\n```text\n.js\n```\n\n```text\nregister()\n```\n\n```text\n--import\n```\n\n```text\nregister()\n```\n\n```text\nnode:module\n```\n\n```text\n--import\n```\n\n```text\n--loader\n```\n\n```text\nts-loader\n```\n\n```text\nts-node/esm\n```\n\n```text\nts-node\n```\n\n```text\nimport\n```\n\n```text\nmodels/index.js\n```\n\n```text\nmodels/index.ts\n```\n\n```text\njs\n```\n\n```text\nts\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\nimport\n```\n\n```text\nts\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\nimport\n```\n\n```text\njsx\n```\n\n```text\ntsx\n```\n\n```text\ntsx\n```\n\n```text\n.ts\n```\n\n```text\n.tsx\n```\n\n```text\n.jsx\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- where you able to solve this . I have the same issue\n- I'm not sure this is very helpful - Node.js handles these imports fine when running locally, and just has trouble on Heroku. Maybe some configuration needs to be set on Heroku. Or could you explain why that's not the case?\n- @dan674 a bit tricky to figure out when running locally without docker, but in most cases it can be happen when there is a diffent in: node JS version, typescript version, OS etc\n- This solved for me! And if the App is a CLI Application, include `--experimental-specifier-resolution=node` in the shebang after `node`\n- Thanks! Using `node --experimental-specifier-resolution=node` worked great!\n- tsx has been growing on me for its simplicity\n- Thanks! Update package.json with below worked for me \"scripts\": { \"start\": \"npx tsx src/index.ts\", }\n- Thanks @Mir , using tsx now. I wonder why nodejs doesnt give the import directory or ts support out of the box.\n- This solution will still throw the error when importing directories\n- This doesn't work","metadata":{"transformedAt":"2026-08-18T18:33:34.337Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":64,"totalLines":600,"estimatedTokens":3245}}64{"id":"stack-14889055","source":"stackoverflow","questionId":14889055,"title":"Nodejs with Sequelizejs using separate files per model","tags":["node.js","sequelize.js"],"text":"Title: Nodejs with Sequelizejs using separate files per model\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThis is an embarrassingly beginner question, but I just want to settle my worries about Sequelizejs. I want to split out each model into its own file to keep my source organized. In order to do that I need to `require(\"sequelize')` and `var sequelize = new Sequelize('DB-Name', 'DB-User', 'DB-Password');` at the start of each file.\n\nMy question is, will that create a new connection to the database per model, or will it just keep re-using the same connection? Should I abandon the whole concept of \"one model per file\" and just create a master Models.js file?\n\nI am very new to Node and am still getting used to its conventions. Thanks for the help!\n\n========================================\n\nTop Answer:\nIn case if one wants to use EcmaScript 6 approach there is great example with explanation in Sequelize documentation here.\n\n```\n// in your server file - e.g. app.js\nconst Project = sequelize.import(__dirname + \"/path/to/models/project\")\n\n// The model definition is done in /path/to/models/project.js\n// As you might notice, the DataTypes are the very same as explained above\nmodule.exports = (sequelize, DataTypes) => {\n return sequelize.define(\"project\", {\n name: DataTypes.STRING,\n description: DataTypes.TEXT\n })\n}\n```\n\nThe import method can also accept a callback as an argument.\n\n```\nsequelize.import('project', (sequelize, DataTypes) => {\n return sequelize.define(\"project\", {\n name: DataTypes.STRING,\n description: DataTypes.TEXT\n })\n})\n```\n\n========================================\n\nCode:\n```text\nrequire(\"sequelize')\n```\n\n```text\nvar sequelize = new Sequelize('DB-Name', 'DB-User', 'DB-Password');\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes){\n    return sequelize.define('Brand', {\n        name: {\n            type: DataTypes.STRING,\n            unique: true,\n            allowNull: false },\n        description: {\n            type: DataTypes.TEXT,\n            allowNull: false },\n        status: {\n            type: DataTypes.INTEGER,\n            unique: false,\n            allowNull: true }\n    })\n};\n```\n\n```text\nvar Sequelize = require(\"sequelize\");\nvar config = require(\"../../config/config.js\");\nvar sequelize = new Sequelize(config.database, config.username, config.password,\n    { dialect: config.dialect, host: config.host, port: config.port,\n      omitNull: true, logging: false });\nvar Brand = require(\"./Brand\").Brand;\n```\n\n```text\n// in your server file - e.g. app.js\nconst Project = sequelize.import(__dirname + \"/path/to/models/project\")\n\n// The model definition is done in /path/to/models/project.js\n// As you might notice, the DataTypes are the very same as explained above\nmodule.exports = (sequelize, DataTypes) => {\n  return sequelize.define(\"project\", {\n    name: DataTypes.STRING,\n    description: DataTypes.TEXT\n  })\n}\n```\n\n```text\nsequelize.import('project', (sequelize, DataTypes) => {\n  return sequelize.define(\"project\", {\n    name: DataTypes.STRING,\n    description: DataTypes.TEXT\n  })\n})\n```\n\n========================================\n\nComments:\n- I had just found a good solution very similar to what you posted. The only difference is I made use of `sequelize.import('.&#47;File')` function. Either way works though! Thanks for another alternative.\n- dankohn, I tried above code I had to pass the reference of sequelize and Sequelize like below, please confirm if I missed something that is causing not work with exact code as you have shared `var Brand = require(\".&#47;dto&#47;brand\")(sequelize, Sequelize);`\n- My code is 5 years old, so please edit if necessary to make it work in the current version.\n- @DanKohn fyi - nodejs module link broken\n- I got it working with: `const { Sequelize, Model, DataTypes, Op } = require('sequelize');` and then `const Brand= require('..&#47;path&#47;to&#47;brand.js')(sequelize, DataTypes)`\n- fyi - sequelize.import is deprecated (see same link you posted) [sequelize.org/master/manual/models-definition.html#import]","metadata":{"transformedAt":"2026-08-18T18:33:34.337Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":111,"estimatedTokens":1011}}65{"id":"stack-22627258","source":"stackoverflow","questionId":22627258,"title":"How does group by works in sequelize?","tags":["javascript","sql","orm","sequelize.js","query-builder"],"text":"Title: How does group by works in sequelize?\nTags: javascript, sql, orm, sequelize.js, query-builder\nSource: Stack Overflow\n\nQuestion:\nI am looking for `group by` queries through Sequelize and cannot seem to find any documentation.\n\n```\nSELECT column, count(column) \n FROM table \n GROUP BY column\n```\n\n========================================\n\nTop Answer:\nI think you looking for something like this:\n\n```\nTable.findAll({\n attributes: ['column1', \n sequelize.fn('count', sequelize.col('column2'))], \n group: [\"Table.column1\"]\n }).success(function (result) { });\n```\n\n**Update:** Newer versions of Sequelize uses **.then** instead of **.success**.\n\n```\nTable.findAll({\n attributes: ['column1', \n sequelize.fn('count', sequelize.col('column2'))], \n group: [\"Table.column1\"]\n }).then(function (result) { });\n```\n\n========================================\n\nCode:\n```sql\nSELECT column, count(column)  \n    FROM table \n    GROUP BY column\n```\n\n```text\ngroup by\n```\n\n```text\nUser.findAll({\n group: ['field']\n})\n```\n\n```text\nTable.findAll({\n   attributes: ['column1', \n     sequelize.fn('count', sequelize.col('column2'))], \n   group: [\"Table.column1\"]\n }).success(function (result) { });\n```\n\n```text\nTable.findAll({\n   attributes: ['column1', \n     sequelize.fn('count', sequelize.col('column2'))], \n   group: [\"Table.column1\"]\n }).then(function (result) { });\n```\n\n```text\nfunction getSumsBySomeId() {\n  const criteria = {\n    attributes: ['some_id', [sequelize.fn('sum', sequelize.col('some_count')), 'some_count_sum']],\n    group: ['some_id'],\n    raw: true\n  };\n  return Table.getAll(criteria);\n}\n```\n\n```text\n{ some_id: 42, some_count_sum: 100 },\n{ some_id: 43, some_count_sum: 150 }\n...\netc.\n```\n\n```text\nUser.findAll({\n      attributes: ['field', [sequelize.fn('count', sequelize.col('field')), 'cnt']],\n      group: ['field'],\n})\n```\n\n```text\nsequelize ORM\n```\n\n```text\n'field'\n```\n\n```text\nfield(column)\n```\n\n```text\n'count'\n```\n\n```text\ncount\n```\n\n```text\nsequelize\n```\n\n```text\n'cnt'\n```\n\n```text\ncount\n```\n\n```text\n3.25.0\n```\n\n```text\nTable.count(\n{\n   attributes: ['column'], \n   group: 'column',\n}\n```\n\n```text\nTable.findAll({ attributes: ['column1', sequelize.fn('count', sequelize.col('column2'))],   group: [\"Table.column1\"]  }).then( (result) => { })\n```\n\n```text\nTable.findAll({\n     group: ['column']\n})\n```\n\n```text\n#!/usr/bin/env node\n// https://cirosantilli.com/sequelize-example\nconst assert = require('assert')\nconst { DataTypes, Op } = require('sequelize')\nconst common = require('./common')\nconst sequelize = common.sequelize(__filename, process.argv[2])\n;(async () => {\nconst UserLikesPost = sequelize.define('UserLikesPost', {\n  userId: {\n    type: DataTypes.INTEGER,\n  },\n  postId: {\n    type: DataTypes.INTEGER,\n  },\n}, {})\nawait UserLikesPost.sync({force: true})\nawait UserLikesPost.create({userId: 1, postId: 1})\nawait UserLikesPost.create({userId: 1, postId: 2})\nawait UserLikesPost.create({userId: 1, postId: 3})\nawait UserLikesPost.create({userId: 2, postId: 1})\nawait UserLikesPost.create({userId: 2, postId: 2})\nawait UserLikesPost.create({userId: 3, postId: 1})\nawait UserLikesPost.create({userId: 4, postId: 1})\n// Count likes on all posts but:\n// - don't consider likes userId 4\n// - only return posts that have at least 2 likes\n// Order posts by those with most likes first.\nconst postLikeCounts = await UserLikesPost.findAll({\n  attributes: [\n    'postId',\n    [sequelize.fn('COUNT', '*'), 'count'],\n  ],\n  group: ['postId'],\n  where: { userId: { [Op.ne]: 4 }},\n  order: [[sequelize.col('count'), 'DESC']],\n  having: sequelize.where(sequelize.fn('COUNT', '*'), Op.gte, 2)\n})\nassert.strictEqual(postLikeCounts[0].postId, 1)\nassert.strictEqual(parseInt(postLikeCounts[0].get('count'), 10), 3)\nassert.strictEqual(postLikeCounts[1].postId, 2)\nassert.strictEqual(parseInt(postLikeCounts[1].get('count'), 10), 2)\nassert.strictEqual(postLikeCounts.length, 2)\nawait sequelize.close()\n})()\n```\n\n```text\nconst path = require('path');\n\nconst { Sequelize } = require('sequelize');\n\nfunction sequelize(filename, dialect, opts) {\n  if (dialect === undefined) {\n    dialect = 'l'\n  }\n  if (dialect === 'l') {\n    return new Sequelize(Object.assign({\n      dialect: 'sqlite',\n      storage: path.parse(filename).name + '.sqlite'\n    }, opts));\n  } else if (dialect === 'p') {\n    return new Sequelize('tmp', undefined, undefined, Object.assign({\n      dialect: 'postgres',\n      host: '/var/run/postgresql',\n    }, opts));\n  } else {\n    throw new Error('Unknown dialect')\n  }\n}\nexports.sequelize = sequelize\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.5.1\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\nSELECT\n  \"postId\",\n  COUNT('*') AS \"count\"\nFROM\n  \"UserLikesPosts\" AS \"UserLikesPost\"\nWHERE\n  \"UserLikesPost\".\"userId\" != 4\nGROUP BY\n  \"postId\"\nHAVING\n  COUNT('*') >= 2\nORDER BY\n  \"count\" DESC;\n```\n\n```text\nrow.get('count')\n```\n\n```text\nrow.count\n```\n\n```text\ncount\n```\n\n```text\n.get()\n```\n\n```text\nattribute\n```\n\n```text\nparseInt\n```\n\n```text\ncount\n```\n\n```text\nORDER BY\n```\n\n```text\nWHERE\n```\n\n```text\nHAVING\n```\n\n```text\nJOIN\n```\n\n```text\nGROUP BY\n```\n\n```text\nSELECT key, COUNT(ref) FROM MyModel GROUP BY key\n```\n\n```text\nconst results = await MyModel.findAll({\n    attributes: ['key', [Sequelize.fn('COUNT', Sequelize.col('ref')), 'count']],\n    group: ['key']\n  });\n```\n\n```text\nresults.map(r => r.getDataValue('count'))\n```\n\n```text\n(MyModel & { count: number })[]\n```\n\n```text\ngetDataValue\n```\n\n```text\ngroup: ['field']\n```\n\n```text\nGROUP BY\n```\n\n```text\nCOUNT, SUM, AVG, MAX, or MIN\n```\n\n========================================\n\nComments:\n- although it can group it cannot execute the above. I am using a raw query now\n- Wow, this is great. How did you know that?\n- Newer versions of sequelize now use `.then(function (result) { });` instead of `.success(function (result) { });`\n- is there any documentation on this?\n- @Ante docs.sequelizejs.com/en/latest/docs/models-usage/&hellip;\n- @mparnisari sorry, I missed this part \"Everything you see below can also be done for group\"\n- No worries. @user964287 this should be marked as the correct answer!\n- Awesome answer is awesome. I've been struggling a bit with sequelize's documentation. This was of much help.\n- This is a very important answer. if you were to leave out 'attributes' then all columns get selected, and you might get an error like `column \"id\" must appear in the GROUP BY clause or be used in an aggregate function`, so i had to exclude column \"id\". you can do that by implicitly excluding it, or only including the column that needed grouping, like this answer shows\n- Meaningless SQL query\n- That is what's on their documentation, I wouldn't be on stackoverflow looking for answers if that example is useful enough. Right really useless.","metadata":{"transformedAt":"2026-08-18T18:33:34.337Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":44,"totalLines":350,"estimatedTokens":1713}}66{"id":"stack-29904939","source":"stackoverflow","questionId":29904939,"title":"Writing Migrations with Foreign Keys Using SequelizeJS","tags":["node.js","database-migration","sequelize.js"],"text":"Title: Writing Migrations with Foreign Keys Using SequelizeJS\nTags: node.js, database-migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**The Background**\n\nI'm building a project with SequelizeJS, a popular ORM for NodeJS. When designing a schema, there appears to be two tactics:\n\n- Create model code and use the .sync() function to automatically generate tables for your models.\n\n- Create model code and write manual migrations using QueryInterface and umzug.\n\nMy understanding is that #1 is better for rapid prototyping, but that #2 is a best practice for projects that are expected to evolve over time and where production data needs to be able to survive migrations.\n\nThis question pertains to tactic #2.\n\n**The Question(s)**\n\nMy tables have relationships which must be reflected through foreign keys.\n\nHow do I create tables with foreign key relationships with one another through the Sequelize QueryInterface?\n\nWhat columns and helper tables are required by Sequelize? For example, it appears that specific columns such as createdAt or updatedAt are expected.\n\n========================================\n\nTop Answer:\nI want to offer another **more manual alternative** because when using manual migrations and queryInterface I ran across the following problem: I had 2 files in the migration folder like so\n\n```\nmigrations/create-project.js\nmigrations/create-projectType.js\n```\n\nbecause `project` had column `projectTypeId` it referenced `projectType`, which wasnt created yet due to the order of the files and this was causing an error.\n\nI solved it by adding a foreign key constraint after creating both tables. In my case I decided to write it inside `create-projectType.js`:\n\n```\nqueryInterface.createTable('project_type', {\n // table attributes ...\n})\n.then(() => queryInterface.addConstraint('project', ['projectTypeId'], {\n type: 'FOREIGN KEY',\n name: 'FK_projectType_project', // useful if using queryInterface.removeConstraint\n references: {\n table: 'project_type',\n field: 'id',\n },\n onDelete: 'no action',\n onUpdate: 'no action',\n}))\n```\n\n========================================\n\nCode:\n```text\nqueryInterface.createTable('users', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  }\n}).then(function() {\n  queryInterface.createTable('user_emails', {\n    userId: {\n      type: Sequelize.INTEGER,\n      references: { model: 'users', key: 'id' }\n    }\n  })\n});\n```\n\n```text\nqueryInterface.createTable('users', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  createdAt: {\n    type: Sequelize.DATE\n  },\n  updatedAt: {\n    type: Sequelize.DATE\n  }\n}\n```\n\n```text\n.createTable()\n```\n\n```text\n.define()\n```\n\n```text\n[attributes.column.*]\n```\n\n```text\nusers\n```\n\n```text\nuser_emails\n```\n\n```text\nid\n```\n\n```text\nupdatedAt\n```\n\n```text\ncreatedAt\n```\n\n```text\nparanoid\n```\n\n```text\ntrue\n```\n\n```text\ndeletedAt\n```\n\n```text\nmigrations/create-project.js\nmigrations/create-projectType.js\n```\n\n```text\nqueryInterface.createTable('project_type', {\n  // table attributes ...\n})\n.then(() => queryInterface.addConstraint('project', ['projectTypeId'], {\n  type: 'FOREIGN KEY',\n  name: 'FK_projectType_project', // useful if using queryInterface.removeConstraint\n  references: {\n    table: 'project_type',\n    field: 'id',\n  },\n  onDelete: 'no action',\n  onUpdate: 'no action',\n}))\n```\n\n```text\nproject\n```\n\n```text\nprojectTypeId\n```\n\n```text\nprojectType\n```\n\n```text\ncreate-projectType.js\n```\n\n```text\nqueryInterface.createTable('Images', {\n\n  //...\n\n}).then(\n\n  return queryInterface.addConstraint('Images', ['postId'], {\n\n    type: 'foreign key',\n\n    name: 'custom_fkey_images',\n\n    references: { //Required field\n\n      table: 'Posts',\n\n      field: 'id'\n\n    },\n\n    onDelete: 'cascade',\n\n    onUpdate: 'cascade'\n\n  })\n)\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nsequelize migration:create --name add-area_id-in-users\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n        return Promise.all([\n          queryInterface.addColumn('users', 'region_id',\n            {\n              type: Sequelize.UUID,\n              references: {\n                model: 'regions',\n                key: 'id',\n              },\n              onUpdate: 'CASCADE',\n              onDelete: 'SET NULL',\n              defaultValue: null, after: 'can_maintain_system'\n            }),\n        ]);\n      },\n\n      down: (queryInterface, Sequelize) => {\n        return Promise.all([\n          queryInterface.removeColumn('users', 'region_id'),\n        ]);\n      }\n    };\n```\n\n========================================\n\nComments:\n- For people ending up here, this answer is fine but the syntax is now deprecated, use the following : *references: { model: 'users', key: 'id' }*\n- you should also remove *referencesKey: 'id'* ;)\n- (herp derp, that's what I get for using StackOverflow on a holiday)\n- How do you define references to multiple entities? So if I wanted to have it so that the \"users\" table has a column that references multiple rows in \"user_emails\" (instead of the current example where the \"user_emails\" row references one row in \"users\").\n- @Vinay I may be misunderstanding, but the nature of a foreign key is that it has to reference a primary key (there can only be one row per primary key value by definition) -- which means the referenced table would only have ONE row that contains that value. You could flip the relationship, so that user emails has the primary key, and users has the foreign key (so more than one user could point to the same email)\n- @slifty I see. Table architecture is not my strong suit. :-) I do remember from my database class that this is the case, so you're correct.\n- @slifty thanks for the detailed answer. It helped a lot.\n- First link is outdated.\n- when i remove the column in another migration (or the down migration), do i need to explicitly remove the reference, too?\n- @FreTimmerman I would ask that as a separate question!\n- Nice! one note -- you may want to consider naming your migrations with orders to start the filename, to ensure they are processed in the desired order regardless of table name (e.g. `01-create-projecttype.js`, `02-create-project.js`). This is also important because as you edit / add tables you can keep your old migration steps in tact (e.g. `03-edit-projecttype.js`).\n- @slifty thank you - i actually started doing just that! hope v4 of the cli has support for multiple migration folders\n- It helped! I was doing a silly mistake where I have defined the different type in both primary and foreign key columns and due to which I have suffered for a couple of mins. Finally worked :)\n- For anyone reading this in 2022, you should probably use sequelize-cli to create migration files for you using sequelize migration:generate --name [my_migration_name] as it automatically adds a timestamp before [my_migration_name] therefore saving you the hassle of having to order your migrations manually\n- Thank you for this. It helped me fix a related issue (adding back a foreign key constraint). And as it has already been mentioned above, we should use sequelize-cli to create the migration files to ensure proper order.\n- Hi, OP asked two questions and you answered no one. Please edit your answer and add some description to your solution. Make sure that you're answering OP's questions.","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":260,"estimatedTokens":1845}}67{"id":"stack-41595755","source":"stackoverflow","questionId":41595755,"title":"Sequelize Sync vs Migrations","tags":["node.js","sequelize.js"],"text":"Title: Sequelize Sync vs Migrations\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIm learning Sequelize and I'd like some clarification around syncing vs migrations.\n\nI understand that sync will create missing tables based on my model schema but I have also read that sync is meant for initializing the database whereas migrations are meant for production.\n\nIf that is the case, the express-example shows calling sync from `bin/www`. Is that something that should not be used in production?\n\nAs an extension of this, if I am not to use sync in production, how do you apply model associations? Do I need to add them to migrations manually?\n\nEssentially I am asking for an explanation of how these two concepts are meant to work together.\n\nThanks\n\n========================================\n\nCode:\n```text\nbin/www\n```\n\n========================================\n\nComments:\n- Thanks for the answer. That article is a good resource. Am I to presume then that adding `underscored: true` or `onDelete: 'cascade'` to the model's JS definition (not the migration) will have no affect if sync is not called?\n- Just discovered that your link is a scraped version of this SO question: stackoverflow.com/questions/21105748/&hellip; The SO version has more information so maybe change your link to the SO instead.","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":29,"estimatedTokens":328}}68{"id":"stack-33775165","source":"stackoverflow","questionId":33775165,"title":"Auto increment id with sequelize in MySQL","tags":["mysql","node.js","sequelize.js"],"text":"Title: Auto increment id with sequelize in MySQL\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following model in NodeJS with sequelize and a MySQL database:\n\n```\nvar Sequelize = require('sequelize');\nvar User = sequelize.define('user', { \n id: {\n type: Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n ...\n};\n```\n\nI am trying to add a new user to my databse with the below code:\n\n```\nsequelize.transaction().then(function(t) {\n User.create({/* User data without id */}, {\n transaction: t\n }).then(function() {\n t.commit();\n }).catch(function(error) {\n t.rollback();\n });\n });\n```\n\nAfter that, I am getting the next error:\n\n```\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): START TRANSACTION;\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET autocommit = 1;\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): INSERT INTO `user` (`id`, /* next fields */) VALUES (DEFAULT, /* next values */);\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): ROLLBACK;\n```\n\nAnd the error message:\n\n```\n[SequelizeDatabaseError: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value]\n name: 'SequelizeDatabaseError',\n message: 'ER_NO_DEFAULT_FOR_FIELD: Field \\'id\\' doesn\\'t have a default value'\n```\n\nHowever, if I manually set the id value, it works. It seems sequelize is trying to set a default value in the id field, instead setting an autoincrement integer. I have defined this field as autoIncrement in my database too. \n\nHow could I do this insertion? Do I have to set the id manually?\n\n**EDIT**\n\nThis is my table definition:\n\n```\nCREATE TABLE `user` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `uid` varchar(9) NOT NULL,\n `name` varchar(20) NOT NULL,\n `email` varchar(30) DEFAULT NULL,\n `birthdate` date NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `uid_UNIQUE` (`uid`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n```\n\n========================================\n\nTop Answer:\nIn migration, add this line of code:\n\n```\nawait queryInterface.sequelize.query(\"ALTER TABLE table_name AUTO_INCREMENT = 1000000;\");\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\nvar User = sequelize.define('user', {        \n        id: {\n            type: Sequelize.INTEGER,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        ...\n};\n```\n\n```text\nsequelize.transaction().then(function(t) {\n        User.create({/* User data without id */}, {\n            transaction: t\n        }).then(function() {\n            t.commit();\n        }).catch(function(error) {\n            t.rollback();\n        });\n    });\n```\n\n```text\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): START TRANSACTION;\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET autocommit = 1;\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): INSERT INTO `user` (`id`, /* next fields */) VALUES (DEFAULT, /* next values */);\nExecuting (47f19f7b-a02d-4d72-ba7e-d5045520fffb): ROLLBACK;\n```\n\n```text\n[SequelizeDatabaseError: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value]\n  name: 'SequelizeDatabaseError',\n  message: 'ER_NO_DEFAULT_FOR_FIELD: Field \\'id\\' doesn\\'t have a default value'\n```\n\n```text\nCREATE TABLE `user` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `uid` varchar(9) NOT NULL,\n  `name` varchar(20) NOT NULL,\n  `email` varchar(30) DEFAULT NULL,\n  `birthdate` date NOT NULL,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `uid_UNIQUE` (`uid`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('cake3', 'root', 'root', {\n    define: {\n        timestamps: false\n    },\n});\nvar User = sequelize.define('user1', {        \n        id: {\n            type: Sequelize.INTEGER,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        name: {\n            type: Sequelize.STRING\n        }\n});\n\nsequelize.transaction().then(function(t) {\n    User.create({name:'test'}, {\n        transaction: t\n    }).then(function() {\n        t.commit();\n    }).catch(function(error) {\n        console.log(error);\n        t.rollback();\n    });\n});\n```\n\n```text\nCREATE TABLE `user1s` (\n  `id` int(11) NOT NULL,\n  `name` varchar(20) NOT NULL\n) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;\nALTER TABLE `user1s`\n  ADD PRIMARY KEY (`id`);\nALTER TABLE `user1s`\n  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;\n```\n\n```text\nid\n```\n\n```js\nawait queryInterface.sequelize.query(\"ALTER TABLE table_name AUTO_INCREMENT = 1000000;\");\n```\n\n========================================\n\nComments:\n- @Genzotto Even I am facing this same issue, But I didn't understand why did you give the initial value for the primary key(autoincrement)? and How did you do it?\n- stackoverflow.com/questions/4678110/&hellip;\n- Your code helped me to discover my problem. In my table definition, I setted the id column as AUTO_INCREMENT, but I didn't set its initial value (AUTO_INCREMENT=1). Now it works beautifly. Thank you very much!\n- Have you checked if you have NO_AUTO_VALUE_ON_ZERO? github.com/sequelize/sequelize/issues/5493\n- Please add more details how to use this line of code","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":190,"estimatedTokens":1334}}69{"id":"stack-40654766","source":"stackoverflow","questionId":40654766,"title":"How to increase max_locks_per_transaction","tags":["macos","postgresql","sequelize.js"],"text":"Title: How to increase max_locks_per_transaction\nTags: macos, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've been performing kind of intensive schema dropping and creating over a PostgreSQL server,\n\n ERROR: out of shared memory\n\n \n HINT: You might need to increase max_locks_per_transaction.\n\nI need to increase max_locks_per_transaction but how can i increase it in **MAC OSX**\n\n========================================\n\nTop Answer:\nIt is a setting in your postgresql.conf if you do not know where that file is run `SHOW config_file;` on an sql prompt/window.\n\nThen when you have modified that file restart postgresql, I don't know how you do that on MacOS a reboot will work of course.\n\n========================================\n\nCode:\n```text\nSHOW config_file;\n```\n\n```text\ndocker exec -it <container_id_or_name> sh\n```\n\n```text\ncd /var/lib/postgresql/data\n```\n\n```text\nsed -i 's/^max_locks_per_transaction = .*/max_locks_per_transaction = new_value/' postgresql.conf\n```\n\n========================================\n\nComments:\n- If you installed Postgres using Brew, you can `brew services restart postgresql`\n- And if you use the app, you can click on the systray icon. In that menu, you first \"stop\", then \"start\".\n- Location of this file in Mac (Postgres was installed using Homebrew) is `&#47;usr&#47;local&#47;var&#47;postgres&#47;`\n- Can we set max_locks_per_transaction using query ?\n- Yes, the query is `ALTER SYSTEM set max_locks_per_transaction = 1024`","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":370}}70{"id":"stack-41519695","source":"stackoverflow","questionId":41519695,"title":"How to get a distinct value of a row with sequelize?","tags":["node.js","express","sequelize.js"],"text":"Title: How to get a distinct value of a row with sequelize?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have table with value\n\n```\nid country \n1 india\n2 usa\n3 india\n```\n\nI need to find the distinct values from the country column using sequelize.js\n\nhere my sample code...\n\n```\nProject.findAll({\n\n attributes: ['country'],\n distinct: true\n}).then(function(country) {\n ...............\n});\n```\n\nIs there any way to find the distict values\n\n========================================\n\nTop Answer:\nYou can specify distinct for one or more attributes using `Sequelize.fn`\n\n```\nProject.findAll({\n attributes: [\n // specify an array where the first element is the SQL function and the second is the alias\n [Sequelize.fn('DISTINCT', Sequelize.col('country')) ,'country'],\n\n // specify any additional columns, e.g. country_code\n // 'country_code'\n\n ]\n}).then(function(country) { })\n```\n\n========================================\n\nCode:\n```text\nid country \n1  india\n2  usa\n3  india\n```\n\n```text\nProject.findAll({\n\n    attributes: ['country'],\n    distinct: true\n}).then(function(country) {\n     ...............\n});\n```\n\n```text\nProject.aggregate('country', 'DISTINCT', { plain: false })\n.then(...)\n```\n\n```text\nProject.findAll({\n    attributes: [\n        // specify an array where the first element is the SQL function and the second is the alias\n        [Sequelize.fn('DISTINCT', Sequelize.col('country')) ,'country'],\n\n        // specify any additional columns, e.g. country_code\n        // 'country_code'\n\n    ]\n}).then(function(country) {  })\n```\n\n```text\nSequelize.fn\n```\n\n```text\nProject.findAll({\n  attributes: ['country'],\n  group: ['country']\n}).then(projects => \n  projects.map(project => project.country)\n);\n```\n\n```text\nProject.aggregate('country', 'DISTINCT', { plain: false })\n  .then(...)\n```\n\n```js\nconst countries = await Project.findAll({\n  attributes: [\n    [Sequelize.fn(\"MAX\", Sequelize.col(\"id\")), \"id\"],\n    \"country\",\n  ],\n  group: [\"country\"],\n});\n```\n\n```sql\nSELECT MAX(`id`) AS `id`, `country` FROM `project` GROUP BY `country`;\n```\n\n```text\ngroup\n```\n\n```text\nincompatible with sql_mode=only_full_group_by\n```\n\n```text\nMAX\n```\n\n```text\nsequelize.fn()\n```\n\n```text\nProject.findAll({\n  attributes: ['country'],\n  distinct: true,\n  col: '__Column name you want to distinct with__'\n}).then(function(country) {\n     ...............\n});\n```\n\n```text\nProject.findAll({\n  where: {....}\n  attributes: ['country'],\n  include: [.....],\n  distinct: true,\n  col: '__Column name you want to distinct with__'\n}).then(function(country) {\n...............\n});\n```\n\n```text\nProject.findAll({\n    attributes: [\n        // specify an array where the first element is the SQL function and the second is the alias\n        [Sequelize.fn('DISTINCT', Sequelize.col('country')) ,'country'],\n\n        // specify any additional columns, e.g. country_code\n        // 'country_code'\n\n    ]\n}).then(function(country) {  })\n```\n\n```text\nconst query = {\n  attributes: [ ['DISTINCT (label)','label'], 'fieldId'],\n  raw: true \n};\nconst labelsAndFields = (await TableModel.findAll(query));\n```\n\n========================================\n\nComments:\n- how do you alias the 'DISTINCT' column name? It returns a table in which the column name is 'DISTINCT'\n- how can you make sure it's distinct but also latest (via createdAt)\n- SequelizeDatabaseError: syntax error at or near \"DISTINCT\"\n- @MuhammadUmer: did you find out the correct syntax?\n- I ended up writing sql query, which was much easier and also did manual work in js\n- using MySQL, this solution works - make sure to use the DISTINCT field as the first attribute.\n- @Endel how ? because sequelize always override the position of the distinct column\n- this works fine for postgres. @MuhammadUmer, which database did you use ?\n- The above syntax works provided you are not including another model, on adding include it throws `SequelizeDatabaseError: syntax error at or near \"DISTINCT\"`\n- The issue for me was that *Sequelize* wanted to prefix the columns list with the primary key of the model, which causes `SELECT id, DISTINCT col1, col2` instead of `SELECT DISTINCT col1, col2`. No matter what I tried, it never worked, and the problem was always that one. Eventually, the solution was cryptic and easy enough: I just needed to add `raw: true` to the options of `findAll`. BTW, here is the documentation of that option: \"If true, sequelize will not try to format the results of the query, or build an instance of a model from the result\". Now, tell me if that's not even more cryptic!","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":190,"estimatedTokens":1137}}71{"id":"stack-37817808","source":"stackoverflow","questionId":37817808,"title":"Counting associated entries with Sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: Counting associated entries with Sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two tables, `locations` and `sensors`. Each entry in `sensors` has a foreign key pointing to `locations`. Using Sequelize, how do I get all entries from `locations` and total count of entries in `sensors` that are associated with each entry in `locations`?\n\nRaw SQL:\n\n```\nSELECT \n `locations`.*,\n COUNT(`sensors`.`id`) AS `sensorCount` \nFROM `locations` \nJOIN `sensors` ON `sensors`.`location`=`locations`.`id`;\nGROUP BY `locations`.`id`;\n```\n\nModels:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var Location = sequelize.define(\"Location\", {\n id: {\n type: DataTypes.INTEGER.UNSIGNED,\n primaryKey: true\n },\n name: DataTypes.STRING(255)\n }, {\n classMethods: {\n associate: function(models) {\n Location.hasMany(models.Sensor, {\n foreignKey: \"location\"\n });\n }\n }\n });\n\n return Location;\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n var Sensor = sequelize.define(\"Sensor\", {\n id: {\n type: DataTypes.INTEGER.UNSIGNED,\n primaryKey: true\n },\n name: DataTypes.STRING(255),\n type: {\n type: DataTypes.INTEGER.UNSIGNED,\n references: {\n model: \"sensor_types\",\n key: \"id\"\n }\n },\n location: {\n type: DataTypes.INTEGER.UNSIGNED,\n references: {\n model: \"locations\",\n key: \"id\"\n }\n }\n }, {\n classMethods: {\n associate: function(models) {\n Sensor.belongsTo(models.Location, {\n foreignKey: \"location\"\n });\n\n Sensor.belongsTo(models.SensorType, { \n foreignKey: \"type\"\n });\n }\n }\n });\n\n return Sensor;\n};\n```\n\n========================================\n\nTop Answer:\n**For Counting associated entries with Sequelize**\n\n```\nLocation.findAll({\n attributes: { \n include: [[Sequelize.fn('COUNT', Sequelize.col('sensors.location')), 'sensorCounts']] \n }, // Sequelize.col() should contain a attribute which is referenced with parent table and whose rows needs to be counted\n include: [{\n model: Sensor, attributes: []\n }],\n group: ['sensors.location'] // groupBy is necessary else it will generate only 1 record with all rows count\n})\n```\n\n**Note :** \n\nSome how, this query generates a error like **sensors.location is not exists in field list.** This occur because of subQuery which is formed by above sequelize query.\n\nSo solution for this is to provide subQuery: false like example\n\n```\nLocation.findAll({\n subQuery: false,\n attributes: { \n include: [[Sequelize.fn('COUNT', Sequelize.col('sensors.location')), 'sensorCounts']] \n },\n include: [{\n model: Sensor, attributes: []\n }],\n group: ['sensors.location']\n })\n```\n\n**Note:**\n**Sometime this could also generate a error bcz of mysql configuration which by default contains only-full-group-by in sqlMode, which needs to be removed for proper working.\n\nThe error will look like this..**\n\nError : Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db.table.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n\nSo to resolve this error this answer\n\nSELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by\n\nNow this will successfully generate all associated counts\n\nHope this will help you or somebody else!\n\n========================================\n\nCode:\n```text\nSELECT \n    `locations`.*,\n    COUNT(`sensors`.`id`) AS `sensorCount` \nFROM `locations` \nJOIN `sensors` ON `sensors`.`location`=`locations`.`id`;\nGROUP BY `locations`.`id`;\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var Location = sequelize.define(\"Location\", {\n        id: {\n            type: DataTypes.INTEGER.UNSIGNED,\n            primaryKey: true\n        },\n        name: DataTypes.STRING(255)\n    }, {\n        classMethods: {\n            associate: function(models) {\n                Location.hasMany(models.Sensor, {\n                    foreignKey: \"location\"\n                });\n            }\n        }\n    });\n\n    return Location;\n};\n\n\nmodule.exports = function(sequelize, DataTypes) {\n    var Sensor = sequelize.define(\"Sensor\", {\n        id: {\n            type: DataTypes.INTEGER.UNSIGNED,\n            primaryKey: true\n        },\n        name: DataTypes.STRING(255),\n        type: {\n            type: DataTypes.INTEGER.UNSIGNED,\n            references: {\n                model: \"sensor_types\",\n                key: \"id\"\n            }\n        },\n        location: {\n            type: DataTypes.INTEGER.UNSIGNED,\n            references: {\n                model: \"locations\",\n                key: \"id\"\n            }\n        }\n    }, {\n        classMethods: {\n            associate: function(models) {\n                Sensor.belongsTo(models.Location, {\n                    foreignKey: \"location\"\n                });\n\n                Sensor.belongsTo(models.SensorType, { \n                    foreignKey: \"type\"\n                });\n            }\n        }\n    });\n\n    return Sensor;\n};\n```\n\n```text\nlocations\n```\n\n```text\nsensors\n```\n\n```text\nsensors\n```\n\n```text\nlocations\n```\n\n```text\nlocations\n```\n\n```text\nsensors\n```\n\n```text\nlocations\n```\n\n```text\nLocation.findAll({\n    attributes: { \n        include: [[Sequelize.fn(\"COUNT\", Sequelize.col(\"sensors.id\")), \"sensorCount\"]] \n    },\n    include: [{\n        model: Sensor, attributes: []\n    }]\n});\n```\n\n```text\nLocation.findAll({\n    attributes: { \n        include: [[Sequelize.fn(\"COUNT\", Sequelize.col(\"sensors.id\")), \"sensorCount\"]] \n    },\n    include: [{\n        model: Sensor, attributes: []\n    }],\n    group: ['Location.id']\n})\n```\n\n```text\nfindAll()\n```\n\n```text\ninclude()\n```\n\n```text\nsequelize.fn()\n```\n\n```text\nCOUNT\n```\n\n```text\ngroup\n```\n\n```text\nLocation.findAll({\n        attributes: { \n            include: [[Sequelize.fn(\"COUNT\", Sequelize.col(\"sensors.id\")), \"sensorCount\"]] \n        },\n        include: [{\n            model: Sensor, attributes: []\n        }]\n    });\n```\n\n```text\nLocation.findAll({\n    attributes: { \n        include: [[Sequelize.fn('COUNT', Sequelize.col('sensors.location')), 'sensorCounts']] \n    }, // Sequelize.col() should contain a attribute which is referenced with parent table and whose rows needs to be counted\n    include: [{\n        model: Sensor, attributes: []\n    }],\n    group: ['sensors.location'] // groupBy is necessary else it will generate only 1 record with all rows count\n})\n```\n\n```text\nLocation.findAll({\n        subQuery: false,\n        attributes: { \n            include: [[Sequelize.fn('COUNT', Sequelize.col('sensors.location')), 'sensorCounts']] \n        },\n        include: [{\n            model: Sensor, attributes: []\n        }],\n        group: ['sensors.location']\n    })\n```\n\n```text\nCREATE OR REPLACE VIEW view_location_sensors_count AS\nselect \"locations\".id as \"locationId\", count(\"sensors\".id) as \"locationSensorsCount\"\nfrom locations\nleft outer join sensors on sensors.\"locationId\" = location.id\ngroup by location.id\n```\n\n```text\nconst { Model, DataTypes } = require('sequelize')\n\nconst attributes = {\n    locationID: {\n        type: DataTypes.UUIDV4, // Or whatever data type is your location ID\n        primaryKey: true,\n        unique: true\n    },\n    locationSensorsCount: DataTypes.INTEGER\n}\n\nconst options = {\n    paranoid: false,\n    modelName: 'ViewLocationSensorsCount',\n    tableName: 'view_location_sensors_count',\n    timestamps: false\n}\n\n\n/**\n * This is only a database view. It is not an actual table, so \n * DO NOT ATTEMPT insert, update or delete statements on this model\n */\nclass ViewLocationSensorsCount extends Model {\n    static associate(models) {\n        ViewLocationSensorsCount.removeAttribute('id')\n        ViewLocationSensorsCount.belongsTo(models.Location, { as:'location', foreignKey: 'locationID' })\n    }\n\n\n    static init(sequelize) {\n        this.sequelize = sequelize\n        return super.init(attributes, {...options, sequelize})\n    }\n}\n\nmodule.exports = ViewLocationSensorsCount\n```\n\n```text\nconst assert = require('assert');\nconst { DataTypes, Op, Sequelize } = require('sequelize');\nconst sequelize = new Sequelize('tmp', undefined, undefined, Object.assign({\n  dialect: 'sqlite',\n  storage: 'tmp.sqlite'\n}));\n;(async () => {\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(Post, {through: 'UserLikesPost'});\nPost.belongsToMany(User, {through: 'UserLikesPost'});\nawait sequelize.sync({force: true});\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\nconst post0 = await Post.create({body: 'post0'})\nconst post1 = await Post.create({body: 'post1'})\nconst post2 = await Post.create({body: 'post2'})\n// Set likes for each user.\nawait user0.addPosts([post0, post1])\nawait user1.addPosts([post0, post2])\n\nlet rows = await User.findAll({\n  attributes: [\n    'name',\n    [sequelize.fn('COUNT', sequelize.col('Posts.id')), 'count'],\n  ],\n  include: [\n    {\n      model: Post,\n      attributes: [],\n      required: false,\n      through: {attributes: []},\n      where: { id: { [Op.ne]: post2.id }},\n    },\n  ],\n  group: ['User.name'],\n  order: [[sequelize.col('count'), 'DESC']],\n  having: sequelize.where(sequelize.fn('COUNT', sequelize.col('Posts.id')), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].get('count'), 10), 1)\nassert.strictEqual(rows[1].name, 'user2')\nassert.strictEqual(parseInt(rows[1].get('count'), 10), 0)\nassert.strictEqual(rows.length, 2)\n})().finally(() => { return sequelize.close() });\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.5.1\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\nlet rows = await User.findAll({\n  attributes: [\n    'name',\n    [sequelize.fn('COUNT', '*'), 'count'],\n  ],\n  include: [\n    {\n      model: Post,\n      attributes: [],\n      through: {attributes: []},\n      where: { id: { [Op.ne]: post2.id }},\n    },\n  ],\n  group: ['User.name'],\n  order: [[sequelize.col('count'), 'DESC']],\n  having: sequelize.where(sequelize.fn('COUNT', '*'), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].get('count'), 10), 1)\nassert.strictEqual(rows.length, 1)\n```\n\n```text\nHAVING\n```\n\n```text\nORDER BY\n```\n\n```text\nINNER\n```\n\n```text\nOUTER\n```\n\n```text\nrow.get('count')\n```\n\n```text\nrow.count\n```\n\n```text\nparseInt\n```\n\n```text\ncolumn X must appear in the GROUP BY clause or be used in an aggregate function\n```\n\n```text\nOUTER JOIN\n```\n\n```text\nrequired: false\n```\n\n```text\nINNER JOIN\n```\n\n========================================\n\nComments:\n- Is that actually the `SQL` you want? I don't think that's going to do what you think it will. In fact, I'm not sure that query will run without throwing an error.\n- @dvlsg I run it and it correctly returned all the rows and fields in the `locations` table and for each row the right number of associated entries in `sensors`.\n- Actually @dvlsg, it isn't right. I did some more testing (with more entries in `locations` table) and it turned out I had forgot a `GROUP BY` statement. I've edited the question.\n- Ah, okay. That makes more sense. I thought maybe MySQL was pulling some shenanigans I wasn't aware of (and I know they do that with implicit `GROUP` statements, so it wasn't entirely unreasonable).\n- stackoverflow.com/questions/52496842/&hellip;\n- Thanks for your answer. This correctly counts the `sensourCount` field but it also includes fields from `sensors` table in the results. Also, although the SQL query it executes shows it includes all fields from the `locations` table, they aren't included in the result (the object it returns in the `then` clause).\n- @MikkoP okay, let me quickly build a sample and debug, thanks.\n- @MikkoP could you please edit the question and post your model definitions? Thanks.\n- I added the model definitions. Here's what your query outputs. pastebin.com/PwnctW1Y\n- @MikkoP thanks, please see the update. I think you should be able to achieve the desired result now. Thanks.\n- Now it produces the correct SQL query, but the returned object is still lacking the fields from `locations`. Adding `raw: true` I see all the right fields. pastebin.com/arv2ip3D\n- Changing the `attributes` value to `attributes: { include: [[Sequelize.fn(\"COUNT\", Sequelize.col(\"sensors.id\")), \"sensorCount\"]] }` solved the problem.\n- @MikkoP great, fixed the answer to reflect your changes. Thanks.\n- It still needs the `include` part, but great! Thanks for your help!\n- stackoverflow.com/questions/52496842/&hellip;\n- @Shareef it will be fixed when you can add query option `subQuery:false` ex: `attributes:{},include:[{}],subQuery:false` and you find more detail in github.com/sequelize/sequelize/issues/&hellip;\n- you can try subQuery: false in query option.\n- @BhavyaSanchaniya Thanks by adding subQuery: false I am able to use limit and offset\n- Cool, but what if you want to add a condition to the sensors table. For example, in the table there is a user_id field, how can we filter there? Is that possible?\n- Yes you can, pass the where attribute inside include 0th index object along with model and attributes","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":516,"estimatedTokens":3314}}72{"id":"stack-27972271","source":"stackoverflow","questionId":27972271,"title":"Sequelize: don't return password","tags":["sequelize.js","password-storage"],"text":"Title: Sequelize: don't return password\nTags: sequelize.js, password-storage\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize to do a DB find for a user record, and I want the default behavior of the model to **not** return the `password` field for that record. The `password` field is a hash but I still don't want to return it.\n\nI have several options that will work, but none seems particularly good:\n\nCreate a custom class method `findWithoutPassword` for the `User` model and within that method do a `User.find` with the `attributes` set as shown in the Sequelize docs\n\nDo a normal `User.find` and filter the results in the controller (not preferred)\n\nUse some other library to strip off unwanted attributes\n\nIs there a better way? Best of all would be if there is a way to specify in the Sequelize model definition to never return the `password` field, but I haven't found a way to do that.\n\n========================================\n\nTop Answer:\nAnother way is to add a default scope to the User model.\n\nAdd this in the model's options object\n\n```\ndefaultScope: {\n attributes: { exclude: ['password'] },\n}\n```\n\nOr you can create a separate scope to use it only in certain queries.\n\nAdd this in the model's options object\n\n```\nscopes: {\n withoutPassword: {\n attributes: { exclude: ['password'] },\n }\n}\n```\n\nThen you can use it in queries\n\n```\nUser.scope('withoutPassword').findAll();\n```\n\n========================================\n\nCode:\n```text\npassword\n```\n\n```text\npassword\n```\n\n```text\nfindWithoutPassword\n```\n\n```text\nUser\n```\n\n```text\nUser.find\n```\n\n```text\nattributes\n```\n\n```text\nUser.find\n```\n\n```text\npassword\n```\n\n```text\nsequelize.define('user', attributes, {\n  instanceMethods: {\n    toJSON: function () {\n      var values = Object.assign({}, this.get());\n\n      delete values.password;\n      return values;\n    }\n  }\n});\n```\n\n```text\nconst User = sequelize.define('user', attributes, {});\n\nUser.prototype.toJSON =  function () {\n  var values = Object.assign({}, this.get());\n\n  delete values.password;\n  return values;\n}\n```\n\n```text\ntoJSON\n```\n\n```text\ntoJSON\n```\n\n```text\nObject.assign\n```\n\n```text\ntoJSON\n```\n\n```text\nget\n```\n\n```text\nthis.constructor.super_.prototype.toJSON.apply(this, arguments)\n```\n\n```text\nvar User = sequelize.define('user', attributes);\n\nUser.findAll({\n    attributes: {\n        exclude: ['password']\n    }\n});\n```\n\n```text\nexclude\n```\n\n```text\nfind\n```\n\n```text\ndefaultScope: {\n  attributes: { exclude: ['password'] },\n}\n```\n\n```text\nscopes: {\n  withoutPassword: {\n    attributes: { exclude: ['password'] },\n  }\n}\n```\n\n```text\nUser.scope('withoutPassword').findAll();\n```\n\n```text\ndefaultScope: {\n    attributes: { exclude: ['password'] },\n},\nscopes: {\n    withPassword: {\n        attributes: { },\n    }\n}\n```\n\n```text\nuserModel.scope('withPassword').findAll()\n```\n\n```text\naccountModel.findAll({\n    include: [{\n        model: userModel,\n        as: 'user'\n    }]\n})\n```\n\n```text\nwithPassword\n```\n\n```js\nconst Sequelize = require('sequelize')\n\nconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname')\n\nconst PROTECTED_ATTRIBUTES = ['password', 'token']\n\nconst Model = Sequelize.Model\n\nclass User extends Model {\n  toJSON () {\n    // hide protected fields\n    let attributes = Object.assign({}, this.get())\n    for (let a of PROTECTED_ATTRIBUTES) {\n      delete attributes[a]\n    }\n    return attributes\n  }\n}\n\nUser.init({\n  email: {\n    type: Sequelize.STRING,\n    unique: true,\n    allowNull: false,\n    validate: {\n      isEmail: true\n    }\n  },\n  password: {\n    type: Sequelize.STRING,\n    allowNull: false\n  },\n  token: {\n    type: Sequelize.STRING(16),\n    unique: true,\n    allowNull: false\n  },\n},\n{\n  sequelize,\n  modelName: 'user'\n})\n\nmodule.exports = User\n```\n\n```text\nfirstName: {\n      type: DataTypes.STRING,\n      get() {\n        return undefined;\n      }\n    }\n```\n\n```text\nundefined\n```\n\n```text\nfullName\n```\n\n```text\nfirstName\n```\n\n```text\nlastName\n```\n\n```text\ndefaultScope\n```\n\n```text\nPatient.findByPk(id, {\n            attributes: {\n              exclude: ['UserId', 'DiseaseId'] // Removing UserId and DiseaseId from Patient response data\n            },\n            include: [\n              { \n                model: models.Disease\n              },\n              {\n                model: models.User,\n                attributes: {\n                  exclude: ['password'] // Removing password from User response data\n                }\n              }\n           ]\n    })\n    .then(data => {\n        res.status(200).send(data);\n    })\n    .catch(err => {\n        res.status(500).send({\n            message: `Error retrieving Patient with id ${id} : ${err}`\n        });\n    });\n```\n\n========================================\n\nComments:\n- This is an interesting approach. Would this preclude ever getting the password (or other blacklisted attributes) out of the model?\n- EDIT: this is not filtering out the password for me. Looks like the instanceMethod `toJSON` isn't getting called for the return of either `user.get()` or `user.dataValues`. Should I be using another method to return attributes?\n- You should either call `toJSON`, or just return the user object. For example `res.send(200, user)` will internally call `JSON.stringify` on the user object, which in turn calls `toJSON`\n- IMPORTANT! If you the above to the letter, `delete values.password` will actually remove the password attribute *from the user instance* - not just JSON output. Use `var values = Object.assign({}, this.get())` or appropriate polyfill to avoid mutating the actual user's properties.\n- got error while using above code `Unhandled rejection Error: TypeError: Cannot read property 'get' of undefined`\n- @AkshayPratapSingh Are you using an arrow function?\n- @JanAagaardMeier yeah\n- You can't do that in this case - we use `.bind` to set the context to the instance - But you can't do that with arrow functions\n- This will work if you're just creating a JSON representation of a user. BUT! If you include a user from another model, the `toJSON` that gets called is the other models! This will cause you to leak your hashed password out when user's are eagerly loaded. See this: github.com/sequelize/sequelize/issues/3891\n- this does not work anymore with sequelize 4, instanceMethods are deprecated, replace with this Model.prototype.someMethod = function () {..}, according to this docs.sequelizejs.com/manual/tutorial/&hellip;\n- I want to exclude certain attributes after a `create` - is that possible? The `toJSON` approach is doing it all the time, that is not working for me.\n- Instead of `Object.assign({}, this.get())` you can use `this.get({ clone: true })`\n- ES syntax makes this nice and tidy: `{ ...this.get(), password: undefined }`\n- This method will only work when directly fetching this model. It will not exclude the attribute through associations. So, if you fetch `UserTransactions` and include `Users`, the user password will show up in the response. The `defaultScope` answer below solves this problem.\n- Is there any why to override the `toJSON` function for all Models at once and not per each Model?\n- adding the block of `attributes` to each query is not so good. a way to define exclude attributes on the model level to apply all queries is needed!\n- IMPORTANT! This is the only answer that worked for me. It is important to know that accepted anwser will work ONLY if you directly fetch user model. If you include user model throug another model toJSON functio in user model will not get called and you will leak your passwords to the client!!\n- that's the best answer. I don't know why that is not on the top.\n- NOTE: This answer works fine but the excluded field will still be exposed for `create`. Overriding `toJSON` protects the field from being exposed during create.\n- @DeanKoštomaj .Using toJSON worked fine for me when using include in findAll. The deleted field wasn't included.\n- @DeanKoštomaj. Noticed the problem when I tried including Parent in the child.\n- This still works in Sequelize 5. Also, it's a great solution!\n- @nonybrighto Wouldn't you want to expose the password field for `create`? Its needed to set the user's password when their account gets created.\n- @pawan samdani Yes, It is needed, but if you will send the created user as JSON after creation, you will also be sending the password too.\n- This comment brought exactly what I needed but I still didn't know. Very good thank you!! Below is a link to the scope definitions sequelize.org/master/manual/scopes.html\n- @nonybrighto Thanks for highlighting that security flaw with this solution! The best fix I found is to add `await user.reload();` in an `afterCreate` hook for the model.\n- For people who want to use the scope way inside an include for relational tables: include: { model: models.users.scope('withoutPassword'), as: \"developer\" },\n- This should be the best practice!\n- Thanks for the hint. I struggled for an hour to find the solution where I needed to hide the column but show in some virtual field.","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":330,"estimatedTokens":2250}}73{"id":"stack-38757728","source":"stackoverflow","questionId":38757728,"title":"using an enviroment variable for local sequelize configuration","tags":["mysql","json","node.js","environment-variables","sequelize.js"],"text":"Title: using an enviroment variable for local sequelize configuration\nTags: mysql, json, node.js, environment-variables, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm looking to use an environment variable inside of the config.json file of my project using sequelize. I'm using dotenv to set environment variables locally. My config.json file looks like this\n\n```\n{\n \"development\": {\n \"username\": process.env.DB_USER,\n \"password\": process.env.DB_PASS,\n \"database\": process.env.DB_DATABASE,\n \"host\": process.env.DB_HOST,\n \"dialect\": \"mysql\"\n },\n \"test\": {\n \"username\": \"root\",\n \"password\": null,\n \"database\": \"database_test\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"mysql\"\n },\n \"production\": {\n \"use_env_variable\": \"JAWSDB_URL\",\n \"dialect\": \"mysql\"\n }\n}\n```\n\nThe issue I'm having is that I can't use variables inside the config.json file. It looks like for production I can use the \"use_env_varable\" key and use the env variable for my connection string. So I guess I either need a way to figure out the combined connection string for my local mysql db or a way to use variables inside the config.json. Any solutions?\n\n========================================\n\nTop Answer:\nI worked on this for quite a bit. I do not know why Sequelize does not use production when it is literally in the environment if you run `heroku run bash`. I was able to get it working by modifying the Sequelize object depending on the `JAWSDB_URL`, not the `NODE_ENV`. \n\n```\nrequire(\"dotenv\").config();\nconst express = require(\"express\")\nconst app = express();\nlet seq;\n\n//express app configuration\n\nif (process.env.JAWSDB_URL) {\n console.log(\"There is a JAWS DB URL\")\n seq = new Sequelize(process.env.JAWSDB_URL)\n}\nelse {\n seq = require(\"./models\").sequelize\n}\nseq.sync().then(() => {\n app.listen(PORT, () => console.log('server started on port ' + PORT));\n})\n```\n\n========================================\n\nCode:\n```text\n{\n  \"development\": {\n    \"username\": process.env.DB_USER,\n    \"password\": process.env.DB_PASS,\n    \"database\": process.env.DB_DATABASE,\n    \"host\": process.env.DB_HOST,\n    \"dialect\": \"mysql\"\n  },\n  \"test\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"database\": \"database_test\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\"\n  },\n  \"production\": {\n    \"use_env_variable\": \"JAWSDB_URL\",\n    \"dialect\": \"mysql\"\n  }\n}\n```\n\n```text\nrequire('dotenv').config(); // this is important!\nmodule.exports = {\n\"development\": {\n    \"username\": process.env.DB_USERNAME,\n    \"password\": process.env.DB_PASSWORD,\n    \"database\": process.env.DB_DATABASE,\n    \"host\": process.env.DB_HOST,\n    \"dialect\": \"mysql\"\n},\n\"test\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"database\": \"database_test\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\"\n},\n\"production\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"database\": \"database_production\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\"\n}\n};\n```\n\n```text\n\"config\": path.resolve('./config', 'config.js'),\n```\n\n```text\nconfig.json\n```\n\n```text\nconfig.js\n```\n\n```text\nrequire\n```\n\n```text\ndotenv\n```\n\n```text\n.sequelizerc\n```\n\n```text\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\n```\n\n```text\nvar sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD, config);\n```\n\n```text\nDB_USERNAME:root (or whatever your username is)\nDB_PASSWORD:NYB (whatever your password is)\nDB_DATABASE:whatever_your_dbNameis_db\n```\n\n```text\nuser.sequelize.sync().then(function(){\n}...\n```\n\n```text\nuser.sequelize.sync().then(function(){\n     database:\"process.env.dbn\"\n}...\n```\n\n```text\ndatabase:process.env.DB_DATABASE\n```\n\n```js\nrequire(\"dotenv\").config();\nconst express = require(\"express\")\nconst app = express();\nlet seq;\n\n//express app configuration\n\nif (process.env.JAWSDB_URL) {\n    console.log(\"There is a JAWS DB URL\")\n    seq = new Sequelize(process.env.JAWSDB_URL)\n}\nelse {\n    seq = require(\"./models\").sequelize\n}\nseq.sync().then(() => {\n  app.listen(PORT, () => console.log('server started on port ' + PORT));\n})\n```\n\n```text\nheroku run bash\n```\n\n```text\nJAWSDB_URL\n```\n\n```text\nNODE_ENV\n```\n\n```text\nvar path = require('path');\nmodule.exports = { \n'config': path.resolve('server/config', 'config.js'),\n'models-path': path.resolve('server/models'),\n'seeders-path': path.resolve('server/seeders'),\n'migrations-path': path.resolve('server/migrations')}\n```\n\n```text\nconst dotenv = require(\"dotenv\");\ndotenv.config({ path: \"config.env\" });\n\nmodule.exports = {\n  development: {\n    username: process.env.DB_USERNAME,\n    password: process.env.DB_PASSWORD,\n    database: process.env.DB_DBNAME,\n    host: process.env.DB_HOST,\n    dialect: process.env.DB_DIALECT,\n    encrypt: process.env.DB_ENCRYPT,\n    pool: {\n      max: parseInt(process.env.DB_POOL_MAX),\n      min: parseInt(process.env.DB_POOL_MIN),\n      acquire: parseInt(process.env.DB_POOL_ACQUIRE),\n      idle: parseInt(process.env.DB_POOL_IDLE),\n    },\n  },\n```\n\n```text\nconst fs = require('fs');\nrequire('dotenv').config();\n\nmodule.exports = {\n  \"development\": {\n    \"username\": process.env.DB_USERNAME,\n    \"password\": process.env.DB_PASSWORD,\n    \"database\": process.env.DB_DATABASE,\n    \"host\": process.env.DB_HOST,\n    \"dialect\": process.env.DB_CONNECTION\n  },\n  \"test\": {\n    \"username\": process.env.DB_USERNAME,\n    \"password\": process.env.DB_PASSWORD,\n    \"database\": process.env.DB_DATABASE,\n    \"host\": process.env.DB_HOST,\n    \"dialect\": process.env.DB_CONNECTION\n  },\n  \"production\": {\n    \"username\": process.env.DB_USERNAME,\n    \"password\": process.env.DB_PASSWORD,\n    \"database\": process.env.DB_DATABASE,\n    \"host\": process.env.DB_HOST,\n    \"dialect\": process.env.DB_CONNECTION\n  }\n};\n```\n\n```text\nrequire('dotenv').config();\n\nmodule.exports = {\n\n    \"development\": {\n        username :process.env.DB_USERNAME,\n        password: process.env.DB_PASSWORD,\n        database: process.env.DB_NAME,\n        host : process.env.DB_HOST,\n        \"dialect\": \"mysql\"\n    },\n    \"production\": {\n        username :process.env.PRO_DB_USERNAME,\n        password: process.env.PRO_DB_PASSWORD,\n        database: process.env.PRO_DB_NAME,\n        host : process.env.PRO_DB_HOST,\n        \"dialect\": \"mysql\"\n     }\n }\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n    'config' : path.resolve('database/config','config.js'),\n    'models-path' : path.resolve('database','models'),\n    'migrations-path' : path.resolve('database','migrations'),\n}\n```\n\n```text\nconst config = require(__dirname + '/../config/config.js')[env];\n```\n\n========================================\n\nComments:\n- Just a hunch, the link above to see how to update your .sequelizerc file from their documentation .sequelizerc docs\n- After struggling for an hour, then try googling and find your answer. My problem is solved. Thank you\n- How can i make it work with NextJS where I'm not able to use dotenv?\n- for new version of sequelize to import `config.js` move to `models&#47;index.js` and change this line `const config = require(__dirname + \"&#47;..&#47;config&#47;config.json\")[env];` to `const config = require(\"..&#47;config&#47;config\")[env];`\n- One thing I forgot to add is you may have to drop(reset) your database/table in order to for this work.","metadata":{"transformedAt":"2026-08-18T18:33:34.338Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":298,"estimatedTokens":1806}}74{"id":"stack-20718534","source":"stackoverflow","questionId":20718534,"title":"Sort sequelize.js query by date","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sort sequelize.js query by date\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\nPost\n .findAll({where: {tag: 'news'}, limit: 10})\n .success(function(result) { ... })\n```\n\nHow to insert the condition of sorting by date in my query with not using `sequelize.query` like\n\n```\n.findAll({ limit: 10, sort: [updatedAt, descending]})\n```\n\n========================================\n\nTop Answer:\nHere's the syntax:\n\n```\nPost.findAll({ limit: 10, order: '\"updatedAt\" DESC' })\n```\n\nHere are more examples from the official documentation.\n\n========================================\n\nCode:\n```text\nPost\n  .findAll({where: {tag: 'news'}, limit: 10})\n  .success(function(result) { ... })\n```\n\n```text\n.findAll({ limit: 10, sort: [updatedAt, descending]})\n```\n\n```text\nsequelize.query\n```\n\n```text\nPost.findAll({ limit: 10, order: [['updatedAt', 'DESC']]});\n```\n\n```text\nPost.findAll({ limit: 10, order: '\"updatedAt\" DESC' })\n```\n\n```text\nPost.findAll({ limit: 10, order: 'updatedAt DESC'});\n```\n\n========================================\n\nComments:\n- Appears to no longer work in newer versions of Sequelize (I'm using 4.4), but Clarkie's answer worked. The error message I received from this method seems to indicate that it was deprecated: \"Unhandled rejection Error: Order must be type of array or instance of a valid sequelize method.\"\n- Not sure that is a good way to delete answer, maybe it's better that you custom mod flag, explaining why it should be deleted, since also after Clarkie's answer needs an edit.\n- Deprecated. `Unhandled rejection Error: Order must be type of array or instance of a valid sequelize method.`\n- @Sandwich Should be like `Post.findAll({ limit: 10, order: [ ['updatedAt', 'DESC'] ] })` in new versions. Edit: did not see last response.\n- OP please update to show which version your answer is correct for. I have Sequelize version 6.0.0 which requires the array [\"FIELD\", \"ASC\"] be nested inside another array as described by @Clarkie\n- my god sequelize has a really terrible API.\n- Correct answer, selected answer is deprecated.\n- This one worked like a charm! Selected one is deprecaated.\n- Can we apply the order on the basis of does value exist in the `JOIN` in sequelize. What I want is that for entries for which associated items are not there they should come in the last place.\n- Sequelize 5.21 will throw that order type must be an array.\n- Cannot be used in ealier versions of sequelize\n- Your answer is working fine. But now it was deprecated and will generate Order must be the type of array or instance of a valid sequelize method. error","metadata":{"transformedAt":"2026-08-18T18:33:34.339Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":72,"estimatedTokens":651}}75{"id":"stack-22643263","source":"stackoverflow","questionId":22643263,"title":"How to get a distinct count with sequelize?","tags":["sequelize.js"],"text":"Title: How to get a distinct count with sequelize?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to get a distinct count of a particular column using sequelize. My initial attempt is using the 'count' method of my model, however it doesn't look like this is possible.\n\nThe DISTINCT feature is needed because I am joining other tables and filtering the rows of the parent based on the related tables.\n\nhere's the query I would like:\n\n```\nSELECT COUNT(DISTINCT Product.id) as `count` \nFROM `Product` \nLEFT OUTER JOIN `Vendor` AS `vendor` ON `vendor`.`id` = `Product`.`vendorId` \nWHERE (`vendor`.`isEnabled`=true );\n```\n\nusing the following query against my Product model:\n\n```\nProduct.count({\n include: [{model: models.Vendor, as: 'vendor'}],\n where: [{ 'vendor.isEnabled' : true }]\n })\n```\n\nGenerates the following query:\n\n```\nSELECT COUNT(*) as `count` \nFROM `Product` \nLEFT OUTER JOIN `Vendor` AS `vendor` ON `vendor`.`id` = `Product`.`vendorId` \nWHERE (`vendor`.`isEnabled`=true );\n```\n\n========================================\n\nTop Answer:\n### UPDATE: New version\n\nThere are now separate `distinct` and `col` options. The docs for `distinct` state:\n\nApply COUNT(DISTINCT(col)) on primary key or on options.col.\n\nYou want something along the lines of:\n\n```\nMyModel.count({\n include: ...,\n where: ...,\n distinct: true,\n col: 'Product.id'\n})\n.then(function(count) {\n // count is an integer\n});\n```\n\n### Original Post\n\n(As mentioned in the comments, things have changed since my original post, so you probably want to ignore this part.)\n\nAfter looking at Model.count method in lib/model.js, and tracing some code, I found that when using `Model.count`, you can just add any kind of aggregate function arguments supported by MYSQL to your options object. The following code will give you the amount of different values in `MyModel`'s `someColumn`:\n\n```\nMyModel.count({distinct: 'someColumn', where: {...}})\n.then(function(count) {\n // count is an integer\n});\n```\n\nThat code effectively generates a query of this kind: `SELECT COUNT(args) FROM MyModel WHERE ...`, where `args` are all properties in the options object that are not reserved (such as `DISTINCT`, `LIMIT` and so on).\n\n========================================\n\nCode:\n```text\nSELECT COUNT(DISTINCT Product.id) as `count` \nFROM `Product` \nLEFT OUTER JOIN `Vendor` AS `vendor` ON `vendor`.`id` = `Product`.`vendorId` \nWHERE (`vendor`.`isEnabled`=true );\n```\n\n```text\nProduct.count({\n        include: [{model: models.Vendor, as: 'vendor'}],\n        where: [{ 'vendor.isEnabled' : true }]\n    })\n```\n\n```text\nSELECT COUNT(*) as `count` \nFROM `Product` \nLEFT OUTER JOIN `Vendor` AS `vendor` ON `vendor`.`id` = `Product`.`vendorId` \nWHERE (`vendor`.`isEnabled`=true );\n```\n\n```text\ncount\n```\n\n```text\nfindAndCountAll\n```\n\n```js\nMyModel.count({\n  include: ...,\n  where: ...,\n  distinct: true,\n  col: 'Product.id'\n})\n.then(function(count) {\n    // count is an integer\n});\n```\n\n```js\nMyModel.count({distinct: 'someColumn', where: {...}})\n.then(function(count) {\n    // count is an integer\n});\n```\n\n```text\ndistinct\n```\n\n```text\ncol\n```\n\n```text\ndistinct\n```\n\n```text\nModel.count\n```\n\n```text\nMyModel\n```\n\n```text\nsomeColumn\n```\n\n```text\nSELECT COUNT(args) FROM MyModel WHERE ...\n```\n\n```text\nargs\n```\n\n```text\nDISTINCT\n```\n\n```text\nLIMIT\n```\n\n```text\nModel.prototype.count = function(options) {\n  options = Utils._.clone(options || {});\n  conformOptions(options, this);\n  Model.$injectScope(this.$scope, options);\n  var col = '*';\n  if (options.include) {\n    col = this.name + '.' + this.primaryKeyField;\n    expandIncludeAll.call(this, options);\n    validateIncludedElements.call(this, options);\n  }\n  Utils.mapOptionFieldNames(options, this);\n  options.plain = options.group ? false : true;\n  options.dataType = new DataTypes.INTEGER();\n  options.includeIgnoreAttributes = false;\n  options.limit = null;\n  options.offset = null;\n  options.order = null;\n  return this.aggregate(col, 'count', options);\n};\n```\n\n```text\nmodel.findAll({\n  attributes: [\n    'category',\n    [Sequelize.literal('COUNT(DISTINCT(product))'), 'countOfProducts']\n  ],\n  group: 'category'\n})\n```\n\n```text\ncount\n```\n\n```text\nSELECT COUNT(DISTINCT(*))\n```\n\n```text\nSELECT COUNT(DISTINCT(primaryKey))\n```\n\n```text\nSELECT category, COUNT(DISTINCT(product)) as 'countOfProducts' GROUP BY category\n```\n\n```text\nSELECT COUNT(DISTINCT(`Product`.`id`)) as `count` \nFROM `Product` \nLEFT OUTER JOIN `Vendor` AS `vendor` ON `vendor`.`id` = `Product`.`vendorId` \nWHERE (`vendor`.`isEnabled`=true );\n```\n\n```text\nProduct.count({\n        include: [{model: models.Vendor, as: 'vendor'}],\n        where: [{ 'vendor.isEnabled' : true }],\n        distinct: 'id' // since count is applied on Product model and distinct is directly passed to its object so Product.id will be selected\n    });\n```\n\n```text\nlet existingUsers = await Users.count({\n        where: whereClouser,\n        attributes: [[sequelize.fn('COUNT', 0), 'count']]\n    });\n```\n\n```text\ndataModel.findAll({\n    attributes: { \n        include: [[Sequelize.literal(\"COUNT(DISTINCT(history.data_id))\"), \"historyModelCount\"]] \n    },\n    include: [{\n        model: historyModel, attributes: []\n    }],\n    group: ['data.id']\n});\n```\n\n========================================\n\nComments:\n- Why not just use a stored procedure and call it? According to this changelog (sequelizejs.com/changelog/v1-6-0) sequelize supports stored procedures. Then you can write the query in a way that's best suited for your needs, and well as optimizing it for the database you're using.\n- That could be a valid solution, are you saying there is no other way to include DISTINCT in a count operation?\n- I do not know of any other way, but other people may have ideas about a way to do it. In general, I try to use stored procedures for all DB related code for reasons such as this. And I use this approach no matter what front end technology I happen to be using. What's really nice is that then you can re-use that stored procedure as different front-end technologies are used against your DB.\n- @Adam how come you love DISTINCT and Sequelize so much?\n- @JoshC Because I love to stand out from the crowd. I'm an iconoclast.\n- I've just recently started using Sequelize, but shouldn't it be `findAndCountAll`? Maybe the method name changed between now and two years ago. Just letting people who see this know.\n- Actually the distinct parameter is a boolean parameter, which only indicates if a distinct should be used or not. distinct counts are always applied on the primary key of the model, so this solution will not work accordingly, at least not with the current sequelize version.","metadata":{"transformedAt":"2026-08-18T18:33:34.342Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":257,"estimatedTokens":1663}}76{"id":"stack-46137212","source":"stackoverflow","questionId":46137212,"title":"Sequelize select * where attribute is NOT x","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: Sequelize select * where attribute is NOT x\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nlooking at the docs you can use \n `model.findAll({where: {attribute: x}})`. However, I want to select all attributes that are simply NOT x. I was looking into a regular expression here but that seemed like not an optimal solution. \n\nWhat is the best way to do this?\n\n========================================\n\nTop Answer:\nUpdated method, for modern Sequelize:\n\n```\nmodel.findAll({\n where: {\n someAttribute: {\n [sequelize.Op.not]: 'some value'\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nmodel.findAll({where: {attribute: x}})\n```\n\n```text\nmodel.findAll({where: {attribute: { $not: 'x'}}})\n```\n\n```text\nmodel.findAll({\n  where: {\n    someAttribute: {\n      [sequelize.Op.not]: 'some value'\n    }\n  }\n});\n```\n\n```text\nmodel.findAll({\n  where: {\n    attribute: {[Op.not]:'x'}\n  }\n});\n```\n\n```text\n$not:'x\n```\n\n```text\n[Op.gt\n```\n\n```text\nmodel.findAll({\n      where: {\n        attribute: {[Op.ne]:'x'} /*eg status: {[Op.ne]:'pending'}*/\n      }\n});\n```\n\n```js\nimport {Op} from 'sequelize';\n// or const { Op } = require(\"sequelize\");\n\n  // ...\n\n  await ChatUsers.update(\n      {unread: true},\n      {where: {\n        chatId,\n        userId: {[Op.not]: req.currentUser.id},\n      }},\n  );\n```\n\n```text\nimport {Op} from 'sequelize'\n```\n\n========================================\n\nComments:\n- Update: now you are supposed to use operators: docs.sequelizejs.com/manual/tutorial/querying.html#operators\n- The operators page has moved to sequelize.org/master/manual/&hellip;\n- You can add more values `[sequelize.Op.not]: ['value1','value2'...]`\n- To use sql operators you can also just `import {Op} from 'sequelize'`, please take a look at Operators docs under Model Querying sequelize.org/docs/v6/core-concepts/model-querying-basics/&hellip;\n- Your answer could be improved by adding more information on what the code does and how it helps the OP.","metadata":{"transformedAt":"2026-08-18T18:33:34.342Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":97,"estimatedTokens":498}}77{"id":"stack-33941943","source":"stackoverflow","questionId":33941943,"title":"Nested include in sequelize?","tags":["javascript","mysql","sequelize.js","join"],"text":"Title: Nested include in sequelize?\nTags: javascript, mysql, sequelize.js, join\nSource: Stack Overflow\n\nQuestion:\nHow to perform nested include ?\nI have table products that has one to many relation with comments, and table comments has many to one relation with users table.\nSo comments has user_id, and product_id.\nMy code is like this \n\n```\nvar models = require('../models');\n\nmodels.products.findAll({\n include: [\n {model: models.comments}\n ]\n }).then(function (products) {\n next(products);\n }).catch(function (err) {\n next(err);\n });\n});\n```\n\nI get the comments, but I would like to have something like\n\n```\nmodels.products.findAll({\n include: [\n {model: models.comments.include(models.comments.users)}\n ]\n })\n```\n\nIs this possible without writing custom queries ?\n\n========================================\n\nTop Answer:\nSolution provided didn't work for me, this is the typescript version I use and guessing the sequelize versions:\n\n\r\n\r\n\n```\n// sequelize-typescript\nmodels.products.findAll({\n where,\n include: [{\n model: Comment,\n include: [User]\n }]\n});\n\n// without typescript (guessing here)\nmodels.products.findAll({\n where,\n include: [{\n model: models.comments,\n include: [{\n model: models.users\n }]\n }]\n});\n```\n\n========================================\n\nCode:\n```text\nvar models = require('../models');\n\nmodels.products.findAll({\n    include: [\n        {model: models.comments}\n    ]\n  }).then(function (products) {\n    next(products);\n  }).catch(function (err) {\n    next(err);\n  });\n});\n```\n\n```text\nmodels.products.findAll({\n    include: [\n        {model: models.comments.include(models.comments.users)}\n    ]\n  })\n```\n\n```text\nmodels.products.findAll({\n  include: [\n    {model: models.comments, include: [models.comments.users] }\n  ]\n})\n```\n\n```text\nCategory = sequelize.define(...);\nProduct = sequelize.define(...);\nProduct.belongsTo(Category, {foreignKey: 'fk_category'});\n\nProduct.findAll({\n    include: [{\n        model: Category\n    }]\n});\n```\n\n```text\ninclude\n```\n\n```text\ncategory\n```\n\n```js\n// sequelize-typescript\nmodels.products.findAll({\n  where,\n  include: [{\n    model: Comment,\n    include: [User]\n  }]\n});\n\n// without typescript (guessing here)\nmodels.products.findAll({\n  where,\n  include: [{\n    model: models.comments,\n    include: [{\n      model: models.users\n    }]\n  }]\n});\n```\n\n```text\n// Fetch all models associated with User\nUser.findAll({ include: { all: true }});\n\n// Fetch all models associated with User and their nested associations (recursively) \nUser.findAll({ include: { all: true, nested: true }});\n```\n\n```text\nUser.findAll({\n  include: [{\n    model: Contact,\n    include: [{\n      model: Address,\n      include: [{\n        model: City,\n        include: [State, Country]\n      }]\n    }]\n  }]\n});\n```\n\n```text\nUser.findAll({\n  include: { // <-- notice the missing square bracket\n    model: Contact,\n    include: { // <-- notice the missing square bracket\n      model: Address,\n      include: { // <-- notice the missing square bracket\n        model: City,\n        include: [State, Country]\n      } // <-- notice the missing square bracket\n    } // <-- notice the missing square bracket\n  } // <-- notice the missing square bracket\n});\n```\n\n```text\ninclude\n```\n\n========================================\n\nComments:\n- please add some explanation to your answer\n- This solution does not work as written (at least not in the version I have, 3.24.1). The inner include should be 'include: [models.users]'.\n- Be carefull if this is a many-to-many association. In this case you should use `hasMany` when define association.\n- This seems to compile, but I have an error on my side : column X->Y.link dos not exist. But I have in X : HasMany Y and in Y I have BelongsTo X. I don't understand why I can't include this way in typescript sequelize","metadata":{"transformedAt":"2026-08-18T18:33:34.342Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":192,"estimatedTokens":945}}78{"id":"stack-29652538","source":"stackoverflow","questionId":29652538,"title":"sequelize.js TIMESTAMP not DATETIME","tags":["mysql","node.js","datetime","timestamp","sequelize.js"],"text":"Title: sequelize.js TIMESTAMP not DATETIME\nTags: mysql, node.js, datetime, timestamp, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn my node.js app I have several models in which I want to define `TIMESTAMP` type columns, including the default timestamps `created_at` and `updated_at`. \n\nAccording to sequelize.js' documentation, there is only a `DATE` data type. It creates `DATETIME` columns in MySQL.\n\nExample:\n\n```\nvar User = sequelize.define('User', {\n... // columns\nlast_login: {\n type: DataTypes.DATE,\n allowNull: false\n },\n...\n}, { // options\n timestamps: true\n});\n```\n\nIs it possible to generate `TIMESTAMP` columns instead?\n\n========================================\n\nTop Answer:\nAccording to the Sequelize Documentation, you can set a defaultValue of Sequelize.NOW to create a timestamp field. This has the effect but relies on Sequelize to actually populate the timestamp. It does not create a \"CURRENT_TIMESTAMP' attribute on the table. \n\n```\nvar Foo = sequelize.define('Foo', {\n // default values for dates => current time\n myDate: { \n type: Sequelize.DATE, \n defaultValue: Sequelize.NOW \n }\n});\n```\n\nSo, this does accomplish the end goal of having a timestamp field, but it is controlled through Sequelize and not through the actual database engine.\n\nIt also appears to work on databases that do not have a timestamp functionality, so that may be a benefit.\n\nReference URL: http://sequelize.readthedocs.org/en/latest/docs/models-definition/#definition\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {\n... // columns\nlast_login: {\n            type: DataTypes.DATE,\n            allowNull: false\n        },\n...\n}, { // options\n        timestamps: true\n});\n```\n\n```text\nTIMESTAMP\n```\n\n```text\ncreated_at\n```\n\n```text\nupdated_at\n```\n\n```text\nDATE\n```\n\n```text\nDATETIME\n```\n\n```text\nTIMESTAMP\n```\n\n```text\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.createTable('users', {\n      id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n      },\n        created_at: {\n        type: 'TIMESTAMP',\n        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),\n        allowNull: false\n      },\n      updated_at: {\n        type: 'TIMESTAMP',\n        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),\n        allowNull: false\n      }\n    });\n  }\n};\n```\n\n```js\nfunction (sequelize, DataTypes) {\n\n    var util = require('util');\n    var timestampSqlFunc = function () {\n        var defaultSql = 'DATETIME DEFAULT CURRENT_TIMESTAMP';\n        if (this._options && this._options.notNull) {\n            defaultSql += ' NOT NULL';\n        }\n        if (this._options && this._options.onUpdate) {\n            // onUpdate logic here:\n        }\n        return defaultSql;\n    };\n    DataTypes.TIMESTAMP = function (options) {\n        this._options = options;\n        var date = new DataTypes.DATE();\n        date.toSql = timestampSqlFunc.bind(this);\n        if (!(this instanceof DataTypes.DATE)) return date;\n        DataTypes.DATE.apply(this, arguments);\n    };\n    util.inherits(DataTypes.TIMESTAMP, DataTypes.DATE);\n\n    DataTypes.TIMESTAMP.prototype.toSql = timestampSqlFunc;\n\n    var table = sequelize.define(\"table\", {\n        /* table fields */\n        createdAt: DataTypes.TIMESTAMP,\n        updatedAt: DataTypes.TIMESTAMP({ onUpdate: true, notNull: true })\n    }, {\n        timestamps: false\n    });\n\n};\n```\n\n```text\n'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'\n```\n\n```text\nvar Foo = sequelize.define('Foo', {\n    // default values for dates => current time\n    myDate: { \n         type: Sequelize.DATE, \n         defaultValue: Sequelize.NOW \n    }\n});\n```\n\n```text\nmodule.exports = (sequelize, type) => {\n    return sequelize.define('blog', {\n        blogId: {\n          type: type.INTEGER,\n          primaryKey: true,\n          autoIncrement: true\n        },\n        text: type.STRING,\n        createdAt:{\n            type: 'TIMESTAMP',\n            defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),\n            allowNull: false\n        },\n        updatedAt:{\n            type: 'TIMESTAMP',\n            defaultValue: sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),\n            allowNull: false\n        }\n    })\n}\n```\n\n```text\ntype: DataTypes.DATE,\n```\n\n```text\ncreatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n        defaultValue: Sequelize.fn('NOW'),\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n        defaultValue: Sequelize.fn('NOW'),\n      },\n```\n\n```text\nconst moment = require('moment-timezone');\n\n    createdAt: {\n      type: DataTypes.NOW,\n      allowNull: false,\n      defaultValue: moment.utc().format('YYYY-MM-DD HH:mm:ss'),\n      field: 'createdAt'\n    },\n```\n\n========================================\n\nComments:\n- i couldn't get this to work. it kept putting `0000-00-00 00:00` in the db. sequelize 6 w/ mysql 5.7\n- It looks like sequelize 6 has changed to use a slightly different syntax: DataTypes.DATE and DataTypes.NOW for the values. sequelize.org/master/manual/model-basics.html#dates Not sure if that's the issue, but it does appear there are some relevant changes in sequelize 6.\n- I tried that as well, but no luck. Only alucic's answer worked for me.\n- this no longer works in sequelize 6, it throws error, anyone know the new method to create `timestamp` columns instead of `datetime` columns?\n- It is NOT Sequelize.literal. It MUST BE sequelize.literal\n- Working fine with mariadb as of dec-2022","metadata":{"transformedAt":"2026-08-18T18:33:34.342Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":221,"estimatedTokens":1385}}79{"id":"stack-48209543","source":"stackoverflow","questionId":48209543,"title":"Sequelize timestamp names","tags":["node.js","sequelize.js"],"text":"Title: Sequelize timestamp names\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a small issue with sequelize that I can't get around and it irritates the hell out of me. \n\nI'm using camelCase for all my model attributes but I'm using snake case to persist them into the database (postgres). That part works fine except if I want to use sequelize timestamps option.\n\nIf I set `underscored: false`, timestamps get persisted to the database in camelCase.\n\nIf I set `underscored: true`, they get persisted in snake_case but then they are in snake_case on the model. \n\n**What I want to achieve is snake_case in the database and camelCase on the model for model timestamps.** \n\nIt feels like those 2 options are mutually exclusive. \n\nThank you\n\n========================================\n\nTop Answer:\nYou can do some workaround like this:\n\n**UPDATE:** As Sergey stated in his answer, we need to keep `timestamp` option to be `true`, so I fixed that.\n\n```\nnew Sequelize(foo, bar, baz, {\n define: {\n timestamps: true,\n underscored: true\n createdAt: {\n type: DataTypes.DATE,\n defaultValue: DataTypes.NOW,\n name: 'createdAt',\n field: 'created_at'\n }\n updatedAt: {\n type: DataTypes.DATE,\n name: 'updatedAt',\n field: 'updated_at'\n }\n }\n});\n```\n\n**Related issue**\n\n========================================\n\nCode:\n```text\nunderscored: false\n```\n\n```text\nunderscored: true\n```\n\n```text\ncreatedAt: { type: Sequelize.DATE, field: 'created_at' },\nupdatedAt: { type: Sequelize.DATE, field: 'updated_at' },\ndeletedAt: { type: Sequelize.DATE, field: 'deleted_at' }\n```\n\n```text\ntimestamps: true,\nunderscored: true\n```\n\n```text\nparanoid\n```\n\n```text\nnew Sequelize(foo, bar, baz, {\n  define: {\n    timestamps: true,\n    underscored: true\n    createdAt: {\n        type: DataTypes.DATE,\n        defaultValue: DataTypes.NOW,\n        name: 'createdAt',\n        field: 'created_at'\n    }\n    updatedAt: {\n        type: DataTypes.DATE,\n        name: 'updatedAt',\n        field: 'updated_at'\n    }\n  }\n});\n```\n\n```text\ntimestamp\n```\n\n```text\ntrue\n```\n\n```text\nsequelize.define('model', {\n}, {\n  timestamps: true,\n  createdAt: 'created_at',\n  updatedAt: 'updated_at'\n})\n```\n\n```text\nnew Sequelize(process.env.DATABASE_URL, {\n   ......,\n   define: {\n      createdAt: 'created_at',\n      updatedAt: 'updated_at',\n      deletedAt: 'deleted_at'\n   },\n   ......\n})\n```\n\n========================================\n\nComments:\n- Sorry, incorrect, I achieved what topic starter asking for in my projects. According to your config, updatedAt will not be updated automatically on update, since it is not managed by Sequelize.\n- @SergeyYarotskiy There is no automated way of doing this. Check the related issue. So I showed a workaround.\n- As I said, it works fine for me in production currently.\n- @SergeyYarotskiy Yeah okay but yours is also workaround? There is a need to modify the field mappings in both cases.\n- Yes, agree, but in my case, result will be exactly as desired. Sequelize will manage these fields correctly. That's what the question was. And in your case updatedAt will not be updated. Don't see the reason for downvote, since my answer is totally correct. If not, please leave a constructive comment.\n- My answer was \"No you cannot do this for timestamps\", (automatically). So it is true. I showed a workaround and related Github issue. Also updated the answer. Sorry for inconvenience @SergeyYarotskiy\n- Let us continue this discussion in chat.\n- This works for me as well. Note the example shows this on the `new Sequelize` call. However, this (the `define` portion) is usually defined in your `config.js` file along with your connection options and then called inside `new Sequelize`\n- This is closest you can get with current version of sequlize, but it's also a hacky way to achieve what you want. I went with this solution, but I'm still not 100% happy. Reason is when I'm serializing the result I get fields `createdAt` and `created_at`. So I've created a custom toJSON method that will remove the duplicate `_at` timestamps. All in all, the best solution currently possible. Thank you both and @gokcand and @Sergey Yarotskiy for your discussion, but I will except this answer because it did come first.","metadata":{"transformedAt":"2026-08-18T18:33:34.342Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":135,"estimatedTokens":1052}}80{"id":"stack-22341138","source":"stackoverflow","questionId":22341138,"title":"Get Sequelize.js ENUM Values from Already Defined Model","tags":["node.js","enums","sequelize.js"],"text":"Title: Get Sequelize.js ENUM Values from Already Defined Model\nTags: node.js, enums, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do we get the ENUM values of a model after defining it in Sequelize.js?\n\nFor example, we define our model as:\n\n```\nsequelize.define('model', {\n states: {\n type: Sequelize.ENUM,\n values: ['active', 'pending', 'deleted']\n }\n})\n```\n\nHow do we get the pre-defined `['active', 'pending' ,'deleted']` values from this model?\n\n========================================\n\nTop Answer:\nCreate JavaScript Enum Object like that\n\n```\nmodule.exports.BookingStatus = Object.freeze({\n Done: 'Done',\n Pending: 'Pending',\n Rejected: 'Rejected'\n});\n```\n\nNext, is to create sequalize Schema having enum\n\n```\nconst Booking = sequalize.define(\n 'booking',\n {\n customerId : DataTypes.STRING,\n bookingStatus : {\n type : DataTypes.ENUM,\n values : Object.values(this.BookingStatus),\n defaultValue : this.BookingStatus.Pending\n },\n },\n {\n timestamps: true,\n }\n);\n```\n\n========================================\n\nCode:\n```text\nsequelize.define('model', {\n  states: {\n    type:   Sequelize.ENUM,\n    values: ['active', 'pending', 'deleted']\n  }\n})\n```\n\n```text\n['active', 'pending' ,'deleted']\n```\n\n```text\nvar Model = sequelize.define('model', {\n  states: {\n    type:   Sequelize.ENUM,\n    values: ['active', 'pending', 'deleted']\n  }\n});\n\nconsole.log(Model.rawAttributes.states.values);\n// logs ['active', 'pending', 'deleted'] in console\n```\n\n```text\nrawAttributes\n```\n\n```text\nsequelize.define('model', {\n  states: {\n    type:   Sequelize.ENUM('active', 'pending', 'deleted')\n  }\n})\n```\n\n```text\nmodule.exports.BookingStatus = Object.freeze({\n  Done: 'Done',\n  Pending: 'Pending',\n  Rejected: 'Rejected'\n});\n```\n\n```text\nconst Booking = sequalize.define(\n  'booking',\n  {\n    customerId : DataTypes.STRING,\n    bookingStatus : {\n      type : DataTypes.ENUM,\n      values : Object.values(this.BookingStatus),\n      defaultValue :  this.BookingStatus.Pending\n    },\n  },\n  {\n    timestamps: true,\n  }\n);\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.342Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":116,"estimatedTokens":503}}81{"id":"stack-62917111","source":"stackoverflow","questionId":62917111,"title":"sequelize.import is not a function","tags":["node.js","sequelize.js"],"text":"Title: sequelize.import is not a function\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to express.\n\nI want to import files to sequelize and declared:\n\n```\nconst model = sequelize.import(path.join(__dirname, file))\n\n ^\n```\n\nIt returned the following type error\n\n```\nTypeError: sequelize.import is not a function\n```\n\nAnd then, edited code to\n\n```\nvar model = require(path.join(__dirname, file))(sequelize, Sequelize);\n\n ^\n```\n\nThen the error is:\n\n```\nTypeError: require(...) is not a function\n```\n\nI think it is the error in importing stuff....\n\nHere is my whole file code:\n\n```\nconst fs = require('fs');\n\nconst path = require('path');\n\nconst Sequelize = require('sequelize');\n\nconst config = require('../config/config');\n\nconst db = {}\n\nvar __dirname = path.resolve();\n\nconst sequelize = new Sequelize(\n config.db.database,\n config.db.user,\n config.db.password,\n config.db.options\n)\n\nfs\n\n .readdirSync(__dirname)\n\n .filter((file) =>\n file !== 'index.js'\n )\n\n .forEach((file) => {\n\n //const model = sequelize.import(path.join(__dirname, file))\n\n var model = require(path.join(__dirname, file))(sequelize, \nSequelize);\n\n db[model.name] = model\n\n })\n\ndb.sequelize = sequelize\ndb.Sequelize = Sequelize\n\nmodule.exports = db\n```\n\n========================================\n\nTop Answer:\nThis might help someone else out there, in version `6.6.5` it's deprecated and you should replace it with `sequelize.define`.\n\n========================================\n\nCode:\n```text\nconst model = sequelize.import(path.join(__dirname, file))\n\n                             ^\n```\n\n```text\nTypeError: sequelize.import is not a function\n```\n\n```text\nvar model = require(path.join(__dirname, file))(sequelize, Sequelize);\n\n                                         ^\n```\n\n```text\nTypeError: require(...) is not a function\n```\n\n```text\nconst fs = require('fs');\n\nconst path = require('path');\n\nconst Sequelize = require('sequelize');\n\nconst config = require('../config/config');\n\nconst db = {}\n\nvar __dirname = path.resolve();\n\n\nconst sequelize = new Sequelize(\n    config.db.database,\n    config.db.user,\n    config.db.password,\n    config.db.options\n)\n\n\nfs\n\n    .readdirSync(__dirname)\n\n    .filter((file) =>\n        file !== 'index.js'\n    )\n\n    .forEach((file) => {\n\n        //const model = sequelize.import(path.join(__dirname, file))\n\n        var model = require(path.join(__dirname, file))(sequelize, \nSequelize);\n\n        db[model.name] = model\n\n    })\n\n\ndb.sequelize = sequelize\ndb.Sequelize = Sequelize\n\nmodule.exports = db\n```\n\n```text\nconst model = sequelize['import'](path.join(__dirname, file))\n```\n\n```text\nconst model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes)\n```\n\n```text\nmv models models.bak && sequelize init:models && mv models.bak/index.js models.bak/index.js.bak && mv models.bak/* models/ && rm models.bak\n```\n\n```text\nnpm i --save-dev sequelize-cli && mv models models.bak && npx sequelize init:models && mv models.bak/index.js models.bak/index.js.bak && mv models.bak/* models/ && rm models.bak\n```\n\n```text\nrequire\n```\n\n```text\nmodels/index.js\n```\n\n```text\nmodels\n```\n\n```text\nindex.js\n```\n\n```text\nconst config = require(...\n```\n\n```text\nmodels/index.js\n```\n\n```text\n\"sequelize\": \"^5.22.3\",\n```\n\n```text\n< 6.0.0\n```\n\n```text\nexport default (sequelize, DataTypes) => {\n    ...\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    ...\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    sequelize.define('User', {\n        email: {\n            type: DataTypes.STRING,\n            unique: true\n        },\n        password: {\n            type: DataTypes.STRING\n        }\n    })\n\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) =>\n    sequelize.define('User', {\n        email: {\n            type: DataTypes.STRING,\n            unique: true\n        },\n        password: DataTypes.STRING\n    })\n```\n\n```text\n6.6.5\n```\n\n```text\nsequelize.define\n```\n\n========================================\n\nComments:\n- Did you look at `sequelize` variable at the line `const model = sequelize.import(path.join(__dirname, file))` using a breakpoint?\n- Seems like a syntax error. the suggestion of @Anatoly and use breakpoints to track code flow. If you can't find the whole code of the file.\n- how did you fix this, I have the same issue??\n- I haven't found a solution yet @bihireboris . I'm new to stack overflow and hoping someone to help.\n- Aight, will let know when I have some progress. keep up the learning\n- If you use something like `js export default (sequelize,DataTypes) => {...}` please make sure that you don't need to call the `default` function as `js const model = require(path.join(__dirname, file)).default(sequelize, Sequelize.DataTypes);`\n- Should I have to downgrade all the dependencies also?\n- downgraded to sequelize@5.22.3, but unfortunately it didn't work.+-- body-parser@1.19.0 +-- cors@2.8.5 +-- UNMET PEER DEPENDENCY eslint@7.4.0 +-- eslint-plugin-vue@6.2.2 +-- express@4.17.1 +-- morgan@1.10.0 +-- mysql@2.18.1 +-- mysql2@2.1.0 +-- nodemon@2.0.4 +-- sequelize@5.22.3 `-- sqlite3@5.0.0......................................These r my modules\n- is it the same error you are getting back though? also use `&#47;&#47; const model = sequelize.import(path.join(__dirname, file))` in your index.js in models @Hot_Pink_Spin\n- Any idea what changed in version 6?\n- the `import` function was removed, check-out the major changes done on version 6 @zwebie\n- Kindly look into using the approved answer for security and new features reasons @Godson\n- Any idea what version this was removed? The sequelize guys really don't give a crap about breaking a known api, huh? (sigh)\n- @ChrisH I'm pretty sure it's version 6 and forward, but I have a vague memory seeing this somewhere in late version 5.\n- It was removed from v5 -> v6: refactor: remove sequelize.import helper #12175. Docs: Upgrade to v6. @DavidKamer I'm sorry, I don't understand how to change the `sequelize.import()` code into a v6 working code...\n- This works fine, but ESLint has a problem with the require statement inside of a function and not using a string literal, because of the rules `global-require` and `import&#47;no-dynamic-require`. I disabled those two rules for the models/index.js but is there maybe a way to forEach() all the existing models in a prettier way? I found this, but it's not the prettiest solution either.\n- require isn't supported in esm.\n- @GregoryBologna if you mean your start script is being loaded with `esm` like `\"start\": \"node -r esm app.js\"`, you need to remove `\"type\": \"module\"` from your `package.json` specifications and you will be fine. This is because specifying type of module implies you can't use `require` anywhere even with esm. Once that is removed, `esm` will compile your code aptly.\n- `ReferenceError: require is not defined`. How do we use the newer Sequelize with ES Modules?\n- When I updated using: `npm i sequelize@latest`, the app broke. ... `const model = sequelize['import'](path.join(__dirname, file))` fixed my problem.\n- version>6 its sequelize.define(path.join(__dirname, file))\n- Those two code snippets are exactly the same!\n- They're not! In the first one, password is object with a key of type. In the second one, password is a String.\n- Do you have the source where you found this?\n- sequelize.define(path.join(__dirname, file))\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Oh god! thak you for this answer, it's a mistake dificult to find out the why. I had an empty file in models folder, after removing it, everything works fine.\n- Your answer could be improved by adding more information on what the code does and how it helps the OP.","metadata":{"transformedAt":"2026-08-18T18:33:34.343Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":285,"estimatedTokens":1971}}82{"id":"stack-25880539","source":"stackoverflow","questionId":25880539,"title":"Join across multiple junction tables with Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Join across multiple junction tables with Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a database with three primary tables: `users`, `teams`, and `folders` joined by two junction tables, `users_teams` and `teams_folders`. There is a many-to-many relationship between users and teams and between teams and folders (a user can be on more than one team and teams can own more than one folder).\n\nSequelize does a wonderful job of managing the user-teams and teams-folder relationship, but I can find no way to establish a relationship between users and folders.\n\n**Is there any way to join across two junction tables without resorting to raw SQL?** \n\nThere seems to be no way to accomplish this elegantly or in a reasonable number of steps. I have tried methods like `user.getFolders()`, `Folder.findAll({ include: [User] })`, but Sequelize doesn't seem to be able to understand a three level hierarchy.\n\n========================================\n\nTop Answer:\nPay attention to following:\n\n- Define relations in *both directions*\n\n- Check you have foreignKey, otherKey in *correct order*\n\n```\nUser.belongsToMany(Team, {\n through: 'users_teams',\n foreignKey: 'user_id',\n otherKey: 'team_id'\n});\n\nTeam.belongsToMany(User, {\n through: 'users_teams',\n foreignKey: 'team_id',\n otherKey: 'user_id'\n});\n```\n\n========================================\n\nCode:\n```text\nusers\n```\n\n```text\nteams\n```\n\n```text\nfolders\n```\n\n```text\nusers_teams\n```\n\n```text\nteams_folders\n```\n\n```text\nuser.getFolders()\n```\n\n```text\nFolder.findAll({ include: [User] })\n```\n\n```text\nUser.belongsToMany(Team, { through: 'users_teams'});\nTeam.belongsToMany(User, { through: 'users_teams'});\n\nFolder.belongsToMany(Team, { through: 'teams_folders'});\nTeam.belongsToMany(Folder, { through: 'teams_folders'});\n```\n\n```text\nUser.findAll({\n  include: [\n    {\n      model: Team, \n      include: [\n        Folder\n      ]  \n    }\n  ]\n});\n```\n\n```text\ninclude\n```\n\n```text\nUser.belongsToMany(Team, {\n  through: 'users_teams',\n  foreignKey: 'user_id',\n  otherKey: 'team_id'\n});\n\nTeam.belongsToMany(User, {\n  through: 'users_teams',\n  foreignKey: 'team_id',\n  otherKey: 'user_id'\n});\n```\n\n========================================\n\nComments:\n- Embarrassingly, the real issue is that I didn't realize this method was referred to as \"eager loading\" and had skimmed over that section of the documentation. Thanks!\n- It seems that `hasMany` is supposed to be used with 1:M relations: `N:M associations are not supported with hasMany. Use belongsToMany instead`\n- With regards to the above is it possible to retrieve a folder that belongs to a user? Or you can only retrieve all of the folders that belong to a team for a user but no way of having different access to folders per user?","metadata":{"transformedAt":"2026-08-18T18:33:34.343Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":112,"estimatedTokens":692}}83{"id":"stack-24282990","source":"stackoverflow","questionId":24282990,"title":"Nested relations with Sequelize","tags":["javascript","mysql","sequelize.js"],"text":"Title: Nested relations with Sequelize\nTags: javascript, mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize with Node + MySQL.\n\nI have a model structure similar to this:\n\n```\n// models:\nvar Group, Issue, Invite;\n\n// many Issues per Group\nGroup.hasMany(Issue);\nIssue.belongsTo(Group);\n\n// Groups can invite other Groups to work on their Issues\nIssue.hasMany(Invite, {foreignKey: groupId});\nInvite.belongsTo(Issue, {foreignKey: groupId});\nGroup.hasMany(Invite, {foreignKey: inviteeId});\nInvite.belongsTo(Group, {foreignKey: inviteeId});\n\n// given an Issue id, include all Invites + invited Groups (inviteeId) - But how?\nvar query = {\n where: {id: ...}, \n include: ???\n};\nIssue.find(query).complete(function(err, issue) {\n var invites = issue.invites;\n var firstInvitedGroup = issue.invites[0].group;\n // ...\n});\n```\n\nIs this at all possible? What are possible work-arounds? Thank you!\n\n========================================\n\nTop Answer:\nIf you want to eager load all nested associations use this function.\n\n```\nIssue.find({\n include:getNestedAssociations(Issue)\n});\n\n//Recursively load all bested associtiaons\nfunction getNestedAssociations(_model) {\n const associations = [];\n for (const association of Object.keys(_model.associations)) {\n const model = _model.associations[association].target;\n const as = association;\n const include = getNestedAssociations(model);\n associations.push({\n model: model,\n as: as,\n ...(include && { include: include }),\n });\n }\n return associations;\n}\n```\n\n========================================\n\nCode:\n```js\n// models:\nvar Group, Issue, Invite;\n\n// many Issues per Group\nGroup.hasMany(Issue);\nIssue.belongsTo(Group);\n\n// Groups can invite other Groups to work on their Issues\nIssue.hasMany(Invite, {foreignKey: groupId});\nInvite.belongsTo(Issue, {foreignKey: groupId});\nGroup.hasMany(Invite, {foreignKey: inviteeId});\nInvite.belongsTo(Group, {foreignKey: inviteeId});\n\n// given an Issue id, include all Invites + invited Groups (inviteeId) - But how?\nvar query = {\n    where: {id: ...}, \n    include: ???\n};\nIssue.find(query).complete(function(err, issue) {\n    var invites = issue.invites;\n    var firstInvitedGroup = issue.invites[0].group;\n    // ...\n});\n```\n\n```js\nIssue.find({\n    include: [\n        {\n            model: Invite,\n            include: [Group]\n        }\n    ]\n});\n```\n\n```text\nIssue.find({\n    include:getNestedAssociations(Issue)\n});\n\n\n\n//Recursively load all bested associtiaons\nfunction getNestedAssociations(_model) {\n  const associations = [];\n  for (const association of Object.keys(_model.associations)) {\n    const model = _model.associations[association].target;\n    const as = association;\n    const include = getNestedAssociations(model);\n    associations.push({\n      model: model,\n      as: as,\n      ...(include && { include: include }),\n    });\n  }\n  return associations;\n}\n```\n\n```text\n{\n    model: User,\n    as: 'users',\n    attributes: [],  // This will work//\n    where: {\n      user_id: 1\n    }\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.343Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":138,"estimatedTokens":751}}84{"id":"stack-22958683","source":"stackoverflow","questionId":22958683,"title":"How to implement many to many association in sequelize","tags":["node.js","express","sequelize.js"],"text":"Title: How to implement many to many association in sequelize\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two tables: Books and Articles with a many-to-many relationship between them.\nJoining table is BookArticles.\n\nmodels/books.js\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return Food = sequelize.define(\"Book\", {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true,\n unique: true\n }\n });\n}\n```\n\nmodels/articles.js\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return Food = sequelize.define(\"Article\", {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true,\n unique: true\n }\n });\n}\n```\n\nmodels/bookArticles.js\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return Food = sequelize.define(\"BookArticles\", {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true,\n unique: true\n },\n bookId: {\n type: DataTypes.INTEGER,\n references: 'Book',\n referencesKey: 'id',\n allowNull: false\n },\n ArticleId: {\n type: DataTypes.INTEGER,\n references: 'Article',\n referencesKey: 'id',\n allowNull: false\n },\n });\n}\n```\n\nAnd models/index.js\n\n```\nm.BookArticles.belongsTo(m.Book);\nm.Book.hasMany(m.Article, {through: m.BookArticles});\n\nm.BookArticles.belongsTo(m.Article);\nm.Article.hasMany(m.Books, {through: m.BookArticles});\n```\n\nbut I could not get book articles\n\nHow can I get it ??\n\n========================================\n\nTop Answer:\ndelete BookArticles model and update relation to: \n\n```\nm.Book.hasMany(m.Article, {through: 'book_articles'});\nm.Article.hasMany(m.Books, {through: 'book_articles'});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return Food = sequelize.define(\"Book\", {\n    id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      allowNull: false,\n      autoIncrement: true,\n      unique: true\n    }\n  });\n}\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return Food = sequelize.define(\"Article\", {\n    id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      allowNull: false,\n      autoIncrement: true,\n      unique: true\n    }\n  });\n}\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return Food = sequelize.define(\"BookArticles\", {\n    id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      allowNull: false,\n      autoIncrement: true,\n      unique: true\n    },\n   bookId: {\n      type: DataTypes.INTEGER,\n      references: 'Book',\n      referencesKey: 'id',\n      allowNull: false\n    },\n    ArticleId: {\n      type: DataTypes.INTEGER,\n      references: 'Article',\n      referencesKey: 'id',\n      allowNull: false\n    },\n  });\n}\n```\n\n```text\nm.BookArticles.belongsTo(m.Book);\nm.Book.hasMany(m.Article, {through: m.BookArticles});\n\n\nm.BookArticles.belongsTo(m.Article);\nm.Article.hasMany(m.Books, {through: m.BookArticles});\n```\n\n```js\n// foreign key has to be defined on both sides.\nParent.hasOne(Child, {foreignKey: 'Parent_parentId'})\n// \"Parent_parentId\" column will exist in the \"belongsTo\" table.\nChild.belongsTo(Parent, {foreignKey: 'Parent_parentId'})\n```\n\n```js\nParent.hasMany(Child, {foreignKey: 'Parent_parentId'})\nChild.belongsTo(Parent, {foreignKey: 'Parent_parentId'})\n```\n\n```text\nParent.belongsToMany(\n    Child, \n    {\n        // this can be string (model name) or a Sequelize Model Object Class\n        // through is compulsory since v2\n        through: 'Parent_Child',\n\n        // GOTCHA\n        // note that this is the Parent's Id, not Child. \n        foreignKey: 'Parent_parentId'\n    }\n)\n\n/*\nThe above reads:\n\"Parents\" belongs to many \"Children\", and is recorded in the \"Parent_child\" table, using \"Parents\"'s ID.\n*/\n\nChild.belongsToMany(\n    Parent, \n    {\n        through: 'Parent_Child',\n\n        // GOTCHA\n        // note that this is the Child's Id, not Parent.\n        foreignKey: 'Child_childId'\n    }\n)\n```\n\n```js\nDB.Parent.findOne({ \n    where: { id: 1 },\n    include: [ DB.Child ]\n}).then(parent => {\n\n    // you should get `parent.Child` as an array of children. \n\n})\n```\n\n```js\nDB.Parent.findOne({ where: { id: 1 } }).then(parent => {\n\n    // `parent` is the DAO\n    // you can use any of the methods below:\n    parent.getChild\n    parent.setChild\n    parent.addChild\n    parent.createChild\n    parent.removeChild\n    parent.hasChild\n\n})\n```\n\n```js\nparent.getChildren,\nparent.setChildren,\nparent.addChild,\nparent.addChildren,\nparent.createChild,\nparent.removeChild,\nparent.hasChild,\nparent.hasChildren,\n```\n\n```js\nchild.getParent,\nchild.setParent,\nchild.createParent,\n\n//belongsToMany\nchild.getParents,\nchild.setParents,\nchild.createParents,\n```\n\n```js\n// a parent can have many children\nParent.belongsToMany(Child, {\n    as: 'Natural',\n    through: 'Parent_Child',\n    foreignKey: 'Parent_parentId'\n})\n// a child must at least have 2 parents (natural mother and father)\nChild.belongsToMany(Parent, {\n    as: 'Natural',\n    through: 'Parent_Child',\n    foreignKey: 'Child_childId'\n})\n```\n\n```js\nParent.belongsToMany(Child, {\n    as: 'Foster',\n    through: 'Parent_Child',\n    foreignKey: 'Parent_parentId'\n})\n\nChild.belongsToMany(Parent, {\n    as: 'Foster',\n    through: 'Parent_Child',\n    foreignKey: 'Child_childId'\n});\n```\n\n```text\nParent.hasOne(Child)\n```\n\n```text\nparent\n```\n\n```text\nParent.hasMany(Child)\n```\n\n```text\nparent\n```\n\n```text\nChild.belongsTo(Parent)\n```\n\n```text\nchild\n```\n\n```text\nParent_Child\n```\n\n```text\nNaturalId\n```\n\n```text\nFosterId\n```\n\n```text\nm.Book.hasMany(m.Article, {through: 'book_articles'});\nm.Article.hasMany(m.Books, {through: 'book_articles'});\n```\n\n```text\nvar user = sequelize.define('user', {\n    name: {\n        Sequelize.STRING(255)\n    },\n    email: {\n        type: Sequelize.STRING(255),\n        unique: true,\n        validate: {\n            isEmail: true\n        }\n    }\n});\n```\n\n```text\nvar Role = sequelize.define('role', {\n    name: {\n        Sequelize.ENUM('ER', 'ALL', 'DL')\n    },\n    description: {\n        type: Sequelize.TEXT\n    }\n});\n```\n\n```text\nvar UserRole = sequelize.define('user_role', {\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    name: {\n        type: Sequelize.ENUM('Admin', 'Staff', 'Customer', 'Owner')\n    }\n});\n```\n\n```text\nUser.belongsToMany(Role, { as: 'Roles', through: { model: UserRole, unique: false }, foreignKey: 'user_id' });\nRole.belongsToMany(User, { as: 'Users', through: { model: UserRole, unique: false }, foreignKey: 'role_id' });\n```\n\n```text\nuser_id\n```\n\n```text\nrole_id\n```\n\n```text\nm.Book.belongsToMany(m.Article, {through: m.BookArticles});\nm.Article.belongsToMany(m.Books, {through: m.BookArticles});\n```\n\n```text\nM:M\n```\n\n```text\nBookArticles\n```\n\n```text\nnpm install sequelize@6.5.1 sqlite3@5.0.2\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'db.sqlite3',\n});\n\n(async () => {\n\n// Create the tables.\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(Post, {through: 'UserLikesPost'});\nPost.belongsToMany(User, {through: 'UserLikesPost'});\nawait sequelize.sync({force: true});\n\n// Create some users and posts.\n\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\n\nconst post0 = await Post.create({body: 'post0'});\nconst post1 = await Post.create({body: 'post1'});\nconst post2 = await Post.create({body: 'post2'});\n\n// Autogenerated add* methods\n\n// Make user0 like post0\nawait user0.addPost(post0)\n// Also works.\n//await user0.addPost(post0.id)\n// Make user0 and user2 like post1\nawait post1.addUsers([user0, user2])\n\n// Autogenerated get* methods\n\n// Get posts liked by a user.\n\nconst user0Likes = await user0.getPosts({order: [['body', 'ASC']]})\nassert(user0Likes[0].body === 'post0');\nassert(user0Likes[1].body === 'post1');\nassert(user0Likes.length === 2);\n\nconst user1Likes = await user1.getPosts({order: [['body', 'ASC']]})\nassert(user1Likes.length === 0);\n\nconst user2Likes = await user2.getPosts({order: [['body', 'ASC']]})\nassert(user2Likes[0].body === 'post1');\nassert(user2Likes.length === 1);\n\n// Get users that like a given post.\n\nconst post0Likers = await post0.getUsers({order: [['name', 'ASC']]})\nassert(post0Likers[0].name === 'user0');\nassert(post0Likers.length === 1);\n\nconst post1Likers = await post1.getUsers({order: [['name', 'ASC']]})\nassert(post1Likers[0].name === 'user0');\nassert(post1Likers[1].name === 'user2');\nassert(post1Likers.length === 2);\n\nconst post2Likers = await post2.getUsers({order: [['name', 'ASC']]})\nassert(post2Likers.length === 0);\n\n// Same as getPosts but with the user ID instead of the model object.\n{\n  const user0Likes = await Post.findAll({\n    include: [{\n      model: User,\n      where: {\n        id: user0.id\n      }\n    }],\n  })\n  assert(user0Likes[0].body === 'post0');\n  assert(user0Likes[1].body === 'post1');\n  assert(user0Likes.length === 2);\n}\n\n// Yet another way that can be more useful in nested includes.\n{\n  const user0Likes = (await User.findOne({\n    where: {id: user0.id},\n    include: [{\n      model: Post,\n    }],\n    order: [[Post, 'body', 'ASC']],\n  })).Posts\n  assert(user0Likes[0].body === 'post0');\n  assert(user0Likes[1].body === 'post1');\n  assert(user0Likes.length === 2);\n}\n\n// Autogenerated has* methods\n\n// Check if user likes post.\nassert( await user0.hasPost(post0))\nassert( await user0.hasPost(post0.id)) // same\nassert( await user0.hasPost(post1))\nassert(!await user0.hasPost(post2))\n\n// Check if post is liked by user.\nassert( await post0.hasUser(user0))\nassert(!await post0.hasUser(user1))\nassert(!await post0.hasUser(user2))\n\n// AND of multiple has checks at once.\nassert( await user0.hasPosts([post0, post1]))\n// false because user0 does not like post2\nassert(!await user0.hasPosts([post0, post1, post2]))\n\n// Autogenerated count* methods\n// user0 likes 2 posts.\nassert(await user0.countPosts() === 2)\n// post0 is liked by 1 user.\nassert(await post0.countUsers() === 1)\n\n// Autogenerated remove* method\n\n// user0 doesn't like post0 anymore.\nawait user0.removePost(post0)\n// user0 and user 2 don't like post1 anymore.\nawait post1.removeUsers([user0, user2])\n// Check that no-one likes anything anymore.\nassert(await user0.countPosts() === 0)\nassert(await post0.countUsers() === 0)\n\n// Autogenerated create* method\n// Create a new post and automatically make user0 like it.\nconst post3 = await user0.createPost({'body': 'post3'})\nassert(await user0.hasPost(post3))\nassert(await post3.hasUser(user0))\n\n// Autogenerated set* method\n// Make user0 like exactly these posts. Unlike anything else.\nawait user0.setPosts([post1, post2])\nassert(!await user0.hasPost(post0))\nassert( await user0.hasPost(post1))\nassert( await user0.hasPost(post2))\nassert(!await user0.hasPost(post3))\n\nawait sequelize.close();\n})();\n```\n\n```text\nUserLikesPost is the name of the relation table.\nSequelize creates it automatically for us.\nOn SQLite that table looks like this:\nCREATE TABLE `UserLikesPost` (\n  `createdAt` DATETIME NOT NULL,\n  `updatedAt` DATETIME NOT NULL,\n  `UserId` INTEGER NOT NULL REFERENCES `Users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n  `PostId` INTEGER NOT NULL REFERENCES `Posts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n  PRIMARY KEY (`UserId`, `PostId`)\n);\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'db.sqlite3',\n});\n\n(async () => {\n\n// Create the tables.\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(User, {through: 'UserFollowUser', as: 'Follows'});\nawait sequelize.sync({force: true});\n\n// Create some users.\n\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\nconst user3 = await User.create({name: 'user3'})\n\n// Make user0 follow user1 and user2\nawait user0.addFollows([user1, user2])\n// Make user2 and user3 follow user0\nawait user2.addFollow(user0)\nawait user3.addFollow(user0)\n\n// Check that the follows worked.\nconst user0Follows = await user0.getFollows({order: [['name', 'ASC']]})\nassert(user0Follows[0].name === 'user1');\nassert(user0Follows[1].name === 'user2');\nassert(user0Follows.length === 2);\n\nconst user1Follows = await user1.getFollows({order: [['name', 'ASC']]})\nassert(user1Follows.length === 0);\n\nconst user2Follows = await user2.getFollows({order: [['name', 'ASC']]})\nassert(user2Follows[0].name === 'user0');\nassert(user2Follows.length === 1);\n\nconst user3Follows = await user3.getFollows({order: [['name', 'ASC']]})\nassert(user3Follows[0].name === 'user0');\nassert(user3Follows.length === 1);\n\n// Same but with ID instead of object.\n{\n  const user0Follows = (await User.findOne({\n    where: {id: user0.id},\n    include: [{model: User, as: 'Follows'}],\n  })).Follows\n  assert(user0Follows[0].name === 'user1');\n  assert(user0Follows[1].name === 'user2');\n  assert(user0Follows.length === 2);\n}\n\n// has methods\nassert(!await user0.hasFollow(user0))\nassert(!await user0.hasFollow(user0.id))\nassert( await user0.hasFollow(user1))\nassert( await user0.hasFollow(user2))\nassert(!await user0.hasFollow(user3))\n\n// Count method\nassert(await user0.countFollows() === 2)\n\nawait sequelize.close();\n})();\n```\n\n```text\nCREATE TABLE IF NOT EXISTS `UserFollowUser` (\n  `createdAt` DATETIME NOT NULL,\n  `updatedAt` DATETIME NOT NULL,=\n  `UserId` INTEGER NOT NULL REFERENCES `Users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n  `FollowId` INTEGER NOT NULL REFERENCES `Users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n  PRIMARY KEY (`UserId`, `FollowId`)\n);\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'db.sqlite3',\n});\n\n(async () => {\n\n// Create the tables.\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n}, {});\nconst UserLikesPost = sequelize.define('UserLikesPost', {\n  UserId: {\n    type: DataTypes.INTEGER,\n    references: {\n      model: User,\n      key: 'id'\n    }\n  },\n  PostId: {\n    type: DataTypes.INTEGER,\n    references: {\n      model: Post,\n      key: 'id'\n    }\n  },\n  score: {\n    type: DataTypes.INTEGER,\n  },\n});\nUser.belongsToMany(Post, {through: UserLikesPost});\nPost.belongsToMany(User, {through: UserLikesPost});\nawait sequelize.sync({force: true});\n\n// Create some users and likes.\n\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\n\nconst post0 = await Post.create({body: 'post0'});\nconst post1 = await Post.create({body: 'post1'});\nconst post2 = await Post.create({body: 'post2'});\n\n// Make some useres like some posts.\nawait user0.addPost(post0, {through: {score: 1}})\nawait user1.addPost(post1, {through: {score: 2}})\nawait user1.addPost(post2, {through: {score: 3}})\n\n// Find what user0 likes.\nconst user0Likes = await user0.getPosts({order: [['body', 'ASC']]})\nassert(user0Likes[0].body === 'post0');\nassert(user0Likes[0].UserLikesPost.score === 1);\nassert(user0Likes.length === 1);\n\n// Find what user1 likes.\nconst user1Likes = await user1.getPosts({order: [['body', 'ASC']]})\nassert(user1Likes[0].body === 'post1');\nassert(user1Likes[0].UserLikesPost.score === 2);\nassert(user1Likes[1].body === 'post2');\nassert(user1Likes[1].UserLikesPost.score === 3);\nassert(user1Likes.length === 2);\n\n// Where on the custom through table column.\n// https://stackoverflow.com/questions/38857156/how-to-query-many-to-many-relationship-sequelize\n{\n  const user1LikesWithScore3 = await Post.findAll({\n    include: [{\n      model: User,\n      where: {\n        id: user1.id\n      },\n      through: {where: {score: 3}},\n    }],\n  })\n  assert(user1LikesWithScore3[0].body === 'post2');\n  assert(user1LikesWithScore3[0].UserLikesPost.score === 3);\n  assert(user1LikesWithScore3.length === 1);\n}\n\n// TODO: this doesn't work. Possible at all in a single addUsers call?\n// Make user0 and user2 like post1\n// This method automatically generated.\n//await post1.addUsers(\n//  [user0, user2],\n//  {through: [\n//    {score: 2},\n//    {score: 3},\n//  ]}\n//)\n\nawait sequelize.close();\n})();\n```\n\n```text\n#!/usr/bin/env node\n\n// Find all posts by users that a given user follows.\n// https://stackoverflow.com/questions/42632943/sequelize-multiple-where-clause\n\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'db.sqlite3',\n});\n\n(async () => {\n\n// Create the tables.\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(User, {through: 'UserFollowUser', as: 'Follows'});\nUser.hasMany(Post);\nPost.belongsTo(User);\nawait sequelize.sync({force: true});\n\n// Create data.\nconst users = await User.bulkCreate([\n  {name: 'user0'},\n  {name: 'user1'},\n  {name: 'user2'},\n  {name: 'user3'},\n])\n\nconst posts = await Post.bulkCreate([\n  {body: 'body00', UserId: users[0].id},\n  {body: 'body01', UserId: users[0].id},\n  {body: 'body10', UserId: users[1].id},\n  {body: 'body11', UserId: users[1].id},\n  {body: 'body20', UserId: users[2].id},\n  {body: 'body21', UserId: users[2].id},\n  {body: 'body30', UserId: users[3].id},\n  {body: 'body31', UserId: users[3].id},\n])\n\nawait users[0].addFollows([users[1], users[2]])\n\n// Get all posts by authors that user0 follows.\n// The posts are placed inside their respetive authors under .Posts\n// so we loop to gather all of them.\n{\n  const user0Follows = (await User.findByPk(users[0].id, {\n    include: [\n      {\n        model: User,\n        as: 'Follows',\n        include: [\n          {\n            model: Post,\n          }\n        ],\n      },\n    ],\n  })).Follows\n  const postsFound = []\n  for (const followedUser of user0Follows) {\n    postsFound.push(...followedUser.Posts)\n  }\n  postsFound.sort((x, y) => { return x.body < y.body ? -1 : x.body > y.body ? 1 : 0 })\n  assert(postsFound[0].body === 'body10')\n  assert(postsFound[1].body === 'body11')\n  assert(postsFound[2].body === 'body20')\n  assert(postsFound[3].body === 'body21')\n  assert(postsFound.length === 4)\n}\n\n// With ordering, offset and limit.\n// The posts are placed inside their respetive authors under .Posts\n// The only difference is that posts that we didn't select got removed.\n\n{\n  const user0Follows = (await User.findByPk(users[0].id, {\n    offset: 1,\n    limit: 2,\n    // TODO why is this needed? It does try to make a subquery otherwise, and then it doesn't work.\n    // https://selleo.com/til/posts/ddesmudzmi-offset-pagination-with-subquery-in-sequelize-\n    subQuery: false,\n    include: [\n      {\n        model: User,\n        as: 'Follows',\n        include: [\n          {\n            model: Post,\n          }\n        ],\n      },\n    ],\n  })).Follows\n  assert(user0Follows[0].name === 'user1')\n  assert(user0Follows[1].name === 'user2')\n  assert(user0Follows.length === 2)\n  const postsFound = []\n  for (const followedUser of user0Follows) {\n    postsFound.push(...followedUser.Posts)\n  }\n  postsFound.sort((x, y) => { return x.body < y.body ? -1 : x.body > y.body ? 1 : 0 })\n  // Note that what happens is that some of the\n  assert(postsFound[0].body === 'body11')\n  assert(postsFound[1].body === 'body20')\n  assert(postsFound.length === 2)\n\n  // Same as above, but now with DESC ordering.\n  {\n    const user0Follows = (await User.findByPk(users[0].id, {\n      order: [[\n        {model: User, as: 'Follows'},\n        Post,\n        'body',\n        'DESC'\n      ]],\n      offset: 1,\n      limit: 2,\n      subQuery: false,\n      include: [\n        {\n          model: User,\n          as: 'Follows',\n          include: [\n            {\n              model: Post,\n            }\n          ],\n        },\n      ],\n    })).Follows\n    // Note how user ordering is also reversed from an ASC.\n    // it likely takes the use that has the first post.\n    assert(user0Follows[0].name === 'user2')\n    assert(user0Follows[1].name === 'user1')\n    assert(user0Follows.length === 2)\n    const postsFound = []\n    for (const followedUser of user0Follows) {\n      postsFound.push(...followedUser.Posts)\n    }\n    // In this very specific data case, this would not be needed.\n    // because user2 has the second post body and user1 has the first\n    // alphabetically.\n    postsFound.sort((x, y) => { return x.body < y.body ? 1 : x.body > y.body ? -1 : 0 })\n    // Note that what happens is that some of the\n    assert(postsFound[0].body === 'body20')\n    assert(postsFound[1].body === 'body11')\n    assert(postsFound.length === 2)\n  }\n\n  // Here user2 would have no post hits due to the limit,\n  // so it is entirely pruned from the user list as desired.\n  // Otherwise we would fetch a lot of unwanted user data\n  // in a large database.\n  const user0FollowsLimit2 = (await User.findByPk(users[0].id, {\n    limit: 2,\n    subQuery: false,\n    include: [\n      {\n        model: User,\n        as: 'Follows',\n        include: [ { model: Post } ],\n      },\n    ],\n  })).Follows\n  assert(user0FollowsLimit2[0].name === 'user1')\n  assert(user0FollowsLimit2.length === 1)\n\n  // Get just the count of the posts authored by users followed by user0.\n  // attributes: [] excludes all other data from the SELECT of the queries\n  // to optimize things a bit.\n  // https://stackoverflow.com/questions/37817808/counting-associated-entries-with-sequelize\n  {\n    const user0Follows = await User.findByPk(users[0].id, {\n      attributes: [\n        [Sequelize.fn('COUNT', Sequelize.col('Follows.Posts.id')), 'count']\n      ],\n      include: [\n        {\n          model: User,\n          as: 'Follows',\n          attributes: [],\n          through: {\n            attributes: []\n          },\n          include: [\n            {\n              model: Post,\n              attributes: [],\n            }\n          ],\n        },\n      ],\n    })\n    assert.strictEqual(user0Follows.dataValues.count, 4);\n  }\n\n  // Case in which our post-sorting is needed.\n  // TODO: possible to get sequelize to do this for us by returning\n  // a flat array directly?\n  // Managed with super many to many as shown below.\n  // It's not big deal since the LIMITed result should be small,\n  // but feels wasteful.\n  // https://stackoverflow.com/questions/41502699/return-flat-object-from-sequelize-with-association\n  // https://github.com/sequelize/sequelize/issues/4419\n  {\n    await Post.truncate({restartIdentity: true})\n    const posts = await Post.bulkCreate([\n      {body: 'body0', UserId: users[0].id},\n      {body: 'body1', UserId: users[1].id},\n      {body: 'body2', UserId: users[2].id},\n      {body: 'body3', UserId: users[3].id},\n      {body: 'body4', UserId: users[0].id},\n      {body: 'body5', UserId: users[1].id},\n      {body: 'body6', UserId: users[2].id},\n      {body: 'body7', UserId: users[3].id},\n    ])\n    const user0Follows = (await User.findByPk(users[0].id, {\n      order: [[\n        {model: User, as: 'Follows'},\n        Post,\n        'body',\n        'DESC'\n      ]],\n      subQuery: false,\n      include: [\n        {\n          model: User,\n          as: 'Follows',\n          include: [\n            {\n              model: Post,\n            }\n          ],\n        },\n      ],\n    })).Follows\n    assert(user0Follows[0].name === 'user2')\n    assert(user0Follows[1].name === 'user1')\n    assert(user0Follows.length === 2)\n    const postsFound = []\n    for (const followedUser of user0Follows) {\n      postsFound.push(...followedUser.Posts)\n    }\n    // We need this here, otherwise we would get all user2 posts first:\n    // body6, body2, body5, body1\n    postsFound.sort((x, y) => { return x.body < y.body ? 1 : x.body > y.body ? -1 : 0 })\n    assert(postsFound[0].body === 'body6')\n    assert(postsFound[1].body === 'body5')\n    assert(postsFound[2].body === 'body2')\n    assert(postsFound[3].body === 'body1')\n    assert(postsFound.length === 4)\n  }\n}\n\nawait sequelize.close();\n})();\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes, Op } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'tmp.' + path.basename(__filename) + '.sqlite',\n  define: {\n    timestamps: false\n  },\n});\n\n(async () => {\n\n// Create the tables.\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n});\nconst UserFollowUser = sequelize.define('UserFollowUser', {\n    UserId: {\n      type: DataTypes.INTEGER,\n      references: {\n        model: User,\n        key: 'id'\n      }\n    },\n    FollowId: {\n      type: DataTypes.INTEGER,\n      references: {\n        model: User,\n        key: 'id'\n      }\n    },\n  }\n);\n\n// Super many to many.\nUser.belongsToMany(User, {through: UserFollowUser, as: 'Follows'});\nUserFollowUser.belongsTo(User)\nUser.hasMany(UserFollowUser)\n\nUser.hasMany(Post);\nPost.belongsTo(User);\n\nawait sequelize.sync({force: true});\n\n// Create data.\nconst users = await User.bulkCreate([\n  {name: 'user0'},\n  {name: 'user1'},\n  {name: 'user2'},\n  {name: 'user3'},\n])\nconst posts = await Post.bulkCreate([\n  {body: 'body0', UserId: users[0].id},\n  {body: 'body1', UserId: users[1].id},\n  {body: 'body2', UserId: users[2].id},\n  {body: 'body3', UserId: users[3].id},\n  {body: 'body4', UserId: users[0].id},\n  {body: 'body5', UserId: users[1].id},\n  {body: 'body6', UserId: users[2].id},\n  {body: 'body7', UserId: users[3].id},\n])\nawait users[0].addFollows([users[1], users[2]])\n\n// Get all the posts by authors that user0 follows.\n// without any post process sorting. We only managed to to this\n// with a super many to many, because that allows us to specify\n// a reversed order in the through table with `on`, since we need to\n// match with `FollowId` and not `UserId`.\n{\n  const postsFound = await Post.findAll({\n    order: [[\n      'body',\n      'DESC'\n    ]],\n    include: [\n      {\n        model: User,\n        attributes: [],\n        required: true,\n        include: [\n          {\n            model: UserFollowUser,\n            on: {\n              FollowId: {[Op.col]: 'User.id' },\n            },\n            attributes: [],\n            where: {UserId: users[0].id},\n          }\n        ],\n      },\n    ],\n  })\n  assert.strictEqual(postsFound[0].body, 'body6')\n  assert.strictEqual(postsFound[1].body, 'body5')\n  assert.strictEqual(postsFound[2].body, 'body2')\n  assert.strictEqual(postsFound[3].body, 'body1')\n  assert.strictEqual(postsFound.length, 4)\n}\n\nawait sequelize.close();\n})();\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'tmp.' + path.basename(__filename) + '.sqlite',\n});\n\n(async () => {\n\n// Create the tables.\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n}, {});\n\nUser.belongsToMany(Post, {through: 'UserLikesPost', as: 'likedPosts'});\nPost.belongsToMany(User, {through: 'UserLikesPost', as: 'likers'});\n\nUser.belongsToMany(Post, {through: 'UserFollowsPost', as: 'followedPosts'});\nPost.belongsToMany(User, {through: 'UserFollowsPost', as: 'followers'});\n\nawait sequelize.sync({force: true});\n\n// Create some users and likes.\n\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\n\nconst post0 = await Post.create({body: 'post0'});\nconst post1 = await Post.create({body: 'post1'});\nconst post2 = await Post.create({body: 'post2'});\n\n// Autogenerated add* methods\n\n// Setup likes and follows.\nawait user0.addLikedPost(post0)\nawait post1.addLikers([user0, user2])\nawait user1.addFollowedPosts([post0, post1])\nawait post1.addFollower(user2)\n\n// Autogenerated get* methods\n\n// Get likes by a user.\n\nconst user0Likes = await user0.getLikedPosts({order: [['body', 'ASC']]})\nassert(user0Likes[0].body === 'post0');\nassert(user0Likes[1].body === 'post1');\nassert(user0Likes.length === 2);\n\nconst user1Likes = await user1.getLikedPosts({order: [['body', 'ASC']]})\nassert(user1Likes.length === 0);\n\nconst user2Likes = await user2.getLikedPosts({order: [['body', 'ASC']]})\nassert(user2Likes[0].body === 'post1');\nassert(user2Likes.length === 1);\n\n// Get users that liked a given post.\n\nconst post0Likers = await post0.getLikers({order: [['name', 'ASC']]})\nassert(post0Likers[0].name === 'user0');\nassert(post0Likers.length === 1);\n\nconst post1Likers = await post1.getLikers({order: [['name', 'ASC']]})\nassert(post1Likers[0].name === 'user0');\nassert(post1Likers[1].name === 'user2');\nassert(post1Likers.length === 2);\n\nconst post2Likers = await post2.getLikers({order: [['name', 'ASC']]})\nassert(post2Likers.length === 0);\n\n// Get follows by a user.\n\nconst user0Follows = await user0.getFollowedPosts({order: [['body', 'ASC']]})\nassert(user0Follows.length === 0);\n\nconst user1Follows = await user1.getFollowedPosts({order: [['body', 'ASC']]})\nassert(user1Follows[0].body === 'post0');\nassert(user1Follows[1].body === 'post1');\nassert(user1Follows.length === 2);\n\nconst user2Follows = await user2.getFollowedPosts({order: [['body', 'ASC']]})\nassert(user2Follows[0].body === 'post1');\nassert(user2Follows.length === 1);\n\n// Get users that followed a given post.\n\nconst post0Followers = await post0.getFollowers({order: [['name', 'ASC']]})\nassert(post0Followers[0].name === 'user1');\nassert(post0Followers.length === 1);\n\nconst post1Followers = await post1.getFollowers({order: [['name', 'ASC']]})\nassert(post1Followers[0].name === 'user1');\nassert(post1Followers[1].name === 'user2');\nassert(post1Followers.length === 2);\n\nconst post2Followers = await post2.getFollowers({order: [['name', 'ASC']]})\nassert(post2Followers.length === 0);\n\n// Same as getLikedPosts but with the user ID instead of the model object.\n{\n  const user0Likes = await Post.findAll({\n    include: [{\n      model: User,\n      as: 'likers',\n      where: {id: user0.id},\n    }],\n    order: [['body', 'ASC']],\n  })\n  assert(user0Likes[0].body === 'post0');\n  assert(user0Likes[1].body === 'post1');\n  assert(user0Likes.length === 2);\n}\n\n// Yet another way that can be more useful in nested includes.\n{\n  const user0Likes = (await User.findOne({\n    where: {id: user0.id},\n    include: [{\n      model: Post,\n      as: 'likedPosts',\n    }],\n    order: [[{model: Post, as: 'likedPosts'}, 'body', 'ASC']],\n  })).likedPosts\n  assert(user0Likes[0].body === 'post0');\n  assert(user0Likes[1].body === 'post1');\n  assert(user0Likes.length === 2);\n}\n\nawait sequelize.close();\n})();\n```\n\n```text\nUser.hasMany(Post, {as: 'authoredPosts', foreignKey: 'authorId'});\nPost.belongsTo(User, {as: 'author', foreignKey: 'authorId'});\n\nUser.hasMany(Post, {as: 'reviewedPosts', foreignKey: 'reviewerId'});\nPost.belongsTo(User, {as: 'reviewer', foreignKey: 'reviewerId'});\n```\n\n```text\nFoo.hasMany(Bar)\n```\n\n```text\nas:\n```\n\n```text\n.belongsToMany\n```\n\n```text\naddFollows\n```\n\n```text\naddFollow\n```\n\n```text\nscore\n```\n\n```text\ninclude:\n```\n\n```text\nbelongsTo\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsToMany\n```\n\n```text\nUser\n```\n\n```text\nPost\n```\n\n```text\nas:\n```\n\n```text\nforeignKey\n```\n\n```text\nforeignKey\n```\n\n```text\nUserId\n```\n\n```text\nauthorId\n```\n\n```text\nJOIN\n```\n\n```text\nGROUP BY\n```\n\n```text\nCOUNT\n```\n\n========================================\n\nComments:\n- the documentation for this senario may help: docs.sequelizejs.com/class/lib/associations/&hellip;\n- Can someone please help me this https://stackoverflow.com/q/69267021/12071145\n- @UladKasach the current link to belongsToMany() is sequelize.org/api/v6/class/src/associations/&hellip;\n- depreciated. see answers below\n- I think @DamonYuan is referring to answers which references `belongsToMany`; instead of this answer, which uses a deprecated `hasMany`\n- I have a similar prob, but i cant get it working after trying the solutions mentioned above. when i query, i get an error, but the error object is empty. Below is how my models are associated: `sequelize.define('A', {id, name}, A.belongsToMany(models.B, {through: models.A_B, foreignKey: 'a_id'})); sequelize.define('B', {id, name}, B.belongsToMany(models.A, {through: models.A_B, foreignKey: 'b_id'})); sequelize.define('A_B', {id, a_id, b_id}); &#47;&#47;mapping table A.findAll(query) .then(function (r){ }) .catch (function(e){ });` @Calvintwr @ahiipsa , could you please help ?\n- I presume that you had `console.log(e)` in your `.catch()` handler. Try losing `a_id` and `b_id` in the `A_B` model.\n- @Calvintwr thank you for this explanation. Does the N:M relationship always require a third model? What if the relationship is just a technical join like the one between User and Project? The table tracking the relationship could be called, user_projects. Does one have to create a model UserProject and if not, how does one create a migration file for this table and how would you declare the relationships in the models: User and Project?\n- it is best to create the model UserProject so that you can use it as well, various purposes. if you don't create the model, sequelize will automatically create a default cross table, which will still work but you cannot query this table directly, unless using raw sql. migration is never problem whether you create or not create. whether you choose to do so has to do with whether there is a higher level usage for the crosstable, such as querying it, to get useful information, or even store useful data about each cross relation.\n- If I do this: `Parent.hasMany(Child)`, I expect setters/getters, like you say : `parent.setChildren`, but does *Sequelize* know how to turn \"child\" into \"children\"; aka does Sequelize create `setChildren` automatically, even though the model is named `Child`?, or must *I manually config* Sequelize using the `as` attribute. **EDIT** I see sequelize uses `node.inflection` which *does* seem capable of handling `child->children`\n- You are right in that sequelize uses the inflection module to convert singular to plural. But usually I just ignore this automagic behaviour and define the singular and plurals myself. It’s a very small effort to take a doubt out of the equation when you need to debug later on. You will run into cases where your models have no plural, like `Equipment`. See docs.sequelizejs.com/manual/tutorial/&hellip;\n- my question almost same, but little nested, jsfiddle.net/j74rt9y1/1 the second assosiation didn't works and no error,, anyone can helps ?\n- How to creating the record by using the above models\n- What about UserRole? Does UserRole belongTo User and belongTo Role? does UserRole hasMany Users and hasMany Roles, what do you write inside UserRole\n- @rickster I'm glad I'm not the only one that was confused by this library! :-)\n- One doubt Ciro, I am doing something like this `const res = await user.getFollower();` with this I am also getting the join table... how do I not include in `res` ? any idea ?\n- @rickster `user0.getFollower({joinTableAttributes: []})` seems to do it, I'll add it to the examples.\n- yeah. it works perfect.","metadata":{"transformedAt":"2026-08-18T18:33:34.343Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":62,"totalLines":1370,"estimatedTokens":8926}}85{"id":"stack-28414395","source":"stackoverflow","questionId":28414395,"title":"How to update with Sequelize with 'NOW()' on a timestamp?","tags":["node.js","datetime","sql-update","sequelize.js"],"text":"Title: How to update with Sequelize with 'NOW()' on a timestamp?\nTags: node.js, datetime, sql-update, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do something like the following:\n\n```\nmodel.updateAttributes({syncedAt: 'NOW()'});\n```\n\nObviously, that doesn't work because it just gets passed as a string. I want to avoid passing a node constructed timestamp, because later I compare it to another 'ON UPDATE CURRENT_TIMESTAMP' field and the database and source could be running different times.\n\nIs my only option to just make a database procedure and call that?\n\n========================================\n\nTop Answer:\nWorth mentioning (for people coming here via search) that NOW() isn't standard and doesn't work on SQL server - so don't do this if you care about portability.\n\n```\nsequelize.literal('CURRENT_TIMESTAMP')\n```\n\nmay work better\n\n========================================\n\nCode:\n```text\nmodel.updateAttributes({syncedAt: 'NOW()'});\n```\n\n```text\ninstance.updateAttributes({syncedAt: sequelize.fn('NOW')});\n```\n\n```text\n'use strict';\n\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize(/*database*/'test', /*username*/'test', /*password*/'test',\n    {host: 'localhost', dialect: 'postgres'});\n\nvar model = sequelize.define('model', {\n    syncedAt: {type: Sequelize.DATE}\n});\n\nsequelize.sync({force: true})\n    .then(function () {\n        return model.create({});\n    })\n    .then(function () {\n        return model.find({});\n    })\n    .then(function(instance){\n        return instance.updateAttributes({syncedAt: sequelize.fn('NOW')});\n    })\n    .then(function () {\n        process.exit(0);\n    })\n    .catch(function(err){\n        console.log('Caught error! ' + err);\n    });\n```\n\n```text\nUPDATE \"models\" SET \"syncedAt\"=NOW(),\"updatedAt\"='2015-02-09 18:05:28.989 +00:00' WHERE \"id\"=1\n```\n\n```text\nSequelize.fn\n```\n\n```text\nsequelize.literal('CURRENT_TIMESTAMP')\n```\n\n```text\nawait PurchaseModel.update( {purchase_date : sequelize.literal('CURRENT_TIMESTAMP') }, { where: {id: purchaseId} } );\n```\n\n```text\nsequelize.literal('CURRENT_TIMESTAMP')\n```\n\n========================================\n\nComments:\n- How about `new Date().toString()`\n- @laggingreflex I could just use moment().format(), but I wanted to avoid later comparing a database time to a client side generated time.\n- Why don't you enable timestamps, so updatedAt will be updated if you simply call model.update({},{where:{my_primary_key:value}})\n- Thanks! sequelize.fn('NOW') is exactly what I needed.\n- is sequelize.fn('NOW(6)') supported for storing fractional seconds/microseconds? since Sequelize.DATE(6) datatype is now supported if we are using mysql >= 5.6\n- OK: sequelize.fn('NOW', 6) is supported for storing fractional seconds/microseconds.\n- Note that this sets the instance's syncedAt attribute to `{fn: \"NOW\", args: []}` and not the current timestamp (since this is determined by the database).\n- To add to @mauvm's note, if you need the value *after* setting it, remember to first call `instance.save()` to actually update the database side, and to also then call `instance.reload()` to get that new timestamp loaded in as an actual timestamp instead of as a function placeholder.\n- Thanks, this is exactly what I needed for using SQLite3 with Sequelize.","metadata":{"transformedAt":"2026-08-18T18:33:34.343Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":98,"estimatedTokens":820}}86{"id":"stack-42707568","source":"stackoverflow","questionId":42707568,"title":"Create a table and add indexes in a single migration with Sequelize","tags":["indexing","migration","sequelize.js"],"text":"Title: Create a table and add indexes in a single migration with Sequelize\nTags: indexing, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the correct way to **create a table** and **add indices** on some of its columns in **a single migration**?\n\n**Example Migration: 2012341234-create-todo.js**\n\nHow would I create an index on the \"author_id\" and \"title\" column?\n\n```\n'use strict';\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Todos', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n author_id: {\n type: Sequelize.INTEGER,\n onDelete: 'CASCADE',\n references: {\n model: 'Authors',\n key: 'id',\n as: 'authorId'\n }\n },\n title: {\n type: Sequelize.STRING\n },\n\n content: {\n type: Sequelize.TEXT\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Todos');\n }\n};\n```\n\nThe Sequelize docs indicate that an index would be added like this:\n\n```\nqueryInterface.addIndex('Todos', ['author_id', 'title']);\n```\n\nCan these methods just be chained? Do \"up\" and \"down\" just need to return a promise? I'm not seeing anything in the docs about it.\n\n========================================\n\nTop Answer:\nThe accepted solution is problematic if the second step fails. Transactions in each step should be used to allow a roll back to ensure all of the migration steps that are inserts or updates are undone if a problem is encountered at any step. For example:\n\n```\nmodule.exports = {\n up: async (queryIntereface) => {\n const transaction = await queryInterface.sequelize.transaction();\n\n try {\n await queryInterface.createTable('Todos', {\n // columns...\n }, { transaction });\n await queryInterface.addIndex('Todos', ['author_id', 'title'], { transaction }));\n\n await transaction.commit();\n } catch (err) {\n await transaction.rollback();\n throw err;\n }\n },\n\n down: async (queryInterface) {\n\n etc...\n```\n\n**Reference**\n\n- https://sequelize.org/master/manual/migrations.html#migration-skeleton (search for \"transaction()\"\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('Todos', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      author_id: {\n        type: Sequelize.INTEGER,\n        onDelete: 'CASCADE',\n        references: {\n          model: 'Authors',\n          key: 'id',\n          as: 'authorId'\n        }\n      },\n      title: {\n        type: Sequelize.STRING\n      },\n\n      content: {\n        type: Sequelize.TEXT\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable('Todos');\n  }\n};\n```\n\n```text\nqueryInterface.addIndex('Todos', ['author_id', 'title']);\n```\n\n```js\nreturn queryInterface.createTable('Todos', {\n    // columns...\n}).then(() => queryInterface.addIndex('Todos', ['author_id', 'title']))\n.then(() => {\n    // perform further operations if needed\n});\n```\n\n```text\naddIndex\n```\n\n```text\ncreateTable\n```\n\n```text\nmodule.exports = {\n up: (queryInterface) => {\n return queryInterface.sequelize.query('CREATE INDEX devices_mac_uuid ON \n  \"Devices\" (\"mac\",\"uuid\")')\n },\n down: (queryInterface) => {\n  return queryInterface.sequelize.query('DROP INDEX devices_mac_uuid')\n }\n}\n```\n\n```js\nmodule.exports = {\n up: async (queryIntereface) => {\n    const transaction = await queryInterface.sequelize.transaction();\n\n    try {\n      await queryInterface.createTable('Todos', {\n        // columns...\n      }, { transaction });\n      await queryInterface.addIndex('Todos', ['author_id', 'title'], { transaction }));\n\n\n      await transaction.commit();\n    } catch (err) {\n      await transaction.rollback();\n      throw err;\n    }\n  },\n\n  down: async (queryInterface) {\n\n    etc...\n```\n\n```js\n'use strict';\n    \n    module.exports = {\n      up: (queryInterface, Sequelize) => {\n        return queryInterface.addIndex('reports', ['client_id'])\n          .then(() => {\n            return queryInterface.addIndex('reports', ['report_name'])\n          })\n          .then(() => {\n            return queryInterface.addIndex('reports', ['report_date'])\n          })\n      },\n    \n      down: (queryInterface, Sequelize) => {\n        return queryInterface.removeIndex('reports', ['client_id'])\n        .then(() => {\n          return queryInterface.removeIndex('reports', ['report_name'])\n        })\n        .then(() => {\n          return queryInterface.removeIndex('reports', ['report_date'])\n        })\n      }\n    };\n```\n\n```js\n'use strict';\n    const { DataTypes } = require('sequelize');\n\n    module.exports = {\n      up: async (queryInterface, Sequelize) => {\n        return await queryInterface.createTable('exampleTable', {\n          id: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n          },\n          userId: {\n              type: DataTypes.INTEGER,\n              allowNull: false,\n              references: {\n                  model: 'user',\n                  key: 'id'\n              }\n          },\n          classId: {\n              type: DataTypes.INTEGER,\n              allowNull: false,\n              references: {\n                  model: 'class',\n                  key: 'id'\n              }\n          },\n      },\n      {\n          uniqueKeys: {\n            unique_tag: {\n                customIndex: true,\n                fields: [\"userId\", \"classId\"]\n            }\n          }\n        });\n      },\n\n      down: async (queryInterface, Sequelize) => {\n        return await queryInterface.dropTable('exampleTable');\n      }\n    };\n```\n\n========================================\n\nComments:\n- If the .addIndex fails the .createTable will remain. This is not how to do migrations that have more than one step. See the answer that uses transactions.\n- ewww ... callback hell\n- how to defined BTREE and unique is false ?\n- check out second answer with transaction please\n- I wonder why they don't just support `indexes` from `queryInterface` like in `sequelize.define`, it is so annoying! Feature request: github.com/sequelize/cli/issues/410\n- While your suggestion will work it does not answer the question of \"the correct way\". If you limit every migration to a single step you lose context as well as having an unnecessary number of files to process with every application build. The use of transactions allows for a safe multi-step migration. See transaction answer for an example.\n- Transactions won't help in certain databases such as MySQL where CREATE statements or ALTER TABLE which perform an implicit commit and cannot be rolled back. dev.mysql.com/doc/refman/8.0/en/cannot-roll-back.html","metadata":{"transformedAt":"2026-08-18T18:33:34.343Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":278,"estimatedTokens":1757}}87{"id":"stack-28206680","source":"stackoverflow","questionId":28206680,"title":"Using group by and joins in sequelize","tags":["sql","node.js","postgresql","sequelize.js"],"text":"Title: Using group by and joins in sequelize\nTags: sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two tables on a PostgreSQL database, contracts and payments. One contract has multiple payments done.\n\nI'm having the two following models:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var contracts = sequelize.define('contracts', {\n id: {\n type: DataTypes.INTEGER,\n autoIncrement: true\n }\n }, {\n createdAt: false,\n updatedAt: false,\n classMethods: {\n associate: function(models) {\n contracts.hasMany(models.payments, {\n foreignKey: 'contract_id'\n });\n }\n }\n });\n\n return contracts;\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n var payments = sequelize.define('payments', {\n id: {\n type: DataTypes.INTEGER,\n autoIncrement: true\n },\n contract_id: {\n type: DataTypes.INTEGER,\n },\n payment_amount: DataTypes.INTEGER,\n }, {\n classMethods: {\n associate: function(models) {\n payments.belongsTo(models.contracts, {\n foreignKey: 'contract_id'\n });\n }\n }\n });\n\n return payments;\n};\n```\n\nI would like to sum all the payments made for every contract, and used this function:\n\n```\nmodels.contracts.findAll({\n attributes: [\n 'id'\n ],\n include: [\n {\n model: models.payments,\n attributes: [[models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']]\n }\n ],\n group: ['contracts.id']\n})\n```\n\nBut it generates the following query:\n\n```\nSELECT \"contracts\".\"id\", \"payments\".\"id\" AS \"payments.id\", sum(\"payments\".\"payment_amount\") AS \"payments.total_cost\" \nFROM \"contracts\" AS \"contracts\" \nLEFT OUTER JOIN \"payments\" AS \"payments\" ON \"contracts\".\"id\" = \"payments\".\"contract_id\" GROUP BY \"contracts\".\"id\";\n```\n\nI do not ask to select payments.id, because I would have to include it in my aggregation or group by functions, as said in the error I have:\n\n Possibly unhandled SequelizeDatabaseError: error: column \"payments.id\"\n must appear in the GROUP BY clause or be used in an aggregate function\n\nAm I missing something here ? I'm following this answer but even there I don't understand how the SQL request can be valid.\n\n========================================\n\nTop Answer:\nTry\n\n```\ngroup: ['contracts.id', 'payments.id']\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var contracts = sequelize.define('contracts', {\n    id: {\n      type: DataTypes.INTEGER,\n      autoIncrement: true\n    }\n  }, {\n    createdAt: false,\n    updatedAt: false,\n    classMethods: {\n      associate: function(models) {\n        contracts.hasMany(models.payments, {\n          foreignKey: 'contract_id'\n        });\n      }\n    }\n  });\n\n\n  return contracts;\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n  var payments = sequelize.define('payments', {\n    id: {\n      type: DataTypes.INTEGER,\n      autoIncrement: true\n    },\n    contract_id: {\n      type: DataTypes.INTEGER,\n    },\n    payment_amount: DataTypes.INTEGER,\n  }, {\n    classMethods: {\n      associate: function(models) {\n        payments.belongsTo(models.contracts, {\n          foreignKey: 'contract_id'\n        });\n      }\n    }\n  });\n\n\n  return payments;\n};\n```\n\n```text\nmodels.contracts.findAll({\n    attributes: [\n        'id'\n    ],\n    include: [\n    {\n        model: models.payments,\n        attributes: [[models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']]\n    }\n    ],\n    group: ['contracts.id']\n})\n```\n\n```text\nSELECT \"contracts\".\"id\", \"payments\".\"id\" AS \"payments.id\", sum(\"payments\".\"payment_amount\") AS \"payments.total_cost\" \nFROM \"contracts\" AS \"contracts\" \nLEFT OUTER JOIN \"payments\" AS \"payments\" ON \"contracts\".\"id\" = \"payments\".\"contract_id\" GROUP BY \"contracts\".\"id\";\n```\n\n```text\nattributes: []\n```\n\n```text\nmodels.contracts.findAll({\n    attributes: ['id', [models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']],\n    include: [\n    {\n        model: models.payments,\n        attributes: []\n    }\n    ],\n    group: ['contracts.id']\n})\n```\n\n```text\npayments\n```\n\n```text\ncontracts\n```\n\n```text\nmodels.contracts.findAll({\n    attributes: [\n        'models.contracts.id'\n    ],\n    include: [\n    {\n        model: models.payments,\n        attributes: [[models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']]\n    }\n    ],\n    group: ['contracts.id']\n})\n```\n\n```text\ngroup: ['contracts.id', 'payments.id']\n```\n\n========================================\n\nComments:\n- Did you mean 'contracts.id' instead of 'models.contracts.id' ? Anyway the first one gives me the same error and the second one throws another SQL error (missing FROM clause).\n- Thanks but if I group by 'payments.id' I won't be able to sum the payments.payment_amount.\n- How bout `attributes: ['payment_amount', [models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']]`. Basically sequelize will select the id if \"nothing\" is selected. If that works I will update my answer. Hope it does.\n- Unfortunately, always the same error: `Possibly unhandled SequelizeDatabaseError: column \"payments.id\" must appear in the GROUP BY clause or be used in an aggregate function`","metadata":{"transformedAt":"2026-08-18T18:33:34.343Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":219,"estimatedTokens":1294}}88{"id":"stack-33918383","source":"stackoverflow","questionId":33918383,"title":"Sequelize update with association","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize update with association\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn sequelize it's possible to create a row and all its associations in one go like this:\n\n```\nreturn Product.create({\n title: 'Chair',\n User: {\n first_name: 'Mick',\n last_name: 'Broadstone'\n }\n}, {\n include: [ User ]\n});\n```\n\nIs there a equivalent for update?\nI tried\n\n```\nmodel.user.update(req.body.user, {where: {id: req.user.user_id}, include: [model.profile]})\n```\n\nBut it's only updating user\n\nDoing this for create works\n\n```\nmodel.user.create(user, {transaction: t, include: [model.profile]})\n```\n\n========================================\n\nTop Answer:\nIf you want to update both models(Product & Profile) at once. One of the approaches can be:\n\n```\n// this is an example of object that can be used for update\nlet productToUpdate = {\n amount: 'new product amount'\n Profile: {\n name: 'new profile name'\n }\n};\nProduct\n .findById(productId)\n .then((product) => {\n if(!product) {\n throw new Error(`Product with id ${productId} not found`);\n }\n\n product.Profile.set(productToUpdate.Profile, null);\n delete productToUpdate.Profile; // We have to delete this object to not reassign values\n product.set(productToUpdate);\n\n return sequelize\n .transaction((t) => {\n return product\n .save({transaction: t})\n .then((updatedProduct) => updatedProduct.Profile.save());\n })\n })\n .then(() => console.log(`Product & Profile updated!`))\n```\n\n========================================\n\nCode:\n```text\nreturn Product.create({\n  title: 'Chair',\n  User: {\n    first_name: 'Mick',\n    last_name: 'Broadstone'\n  }\n}, {\n  include: [ User ]\n});\n```\n\n```text\nmodel.user.update(req.body.user, {where: {id: req.user.user_id}, include: [model.profile]})\n```\n\n```text\nmodel.user.create(user, {transaction: t, include: [model.profile]})\n```\n\n```text\nvar updateProfile = { name: \"name here\" };\nvar filter = {\n  where: {\n    id: parseInt(req.body.id)\n  },\n  include: [\n    { model: Profile }\n  ]\n};\n\nProduct.findOne(filter).then(function (product) {\n  if (product) {\n    return product.Profile.updateAttributes(updateProfile).then(function (result) {\n      return result;\n    });\n  } else {\n    throw new Error(\"no such product type id exist to update\");\n  }\n});\n```\n\n```text\n// this is an example of object that can be used for update\nlet productToUpdate = {\n    amount: 'new product amount'\n    Profile: {\n        name: 'new profile name'\n    }\n};\nProduct\n    .findById(productId)\n    .then((product) => {\n        if(!product) {\n            throw new Error(`Product with id ${productId} not found`);\n        }\n\n        product.Profile.set(productToUpdate.Profile, null);\n        delete productToUpdate.Profile; // We have to delete this object to not reassign values\n        product.set(productToUpdate);\n\n        return sequelize\n            .transaction((t) => {\n                return product\n                    .save({transaction: t})\n                    .then((updatedProduct) => updatedProduct.Profile.save());\n            })\n    })\n    .then(() => console.log(`Product & Profile updated!`))\n```\n\n```text\nawait Job.update(req.body, {\n        where: {\n          id: jobid\n        }\n      }).then(async function () {\n        await Job.findByPk(jobid).then(async function (job) {\n          await Position.findOrCreate({ where: { jobinput: req.body.jobinput } }).then(position => {\n            job.setPositions(position.id)\n          })\n})\n```\n\n```js\nconst { Sequelize, DataTypes } = require(\"sequelize\");\nconst {\n  extendSequelize,\n} = require(\"@hatchifyjs/sequelize-create-with-associations\");\n\n(async function main() {\n  // create your Sequelize instance\n  const sequelize = new Sequelize(\"sqlite::memory:\", {\n    logging: false,\n  });\n\n  // define your models\n  const Product = sequelize.define(\"Product\", {\n    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n    title: DataTypes.STRING,\n  });\n\n  const User = sequelize.define(\"User\", {\n    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n    firstName: DataTypes.STRING,\n    lastName: DataTypes.STRING,\n    productId: DataTypes.INTEGER,\n  });\n\n  Product.hasOne(User, {\n    as: \"user\",\n    foreignKey: \"productId\",\n  });\n\n  User.belongsTo(Product, {\n    as: \"product\",\n    foreignKey: \"productId\",\n  });\n\n  // create the tables\n  await sequelize.sync();\n\n  // extend Sequelize\n  await extendSequelize(Sequelize);\n\n  await Product.create({\n    title: \"Chair\",\n    user: {\n      firstName: \"Mick\",\n      lastName: \"Broadstone\",\n    },\n  });\n\n  const table = await Product.create({\n    title: \"Table\",\n  });\n\n  await User.update(\n    { lastName: \"Updated\", product: { id: table.id } },\n    { where: { id: 1 } }\n  );\n})();\n```\n\n========================================\n\nComments:\n- It would be so easy in pure SQL...\n- @Andy worth noting that SQLite only added \"no subquery\" support in 2020: stackoverflow.com/questions/19270259/update-with-join-in-sql&zwnj;&#8203;ite\n- This seems to be the best solution for updating\n- The only issue I'm seeing with this approach is you assume no other request will update the original filtered object.\n- Whether that is necessary depends on your business logic requirements, and it can be prevented by using a `SERIALIZABLE` or `REAPEATABLE READ` transaction.\n- Doesn't look like `updateAttributes` is a function in version 4 docs.sequelizejs.com/class/lib/model.js~Model.html\n- `updateAttributes` is not found. Which is the latest way\n- Maybe a combination with `set` and `save` solves it?","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":226,"estimatedTokens":1381}}89{"id":"stack-43099808","source":"stackoverflow","questionId":43099808,"title":"-bash: sequelize: command not found","tags":["npm","sequelize.js"],"text":"Title: -bash: sequelize: command not found\nTags: npm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI just ran npm install --save sequelize pg pg-hstore in my project root directory and now I am unable to invoke sequelize init. I get the error: -bash: sequelize: command not found. What am I doing wrong?\n\n========================================\n\nTop Answer:\nThe reason is: sequelize is not installed globally on your cli. To get sequelize access to all your cli just do.\n\n```\nnpm install -g sequelize-cli\n```\n\nThe '-g' means global this will allow you to access sequelize command anywhere in your app directory.\n\nAfter that you can do eg: `sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string`\n\n========================================\n\nCode:\n```text\nnpm install -g sequelize-cli\n```\n\n```text\nsequelize-cli\n```\n\n```text\nsequelize-cli\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules/.bin/sequelize\n```\n\n```text\nnode_modules/.bin/sequelize help\n```\n\n```text\nnpm install -g sequelize-cli\n```\n\n```text\nsequelize model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string\n```\n\n```text\nsequelize\n```\n\n```text\npackage.json\n```\n\n```text\nsequelize-cli\n```\n\n```text\nnpx\n```\n\n```text\n$ npx sequelize-cli <command>\n```\n\n```text\n$ npx sequelize-cli migration:generate --name add-a-column\n```\n\n```text\nnvm install node --reinstall-packages-from=node\n```\n\n```text\nnpm install -g sequelize-cli\n```\n\n```text\n<proj_dir>\\node_modules\\sequelize-automate\\bin\n```\n\n```text\nnode sequelize-automate -t js -h localhost -d <proj_dir> -u postgres -p ****** -P 5432 -e postgres -o root to \\src\\models\n```\n\n```text\nnpx sequelize-cli <command>\n```\n\n```text\nyarn global add sequelize-cli --prefix /usr/local\n```\n\n```text\nsequelize init\n```\n\n```text\nnpm ERR! code E404\nnpm ERR! 404 Not Found - GET https://registry.npmjs.org/create-sequelize - Not found\n```\n\n```text\nnpx sequelize init\n```\n\n```text\nnpm install -g sequelize-cli\n```\n\n```text\nsequelize init\n```\n\n========================================\n\nComments:\n- Possible duplicate of How do I install the sequelize.js binary?\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":129,"estimatedTokens":600}}90{"id":"stack-15737949","source":"stackoverflow","questionId":15737949,"title":"How does autoIncrement work in NodeJs's Sequelize?","tags":["node.js","postgresql-9.1","auto-increment","sequelize.js"],"text":"Title: How does autoIncrement work in NodeJs's Sequelize?\nTags: node.js, postgresql-9.1, auto-increment, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSequelize's document doesn't say a whole lot about `autoIncrement`. It only includes the following example:\n\n```\n// autoIncrement can be used to create auto_incrementing integer columns\nincrementMe: { type: Sequelize.INTEGER, autoIncrement: true }\n```\n\nBased off of this example I have the following code:\n\n```\ndb.define('Entries', {\n id: {\n type: Seq.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n title: {\n type: Seq.STRING,\n allowNull: false\n },\n entry: {\n type: Seq.TEXT,\n allowNull: false\n }\n}\n```\n\nNow when I want to create an entry I want to do something like this:\n\n```\nmodels.Entry.create({title:'first entry', entry:'yada yada yada'})\n```\n\nHowever, when I execute that code I get a database error: \n\n Null value in column \"id\" violates not null constraint\n\nI would assume Sequelize would put the integer in for me or define the database table to do that itself. Apparently not? What am I missing here to ensure that the id is automatically incremented and filled?\n\nThanks much.\n\n========================================\n\nTop Answer:\n`omitNull` config option by default is false. Set it to true, and the `id` will be taken care of by Postgres:\n\n```\nsequelize = new Sequelize('mydb', 'postgres', null, {\n host: 'localhost',\n port: 5432,\n dialect: 'postgres',\n omitNull: true\n})\n\nVisitor = sequelize.define('visitor', {\n email: Sequelize.STRING\n})\n\nVisitor.create({email: 'foo@bar.com'})\n```\n\n========================================\n\nCode:\n```text\n// autoIncrement can be used to create auto_incrementing integer columns\nincrementMe: { type: Sequelize.INTEGER, autoIncrement: true }\n```\n\n```text\ndb.define('Entries', {\n    id: {\n        type: Seq.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    title: {\n        type: Seq.STRING,\n        allowNull: false\n    },\n    entry: {\n        type: Seq.TEXT,\n        allowNull: false\n    }\n}\n```\n\n```text\nmodels.Entry.create({title:'first entry', entry:'yada yada yada'})\n```\n\n```text\nautoIncrement\n```\n\n```text\nsequelize = new Sequelize('mydb', 'postgres', null, {\n  host: 'localhost',\n  port: 5432,\n  dialect: 'postgres',\n  omitNull: true\n})\n\nVisitor = sequelize.define('visitor', {\n  email: Sequelize.STRING\n})\n\nVisitor.create({email: 'foo@bar.com'})\n```\n\n```text\nomitNull\n```\n\n```text\nid\n```\n\n```text\nVisitor = sequelize.define('visitor', {\n  id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n  },\n  email: Sequelize.STRING\n})\n```\n\n```text\nCREATE TABLE IF NOT EXISTS \"visitor\" (\"id\"   SERIAL, \"email\" varchar(255)...\n```\n\n```text\nautoincrement: true\n```\n\n```text\nautoIncrement: true\n```\n\n```text\nCREATE TABLE Entries (\n    id SERIAL PRIMARY KEY,\n    # other values...\n);\n```\n\n```text\nSERIAL\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nINTEGER\n```\n\n```text\nsequelize.sync()\n```\n\n========================================\n\nComments:\n- sorry shifted project priorities, but i will get back to you this weekend on this.\n- this is right for my purposes, but still wondering what the purpose of the `autoIncrement` is if you have to enter it everytime. Perhaps I mis-configured.\n- the problem is how to give custom primarykey names !\n- You can do defaultValue: invokeGenerateCustomId() in the options\n- @yacine I need to specify the id field as am going to use that as a foreign key to refer another table so can you tell me a way?\n- still doesn't work for me. says \"Field 'id' doesn't have a default value\",\n- As per this reported issue, `omitNull` should no longer be used. Use `autoIncrement: true` instead in the corresponding column at the model definition and simply don't provide a value when you do the `create()`.\n- @ThalisK. : This does not work for me. Have the same problem as the author.\n- @mxgrn, thanks its works for me, if you dont ommit null value, postgresql will put null value inside statement. github.com/sequelize/sequelize/issues/925\n- @akohout Have you find a solution?","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":186,"estimatedTokens":1017}}91{"id":"stack-54898994","source":"stackoverflow","questionId":54898994,"title":"bulkUpdate in sequelize orm","tags":["node.js","express","sequelize.js"],"text":"Title: bulkUpdate in sequelize orm\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can we implement bulkUpdate like bulkCreate in sequelize orm,\nI searched the whole documentation of sequelize but didn't find anything related to bulkUpdate,\nso I tried to loop update in for loop, it works but is there any other way to update in bulk\n\n========================================\n\nTop Answer:\nYou can, if you want to update a lot of records with the same values!\nexample:\nI want to update field \"activationStatus\" for 10 users at 1 time,\n1 user = 1 record in DB and I have Array of user IDs then:\n\n```\nUser.update({ activationStatus: 'active'}, {\n where: {\n id: [1,2,3,4,5,6,7,8,9,10]\n }\n });\n```\n\nit will be analogue of SQL query:\n\n```\nUPDATE User SET activationStatus = 'active' WHERE id IN(1,2,3,4,5,6,7,8,9,10);\n```\n\nyou can find more info about Sequelize Operator Aliases HERE\n\n========================================\n\nCode:\n```text\nbulkCreate([...], { updateOnDuplicate: [\"name\"] })\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\ndataArray\n```\n\n```text\nUser.update({ activationStatus: 'active'}, {\n          where: {\n              id: [1,2,3,4,5,6,7,8,9,10]\n          }\n      });\n```\n\n```text\nUPDATE User SET activationStatus = 'active' WHERE id IN(1,2,3,4,5,6,7,8,9,10);\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'tmp.' + path.basename(__filename) + '.sqlite',\n});\n\n(async () => {\nconst Integer = sequelize.define('Integer',\n  {\n    value: {\n      type: DataTypes.INTEGER,\n      unique: true, // mandatory\n      primaryKey: true,\n    },\n    name: {\n      type: DataTypes.STRING,\n    },\n    inverse: {\n      type: DataTypes.INTEGER,\n    },\n  },\n  {\n    timestamps: false,\n  }\n);\nawait Integer.sync({force: true})\nawait Integer.create({value: 2, inverse: -2, name: 'two'});\nawait Integer.create({value: 3, inverse: -3, name: 'three'});\nawait Integer.create({value: 5, inverse: -5, name: 'five'});\n\n// Initial state.\nassert.strictEqual((await Integer.findOne({ where: { value: 2 } })).name, 'two');\nassert.strictEqual((await Integer.findOne({ where: { value: 3 } })).name, 'three');\nassert.strictEqual((await Integer.findOne({ where: { value: 5 } })).name, 'five');\nassert.strictEqual((await Integer.findOne({ where: { value: 2 } })).inverse, -2);\nassert.strictEqual((await Integer.findOne({ where: { value: 3 } })).inverse, -3);\nassert.strictEqual((await Integer.findOne({ where: { value: 5 } })).inverse, -5);\nassert.strictEqual(await Integer.count(), 3);\n\n// Update.\nawait Integer.bulkCreate(\n  [\n    {value: 2, name: 'TWO'},\n    {value: 3, name: 'THREE'},\n    {value: 7, name: 'SEVEN'},\n  ],\n  { updateOnDuplicate: [\"name\"] }\n);\n\n// Final state.\nassert.strictEqual((await Integer.findOne({ where: { value: 2 } })).name, 'TWO');\nassert.strictEqual((await Integer.findOne({ where: { value: 3 } })).name, 'THREE');\nassert.strictEqual((await Integer.findOne({ where: { value: 5 } })).name, 'five');\nassert.strictEqual((await Integer.findOne({ where: { value: 7 } })).name, 'SEVEN');\nassert.strictEqual((await Integer.findOne({ where: { value: 2 } })).inverse, -2);\nassert.strictEqual((await Integer.findOne({ where: { value: 3 } })).inverse, -3);\nassert.strictEqual((await Integer.findOne({ where: { value: 5 } })).inverse, -5);\nassert.strictEqual(await Integer.count(), 4);\n\nawait sequelize.close();\n})();\n```\n\n```text\nINSERT INTO `IntegerNames` (`value`,`name`) VALUES (2,'TWO'),(3,'THREE'),(7,'SEVEN')\n  ON CONFLICT (`value`) DO UPDATE SET `name`=EXCLUDED.`name`;\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\n\nconst { Sequelize, DataTypes, Op } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'tmp.' + path.basename(__filename) + '.sqlite',\n});\n\n(async () => {\nconst Inverses = sequelize.define('Inverses',\n  {\n    value: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n    },\n    inverse: {\n      type: DataTypes.INTEGER,\n    },\n    name: {\n      type: DataTypes.STRING,\n    },\n  },\n  { timestamps: false }\n);\nawait Inverses.sync({force: true})\nawait Inverses.create({value: 2, inverse: -2, name: 'two'});\nawait Inverses.create({value: 3, inverse: -3, name: 'three'});\nawait Inverses.create({value: 5, inverse: -5, name: 'five'});\n\n// Initial state.\nassert.strictEqual((await Inverses.findOne({ where: { value: 2 } })).inverse, -2);\nassert.strictEqual((await Inverses.findOne({ where: { value: 3 } })).inverse, -3);\nassert.strictEqual((await Inverses.findOne({ where: { value: 5 } })).inverse, -5);\nassert.strictEqual(await Inverses.count(), 3);\n\n// Update to fixed value.\nawait Inverses.update(\n  { inverse: 0, },\n  { where: { value: { [Op.gt]: 2 } } },\n);\nassert.strictEqual((await Inverses.findOne({ where: { value: 2 } })).inverse, -2);\nassert.strictEqual((await Inverses.findOne({ where: { value: 3 } })).inverse, 0);\nassert.strictEqual((await Inverses.findOne({ where: { value: 5 } })).inverse, 0);\nassert.strictEqual(await Inverses.count(), 3);\n\n// Update to match another column.\nawait Inverses.update(\n  { inverse: sequelize.col('value'), },\n  { where: { value: { [Op.gt]: 2 } } },\n);\nassert.strictEqual((await Inverses.findOne({ where: { value: 2 } })).inverse, -2);\nassert.strictEqual((await Inverses.findOne({ where: { value: 3 } })).inverse, 3);\nassert.strictEqual((await Inverses.findOne({ where: { value: 5 } })).inverse, 5);\nassert.strictEqual(await Inverses.count(), 3);\n\n// Update to match another column with modification.\nawait Inverses.update(\n  { inverse: sequelize.fn('1 + ', sequelize.col('value')), },\n  { where: { value: { [Op.gt]: 2 } } },\n);\nassert.strictEqual((await Inverses.findOne({ where: { value: 2 } })).inverse, -2);\nassert.strictEqual((await Inverses.findOne({ where: { value: 3 } })).inverse, 4);\nassert.strictEqual((await Inverses.findOne({ where: { value: 5 } })).inverse, 6);\nassert.strictEqual(await Inverses.count(), 3);\n\n// A string function test.\nawait Inverses.update(\n  { name: sequelize.fn('upper', sequelize.col('name')), },\n  { where: { value: { [Op.gt]: 2 } } },\n);\nassert.strictEqual((await Inverses.findOne({ where: { value: 2 } })).name, 'two');\nassert.strictEqual((await Inverses.findOne({ where: { value: 3 } })).name, 'THREE');\nassert.strictEqual((await Inverses.findOne({ where: { value: 5 } })).name, 'FIVE');\nassert.strictEqual(await Inverses.count(), 3);\n\nawait sequelize.close();\n})();\n```\n\n```text\nUPDATE `Inverses` SET `inverse`=$1 WHERE `value` > 2\nUPDATE `Inverses` SET `inverse`=`value` WHERE `value` > 2\nUPDATE `Inverses` SET `inverse`=1 + (`value`)\nUPDATE `Inverses` SET `name`=upper(`name`) WHERE `value` > 2\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => queryInterface.sequelize.transaction(async transaction => {\n    await queryInterface.addColumn('User', 'displayName',\n      {\n        type: Sequelize.STRING(256),\n        allowNull: false,\n        defaultValue: '',\n      },\n      {transaction},\n    )\n    await queryInterface.bulkUpdate('User',\n      {displayName: queryInterface.sequelize.col('username')},\n      {}, // optional where clause to select which rows to update\n          // If empty like this it updates every single row.\n      {transaction},\n    )\n  }),\n  down: async (queryInterface, Sequelize) => {\n    await queryInterface.removeColumn('User', 'displayName')\n  }\n};\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => queryInterface.sequelize.transaction(async transaction => {\n    await queryInterface.addColumn('User', 'displayName',\n      {\n        type: Sequelize.STRING(256),\n        allowNull: false,\n        defaultValue: '',\n      },\n      {transaction},\n    )\n    const [users] = await queryInterface.sequelize.query('SELECT * FROM \"User\";', { transaction });\n    const newUsers = users.map(user =>\n      { return { id: user.id, displayName: user.username } }\n    )\n    await queryInterface.bulkInsert('User',\n      newUsers,\n      {\n        updateOnDuplicate: ['displayName'],\n        transaction,\n      }\n    )\n  }),\n  down: async (queryInterface, Sequelize) => {\n    await queryInterface.removeColumn('User', 'displayName')\n  }\n};\n```\n\n```text\nERROR: Cannot read property 'map' of undefined\n```\n\n```text\nbulkCreate\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\nupdate\n```\n\n```text\nQueryInterface.bulkUpdate\n```\n\n```text\nbulkUpdate\n```\n\n```text\nQueryInterface\n```\n\n```text\nModel\n```\n\n```text\n.update\n```\n\n```text\nbulkUpdate\n```\n\n```text\ndisplayName\n```\n\n```text\nusername\n```\n\n```text\ndisplayName\n```\n\n```text\nusername\n```\n\n```text\nModel.bulkCreate\n```\n\n```text\nUPDATE\n```\n\n```text\nQueryInterface.bulkInsert\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\nbulkUpdate\n```\n\n========================================\n\nComments:\n- does not work for MS SQL. sequelize throws an error: `mssql does not support the updateOnDuplicate option.`\n- \"only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5\" - from docs: sequelize.org/master/class/lib/&hellip;\n- Here's an updated link sequelize.org/api/v6/class/src/&hellip;\n- And you can also update fields based on other fields which is supported by SQL, example at: stackoverflow.com/a/69044138/895245\n- how would you write this query for update user set usename = a for id =1 username = b for id = 2......and so on\n- @PirateApp query mentioned by you is imposible in sequelize\n- in order to see a stack trace in a migration you have to surround everything in a try catch statement: `async up(blah){ try { await queryInterface.... } catch (err) {log it}`","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":361,"estimatedTokens":2407}}92{"id":"stack-35525574","source":"stackoverflow","questionId":35525574,"title":"How to use database connections pool in Sequelize.js","tags":["node.js","sequelize.js"],"text":"Title: How to use database connections pool in Sequelize.js\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need some clarification about what the pool is and what it does. The docs say Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database.\n\n```\nvar sequelize = new Sequelize('database', 'username', 'password', {\n host: 'localhost',\n dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n },\n\n// SQLite only\n storage: 'path/to/database.sqlite'\n});\n```\n\n========================================\n\nTop Answer:\n*pool is draining error*\n\nI found this thread in my search for a Sequalize error was giving my node.js app: *pool is draining*. I could not for the life of me figure it out. So for those who in my footsteps:\n\nThe issue was that I was closing the database earlier than I thought I was, with the command `sequelize.closeConnections()`. For some reason, instead of an error like 'the database has been closed`, it was instead giving the obscure error 'pool is draining'.\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',\n\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  },\n\n// SQLite only\n   storage: 'path/to/database.sqlite'\n});\n```\n\n```text\npool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  }\n```\n\n```text\npool\n```\n\n```text\nmax: 5\n```\n\n```text\nmin: 0\n```\n\n```text\nidle: 10000\n```\n\n```text\npool\n```\n\n```text\nfalse\n```\n\n```text\nsequelize.closeConnections()\n```\n\n========================================\n\nComments:\n- On why connection pools are useful: stackoverflow.com/questions/44081488/&hellip;\n- can you go into more detail about the pool and the pool object\n- wouldn't recommend as it can heavily affect performance of your applicaton\n- Error: Support for pool:false was removed in v4.0\n- Nice answer! With this `idle` configuration, if my query does more than 10 seconds to execute, is the connection closed without me getting a response?\n- no, idle is literally how long the connection will sit there doing nothing. what you're talking about is the `pool.timeout` setting. which i think defaults to 30s. after that the query times out and you'll get an error.\n- Nice answer sir\n- @steev the current docs as well as those of v4 don't talk about pool.timeout. I also can't find pool.timeout in the source code. See stackoverflow.com/a/62697070/4417769 for something like that on postgres\n- @sezanzeb If I recall correctly I think that option is a default of \"generic-pool\", the package that sequelize4 uses to do its pooling. if you can't find mention of it in sequelize code then it might never actually reset it? latest sequelize, btw, uses sequelize-pool instead, it seems, and i have no idea about that. these are guesses, tho, it's been a long time since i looked at this stuff...\n- Is the pool and limits set per user or global ? In another words, max : 5 will allow only 5 user to connect ( mysql max_connections ) or will restrict 5 connections per user ?\n- Thank you for taking the time to post this. In the end, this was my problem, too. Coupled with tricky forEach","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":101,"estimatedTokens":818}}93{"id":"stack-30052254","source":"stackoverflow","questionId":30052254,"title":"Sequelize: Include.where filtering by a 'parent' Model attribute","tags":["javascript","sequelize.js"],"text":"Title: Sequelize: Include.where filtering by a 'parent' Model attribute\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two Models related, Catalog and ProductCategory. The latter has a composed PK, 'id, language_id'.\nHere are the models simplified:\n\n```\nvar Catalog = sequelize.define(\"Catalog\", {\nid: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n},\nuser_id: {\n type: DataTypes.INTEGER,\n allowNull: false\n},\nproduct_category_id: {\n type: DataTypes.STRING(7)\n},\nlanguage_id: {\n type: DataTypes.INTEGER\n}, \n... more stuff ...\n}\n\nvar ProductCategory = sequelize.define(\"ProductCategory\", {\nid: {\n type: DataTypes.STRING(7),\n primaryKey: true\n},\nlanguage_id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n},\n... more stuff ...\n}\n\nCatalog.belongsTo(models.ProductCategory, {foreignKey: 'product_category_id'});\n```\n\nI'm trying to include some info from ProductCategory table related to Catalog, but ONLY when the language_id matches.\n\nAt the moment I'm getting all the possible matches from both tables.\nThis is the query right now:\n\n```\nCatalog.find({where:\n {id: itemId},\n include: {\n model: models.ProductCategory, \n where: {language_id: /* Catalog.language_id */}\n }\n})\n```\n\nIs there a way to use an attribute from Catalog to filter the include where both models have the same language?\n\nBy the way, I've also tried changing the where clause, without any consecuence:\n\n```\nwhere: {'ProductCategory.language_id': 'Catalog.language_id'}\n```\n\n========================================\n\nTop Answer:\nYou can try this (Especially if you are using MariaDB) -\n\n```\nconst Sequelize = require('sequelize'); \nconst op = Sequelize.Op;\n\nCatalog.find({where:\n {id: itemId},\n include: {\n model: models.ProductCategory, \n where: {\n language_id: {[op.col]: 'Catalog.language_id'}\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\nvar Catalog = sequelize.define(\"Catalog\", {\nid: {\n  type: DataTypes.INTEGER,\n  primaryKey: true,\n  autoIncrement: true\n},\nuser_id: {\n  type: DataTypes.INTEGER,\n  allowNull: false\n},\nproduct_category_id: {\n  type: DataTypes.STRING(7)\n},\nlanguage_id: {\n  type: DataTypes.INTEGER\n},  \n... more stuff ...\n}\n\nvar ProductCategory = sequelize.define(\"ProductCategory\", {\nid: {\n  type: DataTypes.STRING(7),\n  primaryKey: true\n},\nlanguage_id: {\n  type: DataTypes.INTEGER,\n  primaryKey: true\n},\n... more stuff ...\n}\n\nCatalog.belongsTo(models.ProductCategory, {foreignKey: 'product_category_id'});\n```\n\n```text\nCatalog.find({where:\n    {id: itemId},\n    include: {\n        model: models.ProductCategory, \n        where: {language_id: /* Catalog.language_id */}\n    }\n})\n```\n\n```text\nwhere: {'ProductCategory.language_id': 'Catalog.language_id'}\n```\n\n```text\nCatalog.find({where:\n    {id: itemId},\n    include: {\n        model: models.ProductCategory, \n        where: {\n          language_id: {$col: 'Catalog.language_id'}\n        }\n    }\n})\n```\n\n```text\n$col\n```\n\n```text\nsequelize.literal('...')\n```\n\n```text\nwhere: {language_id: models.sequelize.literal('Catalog.language_id')}\n```\n\n```text\nconst Sequelize = require('sequelize'); \nconst op = Sequelize.Op;\n\nCatalog.find({where:\n    {id: itemId},\n    include: {\n        model: models.ProductCategory, \n        where: {\n          language_id: {[op.col]: 'Catalog.language_id'}\n        }\n    }\n})\n```\n\n```text\nconst models = require(\"models directory\");\n    {\n       model: models.ModelName,\n       where: {\n            column-name: column-value\n         }\n    }\n```\n\n```text\nCatalog.find({where:\n    {id: itemId},\n    include: {\n        model: ProductCategory, \n        where: {\n          language_id: 'Catalog.language_id'\n        }\n    }\n})\n```\n\n```text\nmodel: models.ProductCategory\n```\n\n```text\n{[op.col]: 'Catalog.language_id'}\n```\n\n========================================\n\nComments:\n- `where: {'$ProductCategory.language_id$': 'Catalog.language_id'}` this probably could have worked too\n- where did this work? using `sequelize.literal('Sale.debt') makes this weird thing: ``Payments`.`quantity` = `val` = \\'Sale.debt\\'``\n- @dan_rocha: Replacing the inner **where** in the **Catalog.find** query I originally posted. If you what you're trying to do I might be able to help you. The output is weird indeed, but it works.\n- Tested it and works like a charm, thanks for the improve over my self-anser. ;)\n- this only returns [Object object] for me\n- Remember to include const Sequelize = require('sequelize'); const Op = Sequelize.Op; and you can [Op.col] instead of $col that fixed it for me\n- What is [op.col] explanation is missing\n- The idea was to match an attribute, not a specific value. I'm afraid your response doesn't match at all the question at hand.\n- it works because you are treating 'Catalog.language_id' as a plain string , so it is actually not working.","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":219,"estimatedTokens":1199}}94{"id":"stack-37078970","source":"stackoverflow","questionId":37078970,"title":"Sequelize: Using Multiple Databases","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize: Using Multiple Databases\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nDo I need to create multiple instances of Sequelize if I want to use two databases? That is, two databases on the same machine.\n\nIf not, what's the proper way to do this? It seems like overkill to have to connect twice to use two databases, to me.\n\nSo for example, I have different databases for different functions, for example, let's say I have customer data in one database, and statistical data in another. \n\nSo in MySQL:\n\n```\nMySQL [customers]> show databases;\n+--------------------+\n| Database |\n+--------------------+\n| customers |\n| stats |\n+--------------------+\n```\n\nAnd I have this to connect with sequelize\n\n```\n// Create a connection....\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('customers', 'my_user', 'some_password', {\n host: 'localhost',\n dialect: 'mysql',\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n },\n logging: function(output) {\n if (opts.log_queries) {\n log.it(\"sequelize_log\",{log: output});\n }\n }\n\n});\n\n// Authenticate it.\nsequelize.authenticate().nodeify(function(err) {\n\n // Do stuff....\n\n});\n```\n\nI tried to \"trick\" it by in a definition of a model using dot notation\n\n```\nvar InterestingStatistics = sequelize.define('stats.interesting_statistics', { /* ... */ });\n```\n\nBut that creates the table `customers.stats.interesting_statistics`. I need to use an existing table in the stats database.\n\nWhat's the proper way to achieve this? Thanks.\n\n========================================\n\nTop Answer:\nif you are trying to associate objects in the same RDS across multiple databases, you can use `schema`. \n\nhttp://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-schema\n\nthis will prepend the db name to the table name so, presumably, your queries would come out like:\n`SELECT A.ColA, B.ColB FROM SchemaA.ATable A INNER JOIN SchemaB.BTable B ON B.BId = A.BId`\n\n========================================\n\nCode:\n```text\nMySQL [customers]> show databases;\n+--------------------+\n| Database           |\n+--------------------+\n| customers          |\n| stats              |\n+--------------------+\n```\n\n```text\n// Create a connection....\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('customers', 'my_user', 'some_password', {\n    host: 'localhost',\n    dialect: 'mysql',\n\n    pool: {\n        max: 5,\n        min: 0,\n        idle: 10000\n    },\n    logging: function(output) {\n        if (opts.log_queries) {\n            log.it(\"sequelize_log\",{log: output});\n        }\n    }\n\n});\n\n// Authenticate it.\nsequelize.authenticate().nodeify(function(err) {\n\n    // Do stuff....\n\n});\n```\n\n```text\nvar InterestingStatistics = sequelize.define('stats.interesting_statistics', { /* ... */ });\n```\n\n```text\ncustomers.stats.interesting_statistics\n```\n\n```text\nconst { Sequelize } = require('sequelize');\nconst userDb = new Sequelize(/* ... */);\nconst contentDb = new Sequelize(/* ... */);\n```\n\n```text\n{\n    /*...*/\n    databases: {\n        user: {\n            path: 'xxxxxxxx'\n        },\n        content: {\n            path: 'xxxxxxxx'\n        }\n    }\n}\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst config = require('./config.json');\n\n// Loop through\nconst db = {};\nconst databases = Object.keys(config.databases);\nfor(let i = 0; i < databases.length; ++i) {\n    let database = databases[i];\n    let dbPath = config.databases[database];\n    db[database] = new Sequelize( dbPath );\n}\n\n// Sequelize instances:\n// db.user\n// db.content\n```\n\n```text\nconfig.json\n```\n\n```text\nconst sequelize = require('db_config');\nfunction test(req, res){\n  const qry = `SELECT * FROM db1.affiliates_order co\nLEFT JOIN db2.affiliates m ON m.id = co.campaign_id`;\n  sequelize.query(qry, null, {  raw: true}).then(result=>{\n    console.log(result);\n  })\n}\n```\n\n```text\nschema\n```\n\n```text\nSELECT A.ColA, B.ColB FROM SchemaA.ATable A INNER JOIN SchemaB.BTable B ON B.BId = A.BId\n```\n\n```text\nconst path = require(\"path\");\n\nmodule.exports = {\n   config: path.resolve(\"config\", \"config.json\"),\n   \"models-path\": path.resolve(\"models\"),\n   \"migrations-path\": path.resolve(\"migrations\", \"accounting\"),\n};\n```\n\n```text\n{\n     \"development\": {\n         \"baseUrl\": \"https://example.com/api/v2/\",\n         \"databases\": {\n         \"accounting\": {\n             \"username\": \"root\",\n             \"password\": \"\",\n             \"database\": \"accounting_development\",\n             \"host\": \"localhost\",\n             \"dialect\": \"mysql\",\n             \"dialectOptions\": {\n             \"decimalNumbers\": true\n             },\n         \"users\": {} etc\n         }\n     },\n\n     // Copy the above config for each db to the top level ---->>\n\n     \"accounting\": {\n         \"username\": \"root\",\n         \"password\": \"\",\n         \"database\": \"accounting_development\",\n         \"host\": \"localhost\",\n         \"dialect\": \"mysql\",\n         \"dialectOptions\": {\n         \"decimalNumbers\": true\n         }\n     },\n     \"users\": {}\n }\n```\n\n```text\n\"scripts\": {\n   \"sequelize:accounting:migrate\": \"sequelize --options-path ./.sequelize-accounting --env accounting db:migrate\",\n   \"sequelize:users:migrate\": \"sequelize --options-path ./.sequelize-users --env users db:migrate\",\n }\n```\n\n```text\nnpm run sequelize:accounting:migrate\n npm run sequelize:users:migrate\n```\n\n```text\nnpm i sequelize-cli\n```\n\n```text\n/server/migrations/accounting\n```\n\n```text\n/server/migrations/users\n```\n\n```text\n.sequelize-mydb\n```\n\n```text\n.sequelize-accounting\n```\n\n```text\n.sequelize-users\n```\n\n```text\npackage.json\n```\n\n```js\n// save in file named index.js\n// you can then execute the code from your console using `node index.js`\nconst { Sequelize, Op, DataTypes } = require(\"sequelize\");\nconst fieldNames = [// These fields will be different for your database\n  `battSoc`,\n  `panelV`,\n  `panelI`,\n  `loadV`,\n  `loadI`,\n  `battV`,\n  `battI`,\n  `battTemp`,\n  `panelW`,\n  `loadW`,\n  `tempEquip`,\n  `ambientTemp`,\n];\n\nconst SolarFields = {\n  id: {\n    type: DataTypes.INTEGER,\n    autoIncrement: true,\n    primaryKey: true,\n  },\n};\n\nSolarFieldNames.map((fieldName) => {\n  SolarFields[fieldName] = { type: DataTypes.FLOAT };\n});\n\nasync function copyDataMariaToPostgres() {\n  const postgres = new Sequelize(\"postgressdbname\", \"username\", \"password\", {\n    host: \"localhost\",\n    dialect: \"postgres\",\n  });\n\n  const mariaDb = new Sequelize(\"mariadbname\", \"username\", \"password\", {\n    host: \"192.168.1.110\",\n    dialect: \"mariadb\",\n  });\n  let solarSource;\n  let solarDest;\n  postgres\n    .authenticate()\n    .then(function (result) {\n      return mariaDb.authenticate();\n    })\n    .then(async function (result) {\n      solarSource = mariaDb.define(\"solar\", SolarFields, {\n        tableName: \"solar\",\n        timestamps: false,\n      });\n      solarDest = postgres.define(\"solar\", SolarFields, {\n        tableName: \"solar\",\n        timestamps: false,\n      });\n\n      await solarSource.sync({ logging: false });\n      await solarDest.sync({ logging: false });\n      // get last row in dest:\n      let lastRow = await solarDest.findOne({ order: [[\"id\", \"desc\"]] });\n      let rows;\n      do {\n        findAllParams = { logging: false, limit: 100, order: [[\"id\", \"asc\"]] };\n        // lastRow is null if the destination is empty\n        if (lastRow) findAllParams.where = { id: { [Op.gt]: lastRow.id } };\n        const promises = [];\n        rows = await solarSource.findAll(findAllParams);\n        rows.forEach(async function (row, i) {\n          promises.push(solarDest.create(row.dataValues, { logging: false }));\n        });\n        const newRows = await Promise.all(promises);\n        newRows.forEach((row, i) => {\n          console.log(`#${i} ${row.dataValues.id}`);\n          lastRow = row;\n        });\n      } while (rows.length > 0);\n    })\n    .catch((e) => {\n      console.error(e);\n    });\n}\ncopyDataMariaToPostgres();\n```\n\n```text\nsolar\n```\n\n```text\nmysql\n```\n\n```text\npostgres\n```\n\n```text\nnodejs\n```\n\n========================================\n\nComments:\n- I am stuck with this. Can you your implementation on this?\n- Excellent answer, and thank you. Confirmed, works flawlessly. I've gone ahead and created multiple instances, and then I reference those when creating my models, and it works a charm. Appreciate the sanity check to make sure I'm not doing it in a hack-ish fashion.\n- I have the similar issue on multiple databases access. In my app, there are a single db connection pool, which handles all the db connections onto multiple databases with the same schema. So, I haven't found a perfect solution yet.\n- @dougBTV Can you snippet to represent relations between them?\n- Is this scalable ? Could this cause any problem if I have over 100 database to handle ? 1000 ? 10 000 ?\n- Can confirm this works, I looped through databases in config.js to get a connection to each.\n- It was too complicated guys. Not recommended way\n- How do you specify which database to use when running an update migration?\n- @leo_cape did you find a solution to running the migrations for multiple databases?\n- Hi @MiguelStevens I just made an answer for you as its too much detail for a comment, cheers stackoverflow.com/a/74729814/1865568\n- Can we put query to get data from two databases in Postgres?\n- The OP asked about querying different DBs not different tables!\n- @alfasin this answer includes dbs the syntax is DB.Table where DB is your DB name.\n- There is no such syntax for db: this is `schema.table` not `db.table`!\n- Tried cross db join... no love. Table does not exist.\n- This is interesting because PG uses schemas somewhat differently than MSSQL. I am currently working on a multi db MSSQL and I guess I will see if the schema dot notation can be applied to databases instead.\n- Yes.. I was able to go into different dbs and schemas with the dot notation as long as the models are loaded for each database\n- By this way ,can we set db name on each api call?if yes how?\n- Have you considered using Umzug for migrations?","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":391,"estimatedTokens":2488}}95{"id":"stack-35079286","source":"stackoverflow","questionId":35079286,"title":"Sequelize bulkCreate() returns NULL value for primary key","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: Sequelize bulkCreate() returns NULL value for primary key\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am writing rest using node, sequelize as ORM for mySQL.\nI am using bulkCreate function to create record in bulk. But in response it is returning **null** for primary key value.\n\nModel\n\n```\nsequelize.define('category', {\n cat_id:{\n type:DataTypes.INTEGER,\n field:'cat_id',\n primaryKey: true,\n autoIncrement: true,\n unique:true\n },\n cat_name:{\n type: DataTypes.STRING,\n field: 'cat_name',\n defaultValue:null\n }\n});\n```\n\nBulk Create operation :\n\n```\nvar data = [\n {\n 'cat_name':'fashion'\n },\n {\n 'cat_name':'food'\n }\n ];\n\n orm.models.category.bulkCreate(data)\n .then(function(response){\n res.json(response);\n })\n .catch(function(error){\n res.json(error);\n })\n```\n\nresponse :\n\n```\n[\n {\n \"cat_id\": null,\n \"cat_name\": \"fashion\",\n \"created_at\": \"2016-01-29T07:39:50.000Z\",\n \"updated_at\": \"2016-01-29T07:39:50.000Z\"\n },\n {\n \"cat_id\": null,\n \"cat_name\": \"food\",\n \"created_at\": \"2016-01-29T07:39:50.000Z\",\n \"updated_at\": \"2016-01-29T07:39:50.000Z\"\n }\n]\n```\n\n========================================\n\nTop Answer:\nTested in MySQL:\n\n```\nModel.bulkCreate(values, { individualHooks: true })\n```\n\n========================================\n\nCode:\n```text\nsequelize.define('category', {\n    cat_id:{\n        type:DataTypes.INTEGER,\n        field:'cat_id',\n        primaryKey: true,\n        autoIncrement: true,\n        unique:true\n    },\n    cat_name:{\n        type: DataTypes.STRING,\n        field: 'cat_name',\n        defaultValue:null\n    }\n});\n```\n\n```text\nvar data = [\n        {\n            'cat_name':'fashion'\n        },\n        {\n            'cat_name':'food'\n        }\n    ];\n\n    orm.models.category.bulkCreate(data)\n    .then(function(response){\n        res.json(response);\n    })\n    .catch(function(error){\n        res.json(error);\n    })\n```\n\n```text\n[\n  {\n    \"cat_id\": null,\n    \"cat_name\": \"fashion\",\n    \"created_at\": \"2016-01-29T07:39:50.000Z\",\n    \"updated_at\": \"2016-01-29T07:39:50.000Z\"\n  },\n  {\n    \"cat_id\": null,\n    \"cat_name\": \"food\",\n    \"created_at\": \"2016-01-29T07:39:50.000Z\",\n    \"updated_at\": \"2016-01-29T07:39:50.000Z\"\n  }\n]\n```\n\n```text\nModel.bulkCreate(values, {returning: true})\n```\n\n```text\nreturning\n```\n\n```text\nvar cat = rm.models.category;\ncat.bulkCreate(data)\n .then(function (instances) {\n    var names = _.map(instances, function (inst) {\n      return inst.cat_name;\n    });\n    return cat.findAll({where: {cat_name: {$in: names}}); \n })\n .then(function(response){\n    res.json(response);\n })\n .catch(function(error){\n    res.json(error);\n });\n```\n\n```text\nvar _ = require('lodash');\n```\n\n```text\nModel.bulkCreate(values, { individualHooks: true })\n```\n\n```text\nvar data = [\n    {\n        'cat_name':'fashion'\n    },\n    {\n        'cat_name':'food'\n    }\n];\n\nModel.bulkCreate(data)\n.then(function() {\n\n //(if you try to immediately return the Model after bulkCreate, the ids may all show up as 'null')\n  return Model.findAll()\n})\n.then(function(response){\n    res.json(response);\n})\n.catch(function(error){\n    res.json(error);\n})\n```\n\n```text\norm.models.category.bulkCreate(data, { returning: true })\n```\n\n```text\nvar data = [{\n   'cat_name':'fashion'\n  },\n  {\n   'cat_name':'food'\n  }\n ];\n\norm.models.category.bulkCreate(data,{individualHooks: true})\n .then(function(response){\n   res.json(response);\n })\n .catch(function(error){\n   res.json(error);\n });\n```\n\n========================================\n\nComments:\n- But only in postgres and mssql\n- It will not update the `values` array. It will return a new array.\n- Hey I am using postgresql 14 but it didn't work for me @Adam\n- { individualHooks: true } is wildly misleading, at least in Sequelize 3. I just traced it and it reverts to doing individual saves! It's NOT BULK! Sorry to be the bearer of bad news...\n- This should be the accepted answer since his question is related to the mysql.\n- I tested this in MySQL and it is currently not working\n- Good use of comments in your example. Nice job on your first answer. Welcome (another woman, YAY) to the Community ;)\n- While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":222,"estimatedTokens":1089}}96{"id":"stack-17667368","source":"stackoverflow","questionId":17667368,"title":"sequelize.js - You need to install mysql package manually","tags":["mysql","node.js","sequelize.js"],"text":"Title: sequelize.js - You need to install mysql package manually\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAfter installing node.js and sequelize.js, and running a basic test, the message \"You need to install mysql package manually\" is displayed.\n\nI've tried searching the web and Stackoverflow for the cause of this message.\n\nI have installed: \n\n- mysql server version 5.5.31-0ubuntu0.13.04.1\n\n- node v0.10.5\n\n- sequelize.js v1.6.0\n\n========================================\n\nTop Answer:\nInstall mysql globally: \n\n```\nnpm install -g mysql\n```\n\n========================================\n\nCode:\n```text\nmysql\n```\n\n```text\nnpm install mysql\n```\n\n```text\nnpm install -g mysql\n```\n\n```text\nnpm install -g mysql\n```\n\n```text\nmysql2\n```\n\n```text\nmysql\n```\n\n```text\nnpm i sequelize@4.23.0 --save\n```\n\n```text\nmysql2\n```\n\n```text\n// Using NPM\n$ npm install --save sequelize\n\n# And one of the following:\n$ npm install --save pg pg-hstore\n$ npm install --save mysql2\n$ npm install --save sqlite3\n$ npm install --save tedious // MSSQL\n```\n\n```text\nnpm install --save mysql2\n```\n\n```text\nnpm uninstall sequelize-cli\nnpm install sequelize-cli -g --force // --force removed the previous bin files\n```\n\n========================================\n\nComments:\n- Why did you specify exactly this alpha version? Wouldn't `npm install mysql` be enough and more useable for future reference? (current npm-module version is alpha9).\n- Well, responding to my own doubts: The sequelize.js module officially works with the modules `mysql@~2.0.0-alpha7` and `sequelize-mysql`: sequelizejs.com/documentation\n- Although accepted, your answer doesn't answer the question. **What's the cause** for this massage?\n- @borisdiakur The lack of installing the mysql module; it seems fairly obvious.\n- @DaveNewton The part that was not fairly obvious is why the mysql module is not listed as a direct dependency of sequelize per default. Meanwhile go-oleg has edited his answer accordingly. +1\n- This should be marked as correct answer because locally mysql will be installed for all. This is the tricky one.\n- -g means install globally.\n- it would be nice if you are gonna add description about this solution","metadata":{"transformedAt":"2026-08-18T18:33:34.344Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":92,"estimatedTokens":549}}97{"id":"stack-36480587","source":"stackoverflow","questionId":36480587,"title":"Sequelize how to check if entry exists in database","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize how to check if entry exists in database\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to check if entry with specific ID exists in the database using Sequelize in Node.js\n\n```\nfunction isIdUnique (id) {\n db.Profile.count({ where: { id: id } })\n .then(count => {\n if (count != 0) {\n return false;\n }\n return true;\n });\n }\n```\n\nI call this function in an if statement but the result is always undefined \n\n```\nif(isIdUnique(id)){...}\n```\n\n========================================\n\nTop Answer:\nI don't prefer using **count** to check for record existence. Suppose you have similarity for hundred in million records why to count them all if you want just to get boolean value, true if exists false if not?\n\n**findOne** will get the job done at the first value when there's matching.\n\n```\nconst isIdUnique = id =>\n db.Profile.findOne({ where: { id} })\n .then(token => token !== null)\n .then(isUnique => isUnique);\n```\n\n========================================\n\nCode:\n```text\nfunction isIdUnique (id) {\n    db.Profile.count({ where: { id: id } })\n      .then(count => {\n        if (count != 0) {\n          return false;\n        }\n        return true;\n      });\n  }\n```\n\n```text\nif(isIdUnique(id)){...}\n```\n\n```text\nfunction isIdUnique (id) {\n    return db.Profile.count({ where: { id: id } })\n      .then(count => {\n        if (count != 0) {\n          return false;\n        }\n        return true;\n    });\n}\n\nisIdUnique(id).then(isUnique => {\n    if (isUnique) {\n        // ...\n    }\n});\n```\n\n```text\nfindOne()\n```\n\n```text\nisIdUnique\n```\n\n```text\nconst isIdUnique = id =>\n  db.Profile.findOne({ where: { id} })\n    .then(token => token !== null)\n    .then(isUnique => isUnique);\n```\n\n```text\nfunction isIdUnique (id, done) {\n    db.Profile.count({ where: { id: id } })\n      .then(count => {\n        done(count == 0);\n      });\n  }\n}\n\nisIdUnique(id, function(isUnique) {\n  if (isUnique) {\n    // stuff\n  }\n});\n```\n\n```text\nProject\n  .findAndCountAll({\n     where: {\n        title: {\n          [Op.like]: 'foo%'\n        }\n     },\n     offset: 10,\n     limit: 2\n  })\n  .then(result => {\n    console.log(result.count);\n    console.log(result.rows);\n  });\n```\n\n```text\nfunction isIdUnique (id, done) {\n  db.Profile.count({ where: { id: id } })\n  .then(count => {\n    return (count > 0) ? true : false\n  });\n}\n```\n\n```text\nconst isIdUnique = id =>\n  db.Profile.findOne({ where: { id }, attributes: ['id'] })\n    .then(token => token !== null)\n    .then(isUnique => isUnique);\n```\n\n```text\nattributes\n```\n\n```text\nid\n```\n\n```text\nconst isIdUnique = async (id, model) => {\n    return await model.count({ where: { id: id } });\n};\n        \nconst checkExistId = await isIdUnique(idUser, User);\nconsole.log(\"checkExistId: \", checkExistId);\n```\n\n========================================\n\nComments:\n- I'd use `db.Profile.findOne` with `options.rejectOnEmpty` to throw an error, and then place the success callback in a preceding `.then` and an error cb (not found, etc.) in `.catch`\n- How do you associate your models as child objects of the main sequelize/db object?\n- Using count means it will go through all records in the database every time. It would be more efficent to use findOne() as in Jalal's answer below\n- How do you load Sequelize models as child objects of the `db` object?\n- Where exactly do we put this piece of code? Can you a full example?\n- what is this extra chaining of Promise `.then(isUnique => isUnique)` for?\n- we should select needed attributes for better performance `findOne({where : {id} , attributes: ['id]} )`","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":167,"estimatedTokens":894}}98{"id":"stack-35337738","source":"stackoverflow","questionId":35337738,"title":"Where to handle the error in a sequelize ORM query statement?","tags":["javascript","express","sequelize.js"],"text":"Title: Where to handle the error in a sequelize ORM query statement?\nTags: javascript, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize ORM in Node/Express.\n\nI have two tables, User and Item. Item has a foreign key linked to UserId.\n\nWhen I try to create an Item with a UserId that is invalid (not present in Users table) a \"SequelizeForeignKeyConstraintError\" is thrown and leads to crashing of the application due to unhandled.\n\nThe problem I have is this:\n\nWhere do I handle the error?\n\nHere is my code.\n\n```\n.post(function(req,res){\n models.Item.create({\n title : req.body.title,\n UserId : req.body.UserId\n }).then(function(item){\n res.json({\n \"Message\" : \"Created item.\",\n \"Item\" : item\n });\n });\n });\n```\n\n========================================\n\nTop Answer:\nYou can handle all ORM errors to return an HTTP 500 status and some default error message by doing something like below\n\n```\nrouter.use((error, request, response, next) => {\n response.status(error.status || 500).json({\n status: 'error',\n error: {\n message: error.message || serverErrorMsg,\n },\n });\n});\n```\n\nThe above code also allows you to throw errors with custom messages that will be sent to the client by passing the error to the `next` function\n\n```\nconst error = new Error(/* your error message */);\nerror.status = 409;\nnext(error);\n```\n\n========================================\n\nCode:\n```text\n.post(function(req,res){\n        models.Item.create({\n            title : req.body.title,\n            UserId : req.body.UserId\n        }).then(function(item){\n            res.json({\n                \"Message\" : \"Created item.\",\n                \"Item\" : item\n            });\n        });\n    });\n```\n\n```text\nmodels.Item.create({\n  title : req.body.title,\n  UserId : req.body.UserId\n}).then(function(item){\n  res.json({\n    \"Message\" : \"Created item.\",\n    \"Item\" : item\n  });\n}).catch(function (err) {\n  // handle error;\n});\n```\n\n```text\n.catch\n```\n\n```text\nrouter.use((error, request, response, next) => {\n  response.status(error.status || 500).json({\n    status: 'error',\n    error: {\n      message: error.message || serverErrorMsg,\n    },\n  });\n});\n```\n\n```text\nconst error = new Error(/* your error message */);\nerror.status = 409;\nnext(error);\n```\n\n```text\nnext\n```\n\n========================================\n\nComments:\n- See sequelize.org/v3/api/errors\n- If you want to catch the specific SequelizeForeignKeyConstraintError error you can pass it to the catch function `.catch(Sequelize.SequelizeForeignKeyConstraintError, function (err) { &#47;&#47; handle onky foreign key errors ; });`\n- is it possible to handle all ORM errors by HTTP 500 status and default error handler in express? actually i don't want to add `.catch(err=>{next(err)});` whenever I hit the database.\n- please add the await version try { ... } catch(err) { ... }","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":118,"estimatedTokens":709}}99{"id":"stack-32649218","source":"stackoverflow","questionId":32649218,"title":"How do I select a column using an alias","tags":["javascript","sql","sequelize.js"],"text":"Title: How do I select a column using an alias\nTags: javascript, sql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do I perform an sql query such as this?\n\n`SELECT column_name AS alias_name FROM table_name;`\n\nExample: I want the column 'first' to be selected as 'firstname'\n\n```\nTable.findAll({\n attributes: [id,\"first\"]\n })\n .then(function(posts) {\n res.json(posts);\n })\n```\n\n========================================\n\nTop Answer:\n**You need to use `row.get('newname')` to access columns aliased by `attributes`**\n\nDoing just `row.newname`, or `row.oldname`, will not work like it does for non-aliased names for some reason:\n\nhttps://github.com/sequelize/sequelize/issues/10592\n\nhttps://sequelize.org/v5/manual/models-usage.html documents it:\n\n```\nProject.findOne({\n where: {title: 'aProject'},\n attributes: ['id', ['name', 'title']]\n}).then(project => {\n // project will be the first entry of the Projects table with the title\n // 'aProject' || null\n // project.get('title') will contain the name of the project\n})\n```\n\nbut https://sequelize.org/master/class/lib/model.js~Model.html doesn't mention it, which is confusing:\n\n```\ninstance.field\n// is the same as\ninstance.get('field')\n```\n\nRelated: Sequelize cannot access alias. Alias is undefined\n\nMinimal runnable example:\n\n```\nconst assert = require('assert');\nconst path = require('path');\nconst { Sequelize, DataTypes, Op } = require('sequelize');\nconst sequelize = new Sequelize({\n dialect: 'sqlite',\n storage: path.basename(__filename) + '.sqlite',\n});\n(async () => {\nconst Int = sequelize.define('Int', {\n value: {\n type: DataTypes.INTEGER,\n },\n name: {\n type: DataTypes.STRING,\n },\n}, {});\nawait Int.sync({force: true})\nawait Int.create({value: 2, name: 'two'});\nlet row;\nrow = await Int.findOne({\n where: { value: 2 },\n attributes: [ 'id', [ 'value', 'newvalue' ] ],\n});\nassert.strictEqual(row.id, 1);\nassert.strictEqual(row.value, undefined);\nassert.strictEqual(row.newvalue, undefined);\nassert.strictEqual(row.get('newvalue'), 2);\nawait sequelize.close();\n})();\n```\n\nThe generated query does exactly what we wanted then:\n\n```\nSELECT `id`, `value` AS `newvalue` FROM `Ints` AS `Int`\n WHERE `Int`.`value` = 2 LIMIT 1;\n```\n\ntested on sequelize 6.5.1, sqlite3 5.0.2.\n\n========================================\n\nCode:\n```text\nTable.findAll({\n      attributes: [id,\"first\"]\n    })\n    .then(function(posts) {\n        res.json(posts);\n    })\n```\n\n```text\nSELECT column_name AS alias_name FROM table_name;\n```\n\n```text\nTable.findAll({\n  attributes: ['id', ['first', 'firstName']] //id, first AS firstName\n})\n.then(function(posts) {\n  res.json(posts);\n});\n```\n\n```js\nconst { Model, DataTypes, Deferrable } = require(\"sequelize\");\n\nclass Foo extends Model { }\nFoo.init({\n    // You can specify a custom column name via the 'field' attribute:\n    fieldWithUnderscores: {\n        type: DataTypes.STRING, \n        field: 'field_with_underscores'\n    },\n}, {\n    sequelize,\n    modelName: 'foo'\n});\n```\n\n```text\nfield\n```\n\n```text\nProject.findOne({\n  where: {title: 'aProject'},\n  attributes: ['id', ['name', 'title']]\n}).then(project => {\n  // project will be the first entry of the Projects table with the title\n  // 'aProject' || null\n  // project.get('title') will contain the name of the project\n})\n```\n\n```text\ninstance.field\n// is the same as\ninstance.get('field')\n```\n\n```text\nconst assert = require('assert');\nconst path = require('path');\nconst { Sequelize, DataTypes, Op } = require('sequelize');\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: path.basename(__filename) + '.sqlite',\n});\n(async () => {\nconst Int = sequelize.define('Int', {\n  value: {\n    type: DataTypes.INTEGER,\n  },\n  name: {\n    type: DataTypes.STRING,\n  },\n}, {});\nawait Int.sync({force: true})\nawait Int.create({value: 2, name: 'two'});\nlet row;\nrow = await Int.findOne({\n  where: { value: 2 },\n  attributes: [ 'id', [ 'value', 'newvalue' ] ],\n});\nassert.strictEqual(row.id, 1);\nassert.strictEqual(row.value, undefined);\nassert.strictEqual(row.newvalue, undefined);\nassert.strictEqual(row.get('newvalue'), 2);\nawait sequelize.close();\n})();\n```\n\n```text\nSELECT `id`, `value` AS `newvalue` FROM `Ints` AS `Int`\n  WHERE `Int`.`value` = 2 LIMIT 1;\n```\n\n```text\nrow.get('newname')\n```\n\n```text\nattributes\n```\n\n```text\nrow.newname\n```\n\n```text\nrow.oldname\n```\n\n```text\nTable.findAll({\n  attributes: ['id', ['first', 'firstName']] //id, first AS firstName\n})\n.then(function(posts) {\n  res.json(posts);\n});\n```\n\n```text\nModel.findAll({\n  attributes: {\n    include: [\n      [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats']\n    ]\n  }\n});\n```\n\n========================================\n\nComments:\n- It works, but when used in a join query, it appends the table name to the alias given. Is there a way to remove the table name?\n- @antew you can find the answer here: stackoverflow.com/questions/50148491/&hellip;\n- It doesn't work in multi-level joins. Lets say, Table A includes ( Table B includes Table C ). I cannot select Table C columns in Table B ( it always prefixes table A )","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":235,"estimatedTokens":1259}}100{"id":"stack-69878173","source":"stackoverflow","questionId":69878173,"title":"SCRAM-SERVER-FIRST-MESSAGE: client password must be a string","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIve read documentation from several pages on SO of this issue, but i havent been able to fix my issue with this particular error.\n\n```\nthrow new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')\n ^\n\nError: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\n at Object.continueSession (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg\\lib\\sasl.js:24:11)\n at Client._handleAuthSASLContinue (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg\\lib\\client.js:257:10)\n at Connection.emit (events.js:400:28)\n at C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg\\lib\\connection.js:114:12\n at Parser.parse (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg-protocol\\dist\\parser.js:40:17)\n at Socket. (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg-protocol\\dist\\index.js:11:42)\n at Socket.emit (events.js:400:28)\n at addChunk (internal/streams/readable.js:290:12)\n at readableAddChunk (internal/streams/readable.js:265:9)\n at Socket.Readable.push (internal/streams/readable.js:204:10)\n```\n\nits as if in my `connectDB()` function its not recognizing the password to the database. I am trying to run a `seeder.js` script to seed the database with useful information for testing purposes, and if i run `npm run server` which is a script that just starts a nodemon server, itll connect to the DB just fine. but when i try to run my script to seed data, i am returning this error.\n\n\r\n\r\n\n```\nimport { Sequelize } from \"sequelize\";\nimport colors from \"colors\";\nimport dotenv from \"dotenv\";\n\ndotenv.config();\n\nconst user = \"postgres\";\nconst host = \"localhost\";\nconst database = \"thePantry\";\nconst port = \"5432\";\n\nconst connectDB = async () => {\n const sequelize = new Sequelize(database, user, process.env.DBPASS, {\n host,\n port,\n dialect: \"postgres\",\n logging: false,\n });\n try {\n await sequelize.authenticate();\n console.log(\"Connection has been established successfully.\".bgGreen.black);\n } catch (error) {\n console.error(\"Unable to connect to the database:\".bgRed.black, error);\n }\n};\n\nexport default connectDB;\n```\n\n\r\n\r\n\r\n\nabove is my connectDB() file, and again, it works when i run the server normally. but i receive this error only when trying to seed the database. Ill post my seeder script below:\n\n\r\n\r\n\n```\nimport dotenv from \"dotenv\";\nimport colors from \"colors\";\nimport users from \"./data/users.js\";\n\nimport User from \"./models/userModel.js\";\n\nimport connectDB from \"./config/db.js\";\n\ndotenv.config();\nconsole.log(process.env.DBPASS);\n\nconnectDB();\n\nconst importData = async () => {\n try {\n await User.drop();\n await User.sync();\n\n await User.bulkCreate(users);\n\n console.log(\"Data Imported\".green.inverse);\n process.exit();\n } catch (e) {\n console.error(`${e}`.red.inverse);\n process.exit(1);\n }\n};\n\nconst destroyData = async () => {\n try {\n await User.bulkDestroy();\n\n console.log(\"Data Destroyed\".red.inverse);\n process.exit();\n } catch (e) {\n console.error(`${e}`.red.inverse);\n process.exit(1);\n }\n};\n\nif (process.argv[2] === \"-d\") {\n destroyData();\n} else {\n importData();\n}\n```\n\n========================================\n\nTop Answer:\nAdd your .env file in your project, I think your .env file is missing in your project folder.\nadd like this:\nhttps://i.sstatic.net/HoHX0.png\n\n========================================\n\nCode:\n```text\nthrow new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')\n    ^\n\nError: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\n    at Object.continueSession (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg\\lib\\sasl.js:24:11)\n    at Client._handleAuthSASLContinue (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg\\lib\\client.js:257:10)\n    at Connection.emit (events.js:400:28)\n    at C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg\\lib\\connection.js:114:12\n    at Parser.parse (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg-protocol\\dist\\parser.js:40:17)\n    at Socket.<anonymous> (C:\\Users\\CNFis\\Desktop\\WulfDevelopments\\ThePantry\\node_modules\\pg-protocol\\dist\\index.js:11:42)\n    at Socket.emit (events.js:400:28)\n    at addChunk (internal/streams/readable.js:290:12)\n    at readableAddChunk (internal/streams/readable.js:265:9)\n    at Socket.Readable.push (internal/streams/readable.js:204:10)\n```\n\n```js\nimport { Sequelize } from \"sequelize\";\nimport colors from \"colors\";\nimport dotenv from \"dotenv\";\n\ndotenv.config();\n\nconst user = \"postgres\";\nconst host = \"localhost\";\nconst database = \"thePantry\";\nconst port = \"5432\";\n\nconst connectDB = async () => {\n  const sequelize = new Sequelize(database, user, process.env.DBPASS, {\n    host,\n    port,\n    dialect: \"postgres\",\n    logging: false,\n  });\n  try {\n    await sequelize.authenticate();\n    console.log(\"Connection has been established successfully.\".bgGreen.black);\n  } catch (error) {\n    console.error(\"Unable to connect to the database:\".bgRed.black, error);\n  }\n};\n\nexport default connectDB;\n```\n\n```js\nimport dotenv from \"dotenv\";\nimport colors from \"colors\";\nimport users from \"./data/users.js\";\n\nimport User from \"./models/userModel.js\";\n\nimport connectDB from \"./config/db.js\";\n\ndotenv.config();\nconsole.log(process.env.DBPASS);\n\nconnectDB();\n\nconst importData = async () => {\n  try {\n    await User.drop();\n    await User.sync();\n\n    await User.bulkCreate(users);\n\n    console.log(\"Data Imported\".green.inverse);\n    process.exit();\n  } catch (e) {\n    console.error(`${e}`.red.inverse);\n    process.exit(1);\n  }\n};\n\nconst destroyData = async () => {\n  try {\n    await User.bulkDestroy();\n\n    console.log(\"Data Destroyed\".red.inverse);\n    process.exit();\n  } catch (e) {\n    console.error(`${e}`.red.inverse);\n    process.exit(1);\n  }\n};\n\nif (process.argv[2] === \"-d\") {\n  destroyData();\n} else {\n  importData();\n}\n```\n\n```text\nconnectDB()\n```\n\n```text\nseeder.js\n```\n\n```text\nnpm run server\n```\n\n```text\nserver.js\n```\n\n```text\nMongoose\n```\n\n```text\nSequelize\n```\n\n```text\nmodel\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize\n```\n\n```text\nseeder.js\n```\n\n```text\nUser\n```\n\n```js\nconst user = \"postgres\";\n    const host = \"localhost\";\n    const database = \"thePantry\";\n    const password = \"yourdatabasepassword\"; if null > const password = \"\"; \n    const port = \"5432\";\n```\n\n```text\nlet sequelize;\nif (config.use_env_variable) {\nsequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n  sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n```\n\n```text\nmodule.exports = {\n  \"development\": {\n    \"url\":\"postgres://username:password@IP_adress:port/db_name\",\n    \"dialect\": \"postgres\",    \n  }, ...\n}\n```\n\n```text\nlet sequelize;\nif (config.use_env_variable) {\n  sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n  sequelize = new Sequelize(config.url, config);\n}\n```\n\n```text\nDATABASE_URL=postgres://username:password@IP_adress:port/db_name\n```\n\n```text\nPOSTGRES=postgres://postgres:test@localhost:5432/default\n```\n\n```text\nPOSTGRES_DB_HOST=localhost\nPOSTGRES_DB_PORT=5432\n...rest of configs\n```\n\n```text\nnodemon\n```\n\n```text\nconst pool = new Pool({\n  user: '****',\n  database: '****',\n  password: '****',\n  port: 5432,\n  host: '****',\n  max: 5,\n  idleTimeoutMillis: 30000,\n  connectionTimeoutMillis: 5000,\n})\n```\n\n```text\nnode-postgres\n```\n\n```text\nnpx sequelize-cli db:...\n```\n\n```text\npostgres -D /usr/local/var/postgres\n```\n\n```js\n// module database.js\n\nconst connectDB = () => {\n  const { POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD } = process.env\n  ...\n}\n```\n\n```js\n// module database.js\nconst { POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD } = process.env\n\nconst connectDB = () => {\n  ...\n}\n```\n\n```js\n// module database.js\nimport 'dotenv/config' // populate process.env for imported files\n\nconst { POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD } = process.env\n\nconst connectDB = () => {\n  ...\n}\n```\n\n```text\ndotenv\n```\n\n```text\nprocess.env\n```\n\n```text\ndotenv\n```\n\n```text\nconnectDB\n```\n\n```text\ndotenv\n```\n\n```text\ndotenv\n```\n\n```text\nconst { Client } = require(\"pg\");let db = new Client({\n    connectionString: \"postgresql://postgres:password_here@localhost/dbName\"  \n});db.connect();\n```\n\n```text\n// This failed\n// const connection = await mysql.createConnection(process.env.DB_APEX_K8S!)\n\n// This worked:\nconst connection = await mysql.createConnection({\n  host: process.env.DB_K8S_APEX_host!,\n  port: Number(process.env.DB_K8S_APEX_port!),\n  user: process.env.DB_K8S_APEX_user!,\n  password: process.env.DB_K8S_APEX_password!,\n  database: process.env.DB_K8S_APEX_database!,\n})\nexport const db_apex_k8s = drizzle(connection)\n```\n\n```text\n.env\n```\n\n```text\nexport NODE_ENV=development\n\nyarn migration:run\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nDBPASS:\"this is your password\"\n```\n\n```text\nDBPASS=\"this is your password\"\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\n=\n```\n\n```text\n:\n```\n\n```text\n/home/user/app/src/main.js\n/home/user/app/.env\n```\n\n```text\npm2\n```\n\n```text\npm2\n```\n\n```text\n.env\n```\n\n```text\n/home/user\n```\n\n```text\npm2 start app/src/main.js\n```\n\n```text\n/home/user/app\n```\n\n```text\npm2 start /src/main.js\n```\n\n```text\npm2\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- I got this error when my local development database was off (because I restarted my computer) 🫠\n- This error is shown if your DB details are not defined i.e either wrong reference or undefined variables(fixed by fixing above and fif using env makes sure the values are properly loaded/read)\n- This was not it, as i stated in my post back in November, the Connection wasnt available in other areas of the App,\n- Ok, but this answer is helpful to others if they have a same issue.\n- its not though, the .env wasnt missing from the folder structure. this answer does not solve the problem.\n- I think this solves the problem in some cases, maybe not in your case...\n- If you are using nextjs, ensure the file is named \".env\" and it's located in the root of your frontend\n- I was looking for solution then saw myself. It is good answer i can say. Because i was using strapi. Then check the environment i saw that there is no password. Now it works. Thanks to me ^.^\n- run npm install dotenv and add import 'dotenv/config'; to your main.js or server.js\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review\n- This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":57,"totalLines":514,"estimatedTokens":2752}}101{"id":"stack-36164694","source":"stackoverflow","questionId":36164694,"title":"Sequelize - subquery in where clause","tags":["orm","subquery","where-clause","sequelize.js"],"text":"Title: Sequelize - subquery in where clause\nTags: orm, subquery, where-clause, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize in my Express app. I need to generate a query that has a subquery in the `WHERE` clause.\n\n```\nSELECT *\n FROM MyTable\n WHERE id NOT IN (\n SELECT fkey\n FROM MyOtherTable\n WHERE field1 = 1\n AND field2 = 2\n AND field3 = 3\n )\n```\n\nI first tried relations/associations through my models but couldn't get it to work. Something like:\n\n```\nMyTable.find( {\n where: {\n id: {\n $notIn: // Then I tried using `Sequelize.where()`, no luck there.\n\nThen I tried `Sequelize.literal()` and that works but not sure if it's a *\"proper\"* way of doing a subquery in a where clause in Sequelize as I'm new to it.\n\n```\nMyTable.find( {\n where: {\n id: {\n $notIn: sequelize.literal( \n '( SELECT fkey ' +\n 'FROM MyOtherTable ' +\n 'WHERE field1 = ' + field1 +\n ' AND field2 = ' + field2 +\n ' AND field3 = ' + field3 + \n ')'\n }\n } \n} );\n```\n\nI also know that I could use `Sequelize.query()` but don't really know if I should reach for it or if `literal()`is the right away as I feel like there's something I'm overlooking.\n\nI would really like to know how to perform a subquery in a `WHERE` clause with Sequelize the *\"proper\"* way.\n\nThanks for the feedback!\n\n========================================\n\nTop Answer:\nIn addition to @Shahar Hadas answer, because i fall into some errors using the code he showed.\n\nHere is a more complexe example. In this example we have a main table named \"Artist\" in a Many-to-Many relationship with \"Tag\". \"Tag\" are associated to a predefined list of tags i named \"TagType\".\nWe want to fetch all Artists linked to all the searched tags (TagType Id).\n\n```\nconst tagsSearched = [1, 2];\n\nconst subQueryOptions = {\n attributes: ['id'], // You have to list at least one attribute\n include: [\n {\n model: models.Tag,\n required: true,\n attributes: [], // Avoid the only_full_group_by error\n through: {\n attributes: [], // Avoid the only_full_group_by error\n },\n include: {\n model: models.TagType,\n required: true,\n attributes: [], // Avoid the only_full_group_by error\n where: {\n id: {\n [Op.in]: tagsSearched, // Array of tags searched\n }\n },\n },\n }\n ],\n group: sequelize.col('artist.id'), // Group by the main parent ID of this query\n having: sequelize.where(sequelize.fn('count', \n sequelize.col('tags.tagType.id')), {\n [Op.gte]: tagsSearched.length,\n }), // Get only the artists that have at least the \"tagsSearched\" associated\n}\n\n// Parse the subQueryOptions, this operation would serialize the queryOptions\nModel._validateIncludedElements.bind(models.Artist)(subQueryOptions);\n\n// First argument has to be a string (table name, by default in plural)\n// Second argument is our serialized query options\n// Third argument is the model used\nconst artistsSubQuery = sequelize.dialect.queryGenerator.selectQuery(\"artists\", subQueryOptions, models.Artist)\n.slice(0,-1); // to remove the ';' from the end of the SQL query\n\nmodels.Artist.findAll({\n where: {\n id: {\n [Op.in]: sequelize.literal(`(${artistsSubQuery})`),\n }\n }\n});\n```\n\nI will update this in case of questions.\n\n========================================\n\nCode:\n```text\nSELECT *\n  FROM MyTable\n WHERE id NOT IN (\n       SELECT fkey\n         FROM MyOtherTable\n        WHERE field1 = 1\n          AND field2 = 2\n          AND field3 = 3\n       )\n```\n\n```js\nMyTable.find( {\n    where: {\n        id: {\n            $notIn: // <= what goes here? Can I somehow reference my include model?\n        }\n    },\n    include: [ {\n        model: MyOtherTable,\n        where: {\n          field1: 1,\n          field2: 2,\n          field3: 3\n    } ]\n} );\n```\n\n```js\nMyTable.find( {\n    where: {\n        id: {\n            $notIn: sequelize.literal( \n                '( SELECT fkey ' +\n                    'FROM MyOtherTable ' +\n                   'WHERE field1 = ' + field1 +\n                    ' AND field2 = ' + field2 +\n                    ' AND field3 = ' + field3 + \n                ')'\n        }\n    } \n} );\n```\n\n```text\nWHERE\n```\n\n```text\nSequelize.where()\n```\n\n```text\nSequelize.literal()\n```\n\n```text\nSequelize.query()\n```\n\n```text\nliteral()\n```\n\n```text\nWHERE\n```\n\n```js\nconst tempSQL = sequelize.dialect.QueryGenerator.selectQuery('MyOtherTable',{\n    attributes: ['fkey'],\n    where: {\n          field1: 1,\n          field2: 2,\n          field3: 3\n    }})\n    .slice(0,-1); // to remove the ';' from the end of the SQL\n\nMyTable.find( {\n    where: {\n        id: {\n              [Sequelize.Op.notIn]: sequelize.literal(`(${tempSQL})`)\n        }\n    } \n} );\n```\n\n```js\nconst tempSQL = sequelize.dialect.queryGenerator.selectQuery('MyOtherTable',{\n    attributes: ['fkey'],\n    where: {\n          field1: 1,\n          field2: 2,\n          field3: 3\n    }})\n    .slice(0,-1); // to remove the ';' from the end of the SQL\n\nMyTable.find( {\n    where: {\n        id: {\n              [Sequelize.Op.notIn]: sequelize.literal(`(${tempSQL})`)\n        }\n    } \n} );\n```\n\n```js\nconst tagsSearched = [1, 2];\n\nconst subQueryOptions = {\n    attributes: ['id'], // You have to list at least one attribute\n    include: [\n        {\n            model: models.Tag,\n            required: true,\n            attributes: [], // Avoid the only_full_group_by error\n            through: {\n                attributes: [], // Avoid the only_full_group_by error\n            },\n            include: {\n                model: models.TagType,\n                required: true,\n                attributes: [], // Avoid the only_full_group_by error\n                where: {\n                    id: {\n                        [Op.in]: tagsSearched, // Array of tags searched\n                    }\n                },\n            },\n        }\n            ],\n    group: sequelize.col('artist.id'), // Group by the main parent ID of this query\n    having: sequelize.where(sequelize.fn('count', \n            sequelize.col('tags.tagType.id')), {\n                [Op.gte]: tagsSearched.length,\n    }), // Get only the artists that have at least the \"tagsSearched\" associated\n}\n\n// Parse the subQueryOptions, this operation would serialize the queryOptions\nModel._validateIncludedElements.bind(models.Artist)(subQueryOptions);\n\n// First argument has to be a string (table name, by default in plural)\n// Second argument is our serialized query options\n// Third argument is the model used\nconst artistsSubQuery = sequelize.dialect.queryGenerator.selectQuery(\"artists\", subQueryOptions, models.Artist)\n.slice(0,-1); // to remove the ';' from the end of the SQL query\n\nmodels.Artist.findAll({\n    where: {\n        id: {\n            [Op.in]: sequelize.literal(`(${artistsSubQuery})`),\n        }\n    }\n});\n```\n\n========================================\n\nComments:\n- Looking at SO I came to this github issue github.com/sequelize/sequelize/issues/3961, through this question stackoverflow.com/questions/38882185/&hellip;, and apparently using sequelize.literal is the only way for the time being.\n- Seems like using `sequelize.literal(...)` is still the way to go\n- I found this src that may help you (UNTESTED). let me know of your test after you this srlm.io/2015/02/04/sequelize-subqueries\n- wouldn't this solution allow sql injection?\n- @Sash depends on the source of `field1`, `field2`, `field3` and/or if they've already been sanitized/escaped. For this example the values are defined on the backend.\n- I've added an example snippet of how I use it my code. It's a different approch.\n- If you are not using data from the client(s) consuming the API (no need to worry about SQL injection), your solution works perfectly already. And it's easier to implement than the accepted answer.\n- Are `where` objects in SQL generator and in find query safely interchangeable? Can I use the same syntax here and there?\n- ASFAIK yes. The `find` method uses the `QueryGenerator` internally. That's how I came with this approach in the 1st place.\n- Thank you. This saved me when I needed to use limit/offset with `where` for included model. I generated a subquery like you show here and it works like charm.\n- This looks very nice solution. But unfortunately it did not work for me. dialect property does not exist in sequelize variable. Is this because of different latest version I am using?\n- Are you using v6 or v5? On v6 try to use getDialect()\n- I am using v6 but getDialect() method is not available to use\n- Whenever I use this Sequelize.getDialect() it shows this error: Property 'getDialect' does not exist on type 'typeof import(\"node_modules/sequelize/types/index\")'.ts(2339)\n- It exists in the code - github.com/sequelize/sequelize/blob/&hellip; but I'm not using v6 as of yet myself...\n- @AyyazZafar `sequelize.getDialect()` is an instance method - **NOT** static method\n- Ok i tried .getDialect() from instance method but then getDialect().QueryGenerator was not available\n- @AyyazZafar if you'll look at the v5 to v6 migration guide (sequelize.org/master/manual/upgrade-to-v6.html), you'll see they changed `QueryGenerator` to `queryGenerator` >> All instances of QueryInterface and QueryGenerator have been renamed to their lowerCamelCase variants eg. queryInterface and queryGenerator when used as property names on Model and Dialect, the class names remain the same.\n- Okay thanks but actually .getDialect() returns only a string == 'mysql' That's why we cannot use .getDialect().queryGenerator() :(\n- I tried both `Sequelize.mysql.queryGenerator.selectQuery(...)` and `Sequelize.mysql.QueryGenerator.selectQuery(...)` - both result in an error `cannot read property selectQuery of undefined`.\n- @Eggon Which version of Sequelize are you using?\n- @ShaharHadas I'm using v. 5.21.3.\n- @Eggon just realized you are calling `Sequelize.mysql...` and not `sequelize.dialect...` which is using the sequelize connection instance. Look at the examples above\n- @ShaharHadas I see, I read more thoroughly other comments here, I was able to do it using the Sequelize instance. Thanks! Upvoted the answer now! :)\n- Note that `selectQuery` doesn't support some options that `findAll` and the like support; for instance, `paranoid`. You'll have to invoke some more internal methods in order for them the work; for instance, `selectQuery(..., Model._paranoidClause(options))`.\n- This works for me `sequelize.getQueryInterface().queryGenerator.selectQuery`","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":300,"estimatedTokens":2570}}102{"id":"stack-18858337","source":"stackoverflow","questionId":18858337,"title":"Sequelize use camel case in JS but underscores in table names","tags":["sequelize.js"],"text":"Title: Sequelize use camel case in JS but underscores in table names\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to have column names be underscored (postgres) but have the JavaScript getters be camelCase per language standards?\n\n========================================\n\nTop Answer:\nFor anyone finding this later on it's now possible to explicitely define what the database field should be named:\n\n```\nvar User = sequelize.define('user', {\n isAdmin: {\n type: DataTypes.BOOLEAN,\n field: 'is_admin'\n }\n});\n```\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('user', {\n  isAdmin: {\n    type: DataTypes.BOOLEAN,\n    field: 'is_admin'\n  }\n});\n```\n\n```text\nconst Post = sequelize.define('post', {\n    id: {\n      type: DataTypes.UUID,\n      defaultValue: DataTypes.UUIDV4,\n      primaryKey: true,\n      allowNull: false,\n    },\n    isActive: {\n      type: DataTypes.BOOLEAN,\n      defaultValue: true,\n      allowNull: false,\n      field: 'is_active',\n    },\n    isDeleted: {\n      type: DataTypes.BOOLEAN,\n      defaultValue: false,\n      allowNull: false,\n      field: 'is_deleted',\n    },\n  }, {\n    indexes: [\n      {\n        unique: false,\n        fields: ['is_active'],\n      },\n      {\n        unique: false,\n        fields: ['is_deleted'],\n      },\n    ],\n    defaultScope: {\n      where: {\n        isActive: true,\n        isDeleted: false,\n      },\n    },\n  });\n\nconst PostComments = sequelize.define('postComments', {\n    id: {\n      type: DataTypes.UUID,\n      defaultValue: DataTypes.UUIDV4,\n      primaryKey: true,\n      allowNull: false,\n    },\n    postId: {\n      type: DataTypes.UUID,\n      allowNull: false,\n      field: 'post_id',\n    },\n    comment: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n  }, {\n    tableName: 'post_comments',\n    indexes: [\n      {\n        unique: false,\n        fields: ['post_id'],\n      },\n    ],\n  });\n\n\n  Post.hasMany(PostComments, {\n    foreignKey: 'postId',\n    constraints: true,\n    as: 'comments',\n  });\n\n  PostComments.belongsTo(Post, {\n    foreignKey: 'postId',\n    constraints: true,\n    as: 'post',\n  });\n```\n\n```text\nsequelize.query('SET FOREIGN_KEY_CHECKS = 0', { raw: true })\n  .then(() => {\n    conn.sync({ force: true }).then(() => {\n      console.log('DONE');\n    });\n  });\n```\n\n```text\nExecuting (default): SET FOREIGN_KEY_CHECKS = 0\nExecuting (default): DROP TABLE IF EXISTS `post_comments`;\nExecuting (default): DROP TABLE IF EXISTS `post`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `post` (`id` CHAR(36) BINARY NOT NULL , `is_active` TINYINT(1) NOT NULL DEFAULT true, `is_deleted` TINYINT(1) NOT NULL DEFAULT false, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`id`) ENGINE=InnoDB;\nExecuting (default): CREATE TABLE IF NOT EXISTS `post_comments` (`id` CHAR(36) BINARY NOT NULL , `post_id` CHAR(36) BINARY NOT NULL, `comment` VARCHAR(255) NOT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`post_id`) REFERENCES `post` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;\n```\n\n```text\nconst User = sequelize.define('User', {\n    username: DataTypes.STRING,\n    password: DataTypes.STRING\n  }, {underscored: true});\n```\n\n```text\nunderscored: true\n```\n\n========================================\n\nComments:\n- bummer, I was afraid of this\n- @futbolpal it's now possible to define a field for attributes, so you can do something like `userId: {type: DataTypes.INTEGER, field: 'user_id'}`\n- @MickHansen - you are correct, and that is a very useful feature. You can also set `options.underscored: true` on your Mode or Sequelize object. It is worth noting that all auto-generated fields (foreign keys, etc) will need to be referenced by their under_scored name - so your code will look like `{firstName: \"Ryan\", parent_id: 1}`\n- Should `underscored: true` and `underscoredAll: true` options automatically convert camelCased model's attributes names to underscored while database request? I mean, in Model we define as `activationKey : DataTypes.STRING`, but request to db will be `SELECT ... \"activation_key\" ...`?\n- @f1nn No that's not supported at the moment.\n- @MickHansen are there any plans to support this?\n- @f1nn, `underscored` attributes are used to rename only automatically created columns eg. Foreign Keys etc.\n- Do you know if this converts it both ways? So when I read from the DB it converts the JSON object to camelCase. Do I need to convert this manually when writing back or does it handle that conversion as well?\n- @James Parker It is automaticaly done by Sequelize :)\n- The reference URL to the `underscored` option is now sequelize.org/master/class/lib/&hellip;.","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":153,"estimatedTokens":1179}}103{"id":"stack-29995868","source":"stackoverflow","questionId":29995868,"title":"Creating instance with an association in Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Creating instance with an association in Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing Sequelize, I've created two models: `User` and `Login`.\n\nUsers can have more than one Login, but a login must have exactly one user, which means a Login cannot be saved without a User ID.\n\nHow do I `.create` a Login with a User association all in one swoop?\n\n**Current Code (Doesn't Work)**\n\n```\n// Set up the models\nvar User = sequelize.define('User', {});\nvar Login = sequelize.define('Login', {});\nLogin.belongsTo(User, {\n onDelete: 'cascade',\n foreignKey: {\n field: 'userId',\n allowNull: false,\n }\n});\n\n// Create the instances\nvar user = User.create().then(function() {\n\n // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION\n var login = Login.create({\n userId: user.get('id')\n });\n\n)};\n```\n\nThe above results in `SequelizeValidationError: notNull Violation: UserId cannot be null`\n\n========================================\n\nTop Answer:\nFirst of all you need to setup the relations in both ways, like this:\n\n```\n// Set up the models\nvar User = sequelize.define('User', {});\nvar Login = sequelize.define('Login', {});\n\n// Set the correct associations\nUser.hasMany(Login, {})\nLogin.belongsTo(User, {});\n```\n\nThen, you need to properly get the instances returned by the promises:\n\n```\n// Create the instances\nUser.create({}).then(function(newUser) {\n // now you can use newUser acessors to create the login\n return newUser.createLogin({});\n).then(function(newLogin){\n // newLogin\n}).catch(function(error){\n // error\n});\n```\n\n========================================\n\nCode:\n```text\n// Set up the models\nvar User = sequelize.define('User', {});\nvar Login = sequelize.define('Login', {});\nLogin.belongsTo(User, {\n  onDelete: 'cascade',\n  foreignKey: {\n    field: 'userId',\n    allowNull: false,\n  }\n});\n\n// Create the instances\nvar user = User.create().then(function() {\n\n  // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION\n  var login = Login.create({\n    userId: user.get('id')\n  });\n\n)};\n```\n\n```text\nUser\n```\n\n```text\nLogin\n```\n\n```text\n.create\n```\n\n```text\nSequelizeValidationError: notNull Violation: UserId cannot be null\n```\n\n```text\nUser.create({\n   name: \"name\",\n   Login: {...}\n},{\n   include: Login\n})\n```\n\n```text\nvar user = User.create().then(function(user) {\n\n  // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION\n  var login = Login.create({\n    userId: user.get('id')\n  });\n\n  return login\n\n}).then(function(login) {\n    // all creation are complete. do something.\n});\n```\n\n```text\n.then\n```\n\n```text\nvar\n```\n\n```text\n// Set up the models\nvar User = sequelize.define('User', {});\nvar Login = sequelize.define('Login', {});\n\n// Set the correct associations\nUser.hasMany(Login, {})\nLogin.belongsTo(User, {});\n```\n\n```text\n// Create the instances\nUser.create({}).then(function(newUser) {\n    // now you can use newUser acessors to create the login\n    return newUser.createLogin({});\n).then(function(newLogin){\n    // newLogin\n}).catch(function(error){\n    // error\n});\n```\n\n```text\n{\n    foreignKey: {\n       name: 'userId',\n       allowNull: false,\n    }\n}\n```\n\n```text\nfield\n```\n\n```text\nname\n```\n\n```text\n//Create Association Alias or just setting association alias by using 'as' keyword will also work\nLogin.User = Login.belongsTo(User);\n\nUser.create({\n name: \"name\",\n  Login: {...}\n}, {\n  include: [{\n    association: Login.User\n  }]\n});\n```\n\n```text\n// Set up the models\n    var User = sequelize.define('User', {});\n    var Login = sequelize.define('Login', {});\n        ...\n\n\n    User.create({\n       name: \"name\",\n       Login:\n            {\n            users: {..i.e several users if a user belongs to another user..}\n            }\n        },{\n       include:{\n      model: Login,\n      include: User //nested model.Create\n         }\n    })\n```\n\n```text\nvar User = sequelize.define('User', {});\nvar Login = sequelize.define('Login', {});\nLogin.belongsTo(User, {\n  onDelete: 'cascade',\n  foreignKey: {\n    field: 'userId',\n    allowNull: false,\n  }\n});\n```\n\n```text\nLogin.create({\n   username: \"username\",\n   User: {...}\n},{\n   include: User\n})\n```\n\n```js\nvar login1 = await Login.create(...);\nvar user1 = await User.create({\n    Login: login1\n}, {\n    include: Login\n});\n```\n\n```js\nvar login1 = await Login.create(...);\nvar user1 = await User.create({\n    loginId: login1.get('id')\n}, {});\n```\n\n========================================\n\nComments:\n- Thank you for the var callout! I blame the fact that I was slamming code together to try to understand how to use sequelize! (updated my example to reflect better practice). The big issue that caused confusion for me is that .create() returns a promise (while .build returns a user).\n- Technically both .create() and .build() returns a `promise`. `instanceof userByBuild &#47;&#47; Promise` :)\n- Darn! Well I have no excuse then! (and good to know for future)\n- @Calvintwr I have problem with this too! When I used `userId: user.id` it doesn't work and throw the error. After I changed it to `UserId: user.id` it works. Do you know about the issue? please help!!!\n- it's probably because \"UserId\" is the field name of your User model. If you don't define the id field of your model, it will just use the name the model and add \"Id\" behind\n- Thanks Matheus. For folks looking at this from the future: the big mistake I was making is that .create returns a promise, not a user (.build returns a user).\n- This just helped my life! why does the documentation say `User.set()` instead of `User.create()`?? docs.sequelizejs.com/manual/tutorial/&hellip;\n- @slifty this should be marked as the correct answer as it's more succinct.\n- The link is outdated. I believe the current one (for now at least) is: docs.sequelizejs.com/manual/tutorial/&hellip;\n- Is there a way to do this for bulkCreate()?\n- I don't know, but have you tried it? Would be interesting. If it doesn't work you could use a transaction...\n- @xabitrigo your link is outdated as well.\n- @testing_22 You are right, the current one is sequelize.org/docs/v6/advanced-association-concepts/&hellip;\n- bear in mind that, depending on how you have everything set up, you might have to capitalize `loginId` (as in: `LoginId: login1.get('id')`)","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":269,"estimatedTokens":1549}}104{"id":"stack-21831119","source":"stackoverflow","questionId":21831119,"title":"Want to get crystal clear about NodeJS app structure (Full JavaScript Stack)","tags":["node.js","mongodb","express","sequelize.js","mean-stack"],"text":"Title: Want to get crystal clear about NodeJS app structure (Full JavaScript Stack)\nTags: node.js, mongodb, express, sequelize.js, mean-stack\nSource: Stack Overflow\n\nQuestion:\nI would like to know the structure of a typical NodeJS app, because the more I read and see the projects, the more confused I am, specifically for questions like these (or even more after I updated this question):\n\nTake the MEAN stack for example, from what I know, NodeJS and Express take care of the server part, providing the server interface, etc. MongoDB and Angular are pretty straightforward. \n\nBut where should the **business logic** go? Say if I have a `controller.js` which contains a function, and the `route.js` file binds the request with this controller function. My question is: **under which module these files belong to/run under (Express or NodeJS?)**\n\nWhere is the **starting point** of a NodeJS app? Say `index.php` is the starting point of a PHP app, but where is it for NodeJS app? I can see that all Nodejs projects have a file called `server.js` or `app.js`, etc.(containing something like `module.exports = app;`) But how can NodeJS know which file to find and execute?\n\nI am a fresh noob on NodeJS, Express, sequelize.js/Mongoose, Jade/EJS but want to get started on a NodeJS project. Could you please elaborate on the actual function that each modules provide and a general introduction of the typical structure for a full JS stacked NodeJS app? Thanks in advance!\n\n========================================\n\nCode:\n```text\ncontroller.js\n```\n\n```text\nroute.js\n```\n\n```text\nindex.php\n```\n\n```text\nserver.js\n```\n\n```text\napp.js\n```\n\n```text\nmodule.exports = app;\n```\n\n```text\napp.get('/path', function(req, res, next){ .. } );\n```\n\n```text\napp.get('/', function(req, res, next){\n\n    //some business logic\n\n    res.render('views/home');\n});\n```\n\n```text\nmodule.exports = function(app){\n\n    app.get('/users', function(req, res){\n        var users = req.db.collection('users').find();\n        if (!users) {\n            console.log(\"no users found\");\n            res.redirect('/');\n        } else {\n            res.render('users/index', {users : users});\n        }\n    });\n\n};\n```\n\n```text\nvar mongoose = require('mongoose'),\n    userSchema = new mongoose.Schema({\n\n        name: { type: String, required: true },\n        joinDate: {type: Date, default: date.now }\n\n    }),\n    User = mongoose.model('user', userSchema);\n\nmodule.exports = user;\n```\n\n```text\n| Controllers\n    - User.js\n| Models\n    - User.js\n| Views\napp.js\n```\n\n```text\nroutes\n```\n\n```text\nmodels\n```\n\n```text\nmodule.exports =\n```\n\n```text\nrequire(..)\n```\n\n```text\nmodule.exports\n```\n\n```text\n/routes/index.js\n```\n\n```text\n'/path'\n```\n\n```text\nreq, res, next\n```\n\n```text\napp.post\n```\n\n```text\n/\n```\n\n```text\nhome\n```\n\n```text\nviews\n```\n\n```text\napp.js\n```\n\n```text\nserver.js\n```\n\n```text\nmodule.exports = ..\n```\n\n```text\nreq.db\n```\n\n```text\nUser\n```\n\n```text\nmodule.exports\n```\n\n```text\nserver.js\n```\n\n```text\napp.js\n```\n\n```text\nrequire(module)\n```\n\n```text\nmodule\n```\n\n```text\napp.js\n```\n\n```text\nrequire('./Controllers/User')\n```\n\n```text\nrequire('./Controllers/User')(app)\n```\n\n```text\nvar User = require('./Models/User');\n```\n\n```text\nUser.find({}, function(err, users){ .. });\n```\n\n```text\nerr\n```\n\n========================================\n\nComments:\n- note: this is how I structure my Node apps. I know that its a pretty subjective concept, so anyone else please feel free to offer suggestions to improve. I myself am pretty newbish when it comes to Node.\n- Thanks for the explicit answer. I think i can get the idea now. Cheers.","metadata":{"transformedAt":"2026-08-18T18:33:34.345Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":39,"totalLines":210,"estimatedTokens":901}}105{"id":"stack-58593200","source":"stackoverflow","questionId":58593200,"title":"DeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed","tags":["mysql","express","sequelize.js"],"text":"Title: DeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed\nTags: mysql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting the below error in ExpressJS with Sequelize:\n\n```\nDeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.\n```\n\nAny idea how to fix this?\n\n========================================\n\nTop Answer:\nBased on my experience\n\nGo to your file\n\n`app\\models\\index.js`\n\n```\nconst sequelize = new Sequelize(\n...\n operatorsAliases: 0, // change this to zero\n\n...\n);\n```\n\nrun again\n\n`\"node server.js\"`\n\n========================================\n\nCode:\n```none\nDeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.\n```\n\n```text\noperatorsAliases\n```\n\n```text\noptions\n```\n\n```text\n'1'\n```\n\n```text\n'0'\n```\n\n```text\noperatorsAliases\n```\n\n```text\nfalse\n```\n\n```text\noperatorsAliases\n```\n\n```text\nconst sequelize = new Sequelize(\n...\n    operatorsAliases: 0, // change this to zero\n\n...\n);\n```\n\n```text\napp\\models\\index.js\n```\n\n```text\n\"node server.js\"\n```\n\n```text\nconst sequelize = new Sequelize(\n    operatorsAliases: 0, // change false to zero\n}\n```\n\n========================================\n\nComments:\n- @leochet I have changed the boolean value to Integer but Still showing the same error.\n- @Rabbani_ did you use integers or strings containing the digits?\n- I am using Integer .\n- you need a string\n- This really isn't an appropriate answer, and doesn't solve anything.\n- This is the appropriate answer, as far as i tested it. However, if you use the logging option, you should make it 0 (int), not '0' (string), or else it will throw an error. You should change all options you provide to sequelize options of type boolean to 0 (if false) and 1 (if true)\n- Relevant docs: \"Deprecated: Operator Aliases. In Sequelize v4, it was possible to specify strings to refer to operators, instead of using Symbols. This is now deprecated and heavily discouraged, and will probably be removed in the next major version. If you really need it, you can pass the `operatorAliases` option in the Sequelize constructor.\"\n- Thanks might not be the best solution but was what make me notice what this was referencing to.\n- Repost of this answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":105,"estimatedTokens":589}}106{"id":"stack-19429152","source":"stackoverflow","questionId":19429152,"title":"Check mysql connection in sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: Check mysql connection in sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a very simple program in where I create a Sequelize instance and then I perform a raw query on a mysql database. \nThe case is that when MySql is up and running there is no problem, I can perform the query with no problems.\nBut when MySql is not running then the query doesn't emmit any error until the query timeout has reached and then it emmits a ETIMEOUT error. But that's not really what's happening. I expect the query to emit ENOTFOUND error or something like that if mysql is not running so I can manage the error and perform different actions if Mysql has gone down or Mysql is very busy and has a very large response time.\nWhat shoul'd I do to check if Mysql is up and running without having to wait the timeout exception.\n\n```\nsequelize = new Sequelize(db_name, db_user, db_pass, opts);\n\nsequelize.query('SELECT * FROM some_table').success(function(result) {\n console.log(result);\n}).error(function(err) {\n console.log(err);\n});\n```\n\n========================================\n\nTop Answer:\nYou won't see errors, like password authentication errors, in `.then`.\n\nFrom the sequelize documentation here:\n\n You can use the .authenticate() function like this to test the\n connection.\n\n```\nsequelize\n .authenticate()\n .then(function(err) {\n console.log('Connection has been established successfully.');\n })\n .catch(function (err) {\n console.log('Unable to connect to the database:', err);\n });\n```\n\n========================================\n\nCode:\n```text\nsequelize = new Sequelize(db_name, db_user, db_pass, opts);\n\nsequelize.query('SELECT * FROM some_table').success(function(result) {\n  console.log(result);\n}).error(function(err) {\n  console.log(err);\n});\n```\n\n```js\nvar sequelize = new Sequelize(\"db\", \"user\", \"pass\");\n\nsequelize.authenticate().then(function(errors) { console.log(errors) });\n```\n\n```js\nsequelize\n  .authenticate()\n  .then(() => {\n    console.log('Connection has been established successfully.');\n  })\n  .catch(err => {\n    console.error('Unable to connect to the database:', err);\n  });\n```\n\n```js\ntry {\n  await sequelize.authenticate()\n} catch (err) {\n  console.error('Unable to connect to the database:', err)\n}\n```\n\n```text\n3.3.2\n```\n\n```text\nauthenticate\n```\n\n```text\nauthenticate\n```\n\n```text\nSELECT 1+1 AS result\n```\n\n```text\ncatch\n```\n\n```text\nasync/await\n```\n\n```text\nsequelize\n  .authenticate()\n  .then(function(err) {\n    console.log('Connection has been established successfully.');\n  })\n  .catch(function (err) {\n    console.log('Unable to connect to the database:', err);\n  });\n```\n\n```text\n.then\n```\n\n```text\nfunction sleep(ms) {\n\n    return new Promise(function(resolve) {\n\n        setTimeout(resolve, ms);\n    });\n}\n\nfor (;;) {\n\n    try {\n\n        await db.authenticate();\n        break;\n    } catch(ex) {\n\n        await sleep(1000);\n    }\n}\n```\n\n========================================\n\nComments:\n- You should be monitoring your MySQL server so it's up all the time, not writing application code that's needlessly paranoid. A timeout is the correct behavior for the server being down and the connection failing. You can tighten up the timeout value if it's too slow.\n- well in cases of paranoia, even if MySQL server is up and the query does emit an error, because of overload, its needless to say that a better database infrastructure is needed, you can use cache server such as Redis, for quicker responses, but if all your queries are like the one in your example, then its not written with performance in mind, i mean, for 10.000 rows it might be ok, but for a million rows queried every 5secs or 10secs then its not ok.. IMHO you should redesign and research for better approaches in what you are doing, i bet there is a better one.\n- @TiagoGouv&#234;a the old API returned the error in `then`. The newer ones use proper promises!\n- Ideally there'd be a max-tries limit on these kind of loops :)","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":147,"estimatedTokens":991}}107{"id":"stack-34460482","source":"stackoverflow","questionId":34460482,"title":"Sequelize - How can I return JSON objects of the database results only?","tags":["javascript","json","sequelize.js"],"text":"Title: Sequelize - How can I return JSON objects of the database results only?\nTags: javascript, json, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo I'm wanting to have the database results returned and nothing else. At the moment I'm getting returned a large chunk of JSON data (Like below):\n\nBut I'm only needing the [dataValues] attribute. I don't want to have to use the this bit of `JSON` to retrieve it: `tagData[0].dataValues.tagId`.\n\nI just noticed: When it finds and **DOESN'T CREATE**, it will return the `JSON` for the database results, but when it **DOESN'T FIND** and creates, it returns the un-needed JSON blob (Like below) Is there a way around this?\n\n```\n[ { dataValues:\n { tagId: 1,\n tagName: '#hash',\n updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),\n createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },\n _previousDataValues:\n { tagId: 1,\n tagName: '#hash',\n createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),\n updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },\n _changed:\n { tagId: false,\n tagName: false,\n createdAt: false,\n updatedAt: false },\n '$modelOptions':\n { timestamps: true,\n instanceMethods: {},\n classMethods: {},\n validate: {},\n freezeTableName: true,\n underscored: false,\n underscoredAll: false,\n paranoid: false,\n whereCollection: [Object],\n schema: null,\n schemaDelimiter: '',\n defaultScope: null,\n scopes: [],\n hooks: {},\n indexes: [],\n name: [Object],\n omitNull: false,\n sequelize: [Object],\n uniqueKeys: [Object],\n hasPrimaryKeys: true },\n '$options':\n { isNewRecord: true,\n '$schema': null,\n '$schemaDelimiter': '',\n attributes: undefined,\n include: undefined,\n raw: true,\n silent: undefined },\n hasPrimaryKeys: true,\n __eagerlyLoadedAssociations: [],\n isNewRecord: false },\n true ]\n```\n\nInstead of getting the big blob like the above I only need the `RAW` json results (Like below):\n\n```\n{ tagId: 1,\n tagName: '#hash',\n updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),\n createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },\n```\n\nI've used the following javascript. I did try add `raw: true`, but it didn't work?\n\n```\n// Find or create new tag (hashtag), then insert it into DB with photoId relation\nmodule.exports = function(tag, photoId) {\n tags.findOrCreate( { \n where: { tagName: tag },\n raw: true\n })\n .then(function(tagData){\n // console.log(\"----------------> \", tagData[0].dataValues.tagId);\n console.log(tagData);\n tagsRelation.create({ tagId: tagData[0].dataValues.tagId, photoId: photoId })\n .then(function(hashtag){\n // console.log(\"\\nHashtag has been inserted into DB: \", hashtag);\n }).catch(function(err){\n console.log(\"\\nError inserting tags and relation: \", err);\n });\n }).catch(function(err){\n if(err){\n console.log(err);\n }\n });\n\n}\n```\n\n### Edit:\n\nSo I've investigated a bit and it seems that the big `JSON` blob is only returned when `Sequelize` is creating and not finding.\n\nIs there a way around this or not?\n\n### Edit 2:\n\nOkay so I've found a workaround, which could be turned into a re-usable function. But if there's something built into `Sequelize`, I'd prefer to use that.\n\n```\nvar tagId = \"\";\n\n// Extract tagId from json blob\nif(tagData[0].hasOwnProperty('dataValues')){\n console.log(\"1\");\n tagId = tagData[0].dataValues.tagId;\n} else {\n console.log(\"2\");\n console.log(tagData);\n tagId = tagData[0].tagId;\n}\n\nconsole.log(tagId);\ntagsRelation.create({ tagId: tagId, photoId: photoId })\n```\n\n### Edit 3:\n\nSo, I don't think there is an \"Official\" sequelize way of achieving this so I simply wrote a custom module which returns the `JSON` data that's needed. This module can be customised and extended to suit various situations! If anyone has any suggestions to how the module can be improved feel free to comment :)\n\nIn this module we're returning a Javascript Object. If you want to turn it into `JSON` just stringify it using `JSON.stringify(data)`. \n\n```\n// Pass in your sequelize JSON object\nmodule.exports = function(json){ \n var returnedJson = []; // This will be the object we return\n json = JSON.parse(json);\n\n // Extract the JSON we need \n if(json[0].hasOwnProperty('dataValues')){\n console.log(\"HI: \" + json[0].dataValues);\n returnedJson = json[0].dataValues; // This must be an INSERT...so dig deeper into the JSON object\n } else {\n console.log(json[0]);\n returnedJson = json[0]; // This is a find...so the JSON exists here\n }\n\n return returnedJson; // Finally return the json object so it can be used\n}\n```\n\n### Edit 4:\n\nSo there is an official sequelize method. Refer to the accepted answer below.\n\n========================================\n\nTop Answer:\nIf you want to work only with the values of an instance try to call `get({plain: true})` or `toJSON()`\n\n```\ntags.findOrCreate( { \n where: { tagName: tag }\n})\n.then(function(tagData){\n console.log(tagData.toJSON());\n})\n```\n\n========================================\n\nCode:\n```text\n[ { dataValues:\n     { tagId: 1,\n       tagName: '#hash',\n       updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),\n       createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },\n    _previousDataValues:\n     { tagId: 1,\n       tagName: '#hash',\n       createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),\n       updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },\n    _changed:\n     { tagId: false,\n       tagName: false,\n       createdAt: false,\n       updatedAt: false },\n    '$modelOptions':\n     { timestamps: true,\n       instanceMethods: {},\n       classMethods: {},\n       validate: {},\n       freezeTableName: true,\n       underscored: false,\n       underscoredAll: false,\n       paranoid: false,\n       whereCollection: [Object],\n       schema: null,\n       schemaDelimiter: '',\n       defaultScope: null,\n       scopes: [],\n       hooks: {},\n       indexes: [],\n       name: [Object],\n       omitNull: false,\n       sequelize: [Object],\n       uniqueKeys: [Object],\n       hasPrimaryKeys: true },\n    '$options':\n     { isNewRecord: true,\n       '$schema': null,\n       '$schemaDelimiter': '',\n       attributes: undefined,\n       include: undefined,\n       raw: true,\n       silent: undefined },\n    hasPrimaryKeys: true,\n    __eagerlyLoadedAssociations: [],\n    isNewRecord: false },\n  true ]\n```\n\n```text\n{ tagId: 1,\n       tagName: '#hash',\n       updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),\n       createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },\n```\n\n```text\n// Find or create new tag (hashtag), then insert it into DB with photoId relation\nmodule.exports = function(tag, photoId) {\n    tags.findOrCreate( { \n        where: { tagName: tag },\n        raw: true\n    })\n    .then(function(tagData){\n        // console.log(\"----------------> \", tagData[0].dataValues.tagId);\n        console.log(tagData);\n        tagsRelation.create({ tagId: tagData[0].dataValues.tagId, photoId: photoId })\n        .then(function(hashtag){\n            // console.log(\"\\nHashtag has been inserted into DB: \", hashtag);\n        }).catch(function(err){\n            console.log(\"\\nError inserting tags and relation: \", err);\n        });\n    }).catch(function(err){\n        if(err){\n            console.log(err);\n        }\n    });\n\n}\n```\n\n```text\nvar tagId = \"\";\n\n// Extract tagId from json blob\nif(tagData[0].hasOwnProperty('dataValues')){\n    console.log(\"1\");\n    tagId = tagData[0].dataValues.tagId;\n} else {\n    console.log(\"2\");\n    console.log(tagData);\n    tagId = tagData[0].tagId;\n}\n\nconsole.log(tagId);\ntagsRelation.create({ tagId: tagId, photoId: photoId })\n```\n\n```text\n// Pass in your sequelize JSON object\nmodule.exports = function(json){ \n    var returnedJson = []; // This will be the object we return\n    json = JSON.parse(json);\n\n\n    // Extract the JSON we need \n    if(json[0].hasOwnProperty('dataValues')){\n        console.log(\"HI: \" + json[0].dataValues);\n        returnedJson = json[0].dataValues; // This must be an INSERT...so dig deeper into the JSON object\n    } else {\n        console.log(json[0]);\n        returnedJson = json[0]; // This is a find...so the JSON exists here\n    }\n\n    return returnedJson; // Finally return the json object so it can be used\n}\n```\n\n```text\nJSON\n```\n\n```text\ntagData[0].dataValues.tagId\n```\n\n```text\nJSON\n```\n\n```text\nRAW\n```\n\n```text\nraw: true\n```\n\n```text\nJSON\n```\n\n```text\nSequelize\n```\n\n```text\nSequelize\n```\n\n```text\nJSON\n```\n\n```text\nJSON\n```\n\n```text\nJSON.stringify(data)\n```\n\n```text\nItem.findOrCreate({...})\n      .spread(function(item, created) {\n        console.log(item.get({\n          plain: true\n        })) // logs only the item data, if it was found or created\n```\n\n```text\n.get({plain:true})\n```\n\n```text\nspread\n```\n\n```text\ncreated\n```\n\n```text\nraw\n```\n\n```text\n{raw:true}\n```\n\n```text\nget\n```\n\n```text\ntags.findOrCreate( { \n    where: { tagName: tag }\n})\n.then(function(tagData){\n     console.log(tagData.toJSON());\n})\n```\n\n```text\nget({plain: true})\n```\n\n```text\ntoJSON()\n```\n\n```text\nsequelize-values\n```\n\n```text\ndb.Message.create({\n    userID: req.user.user_id,\n    conversationID: conversationID,\n    content: req.body.content,\n    seen: false\n  })\n  .then(data => {\n    res.json({'status': 'success', 'data': data.dataValues})\n  })\n  .catch(function (err) {\n    res.json({'status': 'error'})\n  })\n```\n\n```text\ndata.dataValues\n```\n\n```js\nmodule.exports = async function(tagName) {\n  const [tag, created] = await Tag.findOrCreate({\n    where: {tagName},\n    defaults: {tagName}\n  });\n  return tag.get({plain:true});\n}\n```\n\n```text\nasync/await\n```\n\n```text\nconsole.log(JSON.parse(JSON.stringify(await Model.findAll({}))));\n```\n\n========================================\n\nComments:\n- There is an \"Official\" Sequelize way to do this, please refer to my answer.\n- This doesn't seem to work. I get `[TypeError: undefined is not a function]`. I guess I'm just going to have to write my own function to extract the plain `JSON`\n- @James111, oh sorry, try to use without `raw: true` parameter in query\n- Be sure not to ask `toJSON()` in a list, like I just did. Not the case for the question, just for someone searching.\n- This can be used with the results of .findOne() or a single object of a findAll(). On an array, .toJSON() function will throw un-defined\n- Nice one. Sorry for accepting it so late, I saw it briefly then forgot it had an answer.\n- I posted an update with `async&#47;await` syntax, feel free to integrate it to your answer\n- A code-only answer is not high quality. While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please edit your answer to include explanation and link to relevant documentation.","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":436,"estimatedTokens":2632}}108{"id":"stack-35668651","source":"stackoverflow","questionId":35668651,"title":"How to prevent sql-injection in nodejs and sequelize?","tags":["mysql","node.js","express","sql-injection","sequelize.js"],"text":"Title: How to prevent sql-injection in nodejs and sequelize?\nTags: mysql, node.js, express, sql-injection, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to write custom queries using Sequelize, and as far as possible avoid potential issues with SQL Injection. My question is therefore if there exists a secure way of writing custom queries with inserted variables using Sequelize?\n\n========================================\n\nComments:\n- snyk.io/blog/sql-injection-orm-vulnerabilities\n- still input validation and sanitization is a good choice. Together with an ORM","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":12,"estimatedTokens":143}}109{"id":"stack-60131255","source":"stackoverflow","questionId":60131255,"title":"Revert Only One of Two Migrations in Sequelize-CLI?","tags":["javascript","node.js","migration","sequelize.js","sequelize-cli"],"text":"Title: Revert Only One of Two Migrations in Sequelize-CLI?\nTags: javascript, node.js, migration, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nIf we created 2 new migration scripts and ran\n\n```\nsequelize-cli db:migrate\n```\n\n, both migration scripts will run. \n\nBoth migrations are also reverted when we ran once the command\n\n```\nsequelize-cli db:migrate:undo\n```\n\n**Question:** Can we undo only the latest of the 2 migrations?\n\n*Using node 13.7.0, sequelize 5.21.3, sequelize-cli 5.5.1, PostgreSQL 11.2.*\n\n========================================\n\nCode:\n```text\nsequelize-cli db:migrate\n```\n\n```text\nsequelize-cli db:migrate:undo\n```\n\n```text\ndb:migrate:undo --name 20180704124934-create-branch.js\n```\n\n```text\nname\n```\n\n========================================\n\nComments:\n- This worked! Although I must admit, I'm much more used to the idea of \"stepping\" backwards through a migration. I guess using the name makes it more explicit to what point you're exactly migrating back to - just a bit non-standard for the frameworks I've used.\n- Thanks man. it works. Perhaps if sequelize cli is installed globally, a person should run the command from terminal like this `npx sequelize-cli db:migrate:undo --name db:migrate:undo --name 20180704124934-create-branch.js`\n- `npx sequelize-cli db:migrate :undo --name 20230406073112-create-history` Unknown arguments: name, :undo `\"sequelize\": \"^6.6.5\", \"sequelize-cli\": \"^6.2.0\",`","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":359}}110{"id":"stack-46027310","source":"stackoverflow","questionId":46027310,"title":"Sequelize - SQL Server - order by for association tables","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize - SQL Server - order by for association tables\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 3 tables such as `user`, `userProfile` and `userProfileImages`. `User` is mapping with `userPrfoile` as has many and `userProfile` is mapping with `userProfileImages` as has many.\n\nI need to write the **order by query** in `userProfileImages`, I tried as below, but no luck.\n\n```\nUser.findById(uID, { \ninclude: [\n model: sequelize.models.userProfile\n as: userProfile,\n include: [\n {\n model: sequelize.models.userProfileImages,\n as: 'profileImages',\n\n }\n ],\n order: [[sequelize.models.userProfileImages.id, \"desc\"]]\n // order: [[\"id\", \"desc\"]] --> Tried this way also no luck\n] }\n```\n\nI am getting the result, but `userProfilePicture` table's result is not as desc.\n\nKindly give the solutions\n\n========================================\n\nTop Answer:\nUpdate your order in association like below\n\n```\nUser.findById(uID, { \ninclude: [\n model: sequelize.models.userProfile,\n as: userProfile, \n include: [{\n model: sequelize.models.userProfileImages,\n as: 'profileImages',\n separate:true, <-- Magic here\n order: [['id', 'desc']]\n }],\n]});\n```\n\n========================================\n\nCode:\n```text\nUser.findById(uID, { \ninclude: [\n   model: sequelize.models.userProfile\n   as: userProfile,\n   include: [\n    {\n      model: sequelize.models.userProfileImages,\n      as: 'profileImages',\n\n    }\n   ],\n    order: [[sequelize.models.userProfileImages.id, \"desc\"]]\n  // order: [[\"id\", \"desc\"]] --> Tried this way also no luck\n] }\n```\n\n```text\nuser\n```\n\n```text\nuserProfile\n```\n\n```text\nuserProfileImages\n```\n\n```text\nUser\n```\n\n```text\nuserPrfoile\n```\n\n```text\nuserProfile\n```\n\n```text\nuserProfileImages\n```\n\n```text\nuserProfileImages\n```\n\n```text\nuserProfilePicture\n```\n\n```text\n// Will order by an associated model's created_at using an association object. (preferred method)\n    [Subtask.associations.Task, 'createdAt', 'DESC'],\n\n    // Will order by a nested associated model's created_at using association objects. (preferred method)\n    [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],\n```\n\n```text\nUser.findById(uID, { \n    include: [{\n        model: sequelize.models.userProfile\n        as: userProfile,\n        include: [{\n           model: sequelize.models.userProfileImages,\n           as: 'profileImages',\n        }],\n        order: [['profileImages','id', 'desc']]\n    }]\n});\n```\n\n```text\nUser.findById(uID, { \ninclude: [\n    model: sequelize.models.userProfile,\n    as: userProfile,        \n    include: [{\n       model: sequelize.models.userProfileImages,\n       as: 'profileImages',\n       separate:true, <-- Magic here\n       order: [['id', 'desc']]\n    }],\n]});\n```\n\n```text\nUser.findById(uID, { \nsubQuery : false , \ninclude: [\n    model: sequelize.models.userProfile,\n    as: userProfile,        \n    include: [{\n       model: sequelize.models.userProfileImages,\n       as: 'profileImages',\n       separate:true, <-- Magic here\n       order: [['id', 'desc']]\n    }],\n]});\n```\n\n========================================\n\nComments:\n- please try with single array and not 2d array like: `[\"id\", \"desc\"]`\n- I tried, but it doesn't work. one more thing, I have done one more mapping also inside the 2nd include. as\n- Order by keyword is not appended in my query also.\n- finally something that works :), thx buddy.\n- I'm using Sequelize 6.7.0 and with that code I get: \"Error: Unknown structure passed to order / group: NAME_OF_ALIAS\"\n- This worked. Adding the `separate` tag and setting it to `true` did the trick for me.\n- Only HasMany associations support include.separate.\n- Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":167,"estimatedTokens":1022}}111{"id":"stack-64969626","source":"stackoverflow","questionId":64969626,"title":"How to seed a one file only with sequelize-cli?","tags":["javascript","sequelize.js"],"text":"Title: How to seed a one file only with sequelize-cli?\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nsequqlize-cli db:seed:all is working fine, but how to seed only one file? Tried to db:seed:[name-that-i-gave-with-create-command] and db:seed:[full-path-to-seed-file.js] but it doesnt work. It outputs nothing. Docs say **sequelize db:seed Run specified seeder** But how to do that?\n\n========================================\n\nTop Answer:\nWe can launch a specific seeder via **npx sequelize-cli** with the following command :\n\n```\nnpx sequelize-cli db:seed --seed my-seeder-file.js\n```\n\n========================================\n\nCode:\n```text\nsequelize db:seed --seed my_seeder_file.js\n```\n\n```text\n--seed <seed_file_nams.js>\n```\n\n```text\nnpx sequelize-cli db:seed --seed my-seeder-file.js\n```\n\n```text\nsequelize db:seed --seed seeder_file.js --config src/config/db.js --seeders-path src/seeders\n```\n\n```text\nnpx sequelize-cli db:seed:all\n```\n\n```text\nnpx sequelize db:seed --seed temp-seeder.js\n```\n\n```text\nlet data = JSON.parse(await fs.readFileSync('./category.json', 'utf-8'))\ndata.forEach(element => {\n  element.createdAt = new Date()\n  element.updatedAt = new Date()\n})\n\nawait queryInterface.bulkInsert('Categories', data, {})\n```\n\n```text\nawait queryInterface.bulkDelete('Categories', data, {})\n```\n\n```text\nnpx sequelize-cli db:seed:all --config  <your_config_file_location>\n```\n\n```text\nnpx sequelize-cli db:seed:all --config  api/config/config.js\n```\n\n```text\nnpx sequelize-cli db:seed:all <file_name> --config  api/config/config.js\n```\n\n========================================\n\nComments:\n- as far as i know, It is not working (yet).","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":73,"estimatedTokens":416}}112{"id":"stack-48232490","source":"stackoverflow","questionId":48232490,"title":"Sequelize: Where is an example of using bulkDelete with criteria?","tags":["node.js","sequelize.js"],"text":"Title: Sequelize: Where is an example of using bulkDelete with criteria?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to write a seed file's `down` and I'd like to `bulkDelete` the data I created in my `up`. But I can't find any documentation on how to do this. The official docs don't give an example: http://docs.sequelizejs.com/class/lib/query-interface.js~QueryInterface.html#instance-method-bulkDelete\n\nCan someone show me how to `bulkDelete` all rows in table `Foo` where `name` equals `x` or name equals `y`? \n\n```\ndown: (queryInterface, Sequelize) => {\n return queryInterface.bulkDelete('Foo', [what do I put here?], {});\n }\n```\n\n========================================\n\nTop Answer:\n```\ndown: (queryInterface, Sequelize) => {\n const Op = Sequelize.Op; \n\n return queryInterface.bulkDelete(\n 'Foo',\n {[Op.or]: [{name: x}, {name: y}]}\n );\n}\n```\n\n1st arg is the table name, 2nd arg is the `where` value that indicates which rows to delete.\n\n========================================\n\nCode:\n```text\ndown: (queryInterface, Sequelize) => {\n    return queryInterface.bulkDelete('Foo', [what do I put here?], {});\n  }\n```\n\n```text\ndown\n```\n\n```text\nbulkDelete\n```\n\n```text\nup\n```\n\n```text\nbulkDelete\n```\n\n```text\nFoo\n```\n\n```text\nname\n```\n\n```text\nx\n```\n\n```text\ny\n```\n\n```text\ndown: (queryInterface, Sequelize) => {\n  const Op = Sequelize.Op\n  return queryInterface.bulkDelete('users', {id: {[Op.in]: [2, 3]}}, {})\n}\n```\n\n```text\nERROR: Invalid value [object Object]\n```\n\n```text\nwhere\n```\n\n```text\ndown: (queryInterface, Sequelize) => {\n  const Op = Sequelize.Op; \n\n  return queryInterface.bulkDelete(\n    'Foo',\n    {[Op.or]: [{name: x}, {name: y}]}\n  );\n}\n```\n\n```text\nwhere\n```\n\n```text\ndown: function (queryInterface, Sequelize) {\n    return queryInterface.bulkDelete('Flags', {\n        keyword: [\n            \"groupRegistration\",\n            \"memberRegistration\",\n            \"exhibitorRegistration\",\n            \"facilitatorRegistration\",\n            \"volunteerRegistration\",\n            \"workshopSignup\"\n        ]\n    });\n}\n```\n\n```js\nPost.findAll({\n  where: {\n    id: [1,2,3] // Same as using `id: { [Op.in]: [1,2,3] }`\n  }\n});\n// SELECT ... FROM \"posts\" AS \"post\" WHERE \"post\".\"id\" IN (1, 2, 3);\n```\n\n```text\nOp.in\n```\n\n========================================\n\nComments:\n- Thank you, where did you learn how to do that? Is that documented elsewhere?\n- In this case, the docs stated that the second argument contained the where conditions. Then its a usual sequelize where object. The `or` operator is shown with example in the list of operators in the docs see operators here. I'll do a PR to update the docs to give an example for bulkDelete for others in the future\n- @DanielKaplan if this answered your question, can you please accept the answer\n- @MichaelMcCabe Edited your answer to reflect kaszac's comments, which I verified to be correct. 'Hope that's okay. (Also, please be a bit more diligent in verifying your answers actually work as expected. Thanks!)\n- Fixed @MichaelMcCabe's answer so it's correct, since it was already accepted. Thanks for catching that. (Not sure if that was the right way to correct this, but seemed the simplest. Sorry you don't get more credit for it.)","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":138,"estimatedTokens":807}}113{"id":"stack-24611778","source":"stackoverflow","questionId":24611778,"title":"How to include the deleted elements when querying a \"paranoid\" table on sequelize.js?","tags":["javascript","sequelize.js"],"text":"Title: How to include the deleted elements when querying a \"paranoid\" table on sequelize.js?\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want that previously existing users on my application, that have been deleted using the paranoid mode (so now its field `deletedAt` is NOT `null`), to be able to register again using the same email. So when the API notices a user creation with a previously used email it sets to `null` the `deletedAt` field of the previously existing register instead of creating a new user.\n\nUsually for looking for an user I will do,\n\n`User.find( { where: { email: req.body.user.email } })`\n\nBut upon inspection of the SQL query created, it includes\n\n`Users.deletedAt IS NULL`\n\nIs there any special way of finding when dealing with paranoid models?\n\n========================================\n\nTop Answer:\nSequelize has this feature built in. Per their API docs, you can include the 'paranoid' flag in the options of your find call.\n\ne.g.\n\n```\nUser.find({where: {email: req.body.user.email}}, {paranoid: false}).success(models) {\n //models contains both deleted and non-deleted users\n}\n```\n\nReference: http://docs.sequelizejs.com/en/latest/api/model/#findalloptions-promisearrayinstance\n\n========================================\n\nCode:\n```text\ndeletedAt\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\ndeletedAt\n```\n\n```text\nUser.find( { where: { email: req.body.user.email } })\n```\n\n```text\nUsers.deletedAt IS NULL\n```\n\n```text\nUser.find({\n  where: {email: req.body.user.email}, \n  paranoid: false\n})\n```\n\n```text\nvar uuid = require('node-uuid')\nmodule.exports = function (sequelize, DataTypes) {\n    return sequelize.define(\"multi_route\", {\n        email: {\n            type: DataTypes.STRING,\n            unique: false,\n        }\n        //other fields\n    }, {\n        timestamps: true,\n        paranoid: true,\n        hooks: {\n            beforeUpdate: function (multiFare, next) {                  // berforeUpdate will called after beforeDestroy\n                if (multiFare.email.indexOf(\"_____destroyed\") > -1) {   // check contains '_____destroyed' string\n                    multiFare.email = multiFare.email + uuid.v1()       // set unique value\n                }\n                next()\n            },\n            beforeDestroy: [function (multiFare, next) {                // beforeDestroy will called before one instance destroyed\n                multiFare.email = multiFare.email + '_____destroyed'    // flag this will destroy\n                next()\n            }]\n        }\n    })\n}\n```\n\n```text\nUser.find({where: {email: req.body.user.email}}, {paranoid: false}).success(models) {\n    //models contains both deleted and non-deleted users\n}\n```\n\n========================================\n\nComments:\n- It also can query the data that is not be destroyed. sequelize version is 5.8.5","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":104,"estimatedTokens":711}}114{"id":"stack-47874344","source":"stackoverflow","questionId":47874344,"title":"Should I handle a GraphQL ID as a string on the client?","tags":["mysql","sequelize.js","graphql","apollo"],"text":"Title: Should I handle a GraphQL ID as a string on the client?\nTags: mysql, sequelize.js, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am building an application using:\n\n- MySQL as the backend database\n\n- Apollo GraphQL server as a query layer for that database\n\n- Sequelize as the ORM layer between GraphQL and MySQL\n\nAs I am building out my GraphQL schema I'm using the GraphQL ID data type to uniquely identify records. Here's an example schema and its MySQL resolver/connector\n\n**Graphql Type:**\n\n```\ntype Person {\n id: ID!\n firstName: String\n middleName: String\n lastName: String\n createdAt: String\n updatedAt: String\n}\n```\n\n**Sequelize connector**\n\n```\nexport const Person = sequelize.define('person', {\n firstName: { type: Sequelize.STRING },\n middleName: { type: Sequelize.STRING },\n lastName: { type: Sequelize.STRING },\n});\n```\n\n**GraphQL resolver:**\n\n```\nQuery: {\n person(_, args) {\n return Person.findById(args.id);\n}\n```\n\nSo that all works. Here's my question. GraphQL seems to treat the `ID` type as a string. While the ID value gets stored in the MySQL database as an `INT` by Sequelize. I can use GraphQL to query the MySQL db with either a string or a integer that matches the ID value in the database. However, GraphQL will always return the ID value as a string.\n\nHow should I be handling this value in the client? Should I always convert it to an integer as soon as I get it from GraphQL? Should I modify my sequelize code to store the ID value as a string? Is there a correct way to proceed when using GraphQL IDs like this?\n\n========================================\n\nCode:\n```text\ntype Person {\n  id: ID!\n  firstName: String\n  middleName: String\n  lastName: String\n  createdAt: String\n  updatedAt: String\n}\n```\n\n```text\nexport const Person = sequelize.define('person', {\n  firstName: { type: Sequelize.STRING },\n  middleName: { type: Sequelize.STRING },\n  lastName: { type: Sequelize.STRING },\n});\n```\n\n```text\nQuery: {\n  person(_, args) {\n    return Person.findById(args.id);\n}\n```\n\n```text\nID\n```\n\n```text\nINT\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n========================================\n\nComments:\n- This is an excellent explanation of the various considerations around this issue. Thanks. GraphQL offers such an open ended approach to data structures that it can be difficult to figure out the **right** way.\n- Can I just use Int instead of ID type for mysql primary columns? React apollo already allows a custom function 'dataObjectId' to set an object ID. Setting ID scalar type for primary keys doesn't seem to have any benefits.\n- What does it mean by `...it is not intended to be human‐readable` ? Anything is readable as long as the length overexceeds the boundary.\n- human-readable text refers to natural language text that can easily be read and understood by a human familiar with the language used for the text. As opposed to machine-readable text, that can be easily processed by a computer. For example, using latin letters for a string is better human-readable than using ASCII codes, which is more machine-readable.\n- I'd say use ID datatype only if it's a string. Although GraphQL docs says it's agnostic to datatype it clearly prefers strings. Agnostic would be not touching the datatype.\n- If the `ID` really just resolves to a `int` or `string` why do we even need it in the spec? Just use `int` or `string`. I don't understand why we need this abstract `ID` thing that can be either one.","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":117,"estimatedTokens":872}}115{"id":"stack-38426683","source":"stackoverflow","questionId":38426683,"title":"Add Property to Object that is returned by Sequelize FindOne","tags":["javascript","postgresql","sequelize.js"],"text":"Title: Add Property to Object that is returned by Sequelize FindOne\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to add a property to a sequelize instance before passing it back to the client. \n\n```\nrouter.get('/cats/1', function (req, res) {\n Cat.findOne({where: {id: 1}})\n .then(function (cat) {\n // cat exists and looks like {id: 1}\n cat.name = \"Lincoln\";\n // console.log of cat is {id: 1, name: Lincoln}\n res.json(cat);\n });\n});\n```\n\nThe client only see's `{id: 1}` and not the newly added key. \n\n- What is going on here?\n\n- What type of Object is returned by Sequelize?\n\n- How can I add new properties to my Cats and send them back?\n\n========================================\n\nTop Answer:\nThe Sequelize `Model` class (of which your cats are instances) has a `toJSON()` method which res.json will presumably use to serialise your cats. The method returns the result of `Model#get()` (https://github.com/sequelize/sequelize/blob/95adb78a03c16ebdc1e62e80983d1d6a204eed80/lib/model.js#L3610-L3613), which only uses attributes defined on the model. If you want to be able to set the cats name, but not store names in the DB, you can use a virtual column when defining your cat model:\n\n```\nsequelize.define('Cat', {\n // [other columns here...]\n name: Sequelize.VIRTUAL\n});\n```\n\nAlternatively, if you don't want to add properties to the model definition:\n\n```\ncat = cat.toJSON(); // actually returns a plain object, not a JSON string\ncat.name = 'Macavity';\nres.json(cat);\n```\n\n========================================\n\nCode:\n```text\nrouter.get('/cats/1', function (req, res) {\n    Cat.findOne({where: {id: 1}})\n        .then(function (cat) {\n            // cat exists and looks like {id: 1}\n            cat.name = \"Lincoln\";\n            // console.log of cat is {id: 1, name: Lincoln}\n            res.json(cat);\n        });\n});\n```\n\n```text\n{id: 1}\n```\n\n```text\n...\nconst order = Order.findOne(criteria);\norder.setDataValue('additionalProperty', 'some value');\n...\n```\n\n```text\nsequelize.define('Cat', {\n  // [other columns here...]\n  name: Sequelize.VIRTUAL\n});\n```\n\n```text\ncat = cat.toJSON(); // actually returns a plain object, not a JSON string\ncat.name = 'Macavity';\nres.json(cat);\n```\n\n```text\nModel\n```\n\n```text\ntoJSON()\n```\n\n```text\nModel#get()\n```\n\n```text\nconst model = sequelize.define('myobj', {\n  id: {\n    type: Sequelize.INTEGER,\n    autoIncrement: true,\n    primaryKey: true,\n    field: 'eventId',\n  },\n  name: { type: Sequelize.STRING, allowNull: false },\n  history: Sequelize.VIRTUAL,\n  ...\n}\n```\n\n```text\n...\nconst result = yield MyObject.findOne(query);\nresult.history = yield getMyObjectHistoryArray(id);\nreturn result;\n```\n\n```text\n{\n  \"id\": 1,\n  \"name\": \"My Name\",\n  \"history\": [ \n    {...},\n    {...},\n  ]\n}\n```\n\n```text\nlet obj = yield findMyObject(id);\nobj.name = \"New Name\";\nreturn yield obj.save();\n```\n\n```text\n{raw: true}\n```\n\n```text\nresult.get({plain: true})\n```\n\n```text\nUserModel.findById(req.params.id)\n     .then(function (userIns) {\n\n        // here userIns is Sequelize Object \n        // and data is Json Object\n\n        let data = userIns.toJSON();\n        data['displayName'] = 'John';\n\n    })\n```\n\n```text\nrouter.get('/cats/1', function (req, res) {\n    Cat.findOne({where: {id: 1}})\n        .then(function (cat) {\n            cat.setDataValue(\"name\", \"Lincoln\");\n            res.json(cat);\n        });\n});\n```\n\n```text\npublic setDataValue(key: string, value: any)\n\nUpdate the underlying data value\n\nParams:\n\nName    Type    Attribute   Description\nkey     string              key to set in instance data store   \nvalue   any                 new value for given key\n```\n\n```text\nsetDataValue\n```\n\n========================================\n\nComments:\n- The returned object is not a plain object, but a modal instance. Take a look at Data retrieval / Finders\n- I don't want to save any new instances to my DB. Just want `res.json(cat)` to include any new properties I add to the `cat` instance.\n- While this may work, it doesn't seem like this is the best approach.. I am trying to modify an object by assigning it a new key, and passing the modified object, with original key/value pairs + the new key/value pair (instead of the DB instance) to the client.\n- I'm curious - what's your use case for adding a property after db retrieval? If you feel like adding a virtual property is doing the work in the wrong place because it's too close to the db, then I encourage you to think of Sequelize instances as a handy way of modelling your data objects that just happen to get populated from a database. The only other way I can think of to achieve your goal is to first call `cat.toJSON()` (which actually returns an object, not a json string) and set your custom property on that.\n- I think your suggestion of `cat.toJSON()` is the right fit for me. The use case is the following.. I grab some DB info, run some mathematical functions on the outputs, then return to the client the original numbers as well as some new properties that relate to the outputs from the mathematical functions.\n- So the cats were a ruse! Glad I could help - mind accepting my answer?\n- (Also bear in mind what you're describing sounds very much like a computed field. The benefit of using a virtual attribute on the model is that you could define your mathematical transformation in the `get()` of that attribute so that if you access the model instance from somewhere else you don't need to recalculate the result)\n- in sequelize 5 its DataTypes.VIRTUAL sequelize.org/master/manual/getters-setters-virtuals.html\n- Awesome. That's absolutely helpful!\n- Thank you, this was the best and simplest answer to this problem","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":196,"estimatedTokens":1419}}116{"id":"stack-46305459","source":"stackoverflow","questionId":46305459,"title":"Sequelize model references vs associations","tags":["node.js","sequelize.js"],"text":"Title: Sequelize model references vs associations\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nJust starting to use Sequelize and I've setup a bunch of models and seeds, but I can't figure out references vs associations. I don't see the use case for references if they even do what I think they do, but I couldn't find a good explanation in the docs.\n\nIs this redundant having references and associations?\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const UserTask = sequelize.define('UserTask',\n {\n id: {\n primaryKey: true,\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV4\n },\n userId: {\n type: DataTypes.UUID,\n references: { // { <--- makes references redundant?\n UserTask.belongsTo(models.User, {\n onDelete: 'CASCADE',\n foreignKey: {\n fieldName: 'userId',\n allowNull: true,\n require: true\n },\n targetKey: 'id'\n });\n }\n }\n }\n );\n return UserTask;\n};\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const UserTask = sequelize.define('UserTask',\n    {\n      id: {\n        primaryKey: true,\n        type: DataTypes.UUID,\n        defaultValue: DataTypes.UUIDV4\n      },\n      userId: {\n        type: DataTypes.UUID,\n        references: { // <--- is this redundant to associate\n          model: 'User',\n          key: 'id'\n        }\n      }\n      // ... removed for brevity\n    },\n    {\n      classMethods: {\n        associate: models => { <--- makes references redundant?\n          UserTask.belongsTo(models.User, {\n            onDelete: 'CASCADE',\n            foreignKey: {\n              fieldName: 'userId',\n              allowNull: true,\n              require: true\n            },\n            targetKey: 'id'\n          });\n        }\n      }\n    }\n  );\n  return UserTask;\n};\n```\n\n```text\nreferences\n```\n\n```text\nassociation\n```\n\n```text\nUser.getTasks();\n```\n\n```text\nreferences\n```\n\n```text\nassociation\n```\n\n========================================\n\nComments:\n- I was thinking the exact same thing.\n- so I cannot perform joins with just references in my model? I'll \"have to\" have associations?","metadata":{"transformedAt":"2026-08-18T18:33:34.346Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":104,"estimatedTokens":521}}117{"id":"stack-33858334","source":"stackoverflow","questionId":33858334,"title":"Is there a way to get attributes // associations by previously defined Sequelize Model?","tags":["model","sequelize.js"],"text":"Title: Is there a way to get attributes // associations by previously defined Sequelize Model?\nTags: model, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to get some data by previously defined Sequelize Model.\n\nWhat I need:\n\n```\n* attributes list\n * attribute name\n * attribute type (INTEGER, STRING,...)\n * was it generated by association method?\n* list of associations\n * association type (belongsTo, hasMany, ...)\n```\n\nFor some reason it's rather hard to inspect Sequelize models in console:\n\n```\n> db.sequelize.models.Payment\nPayment // db.sequelize.models.Payment.attributes\n...\ntype:\n { type: { values: [Object] },\n values: [ 'cash', 'account', 'transfer' ],\n Model: Payment,\n fieldName: 'type',\n _modelAttribute: true,\n field: 'type' },\nsum: \n { type: \n { options: [Object],\n _length: undefined,\n _zerofill: undefined,\n _decimals: undefined,\n _precision: undefined,\n _scale: undefined,\n _unsigned: undefined },\n Model: Payment,\n fieldName: 'sum',\n _modelAttribute: true,\n field: 'sum' },\n ...\n```\n\nAs you see, there is no actual info about fields types. The same happens with associations.\n\nSo, is there any reliable \"official\" way to extract this data from Model class without digging and reversing object?\n\n========================================\n\nTop Answer:\n### Sequelize v6\n\n`rawAttributes()` method is now deprecated, use `getAttributes()` method instead. Documentation\n\nExample usage:\n\n```\nimport models from \"./src/models/index.js\"\nimport User from \"./src/models/User.js\"\n\nconsole.log(models.sequelize.model('user').getAttributes())\nconsole.log(User.getAttributes())\n```\n\n========================================\n\nCode:\n```text\n* attributes list\n  * attribute name\n  * attribute type (INTEGER, STRING,...)\n  * was it generated by association method?\n* list of associations\n  * association type (belongsTo, hasMany, ...)\n```\n\n```text\n> db.sequelize.models.Payment\nPayment // <- it's valid Sequelize Model {Object}, however its not inspectable\n\n> db.sequelize.models.Payment.attributes\n...\ntype:\n { type: { values: [Object] },\n   values: [ 'cash', 'account', 'transfer' ],\n   Model: Payment,\n   fieldName: 'type',\n   _modelAttribute: true,\n   field: 'type' },\nsum: \n { type: \n    { options: [Object],\n      _length: undefined,\n      _zerofill: undefined,\n      _decimals: undefined,\n      _precision: undefined,\n      _scale: undefined,\n      _unsigned: undefined },\n   Model: Payment,\n   fieldName: 'sum',\n   _modelAttribute: true,\n   field: 'sum' },\n ...\n```\n\n```text\nPayment.rawAttributes\n```\n\n```text\nproperty.type.key\n```\n\n```text\nPayment.associations\n```\n\n```text\nassociationType\n```\n\n```text\nassociation instanceof sequelize.Association.BelongsTo\n```\n\n```js\nimport models from \"./src/models/index.js\"\nimport User from \"./src/models/User.js\"\n\nconsole.log(models.sequelize.model('user').getAttributes())\nconsole.log(User.getAttributes())\n```\n\n```text\nrawAttributes()\n```\n\n```text\ngetAttributes()\n```\n\n========================================\n\nComments:\n- THANK YOU. After thoroughly searching Stack Overflow, I started troving through the Sequelize code and got access to my model's attributes. Couldn't figure out how to read the DataType when it showed up as `ABSTRACT { length: 255 }`. Both of the above work.\n- To get the type as a string used on your database, you can do `ModelName.rawAttributes.propertyName.type.toSql()`\n- Thanks! Just used it today. Is there documentation for this mysterious \"type\" object and all the properties/methods it contains?\n- @NobleUplift I don't see any docs, but the type is `AbstractDataType` and the code for it is here: github.com/sequelize/sequelize/blob/master/types/lib/&hellip;\n- I use `model.rawAttributes.id.autoIncrement` on `beforeValidate` in `new Sequelize` to automatically add `id` when `autoIncrement` is false. `rawAttributes` is deprecated in v7 though.\n- If you only want the Object keys you can do: `Object.keys(User.getAttributes())`","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":154,"estimatedTokens":980}}118{"id":"stack-50614067","source":"stackoverflow","questionId":50614067,"title":"ERROR: Please install mysql2 package manually","tags":["node.js","sequelize.js"],"text":"Title: ERROR: Please install mysql2 package manually\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen using the sequalize **db:migrate** command I am getting the following error. Looking at some of the previous comments on similar issues people said it is a dependency issue but whenever I run \n\n npm install mysql2 \n\nor \n\n npm install -g mysql2 \n\nI get the same error. \n\n```\nlarry@DESKTOP-NSSNPRR:/mnt/c/Users/larry/Desktop/node/AAF-NodeJS$\nsequelize db:migrate\n\nSequelize CLI [Node: 10.1.0, CLI: 4.0.0, ORM: 4.37.10]\n\n(node:2241) ExperimentalWarning: The fs.promises API is experimental\nLoaded configuration file \"db/config/database.json\".\nUsing environment \"development\".\n\nERROR: Please install mysql2 package manually\n```\n\nHere is my package.json like some of you have asked for. \n\n```\n{\n \"name\": \"aaf-website-node\",\n \"version\": \"0.0.1\",\n \"description\": \"Nodejs implementation of the achieve anything website\",\n \"main\": \"app.js\",\n \"scripts\": {\n \"start\": \"node bin/www\",\n \"dev\": \"node node_modules/nodemon/bin/nodemon.js bin/www\",\n \"test\": \"jasmine\",\n \"console\": \"node console.js\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/AchieveGirl/AAF-NodeJS.git\"\n },\n \"keywords\": [\n \"nodejs\",\n \"express\"\n ],\n \"author\": \"Larry Cherry\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/AchieveGirl/AAF-NodeJS/issues\"\n },\n \"homepage\": \"https://github.com/AchieveGirl/AAF-NodeJS/blob/master/README.md\",\n \"dependencies\": {\n \"body-parser\": \"^1.18.2\",\n \"bootstrap\": \"^4.0.0\",\n \"compression\": \"^1.7.2\",\n \"cookie-parser\": \"^1.4.3\",\n \"dotenv\": \"^5.0.1\",\n \"ejs\": \"^2.5.7\",\n \"eslint\": \"^4.19.1\",\n \"express\": \"^4.16.3\",\n \"express-ejs-layouts\": \"^2.3.1\",\n \"express-minify\": \"^1.0.0\",\n \"express-minify-html\": \"^0.12.0\",\n \"jquery\": \"^3.3.1\",\n \"lodash\": \"^4.17.5\",\n \"morgan\": \"^1.9.0\",\n \"mysql2\": \"^1.5.3\",\n \"node-fetch\": \"^2.1.2\",\n \"node-minify\": \"^2.4.1\",\n \"popper.js\": \"^1.14.3\",\n \"sequelize\": \"^4.37.10\",\n \"sequelize-cli\": \"^4.0.0\",\n \"serve-favicon\": \"^2.4.5\",\n \"webpack\": \"^4.1.1\",\n \"webpack-cli\": \"^2.0.12\"\n },\n \"devDependencies\": {\n \"nodemon\": \"^1.17.2\",\n \"pryjs\": \"^1.0.3\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nThis one worked for me\n\n`npm install mysql2 --save`\n\n========================================\n\nCode:\n```text\nlarry@DESKTOP-NSSNPRR:/mnt/c/Users/larry/Desktop/node/AAF-NodeJS$\nsequelize db:migrate\n\nSequelize CLI [Node: 10.1.0, CLI: 4.0.0, ORM: 4.37.10]\n\n(node:2241) ExperimentalWarning: The fs.promises API is experimental\nLoaded configuration file \"db/config/database.json\".\nUsing environment \"development\".\n\nERROR: Please install mysql2 package manually\n```\n\n```text\n{\n  \"name\": \"aaf-website-node\",\n  \"version\": \"0.0.1\",\n  \"description\": \"Nodejs implementation of the achieve anything website\",\n  \"main\": \"app.js\",\n  \"scripts\": {\n    \"start\": \"node bin/www\",\n    \"dev\": \"node node_modules/nodemon/bin/nodemon.js bin/www\",\n    \"test\": \"jasmine\",\n    \"console\": \"node console.js\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/AchieveGirl/AAF-NodeJS.git\"\n  },\n  \"keywords\": [\n    \"nodejs\",\n    \"express\"\n  ],\n  \"author\": \"Larry Cherry\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/AchieveGirl/AAF-NodeJS/issues\"\n  },\n  \"homepage\": \"https://github.com/AchieveGirl/AAF-NodeJS/blob/master/README.md\",\n  \"dependencies\": {\n    \"body-parser\": \"^1.18.2\",\n    \"bootstrap\": \"^4.0.0\",\n    \"compression\": \"^1.7.2\",\n    \"cookie-parser\": \"^1.4.3\",\n    \"dotenv\": \"^5.0.1\",\n    \"ejs\": \"^2.5.7\",\n    \"eslint\": \"^4.19.1\",\n    \"express\": \"^4.16.3\",\n    \"express-ejs-layouts\": \"^2.3.1\",\n    \"express-minify\": \"^1.0.0\",\n    \"express-minify-html\": \"^0.12.0\",\n    \"jquery\": \"^3.3.1\",\n    \"lodash\": \"^4.17.5\",\n    \"morgan\": \"^1.9.0\",\n    \"mysql2\": \"^1.5.3\",\n    \"node-fetch\": \"^2.1.2\",\n    \"node-minify\": \"^2.4.1\",\n    \"popper.js\": \"^1.14.3\",\n    \"sequelize\": \"^4.37.10\",\n    \"sequelize-cli\": \"^4.0.0\",\n    \"serve-favicon\": \"^2.4.5\",\n    \"webpack\": \"^4.1.1\",\n    \"webpack-cli\": \"^2.0.12\"\n  },\n  \"devDependencies\": {\n    \"nodemon\": \"^1.17.2\",\n    \"pryjs\": \"^1.0.3\"\n  }\n}\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nnode_modules/.bin/sequelize db:migrate\n```\n\n```text\nmysql2\n```\n\n```text\ndb:migrate\n```\n\n```text\nmysql2\n```\n\n```text\noptionalDependencies\n```\n\n```text\nmysql2\n```\n\n```text\nnpm install mysql2 --save\n```\n\n```text\nnpm list -g --depth 0\n```\n\n```text\nsequelize\n```\n\n```text\nnpm uninstall -g sequelize\n```\n\n```text\nsequelize\n```\n\n```text\nnpm install --save sequelize\n```\n\n```text\nnpm install mysql2 -g\n```\n\n```text\nyarn global remove sequelize\n```\n\n```text\nyarn add sequelize\n```\n\n```text\nnpm -g uninstall sequelize\n```\n\n```text\nnpm install sequelize\n```\n\n```text\nyarn add mysql2\n```\n\n```text\nnpm install -g sequelize\n```\n\n```text\nnpm uninstall -g sequelize\n```\n\n```text\nnpm install -g sequelize-cli\n```\n\n```text\nyarn add mysql2\n```\n\n```text\nnpm install mysql2\n```\n\n```text\nnpx sequelize-cli db:migrate\n```\n\n```js\nconst sequelize = new Sequelize(config.db.database, config.db.user, config.db.password, {\n  host: config.host,\n  dialect:'mysql',\n  dialectModule: require('mysql2'),\n});\n```\n\n```text\n\"development\": {\n    \"username\": \"\",\n    \"password\": \"\",\n    \"database\": \"\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"postgres\"\n  },\n```\n\n```text\nnpm install sequelize sequelize-cli mysql2\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize-cli\n```\n\n```text\nmysql2\n```\n\n```text\nimport mysql2 from 'mysql2'; // Import mysql2 explicitly\n\n\nsequelize = new Sequelize({\n    dialectModule: mysql2,\n});\n```\n\n========================================\n\nComments:\n- Can you post your `package.json` file\n- I just added it. Hopefully, it helps some.\n- This error also happens if you are tying to webpack sequelize: github.com/sequelize/sequelize/issues/&hellip; because the library is not compatible with webpack.\n- I have tried installing using npm install mysql2 and npm install -g mysql2. Is there another way to install module manually?\n- Use Git to clone the repo\n- How is this different from: `npm install -g mysql2` which the person asking the question has already tried?\n- Works nodejs 14LTS, just ensure you remove any mysql2 global npm installs, then install it with the above command or its equivalent `npm i mysql2`\n- I'm using Sequelize and mysql2 with AWS lambda. Adding the dialectModeul: requre('mysql2') fixed the issue for me.\n- I migrated my project into a nx monorepo and this fixed the issue\n- adding dialectModule: require('mysql2'), in the connection config did it for me in 2023. Had this issue on vercel with Node18. Upvoted.\n- This is the only thing that worked for in Next.js 13.5.2 in 2023. thanks!\n- Adding `dialectModule` worked for me\n- This helped me fixing the issue on a API deployed on Vercel.","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":328,"estimatedTokens":1677}}119{"id":"stack-33232147","source":"stackoverflow","questionId":33232147,"title":"sequelize.query() returns same result twice","tags":["json","node.js","npm","sequelize.js"],"text":"Title: sequelize.query() returns same result twice\nTags: json, node.js, npm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am working in nodejs project in that using `sequelize` for connecting mysql database. I am also using sequelize-values for getting raw data from Sequelize instances.\n\nI have written below code\n\n```\nvar Sequelize = require('sequelize');\nrequire('sequelize-values')(Sequelize);\nvar sequelizeObj = new Sequelize('mysql://root:@localhost/database');\n\nsequelizeObj.authenticate().then(function (errors) {\n console.log(errors)\n});\n\nsequelizeObj.query(\"SELECT * FROM `reports` WHERE `id` = 1200\").then(function (result) {\n\n });\n```\n\nNow the table `reports` have only 1 record for `id` 1200, But the `result` gives two objects for same records, Means both records are same of id 1200.\n\n```\n[ [ { id: 1200,\n productivity_id: 9969,\n gross_percentage_points: 100 } ],\n[ { id: 1200,\n productivity_id: 9969,\n gross_percentage_points: 100 } ] ]\n```\n\nLet me know what I am doing wrong?\n\n========================================\n\nTop Answer:\nTry : \n\n```\nsequelizeObj.query(\"SELECT * FROM `reports` WHERE `id` = 1200\", { type: Sequelize.QueryTypes.SELECT }).then(function (result) {\n });\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\nrequire('sequelize-values')(Sequelize);\nvar sequelizeObj = new Sequelize('mysql://root:@localhost/database');\n\nsequelizeObj.authenticate().then(function (errors) {\n    console.log(errors)\n});\n\nsequelizeObj.query(\"SELECT * FROM `reports` WHERE `id` = 1200\").then(function (result) {\n\n    });\n```\n\n```text\n[ [ { id: 1200,\n  productivity_id: 9969,\n  gross_percentage_points: 100 } ],\n[ { id: 1200,\n  productivity_id: 9969,\n  gross_percentage_points: 100 } ] ]\n```\n\n```text\nsequelize\n```\n\n```text\nreports\n```\n\n```text\nid\n```\n\n```text\nresult\n```\n\n```text\n{ type: Sequelize.QueryTypes.SELECT }\n```\n\n```text\nsequelizeObj.query(\"SELECT * FROM `reports` WHERE `id` = 1200\", { type: Sequelize.QueryTypes.SELECT }).then(function (result) {\n    });\n```\n\n```text\n{ type: Sequelize.QueryTypes.SELECT }\n```\n\n```text\nsequelize.query(\"SELECT ...\", { type: Sequelize.SELECT })\n.then(result => {\n    if (!result ) {\n        res.status(404).send({ message: \"Data Not found.\" });\n    }\n\n    res.status(200).send(result[0]);\n\n})\n.catch(err => {\n    res.status(500).send({ message: err.message });\n});\n```\n\n========================================\n\nComments:\n- const { QueryTypes } = require('sequelize'); var queryString = \"SELECT id from users\"; const userList = await Sequelize.query(queryString, { type: QueryTypes.SELECT });","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":120,"estimatedTokens":651}}120{"id":"stack-46050840","source":"stackoverflow","questionId":46050840,"title":"sequelize - Cannot add foreign key constraint","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: sequelize - Cannot add foreign key constraint\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set a 1:1 relation between two tables. RefreshToken table will have two foreignKey releated to Users table, as in this image:\nhttps://i.sstatic.net/B2fcU.png\n\nI used sequelize-auto to generate my sequelize models.\n\n**Users model:**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('Users', {\n idUsers: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true\n },\n name: {\n type: DataTypes.STRING(45),\n allowNull: true\n },\n mail: {\n type: DataTypes.STRING(45),\n allowNull: false,\n primaryKey: true\n }\n }, {\n tableName: 'Users'\n });\n};\n```\n\n**RefreshToken model:**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('RefreshToken', {\n idRefreshToken: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true\n },\n token: {\n type: DataTypes.TEXT,\n allowNull: true\n },\n userId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n references: {\n model: 'Users',\n key: 'idUsers'\n }\n },\n userEmail: {\n type: DataTypes.STRING(45),\n allowNull: false,\n primaryKey: true,\n references: {\n model: 'Users',\n key: 'mail'\n }\n }\n }, {\n tableName: 'RefreshToken'\n });\n};\n```\n\nWhen I run the application, I receive this error:\n\n Unhandled rejection Error: SequelizeDatabaseError:\n ER_CANNOT_ADD_FOREIGN: Cannot add foreign key constraint\n\nI tried to add explicit the relation, adding in Users table:\n\n```\nUser.associate = (models) => {\n User.hasOne(models.RefreshToken, {\n foreignKey: 'userId'\n });\n User.hasOne(models.RefreshToken, {\n foreignKey: 'userEmail'\n });\n };\n```\n\nand in RefreshToken:\n\n```\nRefreshToken.associate = (models) => {\n RefreshToken.belongsTo(models.Users, {\n foreignKey: 'userId'\n });\n RefreshToken.belongsTo(models.Users, {\n foreignKey: 'userEmail'\n });\n };\n```\n\nBut I receive again the same error. If I remove the references in the RefreshToken table I don't see any error, but when I check the database I don't see any foreign key relation constraint with email and id of the User\n\n========================================\n\nTop Answer:\nI see two issues:\n\nNo table should contain two primary keys and userId shouldn't be in integer it should be a UUID.\n\nI had a foreign key set to INT and it gave me error:\n\n Unhandled rejection SequelizeDatabaseError: foreign key constraint\n \"constraint_name_here\" cannot be implemented\n\n**Try changing:**\n\n```\nuserId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n references: {\n model: 'Users',\n key: 'idUsers'\n }\n},\n```\n\n**To**\n\n```\nuserId: {\n type: DataTypes.UUID,\n allowNull: false,\n foreignKey: true,\n references: {\n model: 'Users',\n key: 'idUsers'\n }\n},\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('Users', {\n    idUsers: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true\n    },\n    name: {\n      type: DataTypes.STRING(45),\n      allowNull: true\n    },\n    mail: {\n      type: DataTypes.STRING(45),\n      allowNull: false,\n      primaryKey: true\n    }\n  }, {\n    tableName: 'Users'\n  });\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('RefreshToken', {\n    idRefreshToken: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true\n    },\n    token: {\n      type: DataTypes.TEXT,\n      allowNull: true\n    },\n    userId: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      references: {\n        model: 'Users',\n        key: 'idUsers'\n      }\n    },\n    userEmail: {\n      type: DataTypes.STRING(45),\n      allowNull: false,\n      primaryKey: true,\n      references: {\n        model: 'Users',\n        key: 'mail'\n      }\n    }\n  }, {\n    tableName: 'RefreshToken'\n  });\n};\n```\n\n```text\nUser.associate = (models) => {\n    User.hasOne(models.RefreshToken, {\n      foreignKey: 'userId'\n    });\n    User.hasOne(models.RefreshToken, {\n      foreignKey: 'userEmail'\n    });\n  };\n```\n\n```text\nRefreshToken.associate = (models) => {\n    RefreshToken.belongsTo(models.Users, {\n      foreignKey: 'userId'\n    });\n    RefreshToken.belongsTo(models.Users, {\n      foreignKey: 'userEmail'\n    });\n  };\n```\n\n```text\nreturn sequelize.define('RefreshToken', {\n    userId: {\n      type: DataTypes.INTEGER(11), // The data type defined here and \n      references: {\n        model: 'Users',\n        key: 'idUsers'\n      }\n    }, \n\n\nreturn sequelize.define('Users', {\n    idUsers: {\n      type: DataTypes.INTEGER(11),  // This data type should be the same\n    },\n```\n\n```text\nreturn sequelize.define('Users', {\n    idUsers: {\n      primaryKey: true  \n    },\n    mail: {\n      type: DataTypes.STRING(45),\n      allowNull: false,\n      primaryKey: true   // You should change this to 'unique:true'. you cant hv two primary keys in one table. \n    }\n```\n\n```text\nunique:true\n```\n\n```text\nuserId: {\n  type: DataTypes.INTEGER(11),\n  allowNull: false,\n  primaryKey: true,\n  references: {\n    model: 'Users',\n    key: 'idUsers'\n  }\n},\n```\n\n```text\nuserId: {\n  type: DataTypes.UUID,\n  allowNull: false,\n  foreignKey: true,\n  references: {\n    model: 'Users',\n    key: 'idUsers'\n  }\n},\n```\n\n```text\nconst { Model, DataTypes, Sequelize } = require('sequelize');\n\nconst { USER_TABLE } = require('./user.model');\n\nconst CUSTOMER_TABLE = 'customers';\n\nconst CustomerSchema = {\n  id: {\n    allowNull: false,\n    autoIncrement: true,\n    primaryKey: true,\n    type: DataTypes.INTEGER,\n  },\n  name: {\n    allowNull: false,\n    type: DataTypes.STRING,\n  },\n  lastName: {\n    allowNull: false,\n    type: DataTypes.STRING,\n    field: 'last_name',\n  },\n  phone: {\n    allowNull: true,\n    type: DataTypes.STRING,\n  },\n  createdAt: {\n    type: DataTypes.DATE,\n    field: 'created_at',\n    defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),\n    allowNull: false,\n  },\n  updatedAt: {\n    type: DataTypes.DATE,\n    field: 'updated_at',\n    defaultValue: Sequelize.literal(\n      'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',\n    ),\n    allowNull: false,\n  },\n  userId: {\n    field: 'user_id',\n    allowNull: false,\n    type: DataTypes.INTEGER,\n    references: {\n      model: USER_TABLE,\n      key: 'id',\n    },\n    onUpdate: 'CASCADE',\n    onDelete: 'SET NULL',\n  },\n};\n\nclass Customer extends Model {\n  static associate(models) {\n    this.belongsTo(models.User, { foreignKey: 'userId', as: 'user' });\n  }\n\n  static config(sequelize) {\n    return {\n      sequelize,\n      tableName: CUSTOMER_TABLE,\n      modelName: 'Customer',\n    };\n  }\n}\n\nmodule.exports = { Customer, CustomerSchema, CUSTOMER_TABLE };\n```\n\n```text\nuserId:{\n    field:'user_id',\n    allowNull:false,\n    type:DataTypes.INTEGER,\n    unique:true,\n    references:{\n      model:USER_TABLE,\n      key:'id',\n        onUpdate:'CASCADE',\n        onDelete:'SET NULL'\n      },\n  }\n```\n\n========================================\n\nComments:\n- Try to use only `userid` as foreign key in RefreshToken table.\n- Or you should use Composite Foreign keys: stackoverflow.com/questions/9780163/&hellip;\n- Here is information that Composite foreign keys are not supported in sequelize.js: github.com/sequelize/sequelize/issues/311\n- I have a table with two primary keys. It's a join table, and the two columns are supposed to act as a joint key. Seems to work just fine.\n- Hey Tom, what you're saying is exactly right. Those two primary keys are indeed primary keys but not in relation to the join table. In the join table's point of view those two keys are foreign keys pointing to the primary keys in different tables.\n- In my case, I don't know why, in my db my reference was bad, the reference was with another table that was not correct, I corrected the reference and solved my problem.\n- My case was nearly as same as @LudOsorio's. Instead of referencing \"clients\" i was referencing \"client\".","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":383,"estimatedTokens":1993}}121{"id":"stack-48732223","source":"stackoverflow","questionId":48732223,"title":"Sequelize: seed with associations","tags":["javascript","node.js","sequelize.js","models","seeding"],"text":"Title: Sequelize: seed with associations\nTags: javascript, node.js, sequelize.js, models, seeding\nSource: Stack Overflow\n\nQuestion:\nI have 2 models, Courses and Videos, for example. And Courses has many Videos.\n\n```\n// course.js\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n const Course = sequelize.define('Course', {\n title: DataTypes.STRING,\n description: DataTypes.STRING\n });\n\n Course.associate = models => {\n Course.hasMany(models.Video);\n };\n\n return Course;\n};\n\n// video.js\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n const Video = sequelize.define('Video', {\n title: DataTypes.STRING,\n description: DataTypes.STRING,\n videoId: DataTypes.STRING\n });\n\n Video.associate = models => {\n Video.belongsTo(models.Course, {\n onDelete: \"CASCADE\",\n foreignKey: {\n allowNull: false\n }\n })\n };\n\n return Video;\n};\n```\n\nI want to create seeds with courses which includes videos. How can I make it? I don't know how to create seeds with included videos.\n\n========================================\n\nTop Answer:\nWhen passing `{ returning: true }` in the options field of `bulkInsert` it will return the created objects.\n\n```\nlet createdOjects = await queryInterface.bulkInsert(\"table_name\", data_to_be_inserted, { returning: true });\n```\n\nAlso, you may pass an array with the fields you are interested in, e.g. the ID `{ returning: ['id'] }` and this will return an array of IDs of the created objects\n\n```\nlet createdIds = await queryInterface.bulkInsert(\"table_name\", data_to_be_inserted, { returning: ['id'] });\n```\n\nYou can loop through the returned objects/ids and insert the nested objects using `bulkInsert` as well.\n\nSample code:\n\n```\nmodule.exports = {\n up: async (queryInterface) => {\n let courses = [\"...\"]\n let videos = [\"...\"]\n let videoIds = await queryInterface.bulkInsert(\"courses\", courses, { returning: [\"id\"] });\n \n //add courseId to each video object -- depends on your scheme\n\n await queryInterface.bulkInsert(\"videos\", videos);\n },\n\n down: async (queryInterface) => {\n await queryInterface.bulkDelete(\"videos\", null, {});\n await queryInterface.bulkDelete(\"courses\", null, {});\n },\n};\n```\n\n========================================\n\nCode:\n```text\n// course.js\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n  const Course = sequelize.define('Course', {\n    title: DataTypes.STRING,\n    description: DataTypes.STRING\n  });\n\n  Course.associate = models => {\n    Course.hasMany(models.Video);\n  };\n\n  return Course;\n};\n\n\n// video.js\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n  const Video = sequelize.define('Video', {\n    title: DataTypes.STRING,\n    description: DataTypes.STRING,\n    videoId: DataTypes.STRING\n  });\n\n  Video.associate = models => {\n    Video.belongsTo(models.Course, {\n      onDelete: \"CASCADE\",\n      foreignKey: {\n        allowNull: false\n      }\n    })\n  };\n\n  return Video;\n};\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface) => {\n    await queryInterface.bulkInsert('courses', [\n      {title: 'Course 1', description: 'description 1', id: 1}\n      {title: 'Course 2', description: 'description 2', id: 2}\n    ], {});\n\n    const courses = await queryInterface.sequelize.query(\n      `SELECT id from COURSES;`\n    );\n\n    const courseRows = courses[0];\n\n    return await queryInterface.bulkInsert('videos', [\n      {title: 'Movie 1', description: '...', id: '1', course_id: courseRows[0].id}\n      {title: 'Movie 2', description: '...', id: '2', course_id: courseRows[0].id},\n      {title: 'Movie 3', description: '...', id: '3', course_id: courseRows[0].id},\n    ], {});\n  },\n\n  down: async (queryInterface) => {\n    await queryInterface.bulkDelete('videos', null, {});\n    await queryInterface.bulkDelete('courses', null, {});\n  }\n};\n```\n\n```text\nqueryInterface\n```\n\n```text\ncourse_id\n```\n\n```js\nfunction getId( firstId, items, needly ) {\n    for ( let i = 0; i < items.length; i++ ) {\n        if ( items[i].title === needly ) {\n            return firstId + i;\n        }\n    }\n\n    return null;\n}\n\nexports.up = async ( queryInterface, Sequelize ) => {\n    const courses = [\n        {\n            title: 'Course 1',\n            description: '...',\n        },\n        {\n            title: 'Course 2',\n            description: '...',\n        },\n        {\n            title: 'Course 3',\n            description: '...',\n        },\n        {\n            title: 'Course 4',\n            description: '...',\n        },\n        {\n            title: 'Course 5',\n            description: '...',\n        },\n    ];\n\n    const firstId = await queryInterface.bulkInsert( 'courses', courses, {} );\n    const course2Id = getId( firstId, courses, 'Course 2' );\n    const course5Id = getId( firstId, courses, 'Course 5' );\n\n    return queryInterface.bulkInsert( 'categories', [\n        { title: 'Video 1', description: '...', courseId: course2Id },\n        { title: 'Video 2', description: '...', courseId: course2Id },\n        { title: 'Video 3', description: '...', courseId: course5Id },\n        { title: 'Video 4', description: '...', courseId: course5Id },\n        { title: 'Video 5', description: '...', courseId: course5Id },\n    ], {} );\n};\n\nexports.down = async ( queryInterface ) => {\n    await queryInterface.bulkDelete( 'videos', null, {} );\n    await queryInterface.bulkDelete( 'courses', null, {} );\n}\n```\n\n```text\nbulkInsert\n```\n\n```text\nlet createdOjects = await queryInterface.bulkInsert(\"table_name\", data_to_be_inserted, { returning: true });\n```\n\n```text\nlet createdIds = await queryInterface.bulkInsert(\"table_name\", data_to_be_inserted, { returning: ['id'] });\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface) => {\n    let courses = [\"...\"]\n    let videos = [\"...\"]\n    let videoIds = await queryInterface.bulkInsert(\"courses\", courses, { returning: [\"id\"] });\n    \n    //add courseId to each video object -- depends on your scheme\n\n     await queryInterface.bulkInsert(\"videos\", videos);\n  },\n\n  down: async (queryInterface) => {\n    await queryInterface.bulkDelete(\"videos\", null, {});\n    await queryInterface.bulkDelete(\"courses\", null, {});\n  },\n};\n```\n\n```text\n{ returning: true }\n```\n\n```text\nbulkInsert\n```\n\n```text\n{ returning: ['id'] }\n```\n\n```text\nbulkInsert\n```\n\n========================================\n\nComments:\n- in the `down` section, shouldn't we delete videos column before the courses column because of the foreign key constraint. Sorry to be picky though.\n- please checkout stackoverflow.com/questions/52227663/&hellip;\n- Latest version will throw 'await is only valid in async function'\n- `queryInterface.sequelize.query` was not working for me so I used `queryInterface.rawSelect` instead\n- Should mention that this technique will only work with incrementing integer IDs, but it's good to know that bulkInsert will resolve to the first inserted ID.\n- NOTE: the `{ returning: true }` option is only available for POSTGRES. If you're using a different dialect/database, it is ignored","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":277,"estimatedTokens":1732}}122{"id":"stack-41860792","source":"stackoverflow","questionId":41860792,"title":"How can I have a datatype of array in mysql Sequelize instance?","tags":["mysql","arrays","sequelize.js"],"text":"Title: How can I have a datatype of array in mysql Sequelize instance?\nTags: mysql, arrays, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am building an application that uses Node/Express and MySQL with Sequelize as the ORM. I want to have a datatype of Array, but the sequelize docs says this is limited to postgres only.\n\nBasically, if I have a users table that has 3 columns for example (name, phone, favColors), I want favColors to get populated with an array of string values retrieved from the user. How can I do this?\n\n========================================\n\nTop Answer:\nYou can define your field as `json`:\n\n```\ntype: Sequelize.JSON\n```\n\nAnd then save the data as an `array`\n\n========================================\n\nCode:\n```text\nfavColors: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    get() {\n        return this.getDataValue('favColors').split(';')\n    },\n    set(val) {\n       this.setDataValue('favColors',val.join(';'));\n    },\n}\n```\n\n```text\ntype: Sequelize.JSON\n```\n\n```text\njson\n```\n\n```text\narray\n```\n\n```js\ntags: {\n    type: Sequelize.ARRAY(Sequelize.TEXT),\n    defaultValue: [],\n}\n```\n\n```js\nfavColors: {\n    type: Sequelize.JSON\n}\n```\n\n```js\nfavColors: string[]\n```\n\n========================================\n\nComments:\n- you'll have to serialize your array and store as a string.\n- Thanks @Adam, I was going to just store the data as a STRING, and then split the values later, but I thought there may be a less hacky way.\n- I wanted to implement this idea, but the vsCode's intellisense adviced that it was only for postgreSQL. So I didn&#180;t even tried\n- Yep, there are some kinds of data types that work only with some kinds of databases. You can read this doc to see if you can use or not a specific datatype.\n- This worked with a MYSQL database?","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":73,"estimatedTokens":448}}123{"id":"stack-39587767","source":"stackoverflow","questionId":39587767,"title":"disable updatedAt (update date) field in sequelize.js","tags":["node.js","sequelize.js","tedious"],"text":"Title: disable updatedAt (update date) field in sequelize.js\nTags: node.js, sequelize.js, tedious\nSource: Stack Overflow\n\nQuestion:\nI used `sequelize-auto` to generate schema, and I tried to use `findOne()` and I got this error:\n\nUnhandled rejection SequelizeDatabaseError: Invalid column name\n'updatedAt'.\n\nin my database table, there is no field `updatedAt`.\n\nfor example, my table name is `Users` my code is `Users.findOne()`, and there is no `updatedAt` field in the `Users` table.\n\n```\ndb.users= sequelize.import(__dirname + \"/models/users\");\napp.get('/users', function (req, res) {\n\n db.user.findOne().then(function (project) {\n res.json(project);\n })\n \n});\n```\n\nhow to solve it?\n\n========================================\n\nTop Answer:\nin Models => if you want to disable insert automatically createdAt, updatedAt use this\n\n```\ncreatedAt: { type: DataTypes.DATE, allowNull: true, defaultValue: sequelize.literal('CURRENT_TIMESTAMP') },\nupdatedAt: { type: DataTypes.DATE, allowNull: true, defaultValue: sequelize.literal('CURRENT_TIMESTAMP') }\n```\n\nin Services => if you want to to show only spesific column use this\n\n```\nasync function getAll() {\n return await db.regencies.findAll({\n attributes: ['id', 'province_id', 'name']\n });\n}\n```\n\n========================================\n\nCode:\n```text\ndb.users= sequelize.import(__dirname + \"/models/users\");\napp.get('/users', function (req, res) {\n\n  db.user.findOne().then(function (project) {\n    res.json(project);\n  })\n  \n});\n```\n\n```text\nsequelize-auto\n```\n\n```text\nfindOne()\n```\n\n```text\nupdatedAt\n```\n\n```text\nUsers\n```\n\n```text\nUsers.findOne()\n```\n\n```text\nupdatedAt\n```\n\n```text\nUsers\n```\n\n```text\nvar user = sequelize.define('user', { /* bla */ }, {\n\n  // don't add the timestamp attributes (updatedAt, createdAt)\n  timestamps: false,\n\n  // If don't want createdAt\n  createdAt: false,\n\n  // If don't want updatedAt\n  updatedAt: false,\n\n  // your other configuration here\n\n});\n```\n\n```text\n-a\n```\n\n```text\n--addtional\n```\n\n```text\ncreatedAt: { type: DataTypes.DATE, allowNull: true, defaultValue: sequelize.literal('CURRENT_TIMESTAMP') },\nupdatedAt: { type: DataTypes.DATE, allowNull: true, defaultValue: sequelize.literal('CURRENT_TIMESTAMP') }\n```\n\n```text\nasync function getAll() {\n    return await db.regencies.findAll({\n        attributes: ['id', 'province_id', 'name']\n    });\n}\n```\n\n========================================\n\nComments:\n- oh ya, i get it too, so we must add config options in sequelize-auto generation, can you help me how to add the config? i just try it but still fail\n- I have added some instructions in my answer\n- The question seems to be about disabling only the updatedAt, not both columns. It shoudn't be the accepted answer, I believe.\n- This approach should be the correct answer: stackoverflow.com/questions/45248189/&hellip;\n- @RafaelCalhau Thanks for your attention.. I have changed my answer according to your concern.","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":135,"estimatedTokens":728}}124{"id":"stack-53117988","source":"stackoverflow","questionId":53117988,"title":"sequelize select and include another table alias","tags":["node.js","postgresql","sequelize.js","sequelize-cli"],"text":"Title: sequelize select and include another table alias\nTags: node.js, postgresql, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize to acess a postgres database and I want to query for a city and for example include the \"Building\" table but I want to rename the output to \"buildings\" and return the http response but I have this error:\n\n { SequelizeEagerLoadingError: building is associated to city using an alias. You'v\n e included an alias (buildings), but it does not match the alias defined in your a\n ssociation.\n\n```\nCity.findById(req.params.id,{\n include: [\n {\n model: Building, as: \"buildings\"\n }\n ]\n }).then(city =>{\n console.log(city.id);\n res.status(201).send(city);\n }) .catch(error => {\n console.log(error);\n res.status(400).send(error)\n });\n```\n\ncity Model\n\n```\nconst models = require('../models2');\n module.exports = (sequelize, DataTypes) => {\n const City = sequelize.define('city', {\n name: { type: DataTypes.STRING, allowNull: false },\n status: { type: DataTypes.INTEGER, allowNull: false },\n latitude: { type: DataTypes.BIGINT, allowNull: false },\n longitude: { type: DataTypes.BIGINT, allowNull: false },\n\n }, { freezeTableName: true});\n City.associate = function(models) {\n // associations can be defined here\n City.hasMany(models.building,{as: 'building', foreignKey: 'cityId'})\n };\n return City;\n };\n```\n\n========================================\n\nCode:\n```text\nCity.findById(req.params.id,{\n      include: [\n        {\n          model: Building, as: \"buildings\"\n        }\n      ]\n    }).then(city =>{\n      console.log(city.id);\n         res.status(201).send(city);\n    }) .catch(error => {\n     console.log(error);\n     res.status(400).send(error)\n   });\n```\n\n```text\nconst models = require('../models2');\n            module.exports = (sequelize, DataTypes) => {\n              const City = sequelize.define('city', {\n              name: { type: DataTypes.STRING, allowNull: false },\n                status: { type: DataTypes.INTEGER, allowNull: false },\n                latitude: { type: DataTypes.BIGINT, allowNull: false },\n                longitude: { type: DataTypes.BIGINT, allowNull: false },\n\n              }, { freezeTableName: true});\n              City.associate = function(models) {\n                // associations can be defined here\n                 City.hasMany(models.building,{as: 'building', foreignKey: 'cityId'})\n              };\n              return City;\n            };\n```\n\n```text\nCity.hasMany(models.building,{as: 'building', foreignKey: 'cityId'})\n```\n\n```text\ninclude: [\n  {\n     model: Building, as: \"buildings\" // <---- HERE\n  }\n]\n```\n\n```text\ninclude: [\n   {\n         model: Building, as: \"building\" // <---- HERE\n   }\n]\n```\n\n```text\nbuilding\n```\n\n```text\nbuildings\n```\n\n```text\nbuilding\n```\n\n========================================\n\nComments:\n- Check the alias name `buildings` is same as defined or not , please post the City model code also\n- Oh I see now, that alias have to match with the model? If I change the alias in model, do I have to create a sequelize migration?\n- Nope , just change the name as it has , and Voila , you are good to go\n- Thanks a lot! it worked!\n- @John , Glad to know. Happy Coding BTW :)\n- Why didn't sequelize team write this to it's documentation? interesting.\n- I can only run this query once after starting the server. any subsequent query throws this error \"You have used the alias company in two separate associations. Aliased associations must have unique aliases.\" any solution?\n- Do you have city.addBuilding function? I am using alias when defining association. However add function is undefined.","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":127,"estimatedTokens":906}}125{"id":"stack-27687546","source":"stackoverflow","questionId":27687546,"title":"Can't connect to heroku postgresql database from local node app with sequelize","tags":["node.js","postgresql","heroku","sequelize.js","heroku-postgres"],"text":"Title: Can't connect to heroku postgresql database from local node app with sequelize\nTags: node.js, postgresql, heroku, sequelize.js, heroku-postgres\nSource: Stack Overflow\n\nQuestion:\nI'm trying to connect to a Heroku postgresql database from a local nodejs app with Sequelize. I followed this two guides an everything is working perfectly fine on the heroky server side, but my node app won't connect to heroku when I run it locally on my Mac.\n\n- http://sequelizejs.com/articles/heroku\n\n- https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku\n\nHere is how I start the local app:\n\n```\nDATABASE_URL=$(heroku config:get DATABASE_URL) nodemon\n```\n\nGets me:\n\n```\nSequelize: Unable to connect to the database:\n```\n\nBut I get the correct URL by doing this:\n\n```\necho $(heroku config:get DATABASE_URL)\n```\n\nAnd those commands are working fine:\n\n```\nheroku pg:psql\npsql $(heroku config:get DATABASE_URL)\n```\n\nHere is my nodejs code :\n\n```\nvar match = process.env.DATABASE_URL.match(/postgres:\\/\\/([^:]+):([^@]+)@([^:]+):(\\d+)\\/(.+)/)\nsequelize = new Sequelize(match[5], match[1], match[2], {\n dialect: 'postgres',\n protocol: 'postgres',\n port: match[4],\n host: match[3],\n logging: false\n})\n\nsequelize\n.authenticate()\n.complete(function(err) {\n if (!!err) {\n log('Sequelize: Unable to connect to the database:', err);\n } else {\n http.listen(process.env.PORT || config.server.port, function(){\n log('Web server listening on port '+process.env.PORT || config.server.port);\n });\n }\n});\n```\n\nI tried to add `native: true` to the sequelize options, but then I get:\n\n```\n/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188\n throw new Error('The dialect ' + this.getDialect() + ' is not supported.\n ^\nError: The dialect postgres is not supported. (Error: Please install postgres package manually)\n at new module.exports.Sequelize (/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188:13)\n at Object. (/Users/clement/Projets/XMM/server.js:17:14)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n at Function.Module.runMain (module.js:497:10)\n at startup (node.js:119:16)\n at node.js:929:3\n```\n\nEven after doing:\n\n```\nnpm install pg\nnpm install -g pg\nbrew install postgresql\n```\n\nThis is working by the way:\n\n```\nvar pg = require('pg');\npg.connect(process.env.DATABASE_URL+'?ssl=true', function(err, client, done) {\n if (err) return console.log(err);\n client.query('SELECT * FROM pg_catalog.pg_tables', function(err, result) {\n done();\n if(err) return console.error(err);\n console.log(result.rows);\n });\n});\n```\n\nBut i'd rather use Sequelize.\n\n========================================\n\nTop Answer:\nYou no longer need to parse the DATABASE_URL env variable, there is a Sequelize constructor which accepts the connection URL:\n\n\r\n\r\n\n```\nsequelize = new Sequelize(process.env.DATABASE_URL, {\r\n dialect: 'postgres',\r\n protocol: 'postgres',\r\n dialectOptions: {\r\n ssl: true\r\n }\r\n});\n```\n\n========================================\n\nCode:\n```text\nDATABASE_URL=$(heroku config:get DATABASE_URL) nodemon\n```\n\n```text\nSequelize: Unable to connect to the database:\n```\n\n```text\necho $(heroku config:get DATABASE_URL)\n```\n\n```text\nheroku pg:psql\npsql $(heroku config:get DATABASE_URL)\n```\n\n```text\nvar match = process.env.DATABASE_URL.match(/postgres:\\/\\/([^:]+):([^@]+)@([^:]+):(\\d+)\\/(.+)/)\nsequelize = new Sequelize(match[5], match[1], match[2], {\n    dialect:  'postgres',\n    protocol: 'postgres',\n    port:     match[4],\n    host:     match[3],\n    logging: false\n})\n\nsequelize\n.authenticate()\n.complete(function(err) {\n    if (!!err) {\n        log('Sequelize: Unable to connect to the database:', err);\n    } else {\n        http.listen(process.env.PORT || config.server.port, function(){\n            log('Web server listening on port '+process.env.PORT || config.server.port);\n        });\n    }\n});\n```\n\n```text\n/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188\n      throw new Error('The dialect ' + this.getDialect() + ' is not supported.\n            ^\nError: The dialect postgres is not supported. (Error: Please install postgres package manually)\n    at new module.exports.Sequelize (/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188:13)\n    at Object.<anonymous> (/Users/clement/Projets/XMM/server.js:17:14)\n    at Module._compile (module.js:456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n    at Function.Module.runMain (module.js:497:10)\n    at startup (node.js:119:16)\n    at node.js:929:3\n```\n\n```text\nnpm install pg\nnpm install -g pg\nbrew install postgresql\n```\n\n```text\nvar pg = require('pg');\npg.connect(process.env.DATABASE_URL+'?ssl=true', function(err, client, done) {\n    if (err) return console.log(err);\n    client.query('SELECT * FROM pg_catalog.pg_tables', function(err, result) {\n        done();\n        if(err) return console.error(err);\n        console.log(result.rows);\n    });\n});\n```\n\n```text\nnative: true\n```\n\n```text\nsequelize = new Sequelize(process.env.DATABASE_URL, {\n    dialect: 'postgres',\n    protocol: 'postgres',\n    dialectOptions: {\n        ssl: true\n    }\n});\n```\n\n```text\nsequelize = new Sequelize(process.env.DATABASE_URL, {\n    dialect: 'postgres',\n    protocol: 'postgres',\n    dialectOptions: {\n        ssl: {\n            require: true,\n            rejectUnauthorized: false\n        }\n    }\n});\n```\n\n```text\nnative: true\n```\n\n```text\nssl: true\n```\n\n```text\ndialectOptions.ssl: true\n```\n\n```text\nself signed certificate\n```\n\n```text\nnode-postgres\n```\n\n```js\nsequelize = new Sequelize(process.env.DATABASE_URL, {\n    dialect: 'postgres',\n    protocol: 'postgres',\n    dialectOptions: {\n        ssl: true\n    }\n});\n```\n\n```text\nconst sequelize = new Sequelize(\n    process.env.DATABASE_NAME_DB_CONFIG,\n    process.env.USER_NAME_DB_CONFIG,\n    process.env.USER_PASSWORD_DB_CONFIG,\n    {\n        host: process.env.HOST_DB_CONFIG,\n        dialect: process.env.DIALECT_DB_CONFIG,\n        protocol: process.env.PROTOCOL_DB_CONFIG,\n        logging:  true,\n        dialectOptions: {\n            ssl: true\n        },\n        pool: {\n            max: 5,\n            min: 0,\n            idle: 10000\n        }\n    }\n);\n```\n\n```text\nssl: true\n```\n\n```text\n\"development\": {\n    \"username\": process.env.DB_USERNAME,\n    \"password\": process.env.DB_PASSWORD,\n    \"database\": process.env.DB_NAME,\n    \"host\": process.env.DB_HOST,\n    \"dialect\": process.env.DB_DIALECT,\n    \"dialectOptions\": {\n        ssl: {\n            require: true,\n            rejectUnauthorized: false\n        }\n    }\n},\n```\n\n```js\nconst sequelize = new Sequelize(`${process.env.DATABASE_URI}?sslmode=require`, {\n  url: process.env.DATABASE_URI,\n  dialect: 'postgres',\n  logging: false,\n  dialectOptions: {\n    ssl: {\n      require: true,\n      rejectUnauthorized: false, // very important\n    }\n  }\n}\n```\n\n```text\n?sslmode=require\n```\n\n```text\nrejectUnauthorized: false\n```\n\n```text\ndialectOptions\n```\n\n========================================\n\nComments:\n- They now have some official Node.js but non-sequelize specific documentation at: devcenter.heroku.com/articles/&hellip; which might also be of interest.\n- Thanks! This took me forever to figure out. There are bad instructions elsewhere online (was also trying to use native). It's important to note that sequelize's error messages are bad (the actual error is not at the top) -- so if you get a dialect unsupported message look a bit lower ... in my case, pg-hstore was missing and needed to be installed.\n- Thanks for this. Maybe this a super noob question - I've got the `ssl` option set as `true` on the server, and I've added this on the client. The connection is working. Is that it? Do I need to do anything else to enable SSL? Super thanks\n- Hi Chris, I can't answer your question, and as it is not directly related to the topic discussed here, I think you should create a brand new question on stackoverflow in order to get help.\n- Holy moly, I spend 3 hours on this error. Thanks a lot!\n- In my case, this got me a little farther, but I still can't connect. Now I'm getting `ERROR: self signed certificate`.\n- To fix the `self signed certificate` error, refer to this post: stackoverflow.com/questions/58965011/&hellip;\n- The second option worked for me like a charm after a whole day of debugging and searching.\n- Thanks again! crazy how many docs have this wrong\n- You already answered your own question (dialectOptions.ssl: true), I just built upon it to provide a simpler solution\n- This worked for me while accepted answer didn't. Must be a recent update.\n- `rejectUnauthorized: false` also mentioned at: stackoverflow.com/questions/58965011/&hellip; The only env var Heroku now defines seems to be `process.env.DATABASE_URL` though, but sequelize parses all the fields out of that correctly via stackoverflow.com/a/27688357/895245","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":338,"estimatedTokens":2257}}126{"id":"stack-41666820","source":"stackoverflow","questionId":41666820,"title":"Node, Sequelize, Mysql - How to define collation and charset to models?","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: Node, Sequelize, Mysql - How to define collation and charset to models?\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIm using sequelize /w node and node-mysql.\n\nI create models using the sequelize-cli, and this is the result:\n\n\r\n\r\n\n```\n'use strict';\r\nmodule.exports = function(sequelize, DataTypes) {\r\n let songs = sequelize.define('songs', {\r\n name: DataTypes.STRING,\r\n link: DataTypes.STRING,\r\n artist: DataTypes.STRING,\r\n lyrics: DataTypes.TEXT,\r\n writer: DataTypes.STRING,\r\n composer: DataTypes.STRING\r\n });\r\n\r\n return songs;\r\n};\n```\n\n\r\n\r\n\r\n\nI want to be able to define collation and charset to each property of the model. \nthe default collation is 'latin1_swedish_ci', and i need it in 'utf-8'.\n\nAnyone?\nTnx\n\n========================================\n\nTop Answer:\nis very simple to add utf-8 just go to any model that you have and do this for example (i edit your code):\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n let songs = sequelize.define('songs', {\n name: {DataTypes.STRING,allowNull : false},\n link: {DataTypes.STRING,allowNull : false},\n artist: {DataTypes.STRING,allowNull : false},\n lyrics: {DataTypes.TEXT,allowNull : false},\n writer: {DataTypes.STRING,allowNull : false},\n composer: {DataTypes.STRING,allowNull : false}\n }, {\ncharset: 'utf8', /* i add this two ligne here for generate the table with collation = 'utf8_general_ci' test it and tell me ? */\ncollate: 'utf8_general_ci'\n\n});\n\n return songs;\n};\n```\n\n========================================\n\nCode:\n```js\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  let songs = sequelize.define('songs', {\n    name: DataTypes.STRING,\n    link: DataTypes.STRING,\n    artist: DataTypes.STRING,\n    lyrics: DataTypes.TEXT,\n    writer: DataTypes.STRING,\n    composer: DataTypes.STRING\n  });\n\n  return songs;\n};\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n  define: {\n    charset: 'utf8',\n    collate: 'utf8_general_ci', \n    timestamps: true\n  },\n  logging:false\n});\n```\n\n```text\nsequelize.define('songs', {\n  name: DataTypes.STRING,\n  link: DataTypes.STRING,\n  artist: DataTypes.STRING,\n  lyrics: DataTypes.TEXT,\n  writer: DataTypes.STRING,\n  composer: DataTypes.STRING\n}, {\n  charset: 'utf8',\n  collate: 'utf8_unicode_ci'\n});\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  let songs = sequelize.define('songs', {\n    name: {DataTypes.STRING,allowNull : false},\n    link: {DataTypes.STRING,allowNull : false},\n    artist: {DataTypes.STRING,allowNull : false},\n    lyrics: {DataTypes.TEXT,allowNull : false},\n    writer: {DataTypes.STRING,allowNull : false},\n    composer: {DataTypes.STRING,allowNull : false}\n  }, {\ncharset: 'utf8', /* i add this two ligne here for generate the table with collation  = 'utf8_general_ci' test it and tell me ? */\ncollate: 'utf8_general_ci'\n\n\n});\n\n  return songs;\n};\n```\n\n========================================\n\nComments:\n- It seems that there's no easy way to set the charset on a per-column basis, which is an incredible pain.\n- @jlh there's a comment in this issue which accomplishes what you're looking for: github.com/sequelize/sequelize/issues/7110\n- @GianniCarlo Thanks! But to me this feels more like a hacky SQL injection. Not what I want in code that I'd like to be solid and future proof. But for some use cases this might be acceptable.\n- apparently, collate is illegal and it should simply be charset\n- FYI, anything you put in the `define` object will be used as defaults when calling model.init()\n- You should use utf8mb4 and not utf8, see the following thread: stackoverflow.com/questions/30074492/&hellip;\n- Does setting charset and collate in Sequelize definition work for the tables already existing in the database also?","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":136,"estimatedTokens":940}}127{"id":"stack-43125925","source":"stackoverflow","questionId":43125925,"title":"Sequelize.js: Query for not in array ($ne for items in array)","tags":["postgresql","sequelize.js"],"text":"Title: Sequelize.js: Query for not in array ($ne for items in array)\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am looking to pull items from a postgres data base with Sequelize, but only return items that have an id that does not equal any items in a given array.\n\nIn the Sequelize documentation, there are operators `$ne` for `not equal` and `$in` for returning items that have properties with values that match the given array, but it doesn't look like there is an operator for something that combines those two.\n\nFor example, if I were to have items in my database with ids `[1, 2, 3, 4, 5, 6]`, and I wanted to filter those by comparing to another array (ie `[2,3,4]`), so that it would return items `[1, 5, 6]`. In my example i also randomize the return order and limit, but that can be disregarded.\n\n```\nfunction quizQuestions(req, res) {\n const query = {\n limit: 10,\n order: [ [sequelize.fn('RANDOM')] ],\n where: {\n id: { $ne: [1, 2, 3] } // This does not work\n }\n };\n\n Question.findAll(query)\n .then(results => res.status(200).json(map(results, r => r.dataValues)))\n .catch(err => res.status(500).json(err));\n}\n```\n\nEdit: With @piotrbienias answer, my query looks like this:\n\n```\nconst query = {\n limit: 10,\n order: [ [sequelize.fn('RANDOM')] ],\n where: {\n id: { $notIn: [1, 2, 3] }\n }\n };\n```\n\n========================================\n\nTop Answer:\nusing\n\n```\nconst Op = Sequelize.Op\nwhere: {\n id: {[Op.notIn]:[1, 2, 3]}\n}\n```\n\nSee operators:\n\nSequelize exposes symbol operators that can be used for to create more complex comparisons\n\n========================================\n\nCode:\n```text\nfunction quizQuestions(req, res) {\n  const query = {\n    limit: 10,\n    order: [ [sequelize.fn('RANDOM')] ],\n    where: {\n      id: { $ne: [1, 2, 3] } // This does not work\n    }\n  };\n\n  Question.findAll(query)\n  .then(results => res.status(200).json(map(results, r => r.dataValues)))\n  .catch(err => res.status(500).json(err));\n}\n```\n\n```text\nconst query = {\n    limit: 10,\n    order: [ [sequelize.fn('RANDOM')] ],\n    where: {\n      id: { $notIn: [1, 2, 3] }\n    }\n  };\n```\n\n```text\n$ne\n```\n\n```text\nnot equal\n```\n\n```text\n$in\n```\n\n```text\n[1, 2, 3, 4, 5, 6]\n```\n\n```text\n[2,3,4]\n```\n\n```text\n[1, 5, 6]\n```\n\n```sql\nSELECT \"id\", \"name\"\nFROM \"categories\" AS \"Category\"\nWHERE \"Category\".\"id\" NOT IN (1, 2);\n```\n\n```text\n$notIn\n```\n\n```text\n$notIn\n```\n\n```text\n2.0\n```\n\n```text\n3.0\n```\n\n```text\nconst Op = Sequelize.Op\nwhere: {\n      id: {[Op.notIn]:[1, 2, 3]}\n}\n```\n\n========================================\n\nComments:\n- Perfect, thanks! I actually didn't notice I was reading the 2.0 docs when I posted. I am using sequelize 3.30.2, thanks for the help!\n- I wonder why they don't make `id: { $ne: [1, 2, 3] }` work :-( Sounds intuitive given that `id: { [1, 2, 3] }` works and so `$in` is never needed anymore. Still doesn't work tested as of 6.14.","metadata":{"transformedAt":"2026-08-18T18:33:34.347Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":142,"estimatedTokens":719}}128{"id":"stack-27014849","source":"stackoverflow","questionId":27014849,"title":"Create multiple rows in table from array?","tags":["javascript","orm","sequelize.js"],"text":"Title: Create multiple rows in table from array?\nTags: javascript, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs possible to add multiple rows at once from array with sequelize.js? This is my code:\n\n```\nvar user = User.build({\n email: req.body.email,\n password: req.body.password,\n userlevel: '3',\n });\n\n User\n .find({ where: { email: req.body.email } })\n .then(function(existingUser){\n\n if (existingUser) {\n return res.redirect('/staff');\n }\n\n user\n .save()\n .complete(function(err){\n if (err) return next(err);\n res.redirect('/staff');\n });\n }).catch(function(err){\n return next(err);\n });\n```\n\nThanks for any advise!\n\n========================================\n\nTop Answer:\nThere has been an update in the document. check this link\n\nhttps://sequelize.org/v5/manual/instances.html#working-in-bulk--creating--updating-and-destroying-multiple-rows-at-once-\n\n```\nUser.bulkCreate([\n { username: 'barfooz', isAdmin: true },\n { username: 'foo', isAdmin: true },\n { username: 'bar', isAdmin: false }\n])\n```\n\n========================================\n\nCode:\n```text\nvar user = User.build({\n    email: req.body.email,\n    password: req.body.password,\n    userlevel: '3',\n  });\n\n  User\n  .find({ where: { email: req.body.email } })\n  .then(function(existingUser){\n\n    if (existingUser) {\n      return res.redirect('/staff');\n    }\n\n    user\n    .save()\n    .complete(function(err){\n      if (err) return next(err);\n      res.redirect('/staff');\n    });\n  }).catch(function(err){\n    return next(err);\n  });\n```\n\n```text\nUser.bulkCreate([{ /*  record one */ }, { /* record two */ }.. ])\n```\n\n```text\nUser.bulkCreate([\n  { username: 'barfooz', isAdmin: true },\n  { username: 'foo', isAdmin: true },\n  { username: 'bar', isAdmin: false }\n])\n```\n\n========================================\n\nComments:\n- Thanks. The link is old. A newer one is sequelize.org/master/class/lib/&hellip;\n- Manual has been updated. Here is a link to new version: sequelize.org/v5/manual/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":96,"estimatedTokens":492}}129{"id":"stack-17963516","source":"stackoverflow","questionId":17963516,"title":"Is there no option to map the column name in sequelize model","tags":["mysql","node.js","sequelize.js"],"text":"Title: Is there no option to map the column name in sequelize model\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a given database with long, cumbersome columnnames. Isn't there any way to map the tablenames to shorter and more descriptive propertyNames in the model ? \nsomething like\n\n```\nvar Employee = sql.define('Employee', {\n id : {type : Sequelize.INTEGER , primaryKey: true, map : \"veryLongNameForJustTheId\"}\n},{\n tableName: 'cumbersomeTableName',\n timestamps: false\n});;\n```\n\n========================================\n\nTop Answer:\nYou can specify a table name by supplying the name as the first parameter to the define() call. For example:\n\n```\nvar User = sequelize.define(\n'a_long_cumbersone_users_table_name',\n{\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true\n },\n name: {\n type: Sequelize.STRING\n },\n email: {\n type: Sequelize.STRING\n },\n password: {\n type: Sequelize.STRING\n },\n rememberToken: {\n type: Sequelize.STRING,\n field: 'remember_token'\n }\n},\n{\n underscored: true,\n timestamps: true,\n createdAt: 'created_at',\n updatedAt: 'updated_at'\n}\n);\n```\n\n========================================\n\nCode:\n```text\nvar Employee = sql.define('Employee', {\n    id : {type : Sequelize.INTEGER , primaryKey: true, map : \"veryLongNameForJustTheId\"}\n},{\n     tableName: 'cumbersomeTableName',\n     timestamps: false\n});;\n```\n\n```text\nid : {\n    field: 'some_long_name_that_is_terrible_thanks_dba_guy',\n    type : Sequelize.INTEGER ,\n    primaryKey: true\n}\n```\n\n```text\nvar User = sequelize.define(\n'a_long_cumbersone_users_table_name',\n{\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true\n    },\n    name: {\n        type: Sequelize.STRING\n    },\n    email: {\n        type: Sequelize.STRING\n    },\n    password: {\n        type: Sequelize.STRING\n    },\n    rememberToken: {\n        type: Sequelize.STRING,\n        field: 'remember_token'\n    }\n},\n{\n    underscored: true,\n    timestamps: true,\n    createdAt: 'created_at',\n    updatedAt: 'updated_at'\n}\n);\n```\n\n========================================\n\nComments:\n- This is the official answer. The document has an example: docs.sequelizejs.com/en/latest/docs/models-definition/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":108,"estimatedTokens":546}}130{"id":"stack-31678813","source":"stackoverflow","questionId":31678813,"title":"Is it possible to filter a query by the attributes in the association table with sequelize?","tags":["node.js","sequelize.js"],"text":"Title: Is it possible to filter a query by the attributes in the association table with sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to filter my query by the attributes of the joining table\n\nI have 2 tables Cities and Categories which I am associating through a third table CityCategory.\nThe idea is to get the Categories associated with a City when `CityCategory`.`year` is a specific integer.\n\nThis is how I specified the associations:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var CityCategory = sequelize.define('CityCategory', {\n year: {\n type: DataTypes.INTEGER,\n allowNull: false,\n validate: {\n notNull: true\n }\n }\n }, {\n indexes: [{\n unique: true,\n fields: ['CityId', 'CategoryId', 'year']\n }]\n });\n\n return CityCategory;\n};\n\nCity.belongsToMany(models.Category, {\n through: {\n model: models.CityCategory\n }\n });\n\nCategory.belongsToMany(models.City, {\n through: {\n model: models.CityCategory\n }\n });\n```\n\nThis is the query I'm currently, unsuccessfully using:\n\n```\nCity.find({\n where: {id: req.params.id},\n attributes: ['id', 'name'],\n include: [{\n model: Category,\n where: {year: 2015},\n attributes: ['id', 'name', 'year']\n }]\n })\n .then(function(city) {\n ...\n });\n```\n\nUnfortunately I'm not sure how to tell sequelize to use the CityCategory's year attribute instead of it searching for an attribute called 'year' in the Category model...\n\n```\nUnhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'Category.CityCategory.year' in 'where clause'\n```\n\nIs this possible or would I have to go and manually write my custom query?\n\nMany thanks in advance!\n\n**edit**\n\nI've been playing around a little more and found a solution! It seems a little messy so I'm sure there must be a better way.\n\n```\nCity.find({\n where: {id: req.params.id},\n attributes: ['id', 'name'],\n include: [{\n model: Category,\n where: [\n '`Categories.CityCategory`.`year` = 2015'\n ],\n attributes: ['id', 'name', 'year']\n }]\n })\n .then(function(city) {\n ...\n });\n```\n\n========================================\n\nTop Answer:\nFor Sequelize v3 it appears the syntax is closer to what you suggested, that is:\n\n```\ninclude: [{\n model: Category,\n where: {year: 2015},\n attributes: ['id']\n}]\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var CityCategory = sequelize.define('CityCategory', {\n        year: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            validate: {\n                notNull: true\n            }\n        }\n    }, {\n        indexes: [{\n            unique: true,\n            fields: ['CityId', 'CategoryId', 'year']\n        }]\n    });\n\n    return CityCategory;\n};\n\nCity.belongsToMany(models.Category, {\n                    through: {\n                        model: models.CityCategory\n                    }\n                });\n\nCategory.belongsToMany(models.City, {\n                    through: {\n                        model: models.CityCategory\n                    }\n                });\n```\n\n```text\nCity.find({\n        where: {id: req.params.id},\n        attributes: ['id', 'name'],\n        include: [{\n            model: Category,\n            where: {year: 2015},\n            attributes: ['id', 'name', 'year']\n        }]\n    })\n    .then(function(city) {\n        ...\n    });\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'Category.CityCategory.year' in 'where clause'\n```\n\n```text\nCity.find({\n    where: {id: req.params.id},\n    attributes: ['id', 'name'],\n    include: [{\n      model: Category,\n      where: [\n        '`Categories.CityCategory`.`year` = 2015'\n      ],\n      attributes: ['id', 'name', 'year']\n    }]\n  })\n  .then(function(city) {\n    ...\n  });\n```\n\n```text\nCityCategory\n```\n\n```text\nyear\n```\n\n```text\ninclude: [{\n  model: Category,\n  through: { where: {year: 2015}},\n  attributes: ['id']\n}]\n```\n\n```text\nthrough.where\n```\n\n```text\nrequired: true\n```\n\n```text\ninclude: [{\n  model: Category,\n  where: {year: 2015},\n  attributes: ['id']\n}]\n```\n\n========================================\n\nComments:\n- What if there is no through model?\n- @user3631341 What do you mean - This question is about filtering on the association table (aka the through model)\n- Is it possible to get this working when using the instance version of `getWhatever`? For example, `hospital.getPatients({ include: [{ model: HospitalPatient, through: { where: { uniqueId: \"test\" } } }] })` where HospitalPatient is the `through` model?\n- The current answer includes the category fields also to the response. How can I remove that?\n- `required` helps me alot when I don't know how to modify LEFT JOIN to INNER JOIN","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":218,"estimatedTokens":1177}}131{"id":"stack-36883437","source":"stackoverflow","questionId":36883437,"title":"Sequelize, foreign keys as composite primary key","tags":["node.js","sequelize.js"],"text":"Title: Sequelize, foreign keys as composite primary key\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nit is possible to define two foreign keys as a composite primary key of a model?\n\nA user can only be a member of one family, a family can have many members and the family-members table need the references of the user and family\n\n```\nconst User = sequelize.define(\n 'User',\n {\n id: { type: dataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },\n name: { type: dataTypes.STRING(30) },\n email: { type: dataTypes.STRING(30) }\n ...\n },\n {\n classMethods: {\n associate(models) {\n User.hasOne(models.FamilyMember, {\n foreignKey: 'user_id'\n }\n }\n }\n }\n)\n\nconst Family = sequelize.define(\n 'Family',\n {\n name: { type: dataTypes.STRING(30) }\n },\n {\n classMethods: {\n associate(models) {\n Family.hasMany(models.FamilyMember, {\n foreignKey: 'family_id'\n }\n }\n }\n }\n)\n\nconst FamilyMember = sequelize.define(\n 'FamilyMember',\n {\n name: { type: dataTypes.STRING(30) },\n /*\n family_id and user_id will be here after associations but I wanted them to be a composite primaryKey\n */\n }\n)\n```\n\n========================================\n\nTop Answer:\nFor anyone looking to create a composite index primary key based of the columns(keys) in your join table when doing migrations. You will need to add a primary key constraint for the two columns that you wish to act as the combined primary key for the table.\n\n```\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.createTable('itemtags', {\n itemId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'items',\n key: 'id',\n },\n onDelete: 'CASCADE',\n onUpdate: 'CASCADE',\n allowNull: false\n },\n tagId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'tags',\n key: 'id',\n },\n onDelete: 'CASCADE',\n onUpdate: 'CASCADE',\n allowNull: false\n }\n })\n .then(() => {\n return queryInterface.addConstraint('itemtags', ['itemId', 'tagId'], {\n type: 'primary key',\n name: 'itemtag_pkey'\n });\n });\n },\n down: function (queryInterface, Sequelize) {\n return queryInterface.dropTable('itemtags');\n }\n};\n```\n\nWhich is roughly the same as doing `ALTER TABLE ONLY my_table ADD CONSTRAINT pk_my_table PRIMARY KEY(column1,column2);` in postgres.\n\n========================================\n\nCode:\n```text\nconst User = sequelize.define(\n    'User',\n    {\n        id: { type: dataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },\n        name: { type: dataTypes.STRING(30) },\n        email: { type: dataTypes.STRING(30) }\n        ...\n    },\n    {\n        classMethods: {\n            associate(models) {\n                User.hasOne(models.FamilyMember, {\n                    foreignKey: 'user_id'\n                }\n            }\n        }\n    }\n)\n\nconst Family = sequelize.define(\n    'Family',\n    {\n        name: { type: dataTypes.STRING(30) }\n    },\n    {\n        classMethods: {\n            associate(models) {\n                Family.hasMany(models.FamilyMember, {\n                    foreignKey: 'family_id'\n                }\n            }\n        }\n    }\n)\n\nconst FamilyMember = sequelize.define(\n    'FamilyMember',\n    {\n        name: { type: dataTypes.STRING(30) },\n        /*\n        family_id and user_id will be here after associations but I wanted them to be a composite primaryKey\n        */\n    }\n)\n```\n\n```text\nUser = sequelize.define('user', {});\nProject = sequelize.define('project', {});\nUserProjects = sequelize.define('userProjects', {\n    status: DataTypes.STRING\n});\n\nUser.belongsToMany(Project, { through: UserProjects });\nProject.belongsToMany(User, { through: UserProjects });\n```\n\n```js\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.createTable('itemtags', {\n      itemId: {\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'items',\n          key: 'id',\n        },\n        onDelete: 'CASCADE',\n        onUpdate: 'CASCADE',\n        allowNull: false\n      },\n      tagId: {\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'tags',\n          key: 'id',\n        },\n        onDelete: 'CASCADE',\n        onUpdate: 'CASCADE',\n        allowNull: false\n      }\n    })\n      .then(() => {\n        return queryInterface.addConstraint('itemtags', ['itemId', 'tagId'], {\n          type: 'primary key',\n          name: 'itemtag_pkey'\n        });\n      });\n  },\n  down: function (queryInterface, Sequelize) {\n    return queryInterface.dropTable('itemtags');\n  }\n};\n```\n\n```text\nALTER TABLE ONLY my_table ADD CONSTRAINT pk_my_table PRIMARY KEY(column1,column2);\n```\n\n========================================\n\nComments:\n- I'm not sure if you can make a composite primary key, but I know you can make a composite unique key. I'm not sure if they helps for your situation though.\n- But how to do this in a migration using sequelize-cli?\n- in a migration you can add this object after you define your table structure, e.g : ` uniqueKeys: [{ name: \"UniqueUserPermissions\", singleField: false, fields: [\"PermissionId\", \"UserId\"], }]`\n- When i try this a error appear, \"multiple primary keys for table \"patients\" are not allowed\". Do you faced this problem?\n- @MaykonMorais Sounds like you are trying to add a constraint on a table which already have a single primary key constraint.\n- you're right. First i drop my constraint on primary key and add my composite primary keys.","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":213,"estimatedTokens":1338}}132{"id":"stack-29461908","source":"stackoverflow","questionId":29461908,"title":"How to do Bulk insert using Sequelize and node.js","tags":["json","node.js","postgresql","sequelize.js"],"text":"Title: How to do Bulk insert using Sequelize and node.js\nTags: json, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\njs + sequelize to insert 280K rows of data using JSON.\nThe JSON is an array of 280K. Is there a way to do bulk insert in chunks. I am seeing that it takes a lot of time to update the data. When i tried to cut down the data to 40K rows it works quick. Am i taking the right approach. Please advice. I am using postgresql as backend.\n\n```\nPNs.bulkCreate(JSON_Small)\n .catch(function(err) {\n console.log('Error ' + err);\n })\n .finally(function(err) {\n console.log('FINISHED + ' \\n +++++++ \\n');\n\n });\n```\n\n========================================\n\nTop Answer:\nYou can use Sequelize's built in `bulkCreate` method to achieve this.\n\n```\nUser.bulkCreate([\n { username: 'barfooz', isAdmin: true },\n { username: 'foo', isAdmin: true },\n { username: 'bar', isAdmin: false }\n]).then(() => { // Notice: There are no arguments here, as of right now you'll have to...\n return User.findAll();\n}).then(users => {\n console.log(users) // ... in order to get the array of user objects\n})\n```\n\nSequelize | Bulk Create and Update\n\n========================================\n\nCode:\n```text\nPNs.bulkCreate(JSON_Small)\n        .catch(function(err) {\n            console.log('Error ' + err);\n        })\n        .finally(function(err) {\n            console.log('FINISHED  + ' \\n +++++++ \\n');\n\n        });\n```\n\n```text\nvar fs = require('fs'),\n    async = require('async'),\n    csv = require('csv');\n\nvar input = fs.createReadStream(filename);\nvar parser = csv.parse({\n  columns: true,\n  relax: true\n});\nvar inserter = async.cargo(function(tasks, inserterCallback) {\n    model.bulkCreate(tasks).then(function() {\n        inserterCallback(); \n      }\n    );\n  },\n  1000\n);\nparser.on('readable', function () {\n  while(line = parser.read()) {\n    inserter.push(line);\n  }\n});\nparser.on('end', function (count) {\n  inserter.drain = function() {\n    doneLoadingCallback();\n  }\n});\ninput.pipe(parser);\n```\n\n```text\ncargo\n```\n\n```text\nUser.bulkCreate([\n  { username: 'barfooz', isAdmin: true },\n  { username: 'foo', isAdmin: true },\n  { username: 'bar', isAdmin: false }\n]).then(() => { // Notice: There are no arguments here, as of right now you'll have to...\n  return User.findAll();\n}).then(users => {\n  console.log(users) // ... in order to get the array of user objects\n})\n```\n\n```text\nbulkCreate\n```\n\n========================================\n\nComments:\n- The same question here, with an answer: stackoverflow.com/questions/33129677/&hellip;\n- I try this solution for my api responses it work perfect for me as well. I write below code in then statement return res.status(201).send({ status: true, message: \"Created successfully\", data: data});","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":108,"estimatedTokens":688}}133{"id":"stack-42166542","source":"stackoverflow","questionId":42166542,"title":"How do I print out the table name of a sequelize instance?","tags":["node.js","database","orm","sequelize.js"],"text":"Title: How do I print out the table name of a sequelize instance?\nTags: node.js, database, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI would like to print out the table name of an instance that I query with sequelize:\n\n```\nmodels.User.findById(id).then(user => {\n console.log('instance type is, ', user.getTableName || user.getType)) // => instance type is, users\n}\n```\n\nIs there any way to print out the table name of an instance? Is there any way to print out the model name of an instance? I've searched the docs and cannot find the API for the above.\n\n========================================\n\nTop Answer:\npiotrbienias' answer is for v3, in v4 you do:\n\n`user.constructor.getTableName()` or `user.constructor.tableName` for table name and `user.constructor.name` for the Model name\n\nref: Breaking Changes in V4\n\nTook me a while to figure that out so though't I'd post it here in case somebody else comes looking for this answer.\n\n========================================\n\nCode:\n```text\nmodels.User.findById(id).then(user => {\n    console.log('instance type is, ', user.getTableName || user.getType)) // => instance type is, users\n}\n```\n\n```text\nuser.Model.getTableName()\n```\n\n```text\nuser.Model.tableName\n```\n\n```text\nuser.Model.name\n```\n\n```text\nuser.constructor.getTableName()\n```\n\n```text\nuser.constructor.tableName\n```\n\n```text\nuser.constructor.name\n```\n\n```text\nUser.name // => Model name => `User` (you don't need that!\n         //     unless you are doing something dynamic!)\n\nUser.tableName // => Users\nUser.getTableName()\n             // => Users (no schema)\n            // or `\"AmASchema\".\"Users\"` (pg), `AmASchema.Users` (MySql)  (schema)\n           // or { tableName: 'Users', schema: 'AmASchema', ... } (schema)\n```\n\n```text\npublic static getTableName(): string | {\n    tableName: string;\n    schema: string;\n    delimiter: string;\n  };\n```\n\n```text\nconst user = User.build(...)\n\nuser.constructor.name // => User\nuser.constructor.tableName // => Users\n\nuser.constructor.getTableName()\n             // => Users (no schema)\n            // or `\"AmASchema\".\"Users\"` (pg), `AmASchema.Users` (MySql)  (schema)\n           // or { tableName: 'Users', schema: 'AmASchema', ... } (schema)\n```\n\n```text\ninstance.name // => undefined\ninstance.tableName // => undefined\n\n// tested in v4.0, v4.28.10 and v6\n```\n\n```text\ninstance.Model.name // Error (instance.Model => undefined)\ninstance.Model.tableName // Error (instance.Model = undefined)\n\n// tested in both v4.0, v4.28.10 and v6\n```\n\n```text\n--------------- Testing Models Classes -----------------------\n\n\nStatic access using getTableName() (without Schema) :\n\nCourse.getTableName(): Courses\n\n\nStatic access using getTableName() (with Schema) :\n\nUser.getTableName(): \"AmASchema\".\"Users\"\n\nAnd ::::\n\nCourse.name: Course\nCourse.tableName: Courses\nUser.name: User\nUser.tableName: Users\n\n----\n\n---------------------- Testing Models instances ----------------\n\nTesting using  Class Extends Model definition :::: \n\nInstance access using instance.name and instance.tableName\ncourse.name: undefined\ncourse.tableName: undefined\n\nInstance access using instance.constructor.name and instance.constructor.tableName and getTableName()\n\ncourse.constructor.name: Course\ncourse.constructor.tableName: Courses\ncourse.constructor.getTableName(): Courses\n\nTesting using  sequelize.define() definition :::: \n\nInstance access using instance.name and instance.tableName\nuser.name: undefined\nuser.tableName: undefined\n\nInstance access using instance.constructor.name and instance.constructor.tableName and getTableName()\n\nuser.constructor.name: User\nuser.constructor.tableName: Users\nuser.constructor.getTableName(): \"AmASchema\".\"Users\"\n```\n\n```text\n---------------------- Testing Models Classes ----------------\n\nStatic access using getTableName() (without Schema) :\n\nCourse.getTableName(): Courses\n\n\nStatic access using getTableName() (with Schema) :\n\nUser.getTableName(): \"AmASchema\".\"Users\"\n\nAnd ::::\n\nCourse.name: Course\nCourse.tableName: Courses\nUser.name: User\nUser.tableName: Users\n\n----\n\n--------------- Testing Models instances -----------------------\n\nTesting using  sequelize.define() definition :::: \n\nInstance access using instance.name and instance.tableName\n\nuser.name: undefined\nuser.tableName: undefined\n\nInstance access using instance.constructor.name and instance.constructor.tableName and getTableName()\n\nuser.constructor.name: User\nuser.constructor.tableName: Users\nuser.constructor.getTableName(): \"AmASchema\".\"Users\"\n```\n\n```js\n// model has no schema\nconst tableName = Course.getTableName();\n\n// or\n\n// model has schema\nconst tableName = Course.getTableName().tableName;\n```\n\n```text\n`\"AmASchema\".\"Users\"`\n```\n\n```text\nModel.getTableName() // No schema: return =>  `Users`\n                   // Schema:\n                  // return => `\"MySchema\".\"Users\"` (Postgres),\n                 // `MySchema.Users` (Mysql)\n               // Or { tableName: 'Users', schema: 'MySchema', ... }\n\ninstance.constructor.getTableName() // same as above\n```\n\n```text\nModel.tableName // return => `Users`\n// or\nuser.constructor.tableName // return => `Users`\n```\n\n```text\nUser -> Users\nClass -> Classes\nPerson -> People\nChild -> Children\nCourse -> Courses\n```\n\n```text\nUser\n```\n\n```text\ninstance.name\n```\n\n```text\nconstructor\n```\n\n```text\nmodeInstance.name\n```\n\n```text\nmodelInstance.tableName\n```\n\n```text\nmodel.d.ts\n```\n\n```text\ntableName\n```\n\n```text\nStatic\n```\n\n```text\ninstance.constructor.tableName\n```\n\n```text\nclass User extends Model\n```\n\n```text\nsequelize.define()\n```\n\n```text\ngetTablename()\n```\n\n```text\nPerson -> People\n```\n\n```text\nuser.constructor.getTableName()\n```\n\n```text\nuser._modelOptions.name.plural\nuser._modelOptions.name.singular\n```\n\n```text\nmodel.name\n```\n\n```text\nmodel.tableName\n```\n\n```text\nmodel\n```\n\n========================================\n\nComments:\n- Your link is broken.","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":37,"totalLines":305,"estimatedTokens":1464}}134{"id":"stack-53799535","source":"stackoverflow","questionId":53799535,"title":"Is it possible to define default value in Sequelize migration?","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Is it possible to define default value in Sequelize migration?\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThere is no documentation details about addColumn options, so I'm trying this:\n\n```\nqueryInterface.addColumn(\n 'OrderBackups',\n 'my_column',\n Sequelize.INTEGER,\n { defaultValue: 0 }\n)\n```\n\nand it does not work.\nps: I'm using postgres\n\n========================================\n\nTop Answer:\naddColumn method doesn't support defaultValue option for Postgres. It only works for MSSQL. Check these docs\n\n========================================\n\nCode:\n```text\nqueryInterface.addColumn(\n    'OrderBackups',\n    'my_column',\n    Sequelize.INTEGER,\n    { defaultValue: 0 }\n)\n```\n\n```text\nqueryInterface.addColumn('OrderBackups', 'my_column', {\n  type: Sequelize.INTEGER,\n  defaultValue: 0\n})\n```\n\n```js\n'use strict'\nconst tableName = 'my_table'\nconst columnName = 'count'\nconst { sequelize } = require('../models')\n\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    const sql = `ALTER TABLE IF EXISTS public.${tableName} ADD COLUMN ${columnName} integer NOT NULL DEFAULT 1;`\n    const [results, metadata] = await sequelize.query(sql, {type: sequelize.QueryTypes.RAW})\n  },\n\n  down: async (queryInterface, Sequelize) => {\n    await queryInterface.removeColumn(tableName, columnName)\n  },\n}\n```\n\n========================================\n\nComments:\n- Check this guide addColumn","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":65,"estimatedTokens":357}}135{"id":"stack-58802463","source":"stackoverflow","questionId":58802463,"title":"@Types/Sequelize Error TS1086: An accessor cannot be declared in ambient context","tags":["node.js","typescript","types","sequelize.js","tsc"],"text":"Title: @Types/Sequelize Error TS1086: An accessor cannot be declared in ambient context\nTags: node.js, typescript, types, sequelize.js, tsc\nSource: Stack Overflow\n\nQuestion:\nI have a project that shows this error when I run 'tsc':\n\n```\n../modules/node_modules/sequelize/types/lib/transaction.d.ts:33:14 - error TS1086: An accessor cannot be declared in an ambient context.\n\n33 static get LOCK(): LOCK;\n ~~~~\n\n../modules/node_modules/sequelize/types/lib/transaction.d.ts:40:7 - error TS1086: An accessor cannot be declared in an ambient context.\n\n40 get LOCK(): LOCK;\n ~~~~\n```\n\nMy versions are:\n\n- \"@types/sequelize\": \"^4.28.6\"\n\n- \"sequelize\": \"^5.8.10\"\n\n- \"sequelize-typescript\": \"1.0.0-beta.4\"\n\nThe project works fine with nodemon but fails when I try to compile the typescript. Anyone knows this error?\n\nThanks.\n\n========================================\n\nTop Answer:\nI have **Angular 8**. it is working with typescript version of 3.4.5. so solve this issue do below steps.\n\nstep 1) go to the **tsconfig.json** file\n\nstep 2) add **skipLibCheck: true** in \"compilerOptions\" object. It works for me. \n\n```\n\"compilerOptions\": {\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"strict\": true,\n \"target\": \"es5\",\n \"declaration\": true,\n \"declarationDir\": \"dist-debug/\",\n \"skipLibCheck\": true, /// Needs to be true to fix wrong alias types being used\n\n },\n```\n\n========================================\n\nCode:\n```text\n../modules/node_modules/sequelize/types/lib/transaction.d.ts:33:14 - error TS1086: An accessor cannot be declared in an ambient context.\n\n33   static get LOCK(): LOCK;\n                ~~~~\n\n../modules/node_modules/sequelize/types/lib/transaction.d.ts:40:7 - error TS1086: An accessor cannot be declared in an ambient context.\n\n40   get LOCK(): LOCK;\n         ~~~~\n```\n\n```text\nTo detect the issue around accessors, TypeScript 3.7 will now emit get/set accessors in .d.ts files so that in TypeScript can check for overridden accessors.\n```\n\n```text\nsequelize\n```\n\n```text\n\"skipLibCheck\": true\n```\n\n```text\n\"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\",\n    \"strict\": true,\n    \"target\": \"es5\",\n    \"declaration\": true,\n    \"declarationDir\": \"dist-debug/\",\n    \"skipLibCheck\": true, /// Needs to be true to fix wrong alias types being used\n\n  },\n```\n\n========================================\n\nComments:\n- What if I can't upgrade to 3.7? have another idea?\n- @ShlomiLevi Use an earlier version of `@types&#47;sequelize`\n- you are right, I had this issue recently and after some searches I discoreved an issue closed in the Github, so to fix the problem I had to upgrade the typescript version to the 3.7.2 version.\n- ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.7.4 was found instead. Im using Angular 7\n- In which file I need to change this?\n- tsconfig.json file\n- Thanks. \"skipLibCheck\": true(added to tsconfig that related to NestJs), worked and NestJs with app that inited through nest g ng-app.\n- This was a better solution than upgrading our Typescript version. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":104,"estimatedTokens":763}}136{"id":"stack-38918840","source":"stackoverflow","questionId":38918840,"title":"querying on where association in sequelize?","tags":["javascript","node.js","sequelize.js"],"text":"Title: querying on where association in sequelize?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n`where` clause use in sequelize in inner joins.\nMy query is\n\n```\nSELECT Cou.country_id,cou.country_name, Sta.state_id, Sta.state_name\nFROM hp_country Cou\nINNER JOIN hp_state Sta ON Cou.country_id = Sta.hp_country_id\nWHERE (Cou.country_status=1 AND Sta.state_status=1 AND Cou.country_id=1)\nAND (Sta.state_name LIKE '%ta%');\n```\n\nI wrote in sequelize code is\n\n```\nhp_country.findAll({\n where: {\n '$hp_state.state_status$': 1\n },\n include: [\n {model: hp_state}\n ]\n})\n```\n\nThe error it's producing is:\n\n```\nSELECT `hp_country`.`country_id`, `hp_country`.`country_name`, `hp_country`.`country_status`, `hp_country`.`created_date`, `hp_country`.`update_date` FROM `hp_country` AS `hp_country` WHERE `hp_state`.`state_status` = 1;\nUnhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'hp_state.state_status' in 'where clause'\n```\n\n========================================\n\nTop Answer:\nYour Sequelize code should look like:\n\n```\nhp_country.findAll({\n attributes: ['country_id', 'country_name'],\n where: {\n country_status: 1,\n country_id: 1\n },\n include: [{\n model: hp_state,\n attributes: ['state_id', 'state_name'],\n where: {\n state_status: 1,\n state_name: {\n $like: '%ta%'\n }\n }\n }]\n});\n```\n\nTo select only some attributes, you can use the `attributes` option.\n`where` clause should be moved inside the `include` statement because the condition you use relates to the `hp_state` model.\n\n========================================\n\nCode:\n```text\nSELECT Cou.country_id,cou.country_name, Sta.state_id, Sta.state_name\nFROM hp_country Cou\nINNER JOIN hp_state Sta ON Cou.country_id = Sta.hp_country_id\nWHERE (Cou.country_status=1 AND Sta.state_status=1 AND Cou.country_id=1)\nAND (Sta.state_name LIKE '%ta%');\n```\n\n```text\nhp_country.findAll({\n    where: {\n        '$hp_state.state_status$': 1\n    },\n    include: [\n        {model: hp_state}\n    ]\n})\n```\n\n```text\nSELECT `hp_country`.`country_id`, `hp_country`.`country_name`, `hp_country`.`country_status`, `hp_country`.`created_date`, `hp_country`.`update_date` FROM `hp_country` AS `hp_country` WHERE `hp_state`.`state_status` = 1;\nUnhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'hp_state.state_status' in 'where clause'\n```\n\n```text\nwhere\n```\n\n```text\nhp_country.findAll({\nwhere: {\n    //main AND condition\n    $and: [\n        //first joint condition\n        {\n            $and: [\n                { country_status: 1 },\n                { country_id: country_id },\n                Sequelize.literal(\"hp_states.state_status = 1\"),\n                Sequelize.literal(\"`hp_states.hp_districts`.`district_status`=1\"),\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities`.`city_status`=1\"),\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities.hp_locations`.`location_status`=1\"),\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities.hp_locations.hp_sub_locations`.`sub_location_status`=1\"),\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities`.`city_name` LIKE '%\"+city+\"%'\")\n\n\n            ]\n        },\n\n        {\n            $or: [\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities.hp_locations`.`location_name` LIKE '%\"+query+\"%'\"),\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities.hp_locations.hp_sub_locations`.`sub_location_name` LIKE '%\"+query+\"%'\"),\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities.hp_locations.hp_sub_locations.hp_property`.`property_name` LIKE '%\"+query+\"%'\"),\n                Sequelize.literal(\"`hp_states.hp_districts.hp_cities.hp_locations.hp_sub_locations.hp_property.hp_builder`.`builders_name` LIKE '%\"+query+\"%'\")\n\n            ]\n        }\n    ]\n},\nattributes: ['country_id', 'country_name'],\nrequired:true,\ninclude: [\n    {\n        model: hp_state,\n        attributes: ['state_id', 'state_name'],\n        required:true,\n\n        include: [\n            {\n                model: hp_district,\n                attributes: ['district_id', 'district_name'],\n                required:true,\n                include: [\n                    {\n                        model: hp_city,\n                        attributes: ['city_id', 'city_name'],\n                        required:true,\n\n                        include: [\n                            {\n                                model: hp_location,\n                                attributes: ['location_id', 'location_name'],\n                                required:true,\n                                include: [\n                                    {\n                                        model: hp_sub_location,\n                                        attributes: ['sub_location_id', 'sub_location_name'],\n                                        required:true,\n                                        include: [\n                                            {\n                                                model: hp_property,\n                                                attributes: ['property_id', 'property_name'],\n                                                required: true,\n                                                include: [\n                                                    {\n                                                        model:hp_builders,\n                                                        attributes: ['builders_id', 'builders_name'],\n                                                        required: true\n\n                                                    }\n                                                    ]\n                                            }\n                                            ]\n\n\n                                    }]\n\n                            }]\n\n                    }]\n            }\n        ]\n    }\n]\n```\n\n```text\nhp_country.findAll({\n    attributes: ['country_id', 'country_name'],\n    where: {\n        country_status: 1,\n        country_id: 1\n    },\n    include: [{\n        model: hp_state,\n        attributes: ['state_id', 'state_name'],\n        where: {\n            state_status: 1,\n            state_name: {\n                $like: '%ta%'\n            }\n        }\n    }]\n});\n```\n\n```text\nattributes\n```\n\n```text\nwhere\n```\n\n```text\ninclude\n```\n\n```text\nhp_state\n```\n\n========================================\n\nComments:\n- ,thanks for the reply ,i know what you are posted, but i want to get the column name of country_id in state include box because i want to check this condition ,see here [where (Cou.country_status=1 AND Sta.state_status=1 AND Cou.country_id=1) AND (Sta.state_name LIKE '%ta%');]\n- @SimhaChalam It seems I haven't understood you properly but I've updated the code above to meet all your conditions.\n- @SimhaChalam If you need to use any column of the `hp_country` table inside the `include` you can use `$col` operator or `Sequelize.col` function.\n- yes, i tried to approach this manner. but its saying col is not their in sequalize because i want to include so many inner joins and have a heavy association from parent model to child model column names\n- Hello, model: ModelType is deprecated\n- This will work only if the relations is 1:N. What if the join should be an OUTER JOIN?","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":229,"estimatedTokens":1825}}137{"id":"stack-31427566","source":"stackoverflow","questionId":31427566,"title":"Sequelize create model with beforeCreate hook","tags":["node.js","sequelize.js"],"text":"Title: Sequelize create model with beforeCreate hook\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI defined my hook beforeCreate as following:\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n var userSchema = sequelize.define('User', {\n // define...\n });\n userSchema.beforeCreate(function (model) {\n debug('Info: ' + 'Storing the password'); \n model.generateHash(model.password, function (err, encrypted) {\n debug('Info: ' + 'getting ' + encrypted);\n\n model.password = encrypted;\n debug('Info: ' + 'password now is: ' + model.password);\n // done;\n });\n });\n};\n```\n\nand when I create a the model\n\n```\nUser.create({\n name: req.body.name.trim(),\n email: req.body.email.toLowerCase(),\n password: req.body.password,\n verifyToken: verifyToken,\n verified: verified\n }).then(function (user) {\n debug('Info: ' + 'after, the password is ' + user.password); \n }).catch(function (err) {\n // catch something\n });\n```\n\nNow what I get from this is \n\n```\nInfo: Storing the password +6ms\nInfo: hashing password 123123 +0ms // debug info calling generateHash()\nExecuting (default): INSERT INTO \"Users\" (\"id\",\"email\",\"password\",\"name\",\"verified\",\"verifyToken\",\"updatedAt\",\"createdAt\") VALUES (DEFAULT,'wwx@test.com','123123','wwx',true,NULL,'2015-07-15 09:55:59.537 +00:00','2015-07-15 09:55:59.537 +00:00') RETURNING *;\n\nInfo: getting $2a$10$6jJMvvevCvRDp5E7wK9MNuSRKjFpieGnO2WrETMFBKXm9p4Tz6VC. +0ms\nInfo: password now is: $2a$10$6jJMvvevCvRDp5E7wK9MNuSRKjFpieGnO2WrETMFBKXm9p4Tz6VC. +0ms\nInfo: after, the password is 123123 +3ms\n```\n\nIt seems that every part of the code is working. Creating a user schema will invoke beforeCreate, which properly generates the hash code for the password.... except it didn't write to the database!\n\nI'm certain that I'm missing a very important and OBVIOUS piece of code, but I just can't find where the problem is (aghh). Any help appreciated!\n\n========================================\n\nTop Answer:\nFor newer versions of Sequelize, the hooks no longer have callback functions but promisses. Therefor the code would look more like the following:\n\n```\nuserSchema.beforeCreate(function(model, options) {\n debug('Info: ' + 'Storing the password');\n\n return new Promise ((resolve, reject) => {\n model.generateHash(model.password, function(err, encrypted) {\n if (err) return reject(err);\n debug('Info: ' + 'getting ' + encrypted);\n\n model.password = encrypted;\n debug('Info: ' + 'password now is: ' + model.password);\n return resolve(model, options);\n });\n });\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function (sequelize, DataTypes) {\n  var userSchema = sequelize.define('User', {\n  // define...\n  });\n  userSchema.beforeCreate(function (model) {\n    debug('Info: ' + 'Storing the password');    \n    model.generateHash(model.password, function (err, encrypted) {\n      debug('Info: ' + 'getting ' + encrypted);\n\n      model.password = encrypted;\n      debug('Info: ' + 'password now is: ' + model.password);\n      // done;\n    });\n  });\n};\n```\n\n```text\nUser.create({\n    name:           req.body.name.trim(),\n    email:          req.body.email.toLowerCase(),\n    password:       req.body.password,\n    verifyToken:    verifyToken,\n    verified:       verified\n  }).then(function (user) {\n    debug('Info: ' + 'after, the password is ' + user.password);    \n  }).catch(function (err) {\n    // catch something\n  });\n```\n\n```text\nInfo: Storing the password +6ms\nInfo: hashing password 123123 +0ms    // debug info calling generateHash()\nExecuting (default): INSERT INTO \"Users\" (\"id\",\"email\",\"password\",\"name\",\"verified\",\"verifyToken\",\"updatedAt\",\"createdAt\") VALUES (DEFAULT,'wwx@test.com','123123','wwx',true,NULL,'2015-07-15 09:55:59.537 +00:00','2015-07-15 09:55:59.537 +00:00') RETURNING *;\n\nInfo: getting $2a$10$6jJMvvevCvRDp5E7wK9MNuSRKjFpieGnO2WrETMFBKXm9p4Tz6VC. +0ms\nInfo: password now is: $2a$10$6jJMvvevCvRDp5E7wK9MNuSRKjFpieGnO2WrETMFBKXm9p4Tz6VC. +0ms\nInfo: after, the password is 123123 +3ms\n```\n\n```text\nuserSchema.beforeCreate(function(model, options, cb) {\n  debug('Info: ' + 'Storing the password');    \n  model.generateHash(model.password, function(err, encrypted) {\n    if (err) return cb(err);\n    debug('Info: ' + 'getting ' + encrypted);\n\n    model.password = encrypted;\n    debug('Info: ' + 'password now is: ' + model.password);\n    return cb(null, options);\n  });\n});\n```\n\n```text\nuserSchema.beforeCreate(function(model, options) {\n    debug('Info: ' + 'Storing the password');\n\n    return new Promise ((resolve, reject) => {\n        model.generateHash(model.password, function(err, encrypted) {\n            if (err) return reject(err);\n            debug('Info: ' + 'getting ' + encrypted);\n\n            model.password = encrypted;\n            debug('Info: ' + 'password now is: ' + model.password);\n            return resolve(model, options);\n        });\n    });\n});\n```\n\n========================================\n\nComments:\n- @user2242178 don't worry, glad to hear it solved your problem :-)\n- Thank you. I didn't see this on sequelize documentation, and it was preventing my server to respond.\n- @Danielo515 yeah it's not very clearly documented :-(\n- updated version of sequlize does not have a callback function\n- @AryehArmon return a promise instead.\n- @robertklep how would i use a function with a callback with promises\n- @AryehArmon stackoverflow.com/questions/22519784/&hellip;\n- Does sequelize support async/await functions in the model hooks?\n- Async/await functions arent implemented in node yet, so when you write Async/Await it is transpiled back to promises by Babel\n- I thought async/await was released with node 8 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/&hellip; I don't use babel in my project, and my code compiles with the async/await functions. Could you explain please?\n- Oh i guess you're right, but the release notes say that async await uses promises so it should still be fine","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":169,"estimatedTokens":1482}}138{"id":"stack-53971268","source":"stackoverflow","questionId":53971268,"title":"Node Sequelize find where $like wildcard","tags":["sequelize.js"],"text":"Title: Node Sequelize find where $like wildcard\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to add a where like clause to a Node Sequelize findAll, to behave like the sql query `select * from myData where name like '%Bob%'` with the below code\n\n```\nlet data: Array = await MyDataSequelizeAccess.findAll({\n where: {\n name: {\n $like: `%Bob%`\n }\n }\n});\n```\n\nWhich is returning the below error\n\n Invalid value { '$like': '%Bob%' }\n\nHow can I perform that type of where wildcard or where like on my sequelize object?\n\n```\nlet data: Array = await MyDataSequelizeAccess.findAll({\n where: {\n name: `Bob`\n }\n});\n```\n\nThis works as expected, but I cannot get the wildcard to work.\n\n*updated* still no dice - per https://sequelize.readthedocs.io/en/latest/docs/querying/#operators my syntax looks correct\n\nI'm also trying (and failing) to do the same with $not as in\n\n```\nlet data: Array = await MyDataSequelizeAccess.findAll({\n where: {\n name: {\n $not: `Bob`\n }\n }\n});\n```\n\nand getting the same error as above `Invalid value { '$not': '%Bob%' }`\n\n========================================\n\nTop Answer:\nExpress sequelize\nfirst import express and defile Op like so:\n\n```\nconst Sequelize = require(\"sequelize\");\nconst Op = Sequelize.Op;\n\nconst { search } = await req.body;\n```\n\nThe do like so:\n\n```\nconst users = await User.findAll({\n where: {\n username: { [Op.like]: `%${search}%` },\n },\n include: [{ model: Tweet, as: \"Tweets\" }],\n raw: true,\n }).catch(errorHandler);\n```\n\n========================================\n\nCode:\n```text\nlet data: Array<any> = await MyDataSequelizeAccess.findAll({\n  where: {\n    name: {\n      $like: `%Bob%`\n    }\n  }\n});\n```\n\n```text\nlet data: Array<any> = await MyDataSequelizeAccess.findAll({\n  where: {\n    name: `Bob`\n  }\n});\n```\n\n```text\nlet data: Array<any> = await MyDataSequelizeAccess.findAll({\n  where: {\n    name: {\n      $not: `Bob`\n    }\n  }\n});\n```\n\n```text\nselect * from myData where name like '%Bob%'\n```\n\n```text\nInvalid value { '$not': '%Bob%' }\n```\n\n```text\nconst Op = Sequelize.Op;\nconst operatorsAliases = {\n  $like: Op.like,\n  $not: Op.not\n}\nconst connection = new Sequelize(db, user, pass, { operatorsAliases })\n\n[Op.like]:  '%Bob%' // LIKE '%Bob%'\n$like: '%Bob%' // same as using Op.like (LIKE '%Bob%')\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst Op = Sequelize.Op;\n\nlet data: Array<any> = await MyDataSequelizeAccess.findAll({\n  where: {\n    name: {\n      [Op.like]: '%Bob%'\n    }\n  }\n});\n```\n\n```text\n$operator\n```\n\n```text\nSequelize.js\n```\n\n```text\nSequelize.Op\n```\n\n```text\n{\n    \"searchString\": \"search\",\n    \"count\": 0,\n    \"limit\": 20\n}\n```\n\n```text\napp.get(\"/api/saloon\", function (req, res) {\nSaloon.findAll({\n    where: {\n        name: {[Op.iLike]: `%${req.body.searchString}%`}\n    },\n    offset: req.body.count,\n    limit: req.body.limit,\n})\n```\n\n```text\nconst Sequelize = require(\"sequelize\");\nconst Op = Sequelize.Op;\n\nconst { search } = await req.body;\n```\n\n```text\nconst users = await User.findAll({\n    where: {\n      username: { [Op.like]: `%${search}%` },\n    },\n    include: [{ model: Tweet, as: \"Tweets\" }],\n    raw: true,\n  }).catch(errorHandler);\n```\n\n```text\nawait Model.findAll({\n    where: {\n        name: { [Op.substring]: \"bob\" }\n    }\n});\n```\n\n========================================\n\nComments:\n- How to make this same query with lower function in field name?\n- To use variable instead of '%Bob%' name: { [Op.like]: `%${name}%` }","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":199,"estimatedTokens":859}}139{"id":"stack-16847672","source":"stackoverflow","questionId":16847672,"title":"Is there a simple way to make Sequelize return it's date/time fields in a particular format?","tags":["node.js","sequelize.js"],"text":"Title: Is there a simple way to make Sequelize return it's date/time fields in a particular format?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWe need to have sequelize return dates in a particular format, not the default one. As far as I can tell, there is no way to set that up in options, or any other way. Short of manually updating the dates every time after they are retrieved, anyone been able to solve this easily? Or am I missing something?\n\n========================================\n\nTop Answer:\nYou can, use the Sequelize `fn` method. From the API Reference, the `fn` function will help create an object representing a SQL function in your query.\n\nFor example:\n\n```\nmodel.findAll({\n attributes: [\n 'id',\n [sequelize.fn('date_format', sequelize.col('date_col'), '%Y-%m-%d'), 'date_col_formed']\n ]})\n .then(function(result) {\n console.log(result);\n });\n```\n\nWill return data values:\n\n```\n[\n {\"id\": 1, \"date_col_formed\": \"2014-01-01\"},\n {\"id\": 2, \"date_col_formed\": \"2014-01-02\"}\n // and so on...\n]\n```\n\n========================================\n\nCode:\n```text\nmodel.findAll({\n  attributes: [\n      'id',\n      [sequelize.fn('date_format', sequelize.col('date_col'), '%Y-%m-%d'), 'date_col_formed']\n  ]})\n  .then(function(result) {\n    console.log(result);\n  });\n```\n\n```text\n[\n  {\"id\": 1, \"date_col_formed\": \"2014-01-01\"},\n  {\"id\": 2, \"date_col_formed\": \"2014-01-02\"}\n   // and so on...\n]\n```\n\n```text\nfn\n```\n\n```text\nfn\n```\n\n```text\nvar sequelize= require('../models');\n    model.findAll({\n            attributes: [\n                       'id',\n                       'title'\n           [sequelize.Sequelize.fn('date_format', sequelize.Sequelize.col('col_name'), '%d %b %y'), 'col_name']\n                            ]}.then(function(result))\n                             { // dateformate=04 Nov 2017\nconsole.log(result)\n}\n```\n\n```text\nconst Test = sequelize.define('test', {\n                // attributes\n                name: {\n                    type: DataType.STRING,\n                    allowNull: false\n                },\n                createdAt: {\n                    type: DataType.DATE,\n     //note here this is the guy that you are looking for                   \n                  get() {\n                        return moment(this.getDataValue('createdAt')).format('DD/MM/YYYY h:mm:ss');\n                    }\n                },\n                updatedAt: {\n                    type: DataType.DATE,\n                    get() {\n                        return moment(this.getDataValue('updatedAt')).format('DD/MM/YYYY h:mm:ss');\n                    }\n                }\n```\n\n```php\nattributes:{include:[[sequelize.cast(sequelize.col('dob'), 'VARCHAR') , 'dob']],exclude:['dob']}\n```\n\n```text\nVARCHAR\n```\n\n```text\nmodel.findAll({\n  attributes: [\n      'id',\n      [sequelize.fn('FORMAT', sequelize.col('col_name'), 'yyyy-mm-dd'), 'col_name']\n  ]})\n  .then(function(result) {\n    console.log(result);\n  });\n```\n\n```text\nattributes: [\n                [sequelize.literal('date(\"dateTime\")'), 'dateWithoutTime'],\n            ],\n```\n\n```text\ndate_format\n```\n\n```text\nFormat\n```\n\n========================================\n\nComments:\n- Thanks. We've decided to move away from Sequelize, but this is certainly what we needed.\n- Just out of curiosity, what did you end up using?\n- @marvin while I can read there how to setup a custom getter/setter I still don't get how I would return a formatted date there. Would you mind to elloborate this?\n- @mrvn the link is not available\n- Is there a list of the functions availables in sequelize?? It just shows the use of the `sequelize.fn` but it doesn't say what functions are available.\n- `sequelize.fn` just creates a object representing a database function. If you're using MySQL, you can find a list here.\n- @JonSaw in my case i've two dates how to get all of them that between these dates. how to add `$between` with `date_format`\n- Very good explanation. But i have to ask, if I want to make the code flexible to all the databases supported by sequelize and I use sequelize.fn, would I have to change the name of the function for different databases?\n- @Freya, looking at the docs & source code, it doesn't seem like Sequelize runs `fn` through any dialect translators.\n- In postgres, check out `to_char` postgresql.org/docs/8.4/functions-formatting.html","metadata":{"transformedAt":"2026-08-18T18:33:34.348Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":146,"estimatedTokens":1083}}140{"id":"stack-42146200","source":"stackoverflow","questionId":42146200,"title":"Selecting a random record from Sequelize findAll","tags":["javascript","node.js","sequelize.js"],"text":"Title: Selecting a random record from Sequelize findAll\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently brute-forcing this, but am confident there is a better solution that uses Sequelize, the code in question (using postgres):\n\n```\n...\nthen((tile_data) => {\n return Encounter.findAll({\n where: {\n level: tile_data.dataValues.level\n },\n transaction: transaction_data\n }).then((encounter_data) => {\n let encounter = encounter_data[Math.floor((Math.random() * encounter_data.length))].dataValues\n return Battle.create({\n character_id: character_data.dataValues.id,\n encounter_id: encounter.id,\n encounter_hp: encounter.max_hp,\n encounter_mana: encounter.max_mana\n }, {\n transaction: transaction_data\n })\n...\n```\n\nAside from seeming 'ugly', with this code I am loading all ENCOUNTERS into memory just to pluck one element out of the array.\n\nDoes anyone know how to do this through Sequelize, ideally without using a raw query?\n\nThank you\n\n========================================\n\nTop Answer:\nI think this solution is the most clear one. You should use a random function from a sequelize instance \n\n```\nconst sequelize = new Sequelize(url, opts);\n```\n\nRecommend to use a sequelize-cli to generate initial schema, it automatically exports sequelize variable.\n\n```\nEncounter.findOne({ \n order: sequelize.random() \n});\n```\n\nAlso with this approach u don't need to solve `RAND()` vs `RANDOM()` problem if you change a db dialect from postgres to MySQL or back.\n\n========================================\n\nCode:\n```text\n...\nthen((tile_data) => {\n  return Encounter.findAll({\n    where: {\n      level: tile_data.dataValues.level\n    },\n    transaction: transaction_data\n  }).then((encounter_data) => {\n    let encounter = encounter_data[Math.floor((Math.random() * encounter_data.length))].dataValues\n    return Battle.create({\n      character_id: character_data.dataValues.id,\n      encounter_id: encounter.id,\n      encounter_hp: encounter.max_hp,\n      encounter_mana: encounter.max_mana\n    }, {\n      transaction: transaction_data\n    })\n...\n```\n\n```text\nEncounter.findAll({ order: Sequelize.literal('rand()'), limit: 5 }).then((encounters) => {\n        // single random encounter\n    });\n```\n\n```text\nEncounter.count({ where: ... })\n```\n\n```text\nEncounter.findById(encounterId)\n```\n\n```text\nEncounter.findOne({ order: 'random()' }).then((encounter) => {\n    // single random encounter\n});\n```\n\n```text\nEncounter.findAll({ order: 'random()', limit: 1 }).then((encounter) => {\n    // single random encounter\n});\n```\n\n```text\nrandom()\n```\n\n```text\nrand()\n```\n\n```text\n.findAll()\n```\n\n```text\nEncounter.findAll({\n      order: [\n        [Sequelize.literal('RAND()')]\n      ],\n\n      limit: 1,\n\n    }).then((resp) => {\n      callback(null, resp)\n    })\n```\n\n```text\norder: sequelize.random()\n```\n\n```text\nconst sequelize = new Sequelize(url, opts);\n```\n\n```text\nEncounter.findOne({ \n  order: sequelize.random() \n});\n```\n\n```text\nRAND()\n```\n\n```text\nRANDOM()\n```\n\n```text\norder: Sequelize.literal('random()')\n```\n\n```text\nexports.uniqueRegistercodes = async (req) => {\n    // console.log(\"code\");\n    const code = await registercodesModal.findAll({ order: db.sequelize.random(), limit: 1 });\n    console.log(\"DATA CODE...\");\n    return code;\n}\n```\n\n```text\n...\nimport Sequelize from 'sequelize';\n...\n\nMyModel.findOne({\n  order: [\n    Sequelize.fn( 'RAND' ),\n  ]\n});\n```\n\n```text\nlet products = await Product.findAll({\n  order: sequelize.random()\n})\n```\n\n```text\nsequelize.random()\n```\n\n```text\nexports.uniqueRegistercodes = async (req) => {\n    const code = await registercodesModal.findAll({ \n         order: db.sequelize.random(), limit: 1 });\n    return code;\n}\n```\n\n========================================\n\nComments:\n- you cant use a string in a order this way, you missing literal\n- The current version of sequalize doesn't support order as string, you need to use `order:[Sequelize.literal('RAND()')]` don't forget to add `var Sequelize = require('sequelize');`\n- This solution worked best for my MySQL project. Thank you!\n- This worked. I tried with SQL Server and used the function \"NEWID()\" instead \"rand()\"\n- Note that the function name literal would be 'random()' for postgres.\n- It should be mentions its in sequelize intance, not in sequelize module\n- Find One also works: `.findOne({ order: Sequelize.literal(\"random()\") })`\n- github.com/sequelize/sequelize/issues/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":204,"estimatedTokens":1105}}141{"id":"stack-32059758","source":"stackoverflow","questionId":32059758,"title":"How to insert a PostGIS GEOMETRY Point in Sequelize ORM?","tags":["node.js","postgresql","postgis","sequelize.js"],"text":"Title: How to insert a PostGIS GEOMETRY Point in Sequelize ORM?\nTags: node.js, postgresql, postgis, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to insert a row in a table that has a geometry column in Sequelize.js ORM.\nI have latitude, longitude and altitude and need to convert it to a point first so I can Insert it as a geometry.\n\nThe PostGIS stored procedure that does the converting is \n\n```\nST_MakePoint( longitude, latitude, altitude )\n```\n\nTo Insert a row I am using the sequelize model.create function\n\n```\nmodels.Data.create({ \n location: \"ST_MakePoint(\"+request.params.lon+\", \"+request.params.lat+\", \"+request.params.alt+\")\", // PSUEDO code, How can I call this function?\n speed: request.params.spd,\n azimuth: request.params.azi,\n accuracy: request.params.acc\n});\n```\n\nNow what I want to do Is make the field `location` have the returned result of `\"ST_MakePoint(\"+request.params.lon+\", \"+request.params.lat+\", \"+request.params.alt+\")\"` when I insert the row.\n\nHow can I do that?\n\n========================================\n\nTop Answer:\nAfter a bit of researching I found that Sequelize 3.5.1 ( is supporting GEOMETRY ) had a test that inserts a `Point`.\n\n```\nvar point = { type: 'Point', coordinates: [39.807222,-76.984722] }; \nreturn User.create({ username: 'user', email: ['foo@bar.com'], location: point})\n```\n\nWhere `location` is a GEOMETRY field. This way I don't need to call `ST_MakePoint` manually, sequelize takes care of that.\n\n========================================\n\nCode:\n```text\nST_MakePoint( longitude, latitude, altitude )\n```\n\n```text\nmodels.Data.create({    \n  location: \"ST_MakePoint(\"+request.params.lon+\", \"+request.params.lat+\", \"+request.params.alt+\")\", // PSUEDO code, How can I call this function?\n  speed: request.params.spd,\n  azimuth: request.params.azi,\n  accuracy: request.params.acc\n});\n```\n\n```text\nlocation\n```\n\n```text\n\"ST_MakePoint(\"+request.params.lon+\", \"+request.params.lat+\", \"+request.params.alt+\")\"\n```\n\n```text\nvar point = { type: 'Point', coordinates: [39.807222,-76.984722]};\n\nUser.create({username: 'username', geometry: point }).then(function(newUser) {\n...\n});\n```\n\n```text\nvar line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] };\n\nUser.create({username: 'username', geometry: line }).then(function(newUser) {\n...\n});\n```\n\n```text\nvar polygon = { type: 'Polygon', coordinates: [\n             [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],\n               [100.0, 1.0], [100.0, 0.0] ]\n             ]};\n\nUser.create({username: 'username', geometry: polygon }).then(function(newUser) {\n...\n});\n```\n\n```text\nvar point = { \n  type: 'Point', \n  coordinates: [39.807222,-76.984722],\n  crs: { type: 'name', properties: { name: 'EPSG:4326'} }\n};\n\nUser.create({username: 'username', geometry: point }).then(function(newUser) {\n...\n});\n```\n\n```text\nvar point = { type: 'Point', coordinates: [39.807222,-76.984722] }; \nreturn User.create({ username: 'user', email: ['foo@bar.com'], location: point})\n```\n\n```text\nPoint\n```\n\n```text\nlocation\n```\n\n```text\nST_MakePoint\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":120,"estimatedTokens":763}}142{"id":"stack-30082625","source":"stackoverflow","questionId":30082625,"title":"Can't exclude association's fields from select statement in sequelize","tags":["javascript","node.js","sqlite","sequelize.js"],"text":"Title: Can't exclude association's fields from select statement in sequelize\nTags: javascript, node.js, sqlite, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following code (simplified):\n\n```\nvar group = sequelize.define(\"group\", {\n id: {type: DataTypes.INTEGER, autoIncrement: false, primaryKey: true},\n name: type: DataTypes.STRING,\n parentId: DataTypes.INTEGER\n}, { classMethods: {\n associate: function (models) {\n group.belongsToMany(models.item, { as:'items', foreignKey: 'group_id', through: models.group_item_tie });\n }}\n});\n\nvar group_item_tie = sequelize.define(\"group_item_tie\", {}, {freezeTableName: true});\n\nvar item = sequelize.define(\"item\", {\n spn: { type: DataTypes.INTEGER, autoIncrement: false, primaryKey: true },\n}, { classMethods: {\n associate: function (models) {\n item.belongsToMany(models.group, { foreignKey: 'spn', through: models.group_item_tie });\n }}\n});\n```\n\nWhen I try to return some records with relationships, let's say like this:\n\n```\ndbcontext.group.findAll({\n where: { id: 6 },\n include: [{\n model: dbcontext.item,\n as: 'items',\n attributes: ['spn']\n }]\n })\n```\n\nI also get in result the fields from a tie table `group_item_tie`:\n\n```\n[{\n \"id\": 6,\n \"name\": \"abc\",\n \"parentId\": 5,\n \"createdAt\": \"2015-05-06T15:54:58.000Z\",\n \"updatedAt\": \"2015-05-06T15:54:58.000Z\",\n \"items\": [\n { \"spn\": 1,\n \"group_item_tie\": {\n \"createdAt\": \"2015-05-06 15:54:58.000 +00:00\",\n \"updatedAt\": \"2015-05-06 15:54:58.000 +00:00\",\n \"group_id\": 6,\n \"spn\": 1\n }\n },\n { \"spn\": 2,\n \"group_item_tie\": {\n \"createdAt\": \"2015-05-06 15:54:58.000 +00:00\",\n \"updatedAt\": \"2015-05-06 15:54:58.000 +00:00\",\n \"group_id\": 6,\n \"spn\": 2\n }\n },\n```\n\nI see it in generated sql query. How to exclude those from select statement? I've tried a few other things but was not successful.\n\nI hope there is something cleaner then just doing:\n\n```\ndelete item.group_item_tie;\n```\n\n========================================\n\nTop Answer:\nI realize this thread is a bit outdated, but since this is high in the Google search results and I struggled to find the answer myself, I thought I'd add this here.\n\nIf you're using `Model.getAssociatedModel()` or `Model.$get()` (for sequelize-typescript), the current answers listed will not work for this use case. In order to hide the model associations you need to add `joinTableAttributes: []`\n\nExample:\n\n```\nModel.getAssociatedModel({\n joinTableAttributes: []\n})\n```\n\nExample:\n\n```\nModel.$get('property', {\n joinTableAttributes: []\n});\n```\n\nAt the time of this post, `joinTableAttributes` is not included in the sequelize-typescript types hence the ``\n\n========================================\n\nCode:\n```js\nvar group = sequelize.define(\"group\", {\n    id: {type: DataTypes.INTEGER, autoIncrement: false, primaryKey: true},\n    name: type: DataTypes.STRING,\n    parentId: DataTypes.INTEGER\n}, { classMethods: {\n        associate: function (models) {\n            group.belongsToMany(models.item, { as:'items', foreignKey: 'group_id', through: models.group_item_tie });\n        }}\n});\n\nvar group_item_tie = sequelize.define(\"group_item_tie\", {}, {freezeTableName: true});\n\nvar item = sequelize.define(\"item\", {\n    spn: { type: DataTypes.INTEGER, autoIncrement: false, primaryKey: true },\n}, { classMethods: {\n        associate: function (models) {\n            item.belongsToMany(models.group, { foreignKey: 'spn', through: models.group_item_tie });\n        }}\n});\n```\n\n```js\ndbcontext.group.findAll({\n    where: { id: 6 },\n    include: [{\n                model: dbcontext.item,\n                as: 'items',\n                attributes: ['spn']\n            }]\n    })\n```\n\n```js\n[{\n    \"id\": 6,\n    \"name\": \"abc\",\n    \"parentId\": 5,\n    \"createdAt\": \"2015-05-06T15:54:58.000Z\",\n    \"updatedAt\": \"2015-05-06T15:54:58.000Z\",\n    \"items\": [\n        {   \"spn\": 1,\n            \"group_item_tie\": {\n                \"createdAt\": \"2015-05-06 15:54:58.000 +00:00\",\n                \"updatedAt\": \"2015-05-06 15:54:58.000 +00:00\",\n                \"group_id\": 6,\n                \"spn\": 1\n            }\n        },\n        {   \"spn\": 2,\n            \"group_item_tie\": {\n                \"createdAt\": \"2015-05-06 15:54:58.000 +00:00\",\n                \"updatedAt\": \"2015-05-06 15:54:58.000 +00:00\",\n                \"group_id\": 6,\n                \"spn\": 2\n            }\n        },\n```\n\n```js\ndelete item.group_item_tie;\n```\n\n```text\ngroup_item_tie\n```\n\n```text\ninclude: [{\n  model: dbcontext.item,\n  as: 'items',\n  attributes: ['spn'],\n  through: {\n    attributes: []\n  }        \n}]\n```\n\n```text\nthrough: {\nattributes: []\n}\n```\n\n```text\nModel.getAssociatedModel({\n  joinTableAttributes: []\n})\n```\n\n```text\nModel.$get('property', <any>{\n  joinTableAttributes: []\n});\n```\n\n```text\nModel.getAssociatedModel()\n```\n\n```text\nModel.$get()\n```\n\n```text\njoinTableAttributes: []\n```\n\n```text\njoinTableAttributes\n```\n\n```text\n<any>\n```\n\n========================================\n\nComments:\n- For the life of me I cannot get this to work... are we sure this works?\n- Worked for me @MirroredFate, if you still have it, post your code on pastebin and lets have a look at it.\n- @GustavoMeira There is already an issue on it here: github.com/sequelize/sequelize/issues/5590\n- I just did empty attributes at the model level and seemed to exclude it in the projection\n- It seems it still includes them in the select statement, just removed them in final output...\n- Is there any way I can exclude the attributes in 'item' model and only include the through table attributes?\n- Please elaborate on your answer and how it applies to the original question. The answer should include enough information to present a complete solution.","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":232,"estimatedTokens":1405}}143{"id":"stack-43403084","source":"stackoverflow","questionId":43403084,"title":"How to use findOrCreate in Sequelize","tags":["database","oauth","sequelize.js"],"text":"Title: How to use findOrCreate in Sequelize\nTags: database, oauth, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am a Sequelize beginner.\nI'd like to oAuth authenticate with Twitter or Facebook and want to save user information in the database.\n\nBut if OAuth authentication is done on multiple sites, there is a problem that information such as `userid` registered in the database will collide with the other sites.\n\nIn order to avoid this, I would like to do a process to update the database only when the specified `userid` does not already exist in the database.\n\nI knew that we could use Sequelize's `findOrCreate` to do it, but I do not know how to use `findOrCreate`.\nI know how to use upsert and I'd like to use `findOrCreate` like the description of upsert below. However, we want to perform conditional branching like this:\n\n`if (userid! = \"○○○\" && username! = \"○○○\")`.\n\n```\nUser.upsert({\n userid: profile.id,\n username: profile.username,\n accountid: c + 1,\n}).then(() => {\n done(null, profile);\n});\n```\n\nWhat should I do?\n\n========================================\n\nTop Answer:\nIn **findOrCreate()** method **defaults:** option is significant and valuable.\n\nYou can use some values for **where:** condition and add the remaining in **defaults:** option.\n\n```\nUser.findOrCreate({\n where: {userId: profile.id},\n defaults: {\n name: profile.name,\n address: profile.address,\n }\n}).then((userRow, isCreated) => {\nif(isCreated){\n //user created\n console.log('creted user', userRow);\n }\n});\n```\n\nIn the above example, we're not adding **name** and **address** values in the where: condition because I believe name and address can be the same and these are also not unique in the table.\n\n========================================\n\nCode:\n```js\nUser.upsert({\n  userid:    profile.id,\n  username:  profile.username,\n  accountid: c + 1,\n}).then(() => {\n  done(null, profile);\n});\n```\n\n```text\nuserid\n```\n\n```text\nuserid\n```\n\n```text\nfindOrCreate\n```\n\n```text\nfindOrCreate\n```\n\n```text\nfindOrCreate\n```\n\n```text\nif (userid! = \"○○○\" && username! = \"○○○\")\n```\n\n```js\n// remember to use a transaction as you are not sure whether the user is\n// already present in DB or not (and you might end up creating the user -\n// a write operation on DB)\n\nmodels.sequelize.transaction(function(t) {\n  return models.users.findOrCreate({\n    where: {\n      userId:    profile.userId,\n      name:      profile.name\n    },\n    transaction: t\n  })\n  .spread(function(userResult, created){\n    // userResult is the user instance\n\n    if (created) {\n      // created will be true if a new user was created\n    }\n  });\n});\n```\n\n```text\nUser.findOrCreate({\n   where: {userId: profile.id},\n   defaults: {\n        name: profile.name,\n        address: profile.address,\n   }\n}).then((userRow, isCreated) => {\nif(isCreated){\n       //user created\n       console.log('creted user', userRow);\n   }\n});\n```\n\n========================================\n\nComments:\n- Worth noting that Sequelize will automatically create the transaction if one is not provided in the options to findOrCreate\n- For more detail official documentation for stable version of V6.0 official findOrCreate","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":133,"estimatedTokens":785}}144{"id":"stack-37115441","source":"stackoverflow","questionId":37115441,"title":"Sequelize instance methods not working","tags":["node.js","sequelize.js"],"text":"Title: Sequelize instance methods not working\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Sequelize's instance method to validate a password on login attempt.\nI have defined the User model as :\n\n```\nvar User = sequelize.define('User',{\n id:{\n type:DataTypes.BIGINT,\n autoIncrement: true,\n allowNull: false,\n primaryKey:true\n },\n username:{\n type:DataTypes.STRING,\n unique:true\n },\n password:{\n type: DataTypes.STRING\n },\n ...\n },\n {\n classMethods:{\n associate:function(models){\n ...\n }\n }\n },\n {\n instanceMethods:{\n validatePassword:function(password){\n return bcrypt.compareSync(password, this.password);\n }\n }\n }\n);\n return User;\n}\n```\n\nIn my login route I do the following :\n\n- 1) Retrieve username & password from request body\n\n- 2) Check if username exists in database\n\n- 3) If user exists, get user object and compare sent password with hashed password in database using validatePassword method.\n\nHere is the relevant code\n\n```\nvar username = req.body.username || \"\";\nvar password = req.body.password || \"\";\nmodels.User.findOne({ where: {username: username} }).\nthen(\n function(user) {\n if(user){\n console.log(user.validatePassword(password));\n }\n ....\n```\n\nEach time I try to login I get the following error\n\n```\n[TypeError: user.validatePassword is not a function]\n```\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nFor anyone who's having a similar problem, I ran into the same issue but using Sequelize 5.21.5. According to this article, Sequelize Instance Methods, starting with Sequelize 4.0 and above, you have to use the prototype methodology in order to define instance methods like so: \n\n```\n// Adding an instance level methods.\n User.prototype.validPassword = function(password) {\n return bcrypt.compareSync(password, this.password);\n};\n```\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User',{\n    id:{\n          type:DataTypes.BIGINT,\n          autoIncrement: true,\n          allowNull: false,\n          primaryKey:true\n        },\n    username:{\n          type:DataTypes.STRING,\n          unique:true\n        },\n    password:{\n          type: DataTypes.STRING\n        },\n    ...\n  },\n  {\n    classMethods:{\n        associate:function(models){\n        ...\n        }\n      }\n  },\n  {\n    instanceMethods:{\n        validatePassword:function(password){\n          return bcrypt.compareSync(password, this.password);\n        }\n      }\n  }\n);\n  return User;\n}\n```\n\n```text\nvar username = req.body.username || \"\";\nvar password = req.body.password || \"\";\nmodels.User.findOne({ where: {username: username} }).\nthen(\n    function(user) {\n     if(user){\n      console.log(user.validatePassword(password));\n     }\n ....\n```\n\n```text\n[TypeError: user.validatePassword is not a function]\n```\n\n```text\nvar User = sequelize.define('User',{}, {\n  classMethods: {\n    method1: ...\n  },\n  instanceMethods: {\n    method2: ...\n  }\n});\n```\n\n```text\nvar User = sequelize.define('User',{}, {\n  classMethods: {\n    method1: ...\n  }\n},{\n  instanceMethods: {\n    method2: ...\n  }\n});\n```\n\n```text\nUser.prototype.your-instance-level-method-name = function() {\n    return 'foo';\n};\n```\n\n```text\n// Adding an instance level methods.\nUser.prototype.validPassword = function(password) {\n    return bcrypt.compareSync(password, this.password);\n};\n```\n\n```text\n// Adding an instance level methods.\n    User.prototype.validPassword = function(password) {\n      return bcrypt.compareSync(password, this.password);\n};\n```\n\n```text\nUser {\n  dataValues: {\n    id: 1,\n    firtName: null,\n    lasteName: null,\n    email: 'ugbanawaji.ekenekiso@ust.edu.ng',\n    phone: null,\n    password: '$2b$10$yEWnBFMAe15RLLgyU3XlrOUyw19c4PCmh8GJe9QVz3YkbdzK5fHWu',\n    createdAt: 2020-05-27T21:45:02.000Z,\n    updatedAt: 2020-05-27T21:45:02.000Z\n  },\n  _previousDataValues: {\n    id: 1,\n    firtName: null,\n    lasteName: null,\n    email: 'ugbanawaji.ekenekiso@ust.edu.ng',\n    phone: null,\n    password: '$2b$10$yEWnBFMAe15RLLgyU3XlrOUyw19c4PCmh8GJe9QVz3YkbdzK5fHWu',\n    createdAt: 2020-05-27T21:45:02.000Z,\n    updatedAt: 2020-05-27T21:45:02.000Z\n  },\n  _changed: {},\n  **_modelOptions: {**\n    timestamps: true,\n    validate: {},\n    freezeTableName: false,\n    underscored: false,\n    paranoid: false,\n    rejectOnEmpty: false,\n    whereCollection: { email: 'ugbanawaji.ekenekiso@ust.edu.ng' },\n    schema: null,\n    schemaDelimiter: '',\n    defaultScope: {},\n    scopes: {},\n    indexes: [],\n    name: { plural: 'Users', singular: 'User' },\n    omitNull: false,\n    **instanceMethods: { comparePasswords: [Function: comparePasswords] },**\n    hooks: { beforeValidate: [Array] },\n    sequelize: Sequelize {\n      options: [Object],\n      config: [Object],\n      dialect: [MysqlDialect],\n      queryInterface: [QueryInterface],\n      models: [Object],\n      modelManager: [ModelManager],\n      connectionManager: [ConnectionManager],\n      importCache: [Object]\n    }\n  },\n  _options: {\n    isNewRecord: false,\n    _schema: null,\n    _schemaDelimiter: '',\n    raw: true,\n    attributes: [\n      'id',        'firtName',\n      'lasteName', 'email',\n      'phone',     'password',\n      'createdAt', 'updatedAt'\n    ]\n  },\n  isNewRecord: false\n}\n```\n\n```text\nmodels.User.findOne({where: {email: req.body.email}}).then((user)=>{\n            console.log(user)\n            if(!user) {\n                res.status(401).json({ message: 'Authentication failed!' });\n                } else {\n                user.comparePasswords(req.body.password, (error, isMatch) =>{\n                    console.log(error + ' -- ' + isMatch)\n                    if(isMatch && !error) {\n                        const token = jwt.sign(\n                            { username: user.username },\n                            keys.secret,\n                            { expiresIn: '30h' }\n                        );\n\n                        res.status(200).json({ success: true,message: 'signed in successfully', token: 'JWT ' + token });\n                    } else {\n                        res.status(401).json({ success: false, message: 'Login failed!' });\n                    }\n                });\n            }\n        }).catch((error)=>{\n            console.log(error)\n            res.status(500).json({ success: false, message: 'There was an error!'});\n        })\n```\n\n```text\n** user.comparePasswords(req.body.password, (error, isMatch) =>{} **\n```\n\n```text\n** user._modelOptions.instanceMethods.comparePasswords(req.body.password, (error, isMatch) =>{}**\n```\n\n```text\nconst bcrypt = require('bcrypt-nodejs');\n\nconst constants = require('../constants/users');\n\nmodule.exports = (Sequelize, type) => {\n  const User = Sequelize.define(constants.TABLE_NAME, {\n    username: {\n      type: type.STRING,\n      unique: true,\n      allowNull: false,\n    },\n    password: {\n      type: type.STRING,\n      allowNull: false,\n    },\n    // bla bla\n  });\n\n  const setSaltAndPassword = async function(user) {\n    if (user.changed('password')) {\n      const salt = bcrypt.genSaltSync(constants.PASSWORD_SALT_SIZE);\n      user.password = bcrypt.hashSync(user.password, salt);\n    }\n  };\n\n  User.prototype.validPassword = async function(password) {\n    return await bcrypt.compare(password, this.password);\n  };\n\n  User.beforeCreate(setSaltAndPassword);\n  User.beforeUpdate(setSaltAndPassword);\n\n  return User;\n};\n```\n\n========================================\n\nComments:\n- Are you sure `user` is not null?\n- @Hopeful Llama nope i can ***console.log(user)*** and retrieve all info\n- Yep that fixed it! Thanks!!\n- This works, thank you. I was hoping to make the instance and class methods work on my Model, but the other suggestions do not work, and I get a \"is not a function\" error code.\n- I can't access to this when I use the function on an instance. Do you know why this could happen?\n- @KevinMamaqi don't use an arrow function. it might affect to `this` keyword","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":332,"estimatedTokens":1975}}145{"id":"stack-60014874","source":"stackoverflow","questionId":60014874,"title":"How to use TypeScript with Sequelize","tags":["node.js","postgresql","typescript","sequelize.js","fastify"],"text":"Title: How to use TypeScript with Sequelize\nTags: node.js, postgresql, typescript, sequelize.js, fastify\nSource: Stack Overflow\n\nQuestion:\nI already have my server application written in Node, PostgreSQL, Sequelize using Fastify.\n\nNow I would like to use TypeScript. Can anyone tell me how to begin rewriting my Server application using TypeScript.\n\n========================================\n\nTop Answer:\nUse sequelize-typescript. Convert your tables and views into a class that extends Model object.\n\nUse annotations in classes for defining your table.\n\n\r\n\r\n\n```\nimport {Table, Column, Model, HasMany} from 'sequelize-typescript';\r\n \r\n@Table\r\nclass Person extends Model {\r\n \r\n @Column\r\n name: string;\r\n \r\n @Column\r\n birthday: Date;\r\n \r\n @HasMany(() => Hobby)\r\n hobbies: Hobby[];\r\n}\n```\n\n\r\n\r\n\r\n\nCreate a connection to DB by creating the object:\n\n```\nconst sequelize = new Sequelize(configuration...).\n```\n\nThen register your tables to this object.\n\n```\nsequelize.add([Person])\n```\n\nFor further reference check this module.\nSequelize-Typescript\n\n========================================\n\nCode:\n```js\n/**\n * Keep this file in sync with the code in the \"Usage\" section\n * in /docs/manual/other-topics/typescript.md\n *\n * Don't include this comment in the md file.\n */\nimport {\n  Association, DataTypes, HasManyAddAssociationMixin, HasManyCountAssociationsMixin,\n  HasManyCreateAssociationMixin, HasManyGetAssociationsMixin, HasManyHasAssociationMixin,\n  HasManySetAssociationsMixin, HasManyAddAssociationsMixin, HasManyHasAssociationsMixin,\n  HasManyRemoveAssociationMixin, HasManyRemoveAssociationsMixin, Model, ModelDefined, Optional,\n  Sequelize, InferAttributes, InferCreationAttributes, CreationOptional, NonAttribute, ForeignKey,\n} from 'sequelize';\n\nconst sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');\n\n// 'projects' is excluded as it's not an attribute, it's an association.\nclass User extends Model<InferAttributes<User, { omit: 'projects' }>, InferCreationAttributes<User, { omit: 'projects' }>> {\n  // id can be undefined during creation when using `autoIncrement`\n  declare id: CreationOptional<number>;\n  declare name: string;\n  declare preferredName: string | null; // for nullable fields\n\n  // timestamps!\n  // createdAt can be undefined during creation\n  declare createdAt: CreationOptional<Date>;\n  // updatedAt can be undefined during creation\n  declare updatedAt: CreationOptional<Date>;\n\n  // Since TS cannot determine model association at compile time\n  // we have to declare them here purely virtually\n  // these will not exist until `Model.init` was called.\n  declare getProjects: HasManyGetAssociationsMixin<Project>; // Note the null assertions!\n  declare addProject: HasManyAddAssociationMixin<Project, number>;\n  declare addProjects: HasManyAddAssociationsMixin<Project, number>;\n  declare setProjects: HasManySetAssociationsMixin<Project, number>;\n  declare removeProject: HasManyRemoveAssociationMixin<Project, number>;\n  declare removeProjects: HasManyRemoveAssociationsMixin<Project, number>;\n  declare hasProject: HasManyHasAssociationMixin<Project, number>;\n  declare hasProjects: HasManyHasAssociationsMixin<Project, number>;\n  declare countProjects: HasManyCountAssociationsMixin;\n  declare createProject: HasManyCreateAssociationMixin<Project, 'ownerId'>;\n\n  // You can also pre-declare possible inclusions, these will only be populated if you\n  // actively include a relation.\n  declare projects?: NonAttribute<Project[]>; // Note this is optional since it's only populated when explicitly requested in code\n\n  // getters that are not attributes should be tagged using NonAttribute\n  // to remove them from the model's Attribute Typings.\n  get fullName(): NonAttribute<string> {\n    return this.name;\n  }\n\n  declare static associations: {\n    projects: Association<User, Project>;\n  };\n}\n\nclass Project extends Model<\n  InferAttributes<Project>,\n  InferCreationAttributes<Project>\n> {\n  // id can be undefined during creation when using `autoIncrement`\n  declare id: CreationOptional<number>;\n\n  // foreign keys are automatically added by associations methods (like Project.belongsTo)\n  // by branding them using the `ForeignKey` type, `Project.init` will know it does not need to\n  // display an error if ownerId is missing.\n  declare ownerId: ForeignKey<User['id']>;\n  declare name: string;\n\n  // `owner` is an eagerly-loaded association.\n  // We tag it as `NonAttribute`\n  declare owner?: NonAttribute<User>;\n\n  // createdAt can be undefined during creation\n  declare createdAt: CreationOptional<Date>;\n  // updatedAt can be undefined during creation\n  declare updatedAt: CreationOptional<Date>;\n}\n\nclass Address extends Model<\n  InferAttributes<Address>,\n  InferCreationAttributes<Address>\n> {\n  declare userId: ForeignKey<User['id']>;\n  declare address: string;\n\n  // createdAt can be undefined during creation\n  declare createdAt: CreationOptional<Date>;\n  // updatedAt can be undefined during creation\n  declare updatedAt: CreationOptional<Date>;\n}\n\nProject.init(\n  {\n    id: {\n      type: DataTypes.INTEGER.UNSIGNED,\n      autoIncrement: true,\n      primaryKey: true\n    },\n    name: {\n      type: new DataTypes.STRING(128),\n      allowNull: false\n    },\n    createdAt: DataTypes.DATE,\n    updatedAt: DataTypes.DATE,\n  },\n  {\n    sequelize,\n    tableName: 'projects'\n  }\n);\n\nUser.init(\n  {\n    id: {\n      type: DataTypes.INTEGER.UNSIGNED,\n      autoIncrement: true,\n      primaryKey: true\n    },\n    name: {\n      type: new DataTypes.STRING(128),\n      allowNull: false\n    },\n    preferredName: {\n      type: new DataTypes.STRING(128),\n      allowNull: true\n    },\n    createdAt: DataTypes.DATE,\n    updatedAt: DataTypes.DATE,\n  },\n  {\n    tableName: 'users',\n    sequelize // passing the `sequelize` instance is required\n  }\n);\n\nAddress.init(\n  {\n    address: {\n      type: new DataTypes.STRING(128),\n      allowNull: false\n    },\n    createdAt: DataTypes.DATE,\n    updatedAt: DataTypes.DATE,\n  },\n  {\n    tableName: 'address',\n    sequelize // passing the `sequelize` instance is required\n  }\n);\n\n// You can also define modules in a functional way\ninterface NoteAttributes {\n  id: number;\n  title: string;\n  content: string;\n}\n\n// You can also set multiple attributes optional at once\ntype NoteCreationAttributes = Optional<NoteAttributes, 'id' | 'title'>;\n\n// And with a functional approach defining a module looks like this\nconst Note: ModelDefined<\n  NoteAttributes,\n  NoteCreationAttributes\n> = sequelize.define(\n  'Note',\n  {\n    id: {\n      type: DataTypes.INTEGER.UNSIGNED,\n      autoIncrement: true,\n      primaryKey: true\n    },\n    title: {\n      type: new DataTypes.STRING(64),\n      defaultValue: 'Unnamed Note'\n    },\n    content: {\n      type: new DataTypes.STRING(4096),\n      allowNull: false\n    }\n  },\n  {\n    tableName: 'notes'\n  }\n);\n\n// Here we associate which actually populates out pre-declared `association` static and other methods.\nUser.hasMany(Project, {\n  sourceKey: 'id',\n  foreignKey: 'ownerId',\n  as: 'projects' // this determines the name in `associations`!\n});\n\nAddress.belongsTo(User, { targetKey: 'id' });\nUser.hasOne(Address, { sourceKey: 'id' });\n\nasync function doStuffWithUser() {\n  const newUser = await User.create({\n    name: 'Johnny',\n    preferredName: 'John',\n  });\n  console.log(newUser.id, newUser.name, newUser.preferredName);\n\n  const project = await newUser.createProject({\n    name: 'first!'\n  });\n\n  const ourUser = await User.findByPk(1, {\n    include: [User.associations.projects],\n    rejectOnEmpty: true // Specifying true here removes `null` from the return type!\n  });\n\n  // Note the `!` null assertion since TS can't know if we included\n  // the model or not\n  console.log(ourUser.projects![0].name);\n}\n\n(async () => {\n  await sequelize.sync();\n  await doStuffWithUser();\n})();\n```\n\n```text\n* @types/node\n * @types/validator // this one is not need it\n * @types/bluebird\n```\n\n```text\nmyProject\n--src\n----models\n------index.ts\n------user-model.ts\n------other-model.ts\n----controllers\n----index.ts\n--package.json\n```\n\n```js\n`./src/models/user-model.ts`\nimport { BuildOptions, DataTypes, Model, Sequelize } from \"sequelize\";\n\nexport interface UserAttributes {\n    id: number;\n    name: string;\n    email: string;\n    createdAt?: Date;\n    updatedAt?: Date;\n}\nexport interface UserModel extends Model<UserAttributes>, UserAttributes {}\nexport class User extends Model<UserModel, UserAttributes> {}\n\nexport type UserStatic = typeof Model & {\n    new (values?: object, options?: BuildOptions): UserModel;\n};\n\nexport function UserFactory (sequelize: Sequelize): UserStatic {\n    return <UserStatic>sequelize.define(\"users\", {\n        id: {\n            type: DataTypes.INTEGER,\n            autoIncrement: true,\n            primaryKey: true,\n        },\n        email: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            unique: true,\n        },\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false,\n        },\n        createdAt: {\n            type: DataTypes.DATE,\n            allowNull: false,\n            defaultValue: DataTypes.NOW,\n        },\n        updatedAt: {\n            type: DataTypes.DATE,\n            allowNull: false,\n            defaultValue: DataTypes.NOW,\n        },\n    });\n}\n```\n\n```js\n`./src/models/another-model.ts`\n\nimport { BuildOptions, DataTypes, Model, Sequelize } from \"sequelize\";\n\nexport interface SkillsAttributes {\n    id: number;\n    skill: string;\n    createdAt?: Date;\n    updatedAt?: Date;\n}\nexport interface SkillsModel extends Model<SkillsAttributes>, SkillsAttributes {}\nexport class Skills extends Model<SkillsModel, SkillsAttributes> {}\n\nexport type SkillsStatic = typeof Model & {\n    new (values?: object, options?: BuildOptions): SkillsModel;\n};\n\nexport function SkillsFactory (sequelize: Sequelize): SkillsStatic {\n    return <SkillsStatic>sequelize.define(\"skills\", {\n        id: {\n            type: DataTypes.INTEGER,\n            autoIncrement: true,\n            primaryKey: true,\n        },\n        skill: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            unique: true,\n        },\n        createdAt: {\n            type: DataTypes.DATE,\n            allowNull: false,\n            defaultValue: DataTypes.NOW,\n        },\n        updatedAt: {\n            type: DataTypes.DATE,\n            allowNull: false,\n            defaultValue: DataTypes.NOW,\n        },\n    });\n}\n```\n\n```js\n`./src/models/index.ts`\n\nimport * as sequelize from \"sequelize\";\nimport {userFactory} from \"./user-model\";\nimport {skillsFactory} from \"./other-model\";\n\nexport const dbConfig = new sequelize.Sequelize(\n    (process.env.DB_NAME = \"db-name\"),\n    (process.env.DB_USER = \"db-user\"),\n    (process.env.DB_PASSWORD = \"db-password\"),\n    {\n        port: Number(process.env.DB_PORT) || 54320,\n        host: process.env.DB_HOST || \"localhost\",\n        dialect: \"postgres\",\n        pool: {\n            min: 0,\n            max: 5,\n            acquire: 30000,\n            idle: 10000,\n        },\n    }\n);\n\n// SOMETHING VERY IMPORTANT them Factory functions expect a\n// sequelize instance as parameter give them `dbConfig`\n\nexport const User = userFactory(dbConfig);\nexport const Skills = skillsFactory(dbConfig);\n\n// Users have skills then lets create that relationship\n\nUser.hasMay(Skills);\n\n// or instead of that, maybe many users have many skills\nSkills.belongsToMany(Users, { through: \"users_have_skills\" });\n\n// the skill is the limit!\n```\n\n```js\ndb.sequelize\n        .authenticate()\n        .then(() => logger.info(\"connected to db\"))\n        .catch(() => {\n            throw \"error\";\n        });\n```\n\n```text\ndb.sequelize\n        .sync()\n        .then(() => logger.info(\"connected to db\"))\n        .catch(() => {\n            throw \"error\";\n        });\n```\n\n```js\nimport * as bodyParser from \"body-parser\";\nimport * as express from \"express\";\nimport { dbConfig } from \"./models\";\nimport { routes } from \"./routes\";\nimport { logger } from \"./utils/logger\";\nimport { timeMiddleware } from \"./utils/middlewares\";\n\nexport function expressApp () {\n    dbConfig\n        .authenticate()\n        .then(() => logger.info(\"connected to db\"))\n        .catch(() => {\n            throw \"error\";\n        });\n\n    const app: Application = express();\n    if (process.env.NODE_ENV === \"production\") {\n        app.use(require(\"helmet\")());\n        app.use(require(\"compression\")());\n    } else {\n        app.use(require(\"cors\")());\n    }\n\n    app.use(bodyParser.json());\n    app.use(bodyParser.urlencoded({ extended: true, limit: \"5m\" }));\n    app.use(timeMiddleware);\n    app.use(\"/\", routes(db));\n\n    return app;\n}\n```\n\n```text\nnpm i -D @types/node @types/bluebird\n```\n\n```text\n./src/models/index.ts\n```\n\n```js\nimport {Table, Column, Model, HasMany} from 'sequelize-typescript';\n \n@Table\nclass Person extends Model<Person> {\n \n  @Column\n  name: string;\n \n  @Column\n  birthday: Date;\n \n  @HasMany(() => Hobby)\n  hobbies: Hobby[];\n}\n```\n\n```js\nconst sequelize = new Sequelize(configuration...).\n```\n\n```js\nsequelize.add([Person])\n```\n\n```text\ninterface UserAttributes extends Model {\n    id: number;\n    name: string;\n    email: string;\n    createdAt?: Date;\n    updatedAt?: Date;\n}\n```\n\n========================================\n\nComments:\n- Hey this was the best solution I found: rousseau-alexandre.fr/en/programming/2019/06/19/&hellip; Hope it helps\n- Sequelize has a document for using Typescript. sequelize.org/docs/v6/other-topics/typescript\n- How to implement this for create works? When i do MyModel.create () he expect an object but not exactly the properties from model\n- Hola, como estas ? you can take a look at this medium post medium.com/@enetoOlveda/&hellip;\n- Many TypeScript features aren't part of the ECMAScript standard, that doesn't mean they should be avoided. And decorators are most definitely not legacy, they're a tc39 stage 2 proposal yet to be finalized.\n- Whatever floats your boat\n- Whether the model compatible with typescript can build from the `sequelize-cli`? as we do like `sequelize-cli model:generate command`?\n- sorry I didn't get that. I am a ESL person that's why my ugly english xDD what you do mean by that ?\n- @Ernesto What does `export class User extends Model {}` even do? I don't see how it could be used. Even the return type of `create()` or `findOne()` are `UserModel` interface. The `class User` looks redundant to me.\n- Is there anything for version 6? I attempted to use the example on the sequelize website as a guide and not having much luck\n- this example is for v5, but let me take a look at v6\n- if you use the `sequelize.define` form its the same thing here you can find an example I wrote github.com/EnetoJara/resume-app\n- I am getting `@Table annotation is missing on class \"User\"` When I tried this approach. Any ideas how I can fix this ? I use NestJs FYI\n- This question was originally asking on how to use decorators that's why I started with `Using Decorators is something you should avoid as much as possible` If you have NestJS this post wont help you, NestJS comes with its own way of implementation as it is a framework","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":546,"estimatedTokens":3774}}146{"id":"stack-35591825","source":"stackoverflow","questionId":35591825,"title":"Using epilogue, is it possible to get back a resource without associations?","tags":["javascript","associations","sequelize.js","epilogue"],"text":"Title: Using epilogue, is it possible to get back a resource without associations?\nTags: javascript, associations, sequelize.js, epilogue\nSource: Stack Overflow\n\nQuestion:\nI have\n\n```\nepilogue.resource({\n model: db.Question,\n endpoints: ['/api/questions', '/api/questions/:id'],\n associations: true\n});\n```\n\nSo when I hit `/api/questions`, I get back all the associations with the resources. Is there something I can pass to not get the associations in certain cases? Or should I create a new endpoint:\n\n```\nepilogue.resource({\n model: db.Question,\n endpoints: ['/api/questions2', '/api/questions2/:id']\n});\n```\n\n========================================\n\nCode:\n```text\nepilogue.resource({\n  model: db.Question,\n  endpoints: ['/api/questions', '/api/questions/:id'],\n  associations: true\n});\n```\n\n```text\nepilogue.resource({\n  model: db.Question,\n  endpoints: ['/api/questions2', '/api/questions2/:id']\n});\n```\n\n```text\n/api/questions\n```\n\n```text\n// my-middleware.js\nmodule.exports = {\n  list: {\n    write: {\n      before: function(req, res, context) {\n        // modify data before writing list data\n        return context.continue;\n      },\n      action: function(req, res, context) {\n        // change behavior of actually writing the data\n        return context.continue;\n      },\n      after: function(req, res, context) {\n        // set some sort of flag after writing list data\n        return context.continue;\n      }\n    }\n  }\n};\n\n// my-app.js\nvar epilogue = require('epilogue'),\n    restMiddleware = require('my-middleware');\n\nepilogue.initialize({\n    app: app,\n    sequelize: sequelize\n});\n\nvar userResource = epilogue.resource({\n    model: User,\n    endpoints: ['/users', '/users/:id']\n});\n\nuserResource.use(restMiddleware);\n```\n\n========================================\n\nComments:\n- Maybe this commit does what you are looking for: Allow not reading associations on read","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":88,"estimatedTokens":471}}147{"id":"stack-50148491","source":"stackoverflow","questionId":50148491,"title":"How to get join data result without prefix table name in Sequelize ORM","tags":["node.js","express","sequelize.js"],"text":"Title: How to get join data result without prefix table name in Sequelize ORM\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize ORM in node js. I am join two table and get result but that result return with table name as prefix.\n\n```\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('test', 'root', '', {\n // configuration\n }\n});\n\nconst db = {};\n\ndb.Sequelize = Sequelize; \ndb.sequelize = sequelize;\n\ndb.role = require('./../model/definitions/role')(sequelize, Sequelize); \ndb.admin = require('./../model/definitions/admin')(sequelize, Sequelize); \n\n db.admin.findAll({ \n include: [{ \n model: db.role, \n where:{status : 'Active'}, \n }],\n raw: true \n\n }).then(function(result) {\n console.log(result);\n }).catch(function(error) {\n console.log(error);\n }).done();\n```\n\nNow I am getting this result:\n\n```\n[{\n \"id\": 36, \n \"email\": \"test@gmail.com\",\n \"username\": \"test\",\n \"status\": \"Active\",\n \"role.role_id\": 1,\n \"role.role_name\": \"Admin\"\n}]\n```\n\nbut I need this result:\n\n```\n[{\n \"id\": 36, \n \"email\": \"test@gmail.com\",\n \"username\": \"test\",\n \"status\": \"Active\",\n \"role_id\": 1,\n \"role_name\": \"Admin\"\n}]\n```\n\nso, how to remove prefix table name 'role' from column.\nI have only need 'role_id' or 'role_name' not need this type data like 'role.role_id', 'role.role_name'\n\n========================================\n\nTop Answer:\nThis should work\n\n`A` is a table that is associated to `B` using a column called `bId` so B has a primary key of `Id` which is associates to a `bid` column in `A` table that is shown in the standard result set as `b.id` but we want these two column to be called as `Id & Name`\n\n```\nA.belongsTo(B);\n return await A.findAll({\n attributes: [\n [Sequelize.col('b.id'), 'Id'],\n [Sequelize.col('b.name'), 'Name']\n ],\n raw: true,\n where: { /*Some condition*/ },\n include: {\n model: B,\n attributes: [],\n required: true\n },\n });\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('test', 'root', '', {\n    // configuration\n  }\n});\n\nconst db = {};\n\ndb.Sequelize = Sequelize;  \ndb.sequelize = sequelize;\n\ndb.role = require('./../model/definitions/role')(sequelize, Sequelize);  \ndb.admin = require('./../model/definitions/admin')(sequelize, Sequelize);  \n\n  db.admin.findAll({ \n    include: [{ \n      model: db.role,                      \n      where:{status : 'Active'},     \n    }],\n    raw: true      \n\n  }).then(function(result) {\n      console.log(result);\n  }).catch(function(error) {\n    console.log(error);\n  }).done();\n```\n\n```text\n[{\n    \"id\": 36,                \n    \"email\": \"test@gmail.com\",\n    \"username\": \"test\",\n    \"status\": \"Active\",\n    \"role.role_id\": 1,\n    \"role.role_name\": \"Admin\"\n}]\n```\n\n```text\n[{\n    \"id\": 36,                \n    \"email\": \"test@gmail.com\",\n    \"username\": \"test\",\n    \"status\": \"Active\",\n    \"role_id\": 1,\n    \"role_name\": \"Admin\"\n}]\n```\n\n```text\ndb.admin.findAll({ \n    attributes: ['id', 'username', 'email', 'status', 'role.role_id', 'role.role_name'],\n    include: [{ \n      model: db.role,                      \n      where:{status : 'Active'}, \n      attributes: []\n    }],\n    raw: true\n})\n```\n\n```text\nraw: true\n```\n\n```text\ndb.admin.findAll({ \n    include: [{ \n      model: db.role,                      \n      where:{status : 'Active'},     \n    }],\n    raw: true // <--------- Remove this   \n})\n```\n\n```text\nraw: true ,\n```\n\n```text\nraw: true\n\n db.admin.findAll({ \n    include: [{ \n      model: db.role,                      \n      where:{status : 'Active'},\n      attributes: [\"role_id\", \"role_name\"],  \n      nested: false,  \n    }],\n    attributes: {exclude: [],\n                 include: [\"role.role_id\", \"role.role_name\"]},\n    raw: true      \n  });\n```\n\n```text\ndb.admin.findAll({ \n    include: [{ \n      model: db.role,                      \n      where:{status : 'Active'},\n      attributes: [[\"role_id\", \"roleId\"], [\"role_name\", \"roleName\"]] \n    }],\n    attributes: {exclude: [],\n                 include: [\"role.roleId\", \"role.roleName\"]},\n    raw: true      \n  });\n```\n\n```text\nA.belongsTo(B);\n        return await A.findAll({\n            attributes: [\n                [Sequelize.col('b.id'), 'Id'],\n                [Sequelize.col('b.name'), 'Name']\n            ],\n            raw: true,\n            where: { /*Some condition*/ },\n            include: {\n                model: B,\n                attributes: [],\n                required: true\n            },\n        });\n```\n\n```text\nA\n```\n\n```text\nB\n```\n\n```text\nbId\n```\n\n```text\nId\n```\n\n```text\nbid\n```\n\n```text\nA\n```\n\n```text\nb.id\n```\n\n```text\nId & Name\n```\n\n========================================\n\nComments:\n- i need result at same level. if remove 'raw: true' then join table data show as object in 'role' key.\n- @MukeshSinghThakur , you can access that `role['role_id']`, you can't get those property to upper level , as it may override the parent keys. This is the standard way to get data.\n- You are right but i need this result at same level.\n- @MukeshSinghThakur, Then you have to use alias name in attributes , for single attribute . `['$role. role_id$','role_id']` , something like this , but for each attribute\n- I have also try ['$role. role_id$','role_id'] but can't get that result.\n- And if you want to rename the column additionally, use `[Sequelize.col('role.role_id'), 'rid']` instead of `role.role_id`.\n- cause error when use `underscored` config\n- It doesn't work in multi-level joins. Lets say, Table A includes ( Table B includes Table C ). I cannot select Table C columns in Table B ( it always prefixes table A )\n- this one doesn't work with me, but this works [`Sequelize.col(role.role_id), 'role_id']`]\n- this worked and chatgpt failed\n- Unfortunatelly it doesn't work with aliases. I tried adding alias both in the atributes of parent and child models. Each time I get \"Unknown column 'tableName.aliasName' in 'field list'\". It works without alias though.","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":265,"estimatedTokens":1487}}148{"id":"stack-47546824","source":"stackoverflow","questionId":47546824,"title":"Sequelize configuration to retrieve total count with details","tags":["node.js","database","postgresql","sequelize.js"],"text":"Title: Sequelize configuration to retrieve total count with details\nTags: node.js, database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am working with node **sequelize** with **postgres** database.\nI am loading paginated records to my UI, now I need to get total records count with the same query which I am using to retrieve paginate records.\nAnyone, please give the sample sequelize configuration to do the same.\nPlease see my expected sample postgres query to clarify my question\n\n```\nSELECT count(*) over() as total ,name FROM students WHERE gender='male' LIMIT 2\n```\n\nThanks in advance\n\n========================================\n\nTop Answer:\nYou can't do that with sequelize, but you can do through 2 separate queries, one to get the data you need and the other one to get the total count.\n\nfirst one :\n\n```\nawait Model.findAll({ where: { columnName: condition }});\n```\n\nsecond one :\n\n```\nawait Model.count({ where: { columnName: condition }});\n```\n\nif you want to do that in one query which is maybe not the best way (because you adding metadata for each result which is not metadata related to the model) you can create a `raw query` like that:\n\n```\nawait sequelize.query('select count(*) over(), name from table where condition', { model: Model });\n```\n\nI hope my explanation will help you :),\n\nHave a nice day!\n\n========================================\n\nCode:\n```text\nSELECT count(*) over() as total ,name FROM students  WHERE gender='male' LIMIT 2\n```\n\n```text\nfindAndCountAll\n```\n\n```text\nawait Model.findAll({ where: { columnName: condition }});\n```\n\n```text\nawait Model.count({ where: { columnName: condition }});\n```\n\n```text\nawait sequelize.query('select count(*) over(), name from table where condition', { model: Model });\n```\n\n```text\nraw query\n```\n\n```text\nconst getStudents = async params => {\n  const { count, rows: students } = await Student.findAndCountAll({\n    where: {\n      gender: 'male',\n    },\n    limit: DEFAULT_PAGE_SIZE,\n    order: [['id', 'ASC']],\n    ...params,\n  });\n\n  return { count, students };\n}\n```\n\n```text\nparams\n```\n\n```text\nlimit\n```\n\n```text\noffset\n```\n\n```text\ndistinct: true\n```\n\n```text\ninclude\n```\n\n```text\nconst students = await students.findAndCountAll({\n  where: {\n     gender : 'male'\n  }\n});\nconsole.log(students)\n```\n\n```text\nconst students = await students.count({\n  where: {\n     gender : 'male'\n  }\n});\nconsole.log(students)\n```\n\n```text\ngender\n```\n\n```text\ngender\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":130,"estimatedTokens":612}}149{"id":"stack-28286811","source":"stackoverflow","questionId":28286811,"title":"sequelize subquery as field","tags":["sequelize.js"],"text":"Title: sequelize subquery as field\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get such query to be generated by sequlized:\n\n```\nSELECT \n \"Customers\".\"id\", \n (SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\"\n WHERE \"Orders\".\"CustomerId\" = \"Customers\".\"id\") AS \"totalAmount\",\n \"Customer\".\"lastName\" AS \"Customer.lastName\",\n \"Customer\".\"firstName\" AS \"Customer.firstName\" \nFROM \"Customers\" AS \"Customer\";\n```\n\nI'm trying to avoid `GROUP BY` clause, as I have a lot of fields to select and I don't want to group by all them (I think it's not efficient, isn't it?)\n\nI've tried several ways for making it happen with sequelize, include `{include: ...}` and `{attributes: [[...]]}`, but without any luck.\n\nAny ideas? or maybe should I use one big `GROUP BY` clause and let all the \"regular\" fields to be grouped-by?\n\n========================================\n\nTop Answer:\nIn Sequelize 4, you can add extra attributes using the `attributes.include` syntax http://docs.sequelizejs.com/manual/tutorial/querying.html\n\n```\nreturn Customer.findAll({\n attributes: {\n include: [\n [sequelize.literal('(SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\" \n WHERE \"Orders\".\"CustomerId\" = \"Customer\".\"id\")'), 'totalAmount']\n ]\n }\n});\n```\n\n========================================\n\nCode:\n```sql\nSELECT \n    \"Customers\".\"id\", \n    (SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\"\n     WHERE \"Orders\".\"CustomerId\" = \"Customers\".\"id\") AS \"totalAmount\",\n    \"Customer\".\"lastName\" AS \"Customer.lastName\",\n    \"Customer\".\"firstName\" AS \"Customer.firstName\" \nFROM \"Customers\" AS \"Customer\";\n```\n\n```text\nGROUP BY\n```\n\n```text\n{include: ...}\n```\n\n```text\n{attributes: [[...]]}\n```\n\n```text\nGROUP BY\n```\n\n```ts\nreturn Customer.findAll({\n        attributes: Object.keys(Customer.attributes).concat([\n            [sequelize.literal('(SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\" WHERE \"Orders\".\"CustomerId\" = \"Customer\".\"id\")'), 'totalAmount']\n        ])\n    });\n```\n\n```ts\nreturn sequelize.query(\n        'SELECT *, (SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\" WHERE \"Orders\".\"CustomerId\" = \"Customer\".\"id\") AS \"totalAmount\" FROM \"Customers\" AS \"Customer\";',\n        Customer,\n        {raw: false}\n    );\n```\n\n```ts\ninstanceMethods: {\n    getOrderSummary: function () {\n        return Order.findAll({\n            where: {\n                CustomerId: this.id\n            },\n            attributes: [\n                [sequelize.fn('SUM', sequelize.col('amount')), 'sum'],\n                'CustomerId'],\n            group: ['CustomerId']\n        });\n    }\n}\n```\n\n```ts\nreturn Customer.findAll({\n        attributes: Object.keys(Customer.attributes).concat([\n            [sequelize.literal('(SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\" WHERE \"Orders\".\"CustomerId\" = \"Customer\".\"id\")'), 'totalAmount']\n        ])\n    });\n```\n\n```ts\nExecuting (default): SELECT \"id\", \"firstName\", \"lastName\", \"createdAt\", \"updatedAt\", (SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\" WHERE \"Orders\".\"CustomerId\" = \"Customer\".\"id\") AS \"totalAmount\" FROM \"Customers\" AS \"Customer\";\n{ id: 1,\n  firstName: 'Test',\n  lastName: 'Testerson',\n  createdAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),\n  updatedAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),\n  totalAmount: 15 }\n{ id: 2,\n  firstName: 'Invisible',\n  lastName: 'Hand',\n  createdAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),\n  updatedAt: Wed Feb 04 2015 08:05:42 GMT-0500 (EST),\n  totalAmount: 99 }\n```\n\n```ts\n// Doesn't work\n    return Order.findAll({\n        attributes: [\n            [Sequelize.fn('COUNT', '*'), 'orderCount'],\n            'CustomerId'\n        ],\n        include: [\n            {model: Customer, attributes: ['id']}\n        ],\n        group: ['CustomerId']\n    });\n```\n\n```text\ninclude\n```\n\n```text\nCustomer\n```\n\n```text\nattribute\n```\n\n```text\nObject.keys()\n```\n\n```text\nfindAll\n```\n\n```text\nOrder\n```\n\n```text\nCustomer\n```\n\n```ts\nreturn Customer.findAll({\n    attributes: {\n        include: [\n           [sequelize.literal('(SELECT SUM(\"Orders\".\"amount\") FROM \"Orders\" \n            WHERE \"Orders\".\"CustomerId\" = \"Customer\".\"id\")'), 'totalAmount']\n        ]\n    }\n});\n```\n\n```text\nattributes.include\n```\n\n========================================\n\nComments:\n- cool. I have to adapt this to my use case, but it seems to workaround my current problem. 10x.\n- Good call on the `Object.keys(Customer.attributes).concat()` I could not figure out why the other attributes were not showing up despite `*`.\n- For those reading this much later, @srlm has created a nice blog post clearly explaining this including an elaboration on the instance method approach. srlm.io/2015/02/04/sequelize-subqueries\n- Note that in current Sequelize, the `attributes` field on the Model has been renamed to `rawAttributes` for some unfathomable reason. So you have to do `Customer.rawAttributes`.\n- Its getting added in the query but how to access it ?\n- You should be able to access it as just an attribute on the returned instance, e.g. if you have a Customer from the above query (which returns an array of Customers) , `Customer.totalAmount`, but if that's not working then try `Customer.get('totalAmount')` or `Customer.dataValues('totalAmount')`.","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":190,"estimatedTokens":1286}}150{"id":"stack-47819267","source":"stackoverflow","questionId":47819267,"title":"Understanding Sequelize database migrations and seeds","tags":["node.js","database","sequelize.js","database-migration"],"text":"Title: Understanding Sequelize database migrations and seeds\nTags: node.js, database, sequelize.js, database-migration\nSource: Stack Overflow\n\nQuestion:\nI'm trying to wrap my head around Sequelize's migrations and how they work together with seeds (or maybe migrations and seeds in general).\n\nI set up everything to get the migrations working.\n\nFirst, lets create a `users` table:\n\n```\n// migrations/01-create-users.js\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable(\"Users\", {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n email: {\n type: Sequelize.STRING\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE,\n defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')\n },\n updatedAt: {\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable(\"Users\");\n }\n};\n```\n\nFine. If I want to seed an (admin) user, I can do this as follows:\n\n```\n// seeders/01-demo-user.js\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.bulkInsert(\n \"Users\",\n [\n {\n email: \"demo@demo.com\"\n }\n ],\n {}\n );\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.bulkDelete(\"Users\", null, {});\n }\n};\n```\n\nThen to make the magic happen, I do:\n\n```\n$ sequelize db:migrate\n```\n\nWhich creates the `users` table in the database. After running the migrations, seeding is the next step, so:\n\n```\n$ sequelize db:seed:all\n```\n\nTataa, now I have a user in the `users` database. Great.\n\nBut now I want to add `firstname` to the `users` table, so I have to add another migration:\n\n```\n// migrations/02-alter-users.js\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.addColumn(\"Users\", \"firstname\", {\n type: Sequelize.STRING\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.removeColumn(\"Users\", \"firstname\");\n }\n};\n```\n\nRunning migrations again would only run the second one because it was saved in the database that the first one was already executed. But by default sequelize re-runs all seeders. So should I adjust the `seeders/01-demo-user.js` or change the default behavior and also store the seeders in the DB and create a new one that just updates the `firstname`?\n\nWhat if `firstname` couldn't be `null`, then running migrations first and then the old version of `seeders/01-demo-user.js` would throw an error because `firstname` can't be `null`.\n\nRe-running seeders leads to another problem: there is already a user with the `demo@demo.com` email. Running it a second time would duplicate the user. Or do I have to check for things like this in the seeder? \n\nPreviously, I just added the user-account in the migration so I could be sure when it was added to the DB and when I had to update it. But someone told me I was doing it all wrong and that I have to use seeders for tasks like this.\n\nAny help/insights much appreciated.\n\n========================================\n\nTop Answer:\nIn my experience migrations change structure. Seeders... seed data. Recently I was on a project that didn't have seeders configured. https://sequelize.org/master/manual/migrations.html#seed-storage. This will allow you to setup a file so your data isn't seeded more than once. Migration configuration is right there as well.\n\n========================================\n\nCode:\n```text\n// migrations/01-create-users.js\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable(\"Users\", {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      email: {\n        type: Sequelize.STRING\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')\n      },\n      updatedAt: {\n        type: Sequelize.DATE\n      }\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable(\"Users\");\n  }\n};\n```\n\n```text\n// seeders/01-demo-user.js\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.bulkInsert(\n      \"Users\",\n      [\n        {\n          email: \"demo@demo.com\"\n        }\n      ],\n      {}\n    );\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.bulkDelete(\"Users\", null, {});\n  }\n};\n```\n\n```text\n$ sequelize db:migrate\n```\n\n```text\n$ sequelize db:seed:all\n```\n\n```text\n// migrations/02-alter-users.js\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.addColumn(\"Users\", \"firstname\", {\n      type: Sequelize.STRING\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.removeColumn(\"Users\", \"firstname\");\n  }\n};\n```\n\n```text\nusers\n```\n\n```text\nusers\n```\n\n```text\nusers\n```\n\n```text\nfirstname\n```\n\n```text\nusers\n```\n\n```text\nseeders/01-demo-user.js\n```\n\n```text\nfirstname\n```\n\n```text\nfirstname\n```\n\n```text\nnull\n```\n\n```text\nseeders/01-demo-user.js\n```\n\n```text\nfirstname\n```\n\n```text\nnull\n```\n\n```text\ndemo@demo.com\n```\n\n```js\n// Add column, allow null at first\nawait queryInterface.addColumn(\"users\", \"user_type\", {\n    type: Sequelize.STRING,\n    allowNull: true\n});\n\n// Update data\nawait queryInterface.sequelize.query(\"UPDATE users SET user_type = 'simple_user' WHERE is_deleted = 0;\");\n\n// Change column, disallow null\nawait queryInterface.changeColumn(\"users\", \"user_type\", {\n    type: Sequelize.STRING,\n    allowNull: false\n});\n```\n\n```text\nsequelize\n```\n\n```text\nup\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) =>  queryInterface.addColumn(\n        'Users',\n        'user_type',\n        {\n          type: Sequelize.STRING,\n          allowNull: false,\n        }\n      ).then(()=>\n        queryInterface.bulkUpdate('Users', {\n            user_type: 'simple_user',\n        }, {\n            is_deleted : 0,\n        })\n      ),\n\n  down: (queryInterface, Sequelize) => \n    queryInterface.removeColumn('Users', 'user_type')\n};\n```\n\n========================================\n\nComments:\n- Were you able to figure this out? I am having the same issues.\n- Not really. Right now, *if* I'm using seeders I also store in the DB that I ran them so they won't run a second time.\n- This should be the accepted answer. Just ran into this same confusion. perfectly put. Thank you\n- The Sequelize docs confuse the issue when they state: \"To manage all data migrations you can use seeders\". It simply isn't true. There are many reasons one should update data in migration files, rather than seeds. in an established application, it seems like updating data in migration files should happen much more often than in seeders.\n- I'm a little confused how things work if I write some migrations and a seeder, which relies on those migrations and then add more migrations that make the seeders invalid with new columns... Sure, I can update the data in the new migration, but what happens if I want to create a new db? The new migration relies on the seeder being run first... I think what should really happen is there be a specific order of migrations and seeders.","metadata":{"transformedAt":"2026-08-18T18:33:34.349Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":294,"estimatedTokens":1781}}151{"id":"stack-45971314","source":"stackoverflow","questionId":45971314,"title":"Unable to resolve sequelize package","tags":["node.js","macos","npm","sequelize.js","npm-install"],"text":"Title: Unable to resolve sequelize package\nTags: node.js, macos, npm, sequelize.js, npm-install\nSource: Stack Overflow\n\nQuestion:\nI'm trying to install sequelize-cli in my Mac OS 10.12.6.\n\nIn Terminal, I did \n\n`npm install -g sequelize-cli`\n\nI got \n\n```\nnpm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.\n/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/bin/sequelize\n/usr/local/lib\n└── sequelize-cli@2.8.0\n```\n\nThen, I tried \n\n`sequelize model:create --name User --attributes name:string,complete:boolean`\n\nI got \n\n Unable to resolve sequelize package in /Users/bheng/Sites/BASE\n\nI even try with the `--save` as this post suggested.\n\n`npm install -g sequelize-cli --save`\n\nI got same result.\n\n```\nnpm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.\n/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/bin/sequelize\n/usr/local/lib\n└── sequelize-cli@2.8.0\n```\n\n`sequelize model:create --name User --attributes name:string,complete:boolean`\n\n Unable to resolve sequelize package in /Users/bheng/Sites/BASE\n\nWhat else should I try ?\n\n========================================\n\nTop Answer:\nI had the same issue. I installed `sequelize-cli` forgetting to add `sequelize` itself:\n\n`npm install sequelize`\n\n========================================\n\nCode:\n```text\nnpm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.\n/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/bin/sequelize\n/usr/local/lib\n└── sequelize-cli@2.8.0\n```\n\n```text\nnpm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue\nnpm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.\n/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/bin/sequelize\n/usr/local/lib\n└── sequelize-cli@2.8.0\n```\n\n```text\nnpm install -g sequelize-cli\n```\n\n```text\nsequelize model:create --name User --attributes name:string,complete:boolean\n```\n\n```text\n--save\n```\n\n```text\nnpm install -g sequelize-cli --save\n```\n\n```text\nsequelize model:create --name User --attributes name:string,complete:boolean\n```\n\n```text\nnpm install sequelize-cli\n```\n\n```text\nnpm install --save sequelize\n```\n\n```text\nsequelize-cli\n```\n\n```text\nsequelize\n```\n\n```text\nnpm install sequelize\n```\n\n```text\nsequelize init\n```\n\n```text\nsequelize --help\n```\n\n```text\nUnable to resolve sequelize package in <my-project-directory>\n```\n\n```text\nyarn init\n```\n\n```text\nyarn add <my dependencies>\n```\n\n```text\nyarn add --dev <my development dependencies>\n```\n\n```text\nnpm install --save-dev sequelize sequelize-cli\n```\n\n```text\nnpx sequelize-cli init\n```\n\n```text\nmodels\n```\n\n```text\nmigrations\n```\n\n```text\nsequelize\n```\n\n```text\n// .sequelizerc\n\nconst path = require('path');\n\nmodule.exports = {\n  config: path.resolve('./src/config', 'config.json'),\n  'models-path': path.resolve('./src', 'models'),\n  'seeders-path': path.resolve('./src', 'seeders'),\n  'migrations-path': path.resolve('./src', 'migrations'),\n};\n```\n\n```text\n.sequelizerc\n```\n\n========================================\n\nComments:\n- If someone faces the same issue make sure you install sequelize first\n- how is your answer different than the accepted one?\n- Because it is simple as it is.","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":186,"estimatedTokens":1145}}152{"id":"stack-19433824","source":"stackoverflow","questionId":19433824,"title":"Using Instance Methods in Sequelize","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: Using Instance Methods in Sequelize\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nCan someone help me understand how to use instance methods in Sequelize? I've reviewed the documentation but have found it to be sparse. At present, I am trying to use setPassword and verifyPassword instance methods on my user model. When I try to call the code in the REPL, after having imported the user model and synced the DB, I get the following:\n\n```\n> models.User.setPassword('test');\nTypeError: Object [object Object] has no method 'setPassword'\n```\n\nHere is the code for the user model:\n\n```\nvar bcrypt = require('bcrypt');\n\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('User', {\n email: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { isEmail: true } },\n password: { type: DataTypes.STRING, allowNull: false},\n firstName: {type: DataTypes.STRING},\n lastName: {type: DataTypes.STRING},\n companyName: {type: DataTypes.STRING},\n admin: {type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false,},\n forgotUrl: {type: DataTypes.STRING, unique: true},\n forgotDate: {type: DataTypes.STRING},\n lastLogin: {\n type: DataTypes.DATE,\n defaultValue: DataTypes.NOW\n }\n }, {\n paranoid: true,\n instanceMethods: {\n setPassword: function(password, done) {\n return bcrypt.genSalt(10, function(err, salt) {\n return bcrypt.hash(password, salt, function(error, encrypted) {\n this.password = encrypted;\n this.salt = salt;\n return done();\n });\n });\n },\n verifyPassword: function(password, done) {\n return bcrypt.compare(password, this.password, function(err, res) {\n return done(err, res);\n });\n }\n }\n });\n};\n```\n\n========================================\n\nTop Answer:\nYou define the function as:\n`function(password, done)`\n\nYet you don't supply the done parameter.\nThus, the function leaves done as undefined and calling done() is executing an undefined function.\n\nYou could fix this in 3 ways:\n\n- Default done to a noop function `function () {}`\n\n- Only return `done()` if done is defined\n\n- Supply a done callback when calling the instance function.\n\nThe alternative is to refactor it to return a promise which it resolves on completion.\n\n========================================\n\nCode:\n```text\n> models.User.setPassword('test');\nTypeError: Object [object Object] has no method 'setPassword'\n```\n\n```text\nvar bcrypt = require('bcrypt');\n\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('User', {\n    email: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { isEmail: true } },\n    password: { type: DataTypes.STRING, allowNull: false},\n    firstName: {type: DataTypes.STRING},\n    lastName: {type: DataTypes.STRING},\n    companyName: {type: DataTypes.STRING},\n    admin: {type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false,},\n    forgotUrl: {type: DataTypes.STRING, unique: true},\n    forgotDate: {type: DataTypes.STRING},\n    lastLogin: {\n      type: DataTypes.DATE,\n      defaultValue: DataTypes.NOW\n    }\n  }, {\n    paranoid: true,\n    instanceMethods: {\n      setPassword: function(password, done) {\n        return bcrypt.genSalt(10, function(err, salt) {\n          return bcrypt.hash(password, salt, function(error, encrypted) {\n            this.password = encrypted;\n            this.salt = salt;\n            return done();\n          });\n        });\n      },\n      verifyPassword: function(password, done) {\n        return bcrypt.compare(password, this.password, function(err, res) {\n          return done(err, res);\n        });\n      }\n    }\n  });\n};\n```\n\n```text\nmodels.User.find(123).success( function( user ) { \n    user.setPassword('test');\n});\n```\n\n```text\nfunction(password, done)\n```\n\n```text\nfunction () {}\n```\n\n```text\ndone()\n```\n\n========================================\n\nComments:\n- Why the returns before all your callback calls?\n- the use of `this` in the `setPassword` instance method will fail to refer to the actual User instance.\n- Ahh, that makes perfect sense. Do you have any idea why I am getting `TypeError: undefined is not a function` from `return done()` when I run: `> models.User.find(1).success( function( user ) { user.setPassword('password'); });`\n- no idea . I'm using this construct in my project without a problem\n- surfearth. \"done\" is the second parameter to setPassword, which has to be a function as you call it \"return done();\". You aren't passing in a parameter, so \"done\" is undefined and is not a function.","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":145,"estimatedTokens":1122}}153{"id":"stack-40709409","source":"stackoverflow","questionId":40709409,"title":"Unhandled rejection SequelizeUniqueConstraintError: Validation error","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Unhandled rejection SequelizeUniqueConstraintError: Validation error\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting this error:\n\n```\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n```\n\nHow can I fix this?\n\nThis is my models/user.js\n\n```\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define(\"User\", {\n id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true},\n name: DataTypes.STRING,\n environment_hash: DataTypes.STRING\n }, {\n tableName: 'users',\n underscored: false,\n timestamps: false\n }\n\n );\n\n return User;\n};\n```\n\nAnd this is my routes.js:\n\n```\napp.post('/signup', function(request, response){\n\n console.log(request.body.email);\n console.log(request.body.password);\n\n User\n .find({ where: { name: request.body.email } })\n .then(function(err, user) {\n if (!user) {\n console.log('No user has been found.');\n\n User.create({ name: request.body.email }).then(function(user) {\n // you can now access the newly created task via the variable task\n console.log('success');\n });\n\n } \n });\n\n });\n```\n\n========================================\n\nTop Answer:\nCheck in your database if you have an **Unique Constraint** created, my guess is that you put some value to `unique: true` and changed it, but sequelize wasn't able to delete it's constraint from your database.\n\n========================================\n\nCode:\n```text\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n```\n\n```text\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define(\"User\", {\n    id:  { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true},\n    name: DataTypes.STRING,\n    environment_hash: DataTypes.STRING\n  }, {\n    tableName: 'users',\n    underscored: false,\n    timestamps: false\n  }\n\n  );\n\n  return User;\n};\n```\n\n```text\napp.post('/signup', function(request, response){\n\n        console.log(request.body.email);\n        console.log(request.body.password);\n\n        User\n        .find({ where: { name: request.body.email } })\n            .then(function(err, user) {\n                if (!user) {\n                        console.log('No user has been found.');\n\n                        User.create({ name: request.body.email }).then(function(user) {\n                            // you can now access the newly created task via the variable task\n                            console.log('success');\n                        });\n\n                } \n            });\n\n\n\n    });\n```\n\n```text\nUser.create({ name: request.body.email })\n.then(function(user) {\n    // you can now access the newly created user\n    console.log('success', user.toJSON());\n})\n.catch(function(err) {\n    // print the error details\n    console.log(err, request.body.email);\n});\n```\n\n```text\ntry {\n  const user = await User.create({ name: request.body.email });\n  // you can now access the newly created user\n  console.log('success', user.toJSON());\n} catch (err) {\n  // print the error details\n  console.log(err, request.body.email);\n}\n```\n\n```text\nUser.create()\n```\n\n```text\nPromise.reject()\n```\n\n```text\n.catch(err)\n```\n\n```text\nrequest.body.email\n```\n\n```text\nunique: true\n```\n\n```text\nunique:true\n```\n\n```text\nSequelizeUniqueConstraintError\n```\n\n```text\nNULL\n```\n\n```text\nValidation error\n```\n\n```text\nreset auto increment counter\n```\n\n========================================\n\nComments:\n- With the try/catch option, interestingly, it goes to the catch section and shows \"TypeError: (intermediate value) is not iterable\", even though the record is inserted in the table\n- @golimar that might be an issue with the call to `toJSON()` - can you leave it out and set a breakpoint to debug?\n- Thanks, doing that I realized I was assigning the create() output to 2 variables and it only returns 1 value (quite a misleading error message)\n- Thanks!. Im just amazed at how sequelize dont have a transparent solution to this on PG, and also a counter-intuitive error code.","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":187,"estimatedTokens":1001}}154{"id":"stack-36470053","source":"stackoverflow","questionId":36470053,"title":"sequelize update transaction","tags":["node.js","transactions","sequelize.js"],"text":"Title: sequelize update transaction\nTags: node.js, transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequalize transaction in Nodejs,but my problem is that it don't take my `users` table in Transaction and update my table\n\n```\nreturn sequelize.transaction(function (t) {\n var Users = objAllTables.users.users();\n return Users.update(updateUser, {\n where: {\n uid: sessionUser.uid,\n status: 'ACTIVE'\n }\n },{ transaction: t }).then(function (result) {\n\n return Utils.sendVerificationEmail(sessionUser.uid, sessionUser.user_email)\n .then(function(data){\n data = false; \n if(data == false){\n throw new Error('Failed Email');\n }\n\n });\n\n }).then(function (result) {\n console.log(result);\n // Transaction has been committed\n // result is whatever the result of the promise chain returned to the transaction callback\n })\n\n}).catch(function(err){\n res.send({message:err.message})\n})\n```\n\n**CONSOLE:**\n\n```\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): START TRANSACTION;\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): SET autocommit = 1;\nExecuting (default): UPDATE `users` SET `username`='edited' WHERE `uid` = 20 AND `status` = 'ACTIVE'\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): ROLLBACK;\n```\n\nAs you can see in the console update query run out of the transaction\n\n========================================\n\nCode:\n```text\nreturn sequelize.transaction(function (t) {\n    var Users = objAllTables.users.users();\n    return Users.update(updateUser, {\n        where: {\n            uid: sessionUser.uid,\n            status: 'ACTIVE'\n        }\n    },{ transaction: t }).then(function (result) {\n\n       return Utils.sendVerificationEmail(sessionUser.uid, sessionUser.user_email)\n            .then(function(data){\n                 data = false;  \n                if(data == false){\n                        throw new Error('Failed Email');\n                }\n\n            });\n\n\n    }).then(function (result) {\n        console.log(result);\n        // Transaction has been committed\n        // result is whatever the result of the promise chain returned to the transaction callback\n    })\n\n}).catch(function(err){\n    res.send({message:err.message})\n})\n```\n\n```text\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): START TRANSACTION;\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): SET autocommit = 1;\nExecuting (default): UPDATE `users` SET `username`='edited' WHERE `uid` = 20 AND `status` = 'ACTIVE'\nExecuting (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): ROLLBACK;\n```\n\n```text\nusers\n```\n\n```text\nreturn Users.update(updateUser, {\n        where: {\n            uid: sessionUser.uid,\n            status: 'ACTIVE'\n        },\n        transaction: t     //second parameter is \"options\", so transaction must be in it\n    })\n```\n\n```text\ntransaction\n```\n\n```text\noptions\n```\n\n========================================\n\nComments:\n- I want to print the same Excution in my console. Hoe to do that?\n- @shumanachowdhury you need to enable logging in sequelize options while connecting to database. see this\n- what if we use destroy method of sequelize ? i-e users.destroy()\n- @AhmerSaeed `destroy` takes only 1 parameter, you have to pass all options in it. *i.e.* `users.destroy({ where: { id: 57 }, transaction: t })`\n- For anyone searching for this (since I occassionally do), the sequelize doc for the update function can be found here (since Google doesn't always find it too well in my opinion): sequelize.org/master/class/lib/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":121,"estimatedTokens":916}}155{"id":"stack-43862055","source":"stackoverflow","questionId":43862055,"title":"How to .update() value to NULL in sequelize","tags":["javascript","database","postgresql","sequelize.js"],"text":"Title: How to .update() value to NULL in sequelize\nTags: javascript, database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm writing my service to update a row using sequelize for PostGres. When I try out my query using a PSequel it works fine:\n\n```\nUPDATE \"test_table\" SET \"test_col\"=NULL WHERE \"id\"= '2'\n```\n\nBut using sequelize it throws a 500 error:\n\n```\ndb.TestTable.update({ testCol: NULL }, { where: { id: id } })\n .then((count) => {\n if (count) {\n return count;\n }\n });\n```\n\nMy model does allowNull which I believe is what allows null values to be the default as well as set:\n\n```\ntestCol: {\n type: DataTypes.INTEGER,\n allowNull: true,\n defaultValue: null,\n field: 'test_col'\n},\n```\n\nAny other value but NULL works as expected. Is there a different method for setting null values?\n\n========================================\n\nTop Answer:\nHave you checked a more detailed error message in logs? I'd suggest you to add a promise catching error and then update your question. \n\nFor now, my guess is that you created your connection with `omitNull: true`. Call an update function with just one null property probably is the reason of error 500 because it'll generate a incomplete `UPDATE` command (without `SET`).\n\nTry to set `omitNull: false` or, if you cannot do this test, try to update this way:\n\n```\ndb.TestTable.testCol = null;\ndb.TestTable.save(['testCol']);\n```\n\nMore info here.\n\n========================================\n\nCode:\n```text\nUPDATE \"test_table\" SET \"test_col\"=NULL WHERE \"id\"= '2'\n```\n\n```text\ndb.TestTable.update({ testCol: NULL }, { where: { id: id } })\n  .then((count) => {\n    if (count) {\n      return count;\n    }\n  });\n```\n\n```text\ntestCol: {\n  type: DataTypes.INTEGER,\n  allowNull: true,\n  defaultValue: null,\n  field: 'test_col'\n},\n```\n\n```text\ndb.TestTable.update({ testCol: null }, { where: { id: id } })\n  .then((count) => {\n    if (count) {\n      return count;\n    }\n  });\n```\n\n```text\ndb.TestTable.testCol = null;\ndb.TestTable.save(['testCol']);\n```\n\n```text\nomitNull: true\n```\n\n```text\nUPDATE\n```\n\n```text\nSET\n```\n\n```text\nomitNull: false\n```\n\n```text\ncontract.set(\"bid\", dataset.bid ?? null); // set `bid` to `null` if the value is `undefined`\n    contract.changed(\"bid\", true); // mark `bid` as changed\n    return contract.save({ omitNull: false }).then(async (contract) => {  // make sure to write null values\n    ...\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- strange, it seems the column structure no problem to me\n- where: { id: id } give id ad no 2 or define it\n- Sunil - I have done that before. Finding the correct row to update is not the problem right now as I can update it to any other value but null.\n- Read and act on minimal reproducible example.\n- This works most of the time, depending on the global configuration of Sequelize you may still run into problems where it is not deleting null values. For this scenario, you may need to add the `omitNull: false` flag to the update options.","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":129,"estimatedTokens":752}}156{"id":"stack-43167937","source":"stackoverflow","questionId":43167937,"title":"sequelize Nested include with where clause","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: sequelize Nested include with where clause\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize for some filtering.\n\nMy current table structure:\n\n- Table1 holds Items (which has images) and Users (irrelevant)\n\n- Table1 has a direct relationship to Table2 through Table2id on Table1 (not to Table3)\n\n- Table2 has a direct relationship to Table3 through Table3id on Table2 (not to Table4)\n\n- Table3 has a direct relationship to Table4 through Table4id on Table3\n\nI want to filter on Table3 and Table4 as well, considering I can only filter on Table2 using the top-level where-clause.\n\nThe way I fill out my where condition is just using a base object:\n\n```\nvar Table2id = parseInt(req.query.Table2id) || null,\n Table3id = parseInt(req.query.Table3id) || null,\n Table4id = parseInt(req.query.Table4id) || null,\n whereCondition = { deleted: 0 }\n\nif (Table2id) { whereCondition['table2id'] = Table2id }\nif (Table3id) { whereCondition['table3id'] = Table3id }\nif (Table4id) { whereCondition['table4id'] = Table4id }\n\nTable1.findAndCountAll({\n limit: limit,\n offset: offset,\n order: 'created_at DESC',\n where: whereCondition,\n include: [\n {\n model: User,\n }, {\n model: Item,\n include: [\n {\n model: Image\n }\n ]\n }, {\n model: Table2,\n include: [\n {\n model: Table3,\n include: [\n {\n model: Table4,\n }\n ]\n }\n ]\n }\n ],\n}).then(function (results) { res.json(results) })\n```\n\nI tried using some hacks I discovered like `whereCondition['$Table3.table3id$'] = Table3id` but to no avail.\n\nHow can I filter on nested includes? Is there another way I can structure the query so I don't have to have nested includes, but still retain this data structure (is there even a better way to structure this than what I've thought of)?\n\nedit: So I would like to both be able to sort on the tables included, and have at least one parameter set in the top-level where-clause (like deleted = 0).\n\nI've tried modifying the query as follows:\n\n```\nvar Table2id = parseInt(req.query.Table2id) || null,\n Table3id = parseInt(req.query.Table3id) || null,\n Table4id = parseInt(req.query.Table4id) || null,\n whereCondition = { deleted: 0 },\n extraWhereCondition = {}\n\nif (Table2id) { whereCondition['table2id'] = Table2id } // figured this can be left alone in this particular case (as it works in top-level where clause)\nif (Table3id) { extraWhereCondition['table3id'] = Table3id }\nif (Table4id) { extraWhereCondition['table4id'] = Table4id }\n\nTable1.findAndCountAll({\n limit: limit,\n offset: offset,\n order: 'created_at DESC',\n where: whereCondition,\n include: [\n {\n model: User,\n }, {\n model: Item,\n include: [\n {\n model: Image\n }\n ]\n }, {\n model: Table2,\n include: [\n {\n model: Table3,\n where: extraWhereCondition,\n include: [\n {\n model: Table4,\n where: extraWhereCondition,\n }\n ]\n }\n ]\n }\n ],\n}).then(function (results) { res.json(results) })\n```\n\nBut this gives me an error that Table2.Table3.Table4.table4id is unknown in field list.\n\n========================================\n\nCode:\n```text\nvar Table2id       = parseInt(req.query.Table2id) || null,\n    Table3id       = parseInt(req.query.Table3id) || null,\n    Table4id       = parseInt(req.query.Table4id) || null,\n    whereCondition = { deleted: 0 }\n\nif (Table2id) { whereCondition['table2id'] = Table2id }\nif (Table3id) { whereCondition['table3id'] = Table3id }\nif (Table4id) { whereCondition['table4id'] = Table4id }\n\nTable1.findAndCountAll({\n        limit: limit,\n        offset: offset,\n        order: 'created_at DESC',\n        where: whereCondition,\n        include: [\n            {\n                model: User,\n            }, {\n                model: Item,\n                include: [\n                    {\n                        model: Image\n                    }\n                ]\n            }, {\n                model: Table2,\n                include: [\n                    {\n                        model: Table3,\n                        include: [\n                            {\n                                model: Table4,\n                            }\n                        ]\n                    }\n                ]\n            }\n        ],\n}).then(function (results) { res.json(results) })\n```\n\n```text\nvar Table2id       = parseInt(req.query.Table2id) || null,\n    Table3id       = parseInt(req.query.Table3id) || null,\n    Table4id       = parseInt(req.query.Table4id) || null,\n    whereCondition = { deleted: 0 },\n    extraWhereCondition = {}\n\nif (Table2id) { whereCondition['table2id'] = Table2id } // figured this can be left alone in this particular case (as it works in top-level where clause)\nif (Table3id) { extraWhereCondition['table3id'] = Table3id }\nif (Table4id) { extraWhereCondition['table4id'] = Table4id }\n\nTable1.findAndCountAll({\n        limit: limit,\n        offset: offset,\n        order: 'created_at DESC',\n        where: whereCondition,\n        include: [\n            {\n                model: User,\n            }, {\n                model: Item,\n                include: [\n                    {\n                        model: Image\n                    }\n                ]\n            }, {\n                model: Table2,\n                include: [\n                    {\n                        model: Table3,\n                        where: extraWhereCondition,\n                        include: [\n                            {\n                                model: Table4,\n                                where: extraWhereCondition,\n                            }\n                        ]\n                    }\n                ]\n            }\n        ],\n}).then(function (results) { res.json(results) })\n```\n\n```text\nwhereCondition['$Table3.table3id$'] = Table3id\n```\n\n```js\nvar Table2 = require(\"../models/\").table2; //and other model that u need\n\nvar option = {\n  limit: limit,\n  offset: offset,\n  order: \"created_at DESC\",\n  where: { deleted: 0 },\n  include: [\n    {\n      model: User,\n    },\n    {\n      model: Item,\n      required: true,\n\n      include: [\n        {\n          model: Image,\n        },\n      ],\n    },\n    {\n      model: Table2,\n      include: [\n        {\n          model: Table3,\n          where: { deleted: 0 },\n          include: [\n            {\n              model: Table4,\n              where: { deleted: 0 },\n            },\n          ],\n        },\n      ],\n    },\n  ],\n};\n\nTable1.findAndCountAll(option).then(function (results) {\n  res.json(results);\n});\n```\n\n```text\nwhere\n```\n\n```text\nwhere condition\n```\n\n```text\ninclude\n```\n\n```text\nrequired true and false\n```\n\n```text\neager-loading\n```\n\n========================================\n\nComments:\n- you can put where clause in each include\n- @Adiii That gives me an `unknown column 'Table2.Table3.Table4.Table4id' in field list` error.\n- what do you need? actually, i did not get your question if u need where clause in inner include then let me know\n- var user = require('../models/').table1; var user = require('../models/').table2; include: [{ model: table1, required: true, include: [ { model: table2, required: true, where:{condtion} } ] }]\n- docs.sequelizejs.com/en/latest/docs/models-usage/#eager-load&zwnj;&#8203;ing\n- All the models are included, couldn't find anything related to my question in the docs which is why I've taken to SO.\n- but the way you putting where in inner include​ its not valid according to doc\n- Thanks, you're completely correct. Sorry... I followed your direction and also changed the way I assigned the where clauses (by looking through the code a little closer). Completely missed out on my own train of thought...\n- can i post that to accept as a answer ;)\n- Yeah, man, of course. I'll happily give you points :D\n- hehe okay check it this will help you to make option then use in your class","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":291,"estimatedTokens":1929}}157{"id":"stack-48297419","source":"stackoverflow","questionId":48297419,"title":"How to lock table in sequelize, wait until another request to be complete","tags":["node.js","sequelize.js"],"text":"Title: How to lock table in sequelize, wait until another request to be complete\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**Description:**\n\nI have one table in db say `Table1`. having only one column `AppNo(numeric)` and only single row, and current value is `0`\n\nI have created API in `node.js` using `Sequelize` ORM named `UpdateAppNo`.\n\nWhenever `UpdateAppNo` api called value of `AppNo` should increment by `1`.\n\n**What i want:**\n\nIf 2 or more simultaneous request comes at a time, current request should wait until previous request to complete.\n\n**What happening now:**\n\nIf previous request is in process, then current request throws an error.\n\n========================================\n\nTop Answer:\nThis is old, but also the first google hit, so I'm posting this in case others have stumbled here.\n\nAs Chase said this is not at all well documented. Here's some code that will do what you want...\n\n\r\n\r\n\n```\nconst User = db.User\n\nconst t = await sequelize.transaction(async(t) => {\n const user = await User.findByPk(userId, {lock: true, transaction: t})\n user.fieldToIncrement++\n await user.save({transaction:t})\n})\n```\n\n\r\n\r\n\r\n\nKey points:\n\nThis code example is using the \"Managed\" transaction provided by Sequelize, so you don't need to manually manage commit/rollback, however the same will work with unmanaged transactions\n\n**You need to provide the lock option as well as the transaction**, otherwise the transaction occurs without the lock you are looking for. Requests to update the table row while it's locked will balk until the lock is released.\n\n**Don't forget to include the transaction object** in the options for any database actions inside the transaction context (see the call to user.save() ), otherwise your transaction will balk on itself...\n\nI hope that's helpful to someone!\n\n========================================\n\nCode:\n```text\nTable1\n```\n\n```text\nAppNo(numeric)\n```\n\n```text\n0\n```\n\n```text\nnode.js\n```\n\n```text\nSequelize\n```\n\n```text\nUpdateAppNo\n```\n\n```text\nUpdateAppNo\n```\n\n```text\nAppNo\n```\n\n```text\n1\n```\n\n```js\nreturn User.findAll({\n  limit: 1,\n  lock: true, // <-- this does the trick\n  transaction: t1\n});\n```\n\n```text\n.findXX\n```\n\n```text\nlock\n```\n\n```text\nSELECT FOR UPDATE\n```\n\n```text\nlock\n```\n\n```js\nconst User = db.User\n\nconst t = await sequelize.transaction(async(t) => {\n  const user = await User.findByPk(userId, {lock: true, transaction: t})\n  user.fieldToIncrement++\n  await user.save({transaction:t})\n})\n```\n\n========================================\n\nComments:\n- Thanks for this answer, can we have live example for this...it will be help full.\n- @PiyushDhamecha have you find a working solution in the end?\n- none of the links work now and without them this answer is meaningless\n- Here's the link to locks: sequelize.org/docs/v6/other-topics/transactions/#locks\n- If another process already locks the row is the transaction commit will wait until the lock is released or will it fail?","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":136,"estimatedTokens":739}}158{"id":"stack-19075805","source":"stackoverflow","questionId":19075805,"title":"Sequelize associations hasOne, belongsTo","tags":["node.js","postgresql","orm","sequelize.js"],"text":"Title: Sequelize associations hasOne, belongsTo\nTags: node.js, postgresql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe problem is that I can not get working the relation hasOne, which does not eager load the state type object.\n\nAll the queries are done on existing tables.\n\nHere is the customer table, whats important is the `cst_state_type` field:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\n return sequelize.define('customer', {\n\n customer: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n allowNull: true,\n validate: {\n isNumeric: true\n }\n },\n first_name: {\n type: DataTypes.STRING(100),\n validate: {\n isAlphanumeric: true\n }\n },\n last_name: DataTypes.STRING(100),\n identity_code: {\n type: DataTypes.STRING(20),\n allowNull: true,\n validate: {\n isNumeric: true\n }\n },\n note: DataTypes.STRING(1000),\n birth_date: DataTypes.DATE,\n\n created_by: DataTypes.INTEGER,\n updated_by: DataTypes.INTEGER,\n\n cst_type: DataTypes.INTEGER,\n cst_state_type: {\n type: DataTypes.INTEGER,\n }\n\n }, {\n tableName: 'customer',\n\n updatedAt: 'updated',\n createdAt: 'created',\n timestamps: true\n });\n};\n```\n\ncst_state_type table:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\n return sequelize.define('StateType', {\n\n cst_state_type: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n validate: {\n }\n },\n name: DataTypes.STRING(100),\n }, {\n tableName: 'cst_state_type',\n timestamps: false\n });\n};\n```\n\nHow the relations are described: \n\n```\nglobal.db.Customer.hasOne(global.db.StateType, {\n foreignKey: 'cst_state_type',\n as: 'state_type'\n });\n\n global.db.StateType.belongsTo(global.db.Customer, {\n foreignKey: 'cst_state_type'\n });\n```\n\nAnd creating eager loading query: \n\n```\ndb.Customer.findAll( {\n include: [\n { model: db.Address, as: 'addresses' },\n { model: db.StateType, as: 'state_type' }\n ]\n })\n .success(function (customers) {\n res.json(200, customers);\n })\n .fail(function (error) {\n res.json(500, { msg: error });\n });\n```\n\n========================================\n\nTop Answer:\nThanks for you answer, it helped me a lot. You can also add the relations directly in your model by using classmethods. I added a example below, hope this helps!\n\n**User** Model (file)\n\n```\nmodule.exports = function(sequelize, DataTypes){\n var User = sequelize.define(\n 'User', {\n name: {\n type: DataTypes.STRING,\n allowNull: false\n }\n },\n {\n classMethods:{\n associate:function(models){\n User.hasMany(models.Comment, { foreignKey: 'userId'} );\n }\n }\n }\n\n );\n return User;\n};\n```\n\n**Comment** Model (file):\n\n```\nmodule.exports = function(sequelize, DataTypes){\n var Comment = sequelize.define(\n 'Comment', {\n text: {\n type: DataTypes.STRING,\n allowNull: false\n }\n },\n {\n classMethods:{\n associate:function(models){\n Comment.belongsTo(models.User, { foreignKey:'userId'} );\n }\n }\n }\n\n );\n return Comment;\n};\n```\n\nYou don't have to set the foreignkey, sequelize will handle it if you don't specify the foreignkeys.\n\nThen in the query:\n\n```\nmodels.Comment.find({\n where: { id: id },\n include: [\n models.User\n ],\n limit: 1\n })\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n    return sequelize.define('customer', {\n\n        customer: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true,\n            allowNull: true,\n            validate: {\n                isNumeric: true\n            }\n        },\n        first_name: {\n            type: DataTypes.STRING(100),\n            validate: {\n                isAlphanumeric: true\n            }\n        },\n        last_name: DataTypes.STRING(100),\n        identity_code: {\n            type: DataTypes.STRING(20),\n            allowNull: true,\n            validate: {\n                isNumeric: true\n            }\n        },\n        note: DataTypes.STRING(1000),\n        birth_date: DataTypes.DATE,\n\n\n        created_by: DataTypes.INTEGER,\n        updated_by: DataTypes.INTEGER,\n\n        cst_type: DataTypes.INTEGER,\n        cst_state_type:  {\n            type: DataTypes.INTEGER,\n        }\n\n    }, {\n        tableName: 'customer',\n\n        updatedAt: 'updated',\n        createdAt: 'created',\n        timestamps: true\n    });\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n    return sequelize.define('StateType', {\n\n        cst_state_type: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true,\n            validate: {\n            }\n        },\n        name: DataTypes.STRING(100),\n    }, {\n        tableName: 'cst_state_type',\n        timestamps: false\n    });\n};\n```\n\n```text\nglobal.db.Customer.hasOne(global.db.StateType, {\n    foreignKey: 'cst_state_type',\n    as: 'state_type'\n  });\n\n  global.db.StateType.belongsTo(global.db.Customer, {\n    foreignKey: 'cst_state_type'\n  });\n```\n\n```text\ndb.Customer.findAll( {\n        include: [\n            { model: db.Address, as: 'addresses' },\n            { model: db.StateType, as: 'state_type' }\n        ]\n    })\n        .success(function (customers) {\n            res.json(200, customers);\n        })\n        .fail(function (error) {\n            res.json(500, { msg: error });\n        });\n```\n\n```text\ncst_state_type\n```\n\n```text\nglobal.db.Customer.belongsTo(global.db.StateType, {\n    foreignKey: 'cst_state_type',\n    as: 'state_type'\n});\n\nglobal.db.StateType.hasMany(global.db.Customer, {\n    foreignKey: 'cst_state_type'\n});\n```\n\n```text\nStateType.hasMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes){\n    var User = sequelize.define(\n        'User', {\n            name: {\n                type: DataTypes.STRING,\n                allowNull: false\n            }\n        },\n        {\n            classMethods:{\n                associate:function(models){\n                    User.hasMany(models.Comment, { foreignKey: 'userId'} );\n                }\n            }\n        }\n\n    );\n    return User;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes){\n    var Comment = sequelize.define(\n        'Comment', {\n            text: {\n                type: DataTypes.STRING,\n                allowNull: false\n            }\n        },\n        {\n            classMethods:{\n                associate:function(models){\n                    Comment.belongsTo(models.User, { foreignKey:'userId'} );\n                }\n            }\n        }\n\n    );\n    return Comment;\n};\n```\n\n```text\nmodels.Comment.find({\n        where: { id: id },\n        include: [\n            models.User\n        ],\n        limit: 1\n    })\n```\n\n========================================\n\nComments:\n- Excellent example! Simple and functional.\n- upvoted! do you have to add BOTH user.hasMany and Comments.belongsTo or one of them will suffice? if one then which one?","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":360,"estimatedTokens":1694}}159{"id":"stack-34258938","source":"stackoverflow","questionId":34258938,"title":"Sequelize classMethods vs instanceMethods","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize classMethods vs instanceMethods\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo starting my adventure into all things Node. One of the tools I am trying to learn is Sequelize. So I will start off what I was trying to do: \n\n```\n'use strict';\nvar crypto = require('crypto');\n\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define('User', {\n username: DataTypes.STRING,\n first_name: DataTypes.STRING,\n last_name: DataTypes.STRING,\n salt: DataTypes.STRING,\n hashed_pwd: DataTypes.STRING\n }, {\n classMethods: {\n\n },\n instanceMethods: {\n createSalt: function() {\n return crypto.randomBytes(128).toString('base64');\n },\n hashPassword: function(salt, pwd) {\n var hmac = crypto.createHmac('sha1', salt);\n\n return hmac.update(pwd).digest('hex');\n },\n authenticate: function(passwordToMatch) {\n return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;\n }\n }\n });\n return User;\n};\n```\n\nI am confused on when to use `classMethods` vs `instanceMethods`. To me when I think about `createSalt()` and `hashPassword()` should be class methods. They are general and for the most part dont really have anything to do with the specific instance they are just used in general. But when I have `createSalt()` and `hashPassword()` in `classMethods` I cannot call them from `instanceMethods`.\n\nI have tried variations of the following:\n\n```\nthis.createSalt();\nthis.classMethods.createSalt();\ncreateSalt();\n```\n\nSomething like below wont work and I am probably just not understanding something simple. \n\n```\nauthenticate: function(passwordToMatch) {\n console.log(this.createSalt());\n return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;\n}\n```\n\nAny hints/tips/direction would be very much so appreciated!\n\n========================================\n\nTop Answer:\nAlthough the basics are that `instance` methods should be used when you want to modify your `instance` ( ergo row ). I would rather not pollute the `classMethods` with methods that don't use the `class` ( ergo the table ) itself.\n\nIn your example I would put `hashPassword` function outside your class and leave it as a helper function somewhere in my utilities module ( or why not the same module but as a normal defined function ) ... like\n\n```\nvar hashPassword = function(...) { ... }\n\n...\n\n...\n\n instanceMethods: { \n authenticate: function( ... ) { hashPassword( ... ) }\n }\n```\n\n========================================\n\nCode:\n```js\n'use strict';\nvar crypto = require('crypto');\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define('User', {\n    username: DataTypes.STRING,\n    first_name: DataTypes.STRING,\n    last_name: DataTypes.STRING,\n    salt: DataTypes.STRING,\n    hashed_pwd: DataTypes.STRING\n  }, {\n    classMethods: {\n\n    },\n    instanceMethods: {\n      createSalt: function() {\n        return crypto.randomBytes(128).toString('base64');\n      },\n      hashPassword: function(salt, pwd) {\n        var hmac = crypto.createHmac('sha1', salt);\n\n        return hmac.update(pwd).digest('hex');\n      },\n      authenticate: function(passwordToMatch) {\n        return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;\n      }\n    }\n  });\n  return User;\n};\n```\n\n```text\nthis.createSalt();\nthis.classMethods.createSalt();\ncreateSalt();\n```\n\n```text\nauthenticate: function(passwordToMatch) {\n  console.log(this.createSalt());\n  return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;\n}\n```\n\n```text\nclassMethods\n```\n\n```text\ninstanceMethods\n```\n\n```text\ncreateSalt()\n```\n\n```text\nhashPassword()\n```\n\n```text\ncreateSalt()\n```\n\n```text\nhashPassword()\n```\n\n```text\nclassMethods\n```\n\n```text\ninstanceMethods\n```\n\n```js\n// Should be a classMethods\nfunction getMyFriends() {\n  return this.find({where{...}})\n}\n\n// Should be a instanceMethods\nfunction checkMyName() {\n  return this.name === \"george\";\n}\n```\n\n```text\nclassMethod\n```\n\n```text\ninstanceMethod\n```\n\n```text\nvar hashPassword = function(...) { ... }\n\n...\n\n...\n\n  instanceMethods: { \n     authenticate: function( ... ) { hashPassword( ... ) }\n  }\n```\n\n```text\ninstance\n```\n\n```text\ninstance\n```\n\n```text\nclassMethods\n```\n\n```text\nclass\n```\n\n```text\nhashPassword\n```\n\n```text\nvar myModel = sequelize.define('model', {\n\n}, {\n  classMethods: {\n    someClassMethod: function() {\n      return true;\n    }\n}, {\n  instanceMethods: {\n    callClassMethod: function() {\n      myModel.someClassMethod();\n    }\n  }\n});\n```\n\n========================================\n\nComments:\n- That makes sense to me and thats what I kind of figured so general functions such as makeSalt() and hashPassword() should be class methods because they really have nothing to do with the specific instance. SO that said now my real problem I guess is not being able to call a classMethond inside my instanceMethod and not sure what the deal is.\n- I got on the IRC and they were able to help me out. Its a bit different then I am use too in other languages but thats just part of the learning process! since its a class method it becomes just part of the model so you dont have to use something like \"this.\" you just call it like \"User.getSalt()\" so its all working now as I would have expected!\n- I appreciate your help!\n- I wondered about doing that as well. I think I will go ahead and do it just to get in the habit of doing so. I couldn't decide if it made since to separate it or not since I will only use hashPassword within the User model.","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":237,"estimatedTokens":1370}}160{"id":"stack-29280785","source":"stackoverflow","questionId":29280785,"title":"Calling stored procedures in Sequelize.js","tags":["node.js","sequelize.js"],"text":"Title: Calling stored procedures in Sequelize.js\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have searched documentation and tried google that, but I did not find a straight answer to the question: \n\n**How can I call a stored procedure in Sequelize?**\n\nI have searched the documentation of Sequelize but I have even not found a trace of the word \"procedure\" in that.\n\nThe closest I got was this bug-report-turned-feature-request:\nhttps://github.com/sequelize/sequelize/issues/959\n\nQuoting from the link:\n\n*What I imagine would be awesome:*\n\n```\nsequelize.query('CALL calculateFees();').success(\n function (settingName1, settingName2, settingName3, users) {\n});\n```\n\nThey mention that it is possible to call stored procedures, but the syntax is not provided.\n\n**Can anyone give me an example with the proper syntax?**\n\nThanks.\n\n========================================\n\nTop Answer:\nChange `success` to `spread` and you're good to go. Note that this will only work on sequlize 2.0\n\n========================================\n\nCode:\n```text\nsequelize.query('CALL calculateFees();').success(\n    function (settingName1, settingName2, settingName3, users) {\n});\n```\n\n```text\nsequelize\n  .query('CALL login (:email, :pwd, :device)', \n        {replacements: { email: \"me@jsbot.io\", pwd: 'pwd', device: 'android', }})\n  .then(v=>console.log(v));\n```\n\n```text\nsuccess\n```\n\n```text\nspread\n```\n\n```text\nsequelize.query('CALL calculateFees();').then(function(response){\n     res.json(response);\n    }).error(function(err){\n       res.json(err);\n});\n```\n\n```text\nsequelize\n.query('EXEC getData :@param1', { replacements: { @param1: 'Test'}, type:sequelize.QueryTypes.SELECT })\n.then(data => /*Do something with the data*/)\n.catch(error => /*Do something with the error*/)\n```\n\n```js\nmodels.sequelize.query('DECLARE @outParam1 INT, @outParam2 INT EXEC procedureName @param1=:param, @outParam1 = @outParam1 output, @outParam2 = @outParam2 output SELECT @outParam1 AS \"outParam1\", @outParam2 AS \"outParam2\"',\n    {\n    replacements:\n    {\n        param: 123\n        },\n        type: models.sequelize.QueryTypes.EXEC\n    }).spread(result => {\n    if (result)\n    {\n        console.log(\"\\nInside result : \" + JSON.stringify(result));\n        //return response here\n    }\n```\n\n```text\ndb.query('EXEC STORED_PROCEDURE_NAME :startDate, :endDate',\n        { replacements: { startDate: moment(payload.startDate).format('YYYY-MM-DD HH:mm:ss'), endDate: moment(payload.endDate).format('YYYY-MM-DD HH:mm:ss')},\n          raw: true }\n      )\n```\n\n```text\nconst existing = await db.sequelize.query(`exec Fetch_Details ${AlphaCode},${Id}`, { type: QueryTypes.SELECT });\nif (existing.length>=0) {\n  res.send({\n    status: \"OK\",\n    message: \"Records found!\",\n    result: existing,\n  });\n}\nelse{\n  res.send({\n    status: 404,\n    message: \"Not Found!\"\n    \n  });\n}\n```\n\n```text\nnew Sequalize(db, user, pass, { dialect: 'mysql', dialectOptions: { multipleStatements: true } }\n```\n\n```text\nCREATE PROCEDURE `get_movie`(\n    IN maxFail INT,\n    IN rrender VARCHAR(255),\n    OUT attemptId INT,\n    OUT rmovie_id INT,\n   )\nBEGIN\n\n   SELECT id, movie_id INTO attemptId, rmovie_id FROM `movie_attempts` WHERE `fail_count` < maxFail AND `render` = rrender FOR UPDATE;\n   UPDATE `movie_attempts` SET `status`='processing' WHERE `id`=attemptId;\n   \nEND\n```\n\n```text\nconst [, results] = // notice its not const [results, metadata]\n      await Database.instance.sequelize.query(\n        \"CALL get_movie(:maxFail, :renderer, @attemptId, @movie_id); SELECT @attemptId AS id, @movie_id AS movie_id;\", \n        {\n          replacements: { maxFail: 3, renderer: \"myname\" },\n          type: QueryTypes.SELECT\n        });\n\nconsole.log(\"\\nInside result : \" + JSON.stringify(results));\n```\n\n========================================\n\nComments:\n- So there's no dedicated function for calling the stored procedure just the raw query (with the change of `success` to `spread`)?\n- and where can I define this function? Using it as a prototype function in Model, I am not able to call it outside of model, e.g. in the controller. Otherwise if I use sequelize in the controller itself, it says sequelize is not defined, Is it a good practice to define sequelize in the controller. ? I usually don't see it anywhere. If not what is the best way to define a custom query using sequelize?\n- @RameshPareek you can access Model.sequelize , I'm not sure about the syntax but you can debug the Model prototype, you'll find the sequelize. also you can directly import sequelize from npm\n- Your doing it incorrectly it should look like this EXEC getData @param1=:param1', { replacements: { @param1: 'Test'}","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":153,"estimatedTokens":1164}}161{"id":"stack-43948920","source":"stackoverflow","questionId":43948920,"title":"How to connect via SSL to sequelize DB","tags":["node.js","sequelize.js"],"text":"Title: How to connect via SSL to sequelize DB\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI can't seem to find any documentation for **SEQUELIZE.JS** on how to use a CA.crt in order to enable connection to my database sitting on a remote server. \n\nI figure its something in the options but I can't seem to figure it out\n\nI have tried\n\n```\n{\n 'ssl': true\n 'dialectOptions':{\n ssl: {\n ca: 'path/to/ca'\n }\n } \n}\n```\n\nand a few other things but nothing seem to work for me.\n\nCan anybody help me?\n\nEdit:\n\nHere is an error i get when using the ca thing\n\n```\nerror connecting to db { Error: unable to verify the first certificate\nat TLSSocket.\n```\n\n========================================\n\nTop Answer:\nThanks to Mark's answer above, I was able to connect to a Postgres RDS instance from a Node.js Lambda function as follows:\n\n```\nconst sequelize = new Sequelize(POSTGRES_DATABASE, POSTGRES_USERNAME, POSTGRES_PASSWORD, {\n host: POSTGRES_HOST,\n port: POSTGRES_PORT,\n dialect: 'postgres',\n dialectOptions: {\n ssl: {\n // CAUTION: there are better ways to load the certificate, see comments below\n ca: fs.readFileSync(join(__dirname, 'rds-combined-ca-bundle.pem')).toString()\n }\n }\n });\n```\n\n(Obviously this required the PEM file to be available, see Using SSL/TLS to encrypt a connection to a DB instance)\n\n========================================\n\nCode:\n```text\n{\n 'ssl': true\n 'dialectOptions':{\n   ssl: {\n     ca: 'path/to/ca'\n   }\n }     \n}\n```\n\n```text\nerror connecting to db { Error: unable to verify the first certificate\nat TLSSocket.<anonymous>\n```\n\n```text\nconst connection = mysql.createConnection({\n  host: dbVars.host,\n  user: dbVars.user,\n  database: dbVars.database,\n  password: dbVars.password,\n  ssl: {\n    key: cKey,\n    cert: cCert,\n    ca: cCA\n  }\n});\n```\n\n```text\nconst sequelize = new Sequelize(dbVars.database, dbVars.user, dbVars.password, {\n  host: dbVars.host,\n  dialect: 'mysql',\n  dialectOptions: {\n    ssl: {\n      key: cKey,\n      cert: cCert,\n      ca: cCA\n    }\n  }\n});\n```\n\n```text\nimport cKey from 'raw-loader!../certs/client-key.pem';\n```\n\n```text\nmysql\n```\n\n```text\ndialect\n```\n\n```text\nmysql2\n```\n\n```text\nimport\n```\n\n```text\nraw-loader\n```\n\n```text\nconst sequelize = new Sequelize(POSTGRES_DATABASE, POSTGRES_USERNAME, POSTGRES_PASSWORD, {\n            host: POSTGRES_HOST,\n            port: POSTGRES_PORT,\n            dialect: 'postgres',\n            dialectOptions: {\n              ssl: {\n                // CAUTION: there are better ways to load the certificate, see comments below\n                ca: fs.readFileSync(join(__dirname, 'rds-combined-ca-bundle.pem')).toString()\n              }\n            }\n          });\n```\n\n========================================\n\nComments:\n- In addition to my below, just a quick remark. You need to pass all 3 components, 2 certs and key file in some form.\n- Related: stackoverflow.com/questions/27687546/&hellip;\n- `fs.fileReadSync` works just as well for me to read the .pem files.\n- Per docs it is `fs.readFileSync`.\n- How do I get `cCert` and `cCA`?\n- Read a file, to finally set it as string? 🤔 just copy the pem content into an ENV VAR and use it.\n- You may be right, but that's not really a central feature of the example :)\n- bad practices propagation, is the copy/paste example. Hope anyone read the good alternative. Regards.\n- @NingaCodingTRV fair point, i've updated the example to point here. another alternative is loading the file outside of the handler so that it's available for the invocation context.","metadata":{"transformedAt":"2026-08-18T18:33:34.350Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":153,"estimatedTokens":877}}162{"id":"stack-29036363","source":"stackoverflow","questionId":29036363,"title":"Sequelize: Querying if ARRAY contains a value","tags":["postgresql","sequelize.js"],"text":"Title: Sequelize: Querying if ARRAY contains a value\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSuppose I have a PG ARRAY field:\n\n```\nid | array |\n===|=============|\n 1|{\"1\",\"2\",\"3\"}|\n```\n\nHow do I use sequelize to query to see if the array field as the value `1`.\n\nI tried:\n\n```\narray: { $contains: \"1\" }\n```\n\nwhich gives me:\n\n```\narray @> \"1\"\n```\n\nwith error:\n\n```\nPossibly unhandled SequelizeDatabaseError: array value must start with \"{\" or dimension information\n```\n\n### UPDATE\n\nI was able to do it by:\n array: { $contains: '{' + value + '}' }\n\nIs there a more correct way?\n\n========================================\n\nTop Answer:\nMaybe so.\n\n```\n`{ genres: { $contains: [genreType] } }`\n```\n\n`genres` is an array. `genreType` can also be an array.\n\n```\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('database', 'username', 'password', {\n host: 'localhost',\n dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,\n operatorsAliases: Sequelize.Op.Aliases,\n});\n```\n\n========================================\n\nCode:\n```text\nid |    array    |\n===|=============|\n  1|{\"1\",\"2\",\"3\"}|\n```\n\n```text\narray: { $contains: \"1\" }\n```\n\n```text\narray @> \"1\"\n```\n\n```text\nPossibly unhandled SequelizeDatabaseError: array value must start with \"{\" or dimension information\n```\n\n```text\n1\n```\n\n```text\narray: { [Op.contains]: [\"1\"] }\n```\n\n```text\nconst { Op } = require('sequelize');\n```\n\n```text\nimport { Op } from 'sequelize';\n```\n\n```text\nOp\n```\n\n```text\nsequelize\n```\n\n```text\n`{ genres: { $contains: [genreType] } }`\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,\n  operatorsAliases: Sequelize.Op.Aliases,\n});\n```\n\n```text\ngenres\n```\n\n```text\ngenreType\n```\n\n========================================\n\nComments:\n- Are you storing serialized data in your database, or is that just a visualization?\n- no it is not serialized. it is a PG ARRAY datatype.\n- Update: new syntax is `array: { [Op.contains] : [\"1\"] }`","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":134,"estimatedTokens":531}}163{"id":"stack-22586712","source":"stackoverflow","questionId":22586712,"title":"Updating attributes in associated models using Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Updating attributes in associated models using Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to update attributes on both the parent model and the associated models all in one go? I am having trouble getting it to work and haven't been able to find any full examples. I'm not sure if it's something wrong with my code or if it wasn't intended to work the way I would expect. I tried adding the onUpdate : 'cascade' to my hasMany definition, but that didn't seem to do anything.\n\nModels:\n\n```\nmodule.exports = function( sequelize, DataTypes ) {\nvar Filter = sequelize.define( 'Filter', {\n id : {\n type : DataTypes.INTEGER,\n autoIncrement : true,\n primaryKey : true\n },\n userId : DataTypes.INTEGER,\n filterRetweets : DataTypes.BOOLEAN,\n filterContent : DataTypes.BOOLEAN\n },\n {\n tableName : 'filter',\n timestamps : false\n }\n);\n\nvar FilteredContent = sequelize.define( 'FilteredContent', {\n id : {\n type : DataTypes.INTEGER,\n autoIncrement : true,\n primaryKey : true\n },\n filterId : {\n type : DataTypes.INTEGER,\n references : \"Filter\",\n referenceKey : \"id\"\n },\n content : DataTypes.STRING\n },\n {\n tableName : \"filteredContent\",\n timestamps : false\n }\n);\n\nFilter.hasMany( FilteredContent, { onUpdate : 'cascade', as : 'filteredContent', foreignKey : 'filterId' } );\nsequelize.sync();\n\n return {\n \"Filter\" : Filter,\n \"FilteredContent\" : FilteredContent\n };\n}\n```\n\nRetrieving the filter and trying to update an attribute on the associated FilteredContent object:\n\n```\nFilter.find({ where: { id: 3 }, \n include: [ { model : FilteredContent, as : 'filteredContent' } ] \n}).success ( function( filter ) {\n var filteredContent = FilteredContent.build( {\n filterId : filter.id,\n id : 2,\n content : 'crap'\n });\n filter.save();\n});\n```\n\nThis results in only attributes in the Filter object being updated. How do I get it to also update the attributes in FilteredContent? \n\nAlso, is the sequelize.sync() necessary after defining my models? I'm not clear on what exactly it is supposed to do. I am able to retrieve my object with associations without it. I added it to my code in desperation to get the updates working, but I'm not sure if it's actually necessary.\n\nThanks\n\n========================================\n\nTop Answer:\nWith `@hatchifyjs/sequelize-create-with-associations` it is as simple as:\n\n```\nawait Filter.update({\n filteredContent: [\n { content: \"x\" },\n { content: \"y\" },\n ]\n}, { where: { id: 3 } });\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function( sequelize, DataTypes ) {\nvar Filter = sequelize.define( 'Filter', {\n    id : {\n            type : DataTypes.INTEGER,\n            autoIncrement : true,\n            primaryKey : true\n         },\n        userId : DataTypes.INTEGER,\n        filterRetweets : DataTypes.BOOLEAN,\n        filterContent : DataTypes.BOOLEAN\n    },\n    {\n        tableName : 'filter',\n        timestamps : false\n    }\n);\n\nvar FilteredContent = sequelize.define( 'FilteredContent', {\n        id : {\n                type : DataTypes.INTEGER,\n                autoIncrement : true,\n                primaryKey : true\n        },\n        filterId : {\n                        type : DataTypes.INTEGER,\n                        references : \"Filter\",\n                        referenceKey : \"id\"\n        },\n        content : DataTypes.STRING\n    },\n    {\n        tableName : \"filteredContent\",\n        timestamps : false\n    }\n);\n\nFilter.hasMany( FilteredContent, { onUpdate : 'cascade', as : 'filteredContent', foreignKey : 'filterId' } );\nsequelize.sync();\n\n    return {\n        \"Filter\" : Filter,\n        \"FilteredContent\" : FilteredContent\n    };\n}\n```\n\n```text\nFilter.find({   where: { id: 3 }, \n            include: [ { model : FilteredContent, as : 'filteredContent' } ] \n}).success ( function( filter ) {\n    var filteredContent = FilteredContent.build( {\n        filterId : filter.id,\n        id : 2,\n        content : 'crap'\n    });\n    filter.save();\n});\n```\n\n```text\nFilter.find({\n  where: { id: 3 }, \n  include: [ { model : FilteredContent, as : 'filteredContent' } ] \n}).then ( function( filter ) {\n  return filter.filteredContent[0].updateAttributes({\n    content: 'crap'\n  })\n}).then(function () {\n  // DONE! :)\n});\n```\n\n```text\nFilter.find({\n  where: { id: 3 }, \n  include: [ { model : FilteredContent, as : 'filteredContent' } ] \n}).then ( function( filter ) {\n  return Promise.all([\n    filter.updateAttributes({}),\n    filter.filteredContent.map(fc => fc.updateAttributes({}))\n  ]);\n}).spread(function (filter, filteredContents) {\n\n})\n```\n\n```text\nbuild\n```\n\n```text\nspread\n```\n\n```text\nPromise.all\n```\n\n```text\nawait Filter.update({\n  filteredContent: [\n    { content: \"x\" },\n    { content: \"y\" },\n  ]\n}, { where: { id: 3 } });\n```\n\n```text\n@hatchifyjs/sequelize-create-with-associations\n```\n\n========================================\n\nComments:\n- Thanks for your response. Sorry it has taken me a while to respond. So based on your response it sounds like it isn't possible to update both Filter and the list of FilteredContent at once? I would need to save the Filter, then iterate through the list of FilteredContent and call updateAttributes for each?\n- Answer updated - Oh and also, I might mention that I'm one of the maintainers of sequelize, that's why I know this :)\n- I recognized your name from the Sequelize github issue tracking so I knew your answer was official. :) Thanks for your help.\n- Could you update your comment to address the idea that filteredContent could contain new records, removed records and changed records","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":213,"estimatedTokens":1390}}164{"id":"stack-32544151","source":"stackoverflow","questionId":32544151,"title":"Sequelize is returning integer as string","tags":["node.js","sequelize.js"],"text":"Title: Sequelize is returning integer as string\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI using nodejs v4 with sequelize, and I have a model like this:\n\n```\nvar Device = sequelize.define('Device', {\nid: {\n type: DataTypes.BIGINT,\n primaryKey: true,\n autoIncrement: true\n},\ntenantId: {\n type: DataTypes.BIGINT,\n allowNull: false\n},\ntoken: {\n type: DataTypes.STRING,\n allowNull: false\n}\n}, {\n tableName: 'devices'\n});\n```\n\nWhen I select a device by id the type of id is a string, exemple:\n\n```\nDevice.findById(9).then( function(result) {\n console.log(result.toJSON().id + 10);\n});\n```\n\nThe output will be 910, rather than 19, so I look at json and a saw this:\n\n```\n{\n id: \"9\"\n tenantId: \"123\"\n token: \"adsadsdsa\"\n}\n```\n\nThe id in found device is a string, but I defined it as a number...\n\nDoesn't it should be { \"id\": 9 } ?\n\nHow can I select a device with the types that I defined previously?\n\n========================================\n\nTop Answer:\nBIGINT maximum value is 2^63-1, javascript can safely represent up to 2^53. To be on the safe side libraries return those numbers as strings.\n\nIf you want to have numbers instead of strings, you can use this library https://github.com/mirek/node-pg-safe-numbers which deals with this issue.\n\n========================================\n\nCode:\n```text\nvar Device = sequelize.define('Device', {\nid: {\n  type: DataTypes.BIGINT,\n  primaryKey: true,\n  autoIncrement: true\n},\ntenantId: {\n  type: DataTypes.BIGINT,\n  allowNull: false\n},\ntoken: {\n  type: DataTypes.STRING,\n  allowNull: false\n}\n}, {\n tableName: 'devices'\n});\n```\n\n```text\nDevice.findById(9).then( function(result) {\n  console.log(result.toJSON().id + 10);\n});\n```\n\n```text\n{\n  id: \"9\"\n  tenantId: \"123\"\n  token: \"adsadsdsa\"\n}\n```\n\n```js\nrequire(\"pg\").defaults.parseInt8 = true;\n\n...\n\ntry {\n    const list = await Posts.findAll();\n    console.log(JSON.stringify(list));\n} catch (e) {\n    console.log(e.message);\n}\n```\n\n```text\n@Column({\n    type: DataType.DECIMAL(9, 2),\n    get() {\n        return parseFloat(this.getDataValue('amount') as string);\n    },\n})\namount?: number;\n```\n\n```text\nparseFloat\n```\n\n```text\ngetter\n```\n\n========================================\n\nComments:\n- Correct me if I am wrong but I think you would have to change your DB schema as well for this to work. In my example (postgres) it doesn't fix anything.\n- but what will be the result if the int from the string is larger then the biggest safe int in JS?)\n- This works for my use case, but worth noting that if you have numbers larger than 2^53 then it may return incorrect values.\n- Sorry, I made an edit request to your answer by mistake.","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":133,"estimatedTokens":660}}165{"id":"stack-30848530","source":"stackoverflow","questionId":30848530,"title":"How to programmatically run sequelize migrations","tags":["node.js","sequelize.js"],"text":"Title: How to programmatically run sequelize migrations\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe documentation for sequelize seems out of date as they no longer support running migrations from sequelize itself, but instead relies on sequelize-cli. Is there an example of how to use sequeliz-cli programmatically to run the latest migrations? All the documentation seems to be focused on using the client in a shell.\n\ndb.js seems to have the function db:migrate that perhaps I can include.\n\nhttps://github.com/sequelize/cli/blob/master/lib/tasks/db.js\n\n========================================\n\nTop Answer:\nI had this exact same problem and implemented the accepted answer. However I ran into concurrency issues while running this as a separate process, especially during tests.\n\nI think this question is rather old, but it still appears very high on search results. Today it's a *much* better idea to run it using umzug.\nIt's the library that sequelize uses to manage migrations on it's end, and is suggested by the docs.\n\n```\nconst fs = require('fs');\nconst Umzug = require('umzug');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst { sequelize } = require('../models/index.js');\n\nconst umzug = new Umzug({\n migrations: {\n // indicates the folder containing the migration .js files\n path: path.join(process.cwd(), './migrations'),\n // inject sequelize's QueryInterface in the migrations\n params: [\n sequelize.getQueryInterface(),\n Sequelize,\n ],\n },\n // indicates that the migration data should be store in the database\n // itself through sequelize. The default configuration creates a table\n // named `SequelizeMeta`.\n storage: 'sequelize',\n storageOptions: {\n sequelize,\n },\n});\n\nasync function migrate() {\n return umzug.up();\n}\n\nasync function revert() {\n return umzug.down({ to: 0 });\n```\n\nAnd with that you can do everything you need to do with migrations without resorting to spawning a different process, which opens you to all sorts of race conditions and problems down the line. Read more about how to use umzug with the docs on github\n\n========================================\n\nCode:\n```text\nconst {exec} = require('child_process');\n\nawait new Promise((resolve, reject) => {\n  const migrate = exec(\n    'sequelize db:migrate',\n    {env: process.env},\n    err => (err ? reject(err): resolve())\n  );\n\n  // Forward stdout+stderr to this process\n  migrate.stdout.pipe(process.stdout);\n  migrate.stderr.pipe(process.stderr);\n});\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst db = new Sequelize('main', 'test', 'test', {\ndialect: 'sqlite',\n// SQLite only\nstorage: 'db.db'\n});\n\nasync function checkForMigrations() {\nlet migrations = fs.readdirSync(__dirname + '/../migrations');\nlet completedMigrations = await db.query(\"SELECT * FROM `SequelizeMeta`\", {type: Sequelize.QueryTypes.SELECT});\nfor (let name in completedMigrations) {\n    if (completedMigrations.hasOwnProperty(name)) {\n        let index = migrations.indexOf(completedMigrations[name].name);\n        if (index !== -1) {\n            migrations.splice(index, 1);\n        }\n    }\n}\n\nfor(let i = 0, c = migrations.length; i < c; i++){\n   let migration = require(__dirname + '/../migrations/' + migrations[i]);\n   migration.up(db.queryInterface, Sequelize);\n   await db.query(\"INSERT INTO `SequelizeMeta` VALUES(:name)\", {type: Sequelize.QueryTypes.INSERT, replacements: {name: migrations[i]}})\n}\n}\n```\n\n```text\nconst fs = require('fs');\nconst Umzug = require('umzug');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst { sequelize } = require('../models/index.js');\n\nconst umzug = new Umzug({\n  migrations: {\n    // indicates the folder containing the migration .js files\n    path: path.join(process.cwd(), './migrations'),\n    // inject sequelize's QueryInterface in the migrations\n    params: [\n      sequelize.getQueryInterface(),\n      Sequelize,\n    ],\n  },\n  // indicates that the migration data should be store in the database\n  // itself through sequelize. The default configuration creates a table\n  // named `SequelizeMeta`.\n  storage: 'sequelize',\n  storageOptions: {\n    sequelize,\n  },\n});\n\nasync function migrate() {\n  return umzug.up();\n}\n\nasync function revert() {\n  return umzug.down({ to: 0 });\n```\n\n========================================\n\nComments:\n- If I understood you correctly, isn't this what umzug was created for ? github.com/sequelize/umzug\n- it does - but I'd like to use all the sequelize configuration that's built in to connection strings objects and what not.. rather than use umzug alone and re-implement the sequelize configuration modules.\n- As the node server itself starts from the code unlike some languages like PHP where server runs always, we are forced to run the migrations only when the node is running when you have table creation logic based on the model defined and not from the migration and this is the best way to go with it. Thank you very much\n- Very elegant solution to a slightly complex problem\n- Doesn't work for sqlite in memory :)\n- Nice, elegant solution. 'Wish I'd known how to do this when I originally encountered this problem. Thanks for sharing.\n- Nice, but getting an 'Umzug is not a constructor' error on the latest version.","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":150,"estimatedTokens":1320}}166{"id":"stack-22938375","source":"stackoverflow","questionId":22938375,"title":"Nodejs sequelize how to truncate a foreign key referenced table","tags":["mysql","node.js","sequelize.js"],"text":"Title: Nodejs sequelize how to truncate a foreign key referenced table\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n[Important: this is only relevant for Sequelize Version I have a \"myTable\" mysql table in which myTable.id is referenced by a foreign key on another table. I need to truncate \"myTable\". Normally with mysql shell I would do:\n\n```\nmysql> SET FOREIGN_KEY_CHECKS = 0; truncate table myTable; SET FOREIGN_KEY_CHECKS = 1;\n```\n\nIs there any way of doing this with sequelize?\n\nI have tried to execute\n\n`sequelize.query('SET FOREIGN_KEY_CHECKS = 0; truncate table myTable; SET FOREIGN_KEY_CHECKS = 1;')`\n\nbut I have the error:\n\n```\n`Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'truncate table myTable; SET FOREIGN_KEY_CHECKS = 1' at line 1`\n```\n\nIf I execute the queries serially, I cannot truncate the table:\n\n```\nERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint\n```\n\n========================================\n\nTop Answer:\nI got this by looking at another question and it worked for me on v4.13.2\n\n```\nMyTableModel.destroy({ truncate: { cascade: true } });\n```\n\n========================================\n\nCode:\n```text\nmysql> SET FOREIGN_KEY_CHECKS = 0; truncate table myTable; SET FOREIGN_KEY_CHECKS = 1;\n```\n\n```text\n`Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'truncate table myTable; SET FOREIGN_KEY_CHECKS = 1' at line 1`\n```\n\n```text\nERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint\n```\n\n```text\nsequelize.query('SET FOREIGN_KEY_CHECKS = 0; truncate table myTable; SET FOREIGN_KEY_CHECKS = 1;')\n```\n\n```text\nsequelize.transaction(function(t) {\n  var options = { raw: true, transaction: t }\n\n  sequelize\n    .query('SET FOREIGN_KEY_CHECKS = 0', null, options)\n    .then(function() {\n      return sequelize.query('truncate table myTable', null, options)\n    })\n    .then(function() {\n      return sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null, options)\n    })\n    .then(function() {\n      return t.commit()\n    })\n}).success(function() {\n  // go on here ...\n})\n```\n\n```text\nsequelize.query\n```\n\n```text\nsequelize.sync({ force: true })\n```\n\n```text\nsequelize.transaction(function(t) {\n  var options = { raw: true, transaction: t }\n\n  return sequelize\n    .query('SET FOREIGN_KEY_CHECKS = 0', options)\n    .then(function() {\n      return sequelize.query('truncate table myTable', options)\n    })\n    .then(function() {\n      return sequelize.query('SET FOREIGN_KEY_CHECKS = 1', options)\n    })\n}).then(function() {\n  // go on here ...\n})\n```\n\n```text\nMyTableModel.truncate({ cascade: true });\n```\n\n```text\ncascade\n```\n\n```text\nMyTableModel.destroy({ truncate: { cascade: true } });\n```\n\n```text\nMyTableModel.destroy({ where: {}});\n```\n\n```js\nawait MyModel.sequelize.query(\"SET FOREIGN_KEY_CHECKS = 0\", null);\nawait MyModel.truncate();\nawait MyModel.sequelize.query(\"SET FOREIGN_KEY_CHECKS = 1\", null);\n```\n\n```text\nonDelete: CASCADE\n```\n\n========================================\n\nComments:\n- So, in other words we have to care about our FKs ourselves because Sequelize fails on that badly all the time github.com/sequelize/sequelize/issues/6894\n- I have an error: `Error: Sequelize.query was refactored to only use the parameters 'sql' and 'options'. Please read the changelog about BC.`\n- NOTE: For V5 and above users, the `options` parameter should be the second argument now, like so: sequelize.query('your query here', options)\n- I have an error: `Error: Sequelize.query was refactored to only use the parameters 'sql' and 'options'. Please read the changelog about BC.`\n- Doesn't work. `SequelizeDatabaseError: ER_TRUNCATE_ILLEGAL_FK: Cannot truncate a table referenced in a foreign key constraint`\n- Are you using a compatible version ?\n- Worked with `sequelize`: `3.24.3`, FK constraints were configured as `ON DELETE SET NULL`.\n- This worked for me on sequelize 6.x","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":139,"estimatedTokens":1027}}167{"id":"stack-34754335","source":"stackoverflow","questionId":34754335,"title":"How to use Lowercase function in Sequelize Postgres","tags":["node.js","postgresql","sequelize.js"],"text":"Title: How to use Lowercase function in Sequelize Postgres\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to use the lowercase function to do string searching in Sequelize.\nI manage to do it using the ilike. \nMy question is how to use the lowercase function in this scenario?\n\nThe `findAll` using ilike is as following:\n\n```\nDb.models.Person.findAll(where: {firstName: {$ilike: `somename`}});\n```\n\nHow do I change it to `lower(firstname) = lower('somename');`\n\n========================================\n\nTop Answer:\nYou can use native functions in the where clause:\n\n```\nDb.models.Person.findAll({\n where: sequelize.where(\n sequelize.fn('lower', sequelize.col('firstname')), \n sequelize.fn('lower', 'somename')\n )\n});\n```\n\nwhich would translate to\n\n```\nselect * from person where lower(firstname) = lower('somename');\n```\n\n========================================\n\nCode:\n```text\nDb.models.Person.findAll(where: {firstName: {$ilike: `somename`}});\n```\n\n```text\nfindAll\n```\n\n```text\nlower(firstname) = lower('somename');\n```\n\n```text\nCREATE TABLE users (\n    nick CITEXT PRIMARY KEY,\n    pass TEXT   NOT NULL\n);\n\nINSERT INTO users VALUES ( 'larry',  md5(random()::text) );\nINSERT INTO users VALUES ( 'Tom',    md5(random()::text) );\nINSERT INTO users VALUES ( 'Damian', md5(random()::text) );\nINSERT INTO users VALUES ( 'NEAL',   md5(random()::text) );\nINSERT INTO users VALUES ( 'Bjørn',  md5(random()::text) );\n\nSELECT * FROM users WHERE nick = 'Larry';\n```\n\n```text\n// Assuming `Conn` is a new Sequelize instance\nconst Person = Conn.define('person', {\n  firstName: {\n    allowNull: false,\n    type: 'citext' // <-- this is the only change\n  }\n});\n```\n\n```text\nsequelize.fn('lower')\n```\n\n```text\nDb.models.Person.findAll(where: {firstName: {$iLike: 'name'}});\n```\n\n```text\nDb.models.Person.findAll(where: {firstName: {$iLike: '%name%'}});\n```\n\n```text\ntext\n```\n\n```text\ncharacter varying\n```\n\n```text\nselect * from people where name = 'DAVID'\n```\n\n```text\nselect * from people where LOWER(name) = LOWER('DAVID')\n```\n\n```text\nCREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public;\n```\n\n```text\ntype\n```\n\n```text\nwhere =\n```\n\n```text\nsequelize.fn\n```\n\n```text\nDb.models.Person.findAll({\n  where: sequelize.where(\n    sequelize.fn('lower', sequelize.col('firstname')), \n    sequelize.fn('lower', 'somename')\n  )\n});\n```\n\n```text\nselect * from person where lower(firstname) = lower('somename');\n```\n\n========================================\n\nComments:\n- dont know if that apply to you, but in my case i try using unaccent function in C# linq and couldnt make it work, at the end just create a new column `u_column` and use postgres function to fill it. Wasnt preatty but work.\n- using this way, when I need to search mutiple arguments how should I do it. For example: lastName and Phone Number. where lastName is similar tyep of field like firstName, phoneNumber is a field where it stores numbers.\n- you would just add them as normal to your `where: {}` object. `where: { sequelize.where(sequelize.fn('lower', sequelize.col('firstname')), sequelize.fn('lower', 'somename')), phoneNumber: 8435551212 }`\n- @Ben: This does not work for me, I suggest: `where: {phoneNumber: '8435551212', $col: sequelize.where(sequelize.fn('lower', sequelize.col('firstname')), sequelize.fn('lower', 'somename'))}`\n- I did the 3rd solution with the following migration. Might be useful for others: module.exports = { up: function (queryInterface, Sequelize) { queryInterface.sequelize.query('CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public;'); queryInterface.sequelize.query('CREATE TABLE mytable(email CITEXT PRIMARY KEY NOT NULL, password TEXT NOT NULL);'); }, down: function (queryInterface, Sequelize) { queryInterface.dropTable('mytable'); } };\n- Re #2: Additional code may be necessary to escape special characters in `name` if it's coming from a user.\n- I wonder how someone would design for case-insensitive searches generally, but still opt into case-sensitive matching sometimes. Would we need to do a second pass in application code to apply the case-sensitivity, or is there a SQL operator that means \"this time, honor case, even though this field is citext\"?\n- Another con for CITEXT imho is that it cannot be combined with a maxlength for the field! Also, it's quite a hassle to set it up correctly when using a dockerized psql database, but that may be an individual thing.","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":145,"estimatedTokens":1104}}168{"id":"stack-9321225","source":"stackoverflow","questionId":9321225,"title":"Using dynamic search parameters with Sequelize.js","tags":["javascript","node.js","sequelize.js"],"text":"Title: Using dynamic search parameters with Sequelize.js\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to the Sequelize tutorial on their website.\n\nI have reached the following line of code.\n\n```\nProject.findAll({where: [\"id > ?\", 25]}).success(function(projects) {\n // projects will be an array of Projects having a greater id than 25\n})\n```\n\nIf I tweak it slightly as follows\n\n```\nProject.findAll({where: [\"title like '%awe%'\"]}).success(function(projects) {\n for (var i=0; ieverything works fine. However when I try to make the search parameter dynamic as follows\n\n```\nProject.findAll({where: [\"title like '%?%'\", 'awe']}).success(function(projects) {\n for (var i=0; iIt no longer returns any results. How can I fix this?\n\n========================================\n\nTop Answer:\nNow on Sequelize you can try this\n\n```\n{ where: { columnName: { $like: '%awe%' } } }\n```\n\nSee http://docs.sequelizejs.com/en/latest/docs/querying/#operators for updated syntax\n\n========================================\n\nCode:\n```text\nProject.findAll({where: [\"id > ?\", 25]}).success(function(projects) {\n  // projects will be an array of Projects having a greater id than 25\n})\n```\n\n```text\nProject.findAll({where: [\"title like '%awe%'\"]}).success(function(projects) {\n    for (var i=0; i<projects.length; i++) {\n        console.log(projects[i].title + \" \" + projects[i].description);\n    }\n});\n```\n\n```text\nProject.findAll({where: [\"title like '%?%'\", 'awe']}).success(function(projects) {\n    for (var i=0; i<projects.length; i++) {\n        console.log(projects[i].title + \" \" + projects[i].description);\n    }\n});\n```\n\n```text\nwhere: [\"title like ?\", '%' + 'awe' + '%']\n```\n\n```text\nProject.findAll({where: [\"title like ?\", '%' + x + '%']}).success(function(projects) {\n    for (var i=0; i<projects.length; i++) {\n        console.log(projects[i].title + \" \" + projects[i].description);\n    }\n});\n```\n\n```text\nProject.findAll({where: {title: {like: '%' + x + '%'}, id: {gt: 10}}).success(function(projects) {\n  for (var i=0; i<projects.length; i++) {\n    console.log(projects[i].title + \" \" + projects[i].description);\n  }\n});\n```\n\n```text\n{ where: { columnName: { $like: '%awe%' } } }\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst Op = Sequelize.Op;\n{ where: { columnName: { [Op.like]: '%awe%' } } }\n```\n\n```text\n[\"columnName like ?\", '%' + x + '%']\n```\n\n```text\nwhere\n```\n\n```text\nmodelName.findAll({ where : { columnName : { searchCriteria } } });\n```\n\n```text\n[Op.like]: '%awe%'\n```\n\n```text\n$like: '%awe%' }\n```\n\n```text\nLIKE '\\\"%awe%\\\"'\n```\n\n```text\n[Op.like] : `%${parameter}%`\n```\n\n```text\nLIKE '\\\"%findMe\\\"'\n```\n\n```text\n[Op.like]: [`%${parameter}%`]\n```\n\n```text\nLIKE '[\\\"%findMe%\\\"]'\n```\n\n```text\nSequelize.query('SELECT * FROM tableName WHERE columnName LIKE \"%searchCriteria%\"');\n```\n\n========================================\n\nComments:\n- I found the wording of your question a little confusing, so I edited it. I hope I understood correctly, please feel free to change it back if you think I screwed up.\n- Good simplistic answer. Quick note for new users, title is the name of the column you are wanting to find the match against.\n- Thanks @JMM I fixed it ;)","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":141,"estimatedTokens":802}}169{"id":"stack-53946532","source":"stackoverflow","questionId":53946532,"title":"How to define an index, within a Sequelize model?","tags":["mysql","sql","node.js","sequelize.js"],"text":"Title: How to define an index, within a Sequelize model?\nTags: mysql, sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a simple non-unique index for one of my SQL columns, inside a Sequelize model. I tried to this post :How to define unique index on multiple columns in sequelize .\n\nThis is my code:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Item = sequelize.define('Item', {\n itemId: DataTypes.STRING,\n ownerId: DataTypes.INTEGER,\n status: DataTypes.STRING,\n type: DataTypes.STRING,\n nature: DataTypes.STRING,\n content: DataTypes.STRING,\n moment: DataTypes.BIGINT,\n indexes:[\n {\n unique: 'false',\n fields:['ownerId']\n }\n ]\n\n });\n\n return Item;\n};\n```\n\nI get this error:\n\n Unhandled rejection SequelizeDatabaseError: You have an error in your\n SQL syntax; check the manual that corresponds to your MariaDB server\n version for the right syntax to use near '[object Object], `createdAt`\n DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, P' at line 1\n\nThe code that i have in my server.js file is this:\n\n```\nmodels.sequelize.sync().then(function () {\n server.listen(port, () => {\n console.log('server ready')\n })\n});\n```\n\nWhat is wrong with my setup? Is there any other way this can be done with Sequelize?\n\n========================================\n\nTop Answer:\nIt can work in single migration also.\n\nIn my case, just perform the addIndex after createTable method in the migration file \n\n**Migration:**\n\n```\nreturn queryInterface.createTable('Item', {\n // columns...\n}).then(() => queryInterface.addIndex('Item', ['OwnerId']))\n.then(() => {\n // perform further operations if needed\n});\n```\n\nit's work for me in the migration file.\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Item = sequelize.define('Item', {\n        itemId:  DataTypes.STRING,\n        ownerId:  DataTypes.INTEGER,\n        status: DataTypes.STRING,\n        type: DataTypes.STRING,\n        nature: DataTypes.STRING,\n        content: DataTypes.STRING,\n        moment: DataTypes.BIGINT,\n        indexes:[\n            {\n                unique: 'false',\n                fields:['ownerId']\n            }\n        ]\n\n    });\n\n    return Item;\n};\n```\n\n```text\nmodels.sequelize.sync().then(function () {\n    server.listen(port, () => {\n        console.log('server ready')\n    })\n});\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Item = sequelize.define('Item', {\n        itemId:  DataTypes.STRING,\n        ownerId:  DataTypes.INTEGER,\n        status: DataTypes.STRING,\n        type: DataTypes.STRING,\n        nature: DataTypes.STRING,\n        content: DataTypes.STRING,\n        moment: DataTypes.BIGINT\n    },\n    {\n      indexes:[\n       {\n         unique: false,\n         fields:['ownerId']\n       }\n      ]\n    });\n\n    return Item;\n};\n```\n\n```text\nreturn queryInterface.createTable('Item', {\n    // columns...\n}).then(() => queryInterface.addIndex('Item', ['OwnerId']))\n.then(() => {\n    // perform further operations if needed\n});\n```\n\n========================================\n\nComments:\n- Hehe. If this solves this issue, then please accept my answer :)\n- I will, in 4 minutes, when it allows me to :D\n- @Roi Does it need to be the actual field which is in table or the field name which is mentioned in define of the code\n- @Root I'm not sure what you mean by that. The field name which is inserted into the fields array corresponds to one of the fields in the Item model. Correct me if I am wrong, but these names will also always reflect the names of the fields in the database table.\n- @Roi suppose there is one model definition having column as ItemId: { type: DataTypes.BIGINT, field: 'item_id', autoIncrement: true } In this what should the index be? ItemId or item_id\n- upvoted! if ownerId was a date instead how would you make it DESC\n- how to define on 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('tables', { id: {\n- Yeah, but why go in two steps, when you can do it in just one?","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":157,"estimatedTokens":1025}}170{"id":"stack-28418499","source":"stackoverflow","questionId":28418499,"title":"How can I drop all tables with Sequelize.js using postgresql?","tags":["postgresql","sequelize.js"],"text":"Title: How can I drop all tables with Sequelize.js using postgresql?\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying:\n\n```\nif (process.NODE_ENV === 'test') {\n foreignKeyChecks = 0;\n forceSync = true;\n} else {\n foreignKeyChecks = 1;\n forceSync = false;\n}\n\nglobal.db.sequelize.query(\"SET FOREIGN_KEY_CHECKS = \" + foreignKeyChecks).then(function() {\n return global.db.sequelize.sync({\n force: forceSync\n });\n}).then(function() {\n return global.db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');\n}).then(function() {\n var server;\n console.log('Initialzed database on:');\n console.log(config.db);\n return server = app.listen(port, function() {\n return console.log(\"Server listening at http://\" + (server.address().address) + \":\" + (server.address().port));\n });\n})[\"catch\"](function(err) {\n return console.log('err', err);\n});\n\nmodule.exports = app;\n```\n\nBut I get: `SequelizeDatabaseError: unrecognized configuration parameter \"foreign_key_checks\"`\n\nI assume I can't have that keyword in postgres? But is there an equivalent way to drop all tables and recreate?\n\n========================================\n\nTop Answer:\nFor wiping out data and create all again from scratch (like in tests):\n\n```\nsequelize.sync({force: true});\n```\n\n========================================\n\nCode:\n```text\nif (process.NODE_ENV === 'test') {\n  foreignKeyChecks = 0;\n  forceSync = true;\n} else {\n  foreignKeyChecks = 1;\n  forceSync = false;\n}\n\nglobal.db.sequelize.query(\"SET FOREIGN_KEY_CHECKS = \" + foreignKeyChecks).then(function() {\n  return global.db.sequelize.sync({\n    force: forceSync\n  });\n}).then(function() {\n  return global.db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');\n}).then(function() {\n  var server;\n  console.log('Initialzed database on:');\n  console.log(config.db);\n  return server = app.listen(port, function() {\n    return console.log(\"Server listening at http://\" + (server.address().address) + \":\" + (server.address().port));\n  });\n})[\"catch\"](function(err) {\n  return console.log('err', err);\n});\n\nmodule.exports = app;\n```\n\n```text\nSequelizeDatabaseError: unrecognized configuration parameter \"foreign_key_checks\"\n```\n\n```text\ndrop(options) => promise\n```\n\n```js\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\n\nvar someModel = sequelize.define('somemodel', {\n  name: DataTypes.STRING\n});\n\nsequelize\n  .sync() // create the database table for our model(s)\n  .then(function(){\n    // do some work\n  })\n  .then(function(){\n    return sequelize.drop() // drop all tables in the db\n  });\n```\n\n```text\ndrop owned by <our_user_name cascade\n```\n\n```text\nsequelize.sync({force: true});\n```\n\n```text\nsequelize_cli db:drop\n\nsequelize_cli db:create\n```\n\n```text\nsequelize-cli db:drop && sequelize-cli db:create && sequelize-cli db:migrate\n```\n\n========================================\n\nComments:\n- There is no such option `foreign_key_checks` in Postgres. Where in the manual did you find that?\n- I assumed not. I copied from some post and I assume they were using `MySQL`\n- It seems reading the manual is *really* a lost art.\n- Any way to turn off foreign key constraints when dropping tables?\n- @Shamoon: you don't need to. The `cascade` keyword will automatically drop all foreign keys.\n- I realize that I don't `need` to, but I'm trying to stay within the confines of the ORM\n- You are wrong. It does not delete tables that exist in database but not in sequelize model list\n- Sequelize also has `sequelize.truncate` to truncate all tables for those that don't want to actually delete the tables, it could be faster than drop + recreate which `.sync` seems to do: stackoverflow.com/a/66985334/895245","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":135,"estimatedTokens":916}}171{"id":"stack-14002646","source":"stackoverflow","questionId":14002646,"title":"sequelize for Node.js : ER_NO_SUCH_TABLE","tags":["node.js","sequelize.js"],"text":"Title: sequelize for Node.js : ER_NO_SUCH_TABLE\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to sequelize and Node.js.\n\nI coded for test sequelize, but error occured **\"ER_NO_SUCH_TABLE : Table 'db.node_tests' doesn't exist\"**\n\nError is very simple. \n\nHowever, I want to get data from \"**node_test**\" table.\n\nI think sequelize appends 's' character.\n\nThere is my source code.\n\n```\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('db', 'user', 'pass');\nvar nodeTest = sequelize.define('node_test',\n { uid: Sequelize.INTEGER \n , val: Sequelize.STRING} );\n\nnodeTest.find({where:{uid:'1'}})\n .success(function(tbl){\n console.log(tbl);\n });\n```\n\nI already create table \"node_test\", and inserted data using mysql client.\n\nDoes I misunderstood usage?\n\n========================================\n\nTop Answer:\nThough the answer works nicely, I nowadays recommend the use of the `tableName` option when declaring the model:\n\n```\nsequelize.define('node_test', { \n uid: Sequelize.INTEGER,\n val: Sequelize.STRING\n}, {\n tableName: 'node_test'\n});\n```\n\nhttp://docs.sequelizejs.com/manual/tutorial/models-definition.html\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('db', 'user', 'pass');\nvar nodeTest = sequelize.define('node_test',\n        { uid: Sequelize.INTEGER \n         , val: Sequelize.STRING} );\n\nnodeTest.find({where:{uid:'1'}})\n    .success(function(tbl){\n        console.log(tbl);\n    });\n```\n\n```text\n{define:{freezeTableName:true}}\n```\n\n```text\nnodeTest.sync().success(function() {\n  // here comes your find command.\n})\n```\n\n```text\nsync({ force: true })\n```\n\n```text\nsequelize.define('node_test', { \n  uid: Sequelize.INTEGER,\n  val: Sequelize.STRING\n}, {\n   tableName: 'node_test'\n});\n```\n\n```text\ntableName\n```\n\n```text\nvar nodeTest = sequelize.define('node_test',\n        { uid: Sequelize.INTEGER , val: Sequelize.STRING},\n        { freezeTableName: true , timestamps: false} //add both options here\n);\n```\n\n```text\nsequelize.define('name_of_your_table',\n    {attributes_of_your_table_columns},\n    {options}\n     );\n```\n\n```text\n> ER_NO_SUCH_TABLE    //freezeTableName\n> ER_BAD_FIELD_ERROR  //timestamps\n```\n\n```text\nsequelize.define('User', {\n```\n\n```text\nsequelize.define('user', {\n```\n\n========================================\n\nComments:\n- I'm using Mysql 5.5.28 / sequelize 1.6.0-beta4 / Node.js 0.8.15.\n- you are welcome. let me know if you need further information.\n- just a side not: `dresende&#47;node-orm2` module gave me the same `Error: ER_NO_SUCH_TABLE`... you need to call `sync()` for the first time, before adding data.\n- Thank you for your new answer. I'll try it. :)\n- @sdepold You may wish to update the link to the documentation.","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":130,"estimatedTokens":694}}172{"id":"stack-59437636","source":"stackoverflow","questionId":59437636,"title":"Sequelize find in JSON field","tags":["javascript","json","postgresql","sequelize.js"],"text":"Title: Sequelize find in JSON field\nTags: javascript, json, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have PostgreSQL database with JSON type field named \"data\" that has following content structure:\n\n```\n{\n \"requestData\" : {\n \"url\": \"some url\"\n \"body\": {\n \"page_id\": 12\n }\n }\n}\n```\n\nI try to make `findAll` query request with filter by `page_id` using Sequelize, but don't get some results. \n\nThe question is: could I search by nested field in JSON type, or only in JSONB type? And how?\n\n========================================\n\nCode:\n```text\n{\n  \"requestData\" : {\n    \"url\": \"some url\"\n    \"body\": {\n      \"page_id\": 12\n    }\n  }\n}\n```\n\n```text\nfindAll\n```\n\n```text\npage_id\n```\n\n```text\n{\n  \"meta.audio.length\": {\n    [Op.gt]: 20\n  }\n}\n```\n\n```text\n{\n  meta: {\n    video: {\n      url: {\n        [Op.ne]: null\n      }\n    }\n  }\n}\n```\n\n```text\n{\n  \"meta\": {\n    [Op.contains]: {\n      site: {\n        url: 'http://google.com'\n      }\n    }\n  }\n}\n```\n\n========================================\n\nComments:\n- Why donot you try querying via Sequelize as raw query? It will be easy for you to search in MYSQL query.\n- Provided link to Sequelize docs doesn't work, here is the updated one: sequelize.org/master/manual/&hellip;\n- @Simon Thank you, I will update the link in the answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":82,"estimatedTokens":324}}173{"id":"stack-30452977","source":"stackoverflow","questionId":30452977,"title":"Sequelize query - compare dates in two columns","tags":["sequelize.js"],"text":"Title: Sequelize query - compare dates in two columns\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table in Sequelize with two date columns - i.e. with :\n\n```\nvar Visit = sequelize.define(\"Visit\", {\n /*...*/\n scheduleEndDate: {\n type: DataTypes.DATE\n }\n actualEndDate: {\n type: DataTypes.DATE\n }\n /*...*/\n});\n```\n\nI want to make a query that returns rows where actualEndDate is before scheduleEndDate - and can't get the format right. What I've tried for the `where` part of my `findAll` query is:\n\n```\nwhere: { actualEndDate: { lt: Visit.scheduleEndDate } }\n```\n\n- throws an error because Visit not defined (have also tried with this.scheduleEndDate - also throws an error)\n\n```\nwhere: { actualEndDate: '- does a string comparison of actualEndDate against the string 'Do I need to define an instance method to do the date comparison / how best to solve?\n\n========================================\n\nTop Answer:\nIn lastest version (v5) you need to use `Sequelize.Op`. Docs\n\n```\nconst Op = Sequelize.Op;\n...\nwhere: {\n actualEndDate: {\n [Op.lt]: sequelize.col('scheduleEndDate')\n }\n}\n```\n\nAll operations:\n\n```\nProject.findAll({\n where: {\n id: {\n [Op.and]: {a: 5}, // AND (a = 5)\n [Op.or]: [{a: 5}, {a: 6}], // (a = 5 OR a = 6)\n [Op.gt]: 6, // id > 6\n [Op.gte]: 6, // id >= 6\n [Op.lt]: 10, // id [1, 2] (PG array contains operator)\n [Op.contained]: [1, 2], // <@ [1, 2] (PG array contained by operator)\n [Op.any]: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only)\n },\n status: {\n [Op.not]: false // status NOT FALSE\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\nvar Visit = sequelize.define(\"Visit\", {\n  /*...*/\n  scheduleEndDate: {\n    type: DataTypes.DATE\n  }\n  actualEndDate: {\n    type: DataTypes.DATE\n  }\n  /*...*/\n});\n```\n\n```text\nwhere: { actualEndDate: { lt: Visit.scheduleEndDate } }\n```\n\n```text\nwhere: { actualEndDate: '< scheduleEndDate' }\n```\n\n```text\nwhere\n```\n\n```text\nfindAll\n```\n\n```text\nwhere: { actualEndDate: { $lt: sequelize.col('scheduleEndDate') } }\n```\n\n```text\nconst Op = Sequelize.Op;\n...\nwhere: {\n    actualEndDate: {\n        [Op.lt]: sequelize.col('scheduleEndDate')\n    }\n}\n```\n\n```text\nProject.findAll({\n  where: {\n    id: {\n      [Op.and]: {a: 5},           // AND (a = 5)\n      [Op.or]: [{a: 5}, {a: 6}],  // (a = 5 OR a = 6)\n      [Op.gt]: 6,                // id > 6\n      [Op.gte]: 6,               // id >= 6\n      [Op.lt]: 10,               // id < 10\n      [Op.lte]: 10,              // id <= 10\n      [Op.ne]: 20,               // id != 20\n      [Op.between]: [6, 10],     // BETWEEN 6 AND 10\n      [Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15\n      [Op.in]: [1, 2],           // IN [1, 2]\n      [Op.notIn]: [1, 2],        // NOT IN [1, 2]\n      [Op.like]: '%hat',         // LIKE '%hat'\n      [Op.notLike]: '%hat',       // NOT LIKE '%hat'\n      [Op.iLike]: '%hat',         // ILIKE '%hat' (case insensitive)  (PG only)\n      [Op.notILike]: '%hat',      // NOT ILIKE '%hat'  (PG only)\n      [Op.overlap]: [1, 2],       // && [1, 2] (PG array overlap operator)\n      [Op.contains]: [1, 2],      // @> [1, 2] (PG array contains operator)\n      [Op.contained]: [1, 2],     // <@ [1, 2] (PG array contained by operator)\n      [Op.any]: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)\n    },\n    status: {\n      [Op.not]: false           // status NOT FALSE\n    }\n  }\n})\n```\n\n```text\nSequelize.Op\n```\n\n========================================\n\nComments:\n- Yup - that works. Have deleted my incorrect response. Thanks.\n- Could you please explain why this does what it does? I am having difficulty seeing how creating a column object helps in comparing dates. Thank!\n- `$lt` translates to the operator (`<`) - Anything prefixed with $ is an operator in sequelize ($lte, $in, $contains etc.) sequelize.col allows you to refer to a column. If you do `$lt: scheduleEndDate`, scheduleEndDate will be escaped as a string literal\n- Aah, that makes total sense. Thanks for the insight!","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":155,"estimatedTokens":989}}174{"id":"stack-51445651","source":"stackoverflow","questionId":51445651,"title":"How to use iLike operator with Sequelize to make case insensitive queries","tags":["javascript","node.js","postgresql","sequelize.js","case-insensitive"],"text":"Title: How to use iLike operator with Sequelize to make case insensitive queries\nTags: javascript, node.js, postgresql, sequelize.js, case-insensitive\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize along with PostgreSQL in managing my database.\n\nI would like to perform a case insensitive search query. When I googled it up, some people said that I can use \"iLike\" operator to do so. I tried to implement this way:\n\n```\nvar getRadiosByGenre = function(Radio,Genre,genreName){\n Genre.findOne({where:{name: { $iLike: genreName}}})}\n```\n\nwhere genreName is a string.\nBut, I keep getting this error:\n\n Error: Invalid value { '$iLike': 'art' }\n\nDoes anyone know the correct way of using iLike with sequelize?\nThanks mates(s). :)\n\n========================================\n\nCode:\n```text\nvar getRadiosByGenre = function(Radio,Genre,genreName){\n    Genre.findOne({where:{name: { $iLike: genreName}}})}\n```\n\n```text\nvar getRadiosByGenre = function(Radio,Genre,genreName) {\n  Genre.findOne({\n    where: {\n      name: {\n        [Sequelize.Op.iLike]: genreName\n      }\n    }\n  });\n}\n```\n\n```text\nSequelize.Op\n```\n\n```text\n%\n```\n\n```text\ngenreName\n```\n\n========================================\n\nComments:\n- Thank you, for the reference but this is how to implement it exactly: var getRadiosByGenre = function(Radio,Genre,genreName){ Genre.findOne({where :{name:{[ Op.iLike ]:'%'+genreName}}})\n- Yes as I stated you should add the % sign if needed ! glad I could help","metadata":{"transformedAt":"2026-08-18T18:33:34.351Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":59,"estimatedTokens":366}}175{"id":"stack-41058479","source":"stackoverflow","questionId":41058479,"title":"Sequelize findAll is not a function","tags":["mysql","node.js","express","passport.js","sequelize.js"],"text":"Title: Sequelize findAll is not a function\nTags: mysql, node.js, express, passport.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm making a project with Sequelize and I'm stucked in this step. The problem is that when I try to log in and the passport-local code is executed, **when it reaches the User.findAll(...) it throws that findAll is not a function**.\n\nIf I make console.log(User) it shows [function].\n\nMy structure:\n\n- /config/config.js\n\n- /config/passport.js\n\n- /models/index.js\n\n- /models/nuke_users.js (generated by sequelize-auto)\n\n- /index.js\n\nconfig.js:\n\n```\n//Setting up the config\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('rocarenav2', 'root', '123456', {\n host: \"localhost\",\n port: 3306,\n dialect: 'mysql'\n});\n\nmodule.exports = sequelize;\n```\n\npassport.js:\n\n```\n// config/passport.js\n\n// load all the things we need\nvar LocalStrategy = require('passport-local').Strategy;\n\n// load up the user model\nvar User = require('../models/nuke_users');\n\nvar crypto = require('crypto');\n\nfunction hashPasswordForNuke(password) {\n return md5password = crypto.createHash('md5').update(password).digest('hex');\n}\n\n// expose this function to our app using module.exports\nmodule.exports = function(passport) {\n\n// =========================================================================\n// passport session setup ==================================================\n// =========================================================================\n// required for persistent login sessions\n// passport needs ability to serialize and unserialize users out of session\n\n// used to serialize the user for the session\npassport.serializeUser(function(user, done) {\n done(null, user.id);\n});\n\n// used to deserialize the user\npassport.deserializeUser(function(id, done) {\n User.findById(id, {})\n .then(function (user) {\n done(err, user);\n })\n .catch(function (error){\n done(error);\n });\n});\n\n// =========================================================================\n// LOCAL LOGIN =============================================================\n// =========================================================================\n// we are using named strategies since we have one for login and one for signup\n// by default, if there was no name, it would just be called 'local'\n\npassport.use('local-login', new LocalStrategy({\n // by default, local strategy uses username and password, we will override with email\n usernameField : 'email',\n passwordField : 'password',\n passReqToCallback : true // allows us to pass back the entire request to the callback\n},\nfunction(req, email, password, done) { // callback with email and password from our form\n User.findAll({\n where: {\n 'user_email': email\n }\n }).then(function (user) {\n if(!user)\n return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash\n\n // if the user is found but the password is wrong\n if ((user.user_password).localeCompare(hashPasswordForNuke(password)) === -1)\n return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata\n\n return done(null, user);\n })\n .catch(function (error){\n done(error);\n });\n\n}));\n\n};\n```\n\nmodels/index.js\n\n```\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(module.filename);\nvar config = require(__dirname + '/../config/config');\nvar db = {};\n\n//Create a Sequelize connection to the database using the URL in config/config.js\nvar sequelize = config;\n\n//Load all the models\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n.forEach(function(file) {\n var model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n});\n\nObject.keys(db).forEach(function(modelName) {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\n//Export the db Object\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n/models/nuke_users.js\n\n```\n/* jshint indent: 2 */\n\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('nuke_users', {\n user_id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n username: {\n type: DataTypes.STRING,\n allowNull: false,\n defaultValue: \"\",\n references: {\n model: 'reps_table',\n key: 'PostName'\n }\n },\n user_email: {\n type: DataTypes.STRING,\n allowNull: false,\n defaultValue: \"\"\n },\n user_avatar: {\n type: DataTypes.STRING,\n allowNull: false,\n defaultValue: \"\"\n },\n user_password: {\n type: DataTypes.STRING,\n allowNull: false,\n defaultValue: \"\"\n }\n }, {\n tableName: 'nuke_users'\n });\n};\n```\n\n/index.js\n\n```\n...\nvar models = require('./models/');\n...\n```\n\nSo, what am I doing wrong?\n\n========================================\n\nTop Answer:\nInstead of returning the model, export it from `NukeUser.js`:\n\n```\nconst NukeUser = sequelize.define('nuke_users', {\n // ...\n});\n\nmodule.exports = NukeUser;\n```\n\nThen in `index.js`:\n\n```\nconst NukeUser = require('../models/NukeUser');\nNukeUser.findAll() //.then() ...\n```\n\n========================================\n\nCode:\n```text\n//Setting up the config\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('rocarenav2', 'root', '123456', {\n   host: \"localhost\",\n   port: 3306,\n   dialect: 'mysql'\n});\n\nmodule.exports = sequelize;\n```\n\n```text\n// config/passport.js\n\n// load all the things we need\nvar LocalStrategy   = require('passport-local').Strategy;\n\n// load up the user model\nvar User            = require('../models/nuke_users');\n\nvar crypto          = require('crypto');\n\nfunction hashPasswordForNuke(password) {\n    return md5password =        crypto.createHash('md5').update(password).digest('hex');\n}\n\n// expose this function to our app using module.exports\nmodule.exports = function(passport) {\n\n// =========================================================================\n// passport session setup ==================================================\n// =========================================================================\n// required for persistent login sessions\n// passport needs ability to serialize and unserialize users out of session\n\n// used to serialize the user for the session\npassport.serializeUser(function(user, done) {\n    done(null, user.id);\n});\n\n// used to deserialize the user\npassport.deserializeUser(function(id, done) {\n    User.findById(id, {})\n    .then(function (user) {\n        done(err, user);\n    })\n    .catch(function (error){\n        done(error);\n    });\n});\n\n\n\n// =========================================================================\n// LOCAL LOGIN =============================================================\n// =========================================================================\n// we are using named strategies since we have one for login and one for signup\n// by default, if there was no name, it would just be called 'local'\n\npassport.use('local-login', new LocalStrategy({\n    // by default, local strategy uses username and password, we will override with email\n    usernameField : 'email',\n    passwordField : 'password',\n    passReqToCallback : true // allows us to pass back the entire request to the callback\n},\nfunction(req, email, password, done) { // callback with email and password from our form\n    User.findAll({\n        where: {\n            'user_email': email\n        }\n    }).then(function (user) {\n        if(!user)\n            return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash\n\n        // if the user is found but the password is wrong\n        if ((user.user_password).localeCompare(hashPasswordForNuke(password)) === -1)\n            return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata\n\n        return done(null, user);\n    })\n    .catch(function (error){\n        done(error);\n    });\n\n}));\n\n};\n```\n\n```text\n'use strict';\n\nvar fs        = require('fs');\nvar path      = require('path');\nvar Sequelize = require('sequelize');\nvar basename  = path.basename(module.filename);\nvar config    = require(__dirname + '/../config/config');\nvar db        = {};\n\n//Create a Sequelize connection to the database using the URL in         config/config.js\nvar sequelize = config;\n\n//Load all the models\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n      return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n.forEach(function(file) {\n    var model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n});\n\nObject.keys(db).forEach(function(modelName) {\n   if (db[modelName].associate) {\n      db[modelName].associate(db);\n   }\n});\n\n//Export the db Object\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n/* jshint indent: 2 */\n\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('nuke_users', {\n   user_id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n   },\n   username: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      defaultValue: \"\",\n      references: {\n         model: 'reps_table',\n         key: 'PostName'\n      }\n   },\n   user_email: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      defaultValue: \"\"\n   },\n   user_avatar: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      defaultValue: \"\"\n   },\n   user_password: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      defaultValue: \"\"\n   }\n }, {\n    tableName: 'nuke_users'\n });\n};\n```\n\n```text\n...\nvar models = require('./models/');\n...\n```\n\n```text\nvar User = require('../models/nuke_users')(sequelize, DataTypes);\n```\n\n```text\nvar models = require('../models'); // loads index.js\nvar User = models.nuke_user;       // the model keyed by its name\nUser.findOne(...);                 // search the model\n```\n\n```text\nnuke_users\n```\n\n```text\nModel\n```\n\n```text\nModel\n```\n\n```text\nsequelize\n```\n\n```text\nDataTypes\n```\n\n```text\nindex.js\n```\n\n```text\ndb\n```\n\n```text\nconst NukeUser = sequelize.define('nuke_users', {\n    // ...\n});\n\nmodule.exports = NukeUser;\n```\n\n```text\nconst NukeUser = require('../models/NukeUser');\nNukeUser.findAll() //.then() ...\n```\n\n```text\nNukeUser.js\n```\n\n```text\nindex.js\n```\n\n```text\nasync read(id) {\n    try {\n      if(id) {\n        return await this.model.findOne({where: {id: id}});\n      } else {\n        return await this.model.findAll();\n      }\n    } catch (e) {\n      console.error(`Error in reading data with the id: ${id}`);\n    }\n  }\n```\n\n```text\nread()\n```\n\n```text\nfindAll()\n```\n\n```text\nread()\n```\n\n========================================\n\nComments:\n- In your passport.js try to do it like var models = require('../models'); var User = models.nuke_users;\n- Okay, that worked. How do I mark your answer as correct?\n- Don't worry about it. I was too tired to write a properly answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":493,"estimatedTokens":2775}}176{"id":"stack-33576129","source":"stackoverflow","questionId":33576129,"title":"Sequelize return array with Strings instead of Objects","tags":["sql-server","sequelize.js"],"text":"Title: Sequelize return array with Strings instead of Objects\nTags: sql-server, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSometimes i only want to select a single value from multiple rows.\n\nLets imagine i have an account model which looks like this:\n\n**Account**\n\n- Id\n\n- Name\n\n- Age\n\nAnd i would only like to select the names.\n\nYou would write something like this:\n\n```\nAccountModel.findAll({\n where: {\n Age: {\n $gt : 18\n }\n },\n attributes: ['Name'],\n raw : true\n });\n```\n\nBut this would return in an array with objects.\n\n```\n[{Name : \"Sample 1\"}, {\"Name\" : \"Sample 2\"}]\n```\n\nI would like to get an array with only names like this:\n\n```\n[\"Sample 1\", \"Sample 2\"]\n```\n\nIs it possible to achieve this with Sequelize?\nI've searched trough the documentation but couldn't find it.\n\n========================================\n\nTop Answer:\nHere is a nice ES6 version of cfogelberg's answer using lambda expressions (`Array.prototype.map()` only works in IE9+ and lambda (arrow) functions have no IE support):\n\n```\nAccountModel.findAll({\n where: {\n Age: {\n $gt : 18\n }\n },\n attributes: ['Name'],\n raw : true\n})\n.then(accounts => accounts.map(account => account.Name));\n```\n\n### Snippet (does not work in ie):\n\nHere is a baby snippet I used for proof of concept. If it doesn't work, you are using one of the unsupported browsers mentioned above (and you shouldn't be making db calls directly from the browser anyway):\n\n\r\n\r\n\n```\nconst objArray=[{key:1},{key:2},{key:3}];\nconsole.log(\"Not IE friendly:\");\nconsole.log(objArray.map(obj => obj.key));\nconsole.log(\"IE friendly (might even be ES3 if you change \\\"let\\\" to \\\"var\\\"):\");\nlet names = [];\nfor(let i=0 ; i\n\n========================================\n\nCode:\n```text\nAccountModel.findAll({\n        where: {\n            Age: {\n                $gt : 18\n            }\n        },\n        attributes: ['Name'],\n        raw : true\n    });\n```\n\n```text\n[{Name : \"Sample 1\"}, {\"Name\" : \"Sample 2\"}]\n```\n\n```text\n[\"Sample 1\", \"Sample 2\"]\n```\n\n```text\nAccountModel.findAll({\n    where: {\n        Age: {\n            $gt : 18\n        }\n    },\n    attributes: ['Name'],\n    raw : true\n})\n.then(function(accounts) {\n  return _.map(accounts, function(account) { return account.Name; })\n})\n```\n\n```text\nfind\n```\n\n```text\nraw: true\n```\n\n```js\nvar pluck = require('arr-pluck');\n\nAccountModel.findAll({\n    where: {\n        Age: {\n            $gt : 18\n        }\n    },\n    attributes: ['Name'],\n    raw : true\n})\n.then(function(accounts) {\n  return pluck(accounts, 'Name');\n})\n```\n\n```text\nAccountModel.findAll({\n    where: {\n        Age: {\n            $gt : 18\n        }\n    },\n    attributes: ['Name'],\n    raw : true\n})\n.then(accounts => accounts.map(account => account.Name));\n```\n\n```js\nconst objArray=[{key:1},{key:2},{key:3}];\nconsole.log(\"Not IE friendly:\");\nconsole.log(objArray.map(obj => obj.key));\nconsole.log(\"IE friendly (might even be ES3 if you change \\\"let\\\" to \\\"var\\\"):\");\nlet names = [];\nfor(let i=0 ; i<objArray.length ; i++){\n    names[i] = objArray[i].key\n}\nconsole.log(names)\n```\n\n```text\nArray.prototype.map()\n```\n\n```text\nconst someVariable = [\n  ... ( await AccountModel.findAll({\n    where: {\n        Age: {\n            $gt : 18\n        }\n    },\n    attributes: ['Name'],\n    raw : true\n  })),\n].map(account => account.Name);\n```\n\n========================================\n\nComments:\n- Idk why anyone downvoted this, other answers also use 3rd party libs (like lodash). Technically mine is the only pure nodejs/sequelize solution, but there is nothing wrong with this one...\n- Update: Fabio's answer is also pure js\n- This is a nice ES7 solution","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":193,"estimatedTokens":900}}177{"id":"stack-33502641","source":"stackoverflow","questionId":33502641,"title":"Multiple migration statements in one migration file","tags":["node.js","error-handling","migration","sails.js","sequelize.js"],"text":"Title: Multiple migration statements in one migration file\nTags: node.js, error-handling, migration, sails.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to execute multiple migration statements in a single migration file in order to make changes to multiple columns of same table in one go.\n\nI want to know that whether I am doing it in a write way or not or is there a better and *more appropriate way* to do it:\n\n### Migration Code\n\n```\nmodule.exports = {\n up: function(queryInterface, Sequelize, done) {\n\n queryInterface.changeColumn('users', 'name', {\n type: Sequelize.STRING,\n allowNull: false,\n require: true,\n unique: true\n }).success(function() {\n queryInterface.changeColumn('users', 'address', {\n type: Sequelize.STRING,\n allowNull: false,\n require: true,\n unique: true\n }).success(function() {\n queryInterface.changeColumn('users', 'city', {\n type: Sequelize.STRING,\n allowNull: false,\n require: true,\n unique: true\n }).success(function() {\n queryInterface.changeColumn('users', 'state', {\n type: Sequelize.STRING,\n allowNull: false,\n require: true,\n defaultValue: \"ncjnbcb\"\n });\n done();\n });\n });\n });\n }\n};\n```\n\nBut I face an error which says: \n\n TypeError: undefined is not a function\n\nSince i couldn't find any way of debugging error in migrations, it will be great if someone helps me out in resolving it or if possible, tell about the way as of how can we figure out the errors in a migration.\n\n========================================\n\nTop Answer:\n**Using `Promise.all` with transactions (safer migration) :**\n\n```\nmodule.exports = {\n up: async (queryInterface, Sequelize) => {\n return queryInterface.sequelize.transaction(t => {\n return Promise.all([\n queryInterface.changeColumn('users', 'name', \n { type: Sequelize.STRING },\n { transaction: t }\n ),\n queryInterface.changeColumn('users', 'address', \n { type: Sequelize.STRING },\n { transaction: t }\n ),\n queryInterface.changeColumn('users', 'city', \n { type: Sequelize.STRING },\n { transaction: t }\n )\n ]);\n });\n },\n\n down: async (queryInterface, Sequelize) => {\n return queryInterface.sequelize.transaction((t) => {\n return Promise.all([\n queryInterface.removeColumn('users', 'name', { transaction: t }),\n queryInterface.removeColumn('users', 'address', { transaction: t }),\n queryInterface.removeColumn('users', 'city', { transaction: t })\n ])\n })\n }\n};\n```\n\nUsing `Promise.all` without transactions would cause issues if some of the queries are rejected. It is safe to use transactions so that all operations would be executed successfully or none of the changes would be made.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n    up: function(queryInterface, Sequelize, done) {\n\n        queryInterface.changeColumn('users', 'name', {\n            type: Sequelize.STRING,\n            allowNull: false,\n            require: true,\n            unique: true\n        }).success(function() {\n            queryInterface.changeColumn('users', 'address', {\n                type: Sequelize.STRING,\n                allowNull: false,\n                require: true,\n                unique: true\n            }).success(function() {\n                queryInterface.changeColumn('users', 'city', {\n                    type: Sequelize.STRING,\n                    allowNull: false,\n                    require: true,\n                    unique: true\n                }).success(function() {\n                    queryInterface.changeColumn('users', 'state', {\n                        type: Sequelize.STRING,\n                        allowNull: false,\n                        require: true,\n                        defaultValue: \"ncjnbcb\"\n                    });\n                    done();\n                });\n            });\n        });\n    }\n};\n```\n\n```text\nreturn Promise.all([\n  queryInterface.changeColumn..., \n  queryInterface.changeColumn...\n]);\n```\n\n```text\ndone\n```\n\n```js\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    try {\n      await queryInterface.addColumn('User', 'name', {\n        type: Sequelize.STRING\n      });\n      await queryInterface.addColumn('User', 'nickname', {\n        type: Sequelize.STRING\n      });\n      return Promise.resolve();\n    } catch (e) {\n      return Promise.reject(e);\n    }\n  },\n\n  down: async (queryInterface, Sequelize) => {\n    try {\n      await queryInterface.removeColumn('Challenges', 'name');\n      await queryInterface.removeColumn('Challenges', 'nickname');\n      return Promise.resolve();\n    } catch (e) {\n      return Promise.reject(e);\n    }\n  }\n};\n```\n\n```js\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    return queryInterface.sequelize.transaction(t => {\n      return Promise.all([\n        queryInterface.changeColumn('users', 'name', \n          { type: Sequelize.STRING },\n          { transaction: t }\n        ),\n        queryInterface.changeColumn('users', 'address', \n          { type: Sequelize.STRING },\n          { transaction: t }\n        ),\n        queryInterface.changeColumn('users', 'city', \n          { type: Sequelize.STRING },\n          { transaction: t }\n        )\n      ]);\n    });\n  },\n\n  down: async (queryInterface, Sequelize) => {\n    return queryInterface.sequelize.transaction((t) => {\n      return Promise.all([\n        queryInterface.removeColumn('users', 'name', { transaction: t }),\n        queryInterface.removeColumn('users', 'address', { transaction: t }),\n        queryInterface.removeColumn('users', 'city', { transaction: t })\n      ])\n    })\n  }\n};\n```\n\n```text\nPromise.all\n```\n\n```text\nPromise.all\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    return queryInterface.sequelize.transaction(async t => {\n      try {\n        await queryInterface.createTable(\n          'phonenumbers',\n          {\n            id: {\n              allowNull: false,\n              autoIncrement: true,\n              primaryKey: true,\n              type: Sequelize.INTEGER\n            },\n            full_number: {\n              type: Sequelize.STRING,\n              unique: true\n            },\n            phone: {\n              type: Sequelize.STRING\n            },\n            extension: {\n              type: Sequelize.INTEGER,\n            },\n            country_id: {\n              type: Sequelize.INTEGER\n            },\n            is_valid_format: {\n              type: Sequelize.BOOLEAN\n            },\n            type: {\n              type: Sequelize.STRING\n            },\n            createdAt: {\n              allowNull: false,\n              type: Sequelize.DATE\n            },\n            updatedAt: {\n              allowNull: false,\n              type: Sequelize.DATE\n            },\n          },\n          { transaction: t }\n        ),\n        await queryInterface.addIndex(\n          'phonenumbers',\n          ['phone'],\n          {\n            name: 'constraint-phone-extension',\n            where: {extension: null},\n            transaction: t\n          }\n        )\n        return Promise.resolve();\n      } catch (e) {\n        return Promise.reject(e);\n      }\n    });\n  },\n  down: async (queryInterface, Sequelize) => {\n    return queryInterface.sequelize.transaction(async t => {\n      try {\n        await queryInterface.dropTable('phonenumbers', { transaction: t }),\n        return Promise.resolve();\n      } catch (e) {\n        return Promise.reject(e);\n      }\n    })\n  }\n};\n```\n\n========================================\n\nComments:\n- helpful feedback please?\n- This method isn't quite right. Any failed queries in there will cause migrations to get stuck. See github.com/sequelize/cli/issues/133#issuecomment-236402184\n- As mentioned by @KevinCarmody doing multiple transactions in a single file puts you at risk in getting into an unrecoverable state. Furthermore, using `Promise.all` will run the migrations in parallel. These days you may be better off using `async` and `await`.\n- My answer is significantly outdated at this point. It is correct in the sense that it addresses OP's primary issue, but see the other answers for ways to write a better implementation.\n- This should be the right answer, with regard to the last sentence\n- I tried to use return promise.all, but the job was just hanging there.","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":294,"estimatedTokens":2047}}178{"id":"stack-45790759","source":"stackoverflow","questionId":45790759,"title":"sequalize migration with dotenv","tags":["json","node.js","sequelize.js","sequelize-cli"],"text":"Title: sequalize migration with dotenv\nTags: json, node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am saving my database config in dotenv file.\n\nI am using sequelize migration which has a config.json file in config folder:\n\n```\n{\n \"development\": {\n \"username\": \"root\",\n \"password\": null,\n \"database\": \"test\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"postgres\"\n },\n ....\n}\n```\n\nSince I have configuration in dotenv do I have to convert it to js file:\n\n```\nrequire('dotenv').config({ silent: env === 'production'})\n\nconst devConfig = {\n dialect: 'postgres',\n host: process.env.DB_HOST || 'localhost',\n port: process.env.DB_PORT || 5432,\n database: process.env.DB_NAME || '',\n username: process.env.DB_USER || 'postgres',\n password: process.env.DB_PASSWORD || '',\n migrationStorageTableName: 'migrations'\n};\n\nmodule.exports = {\n development: devConfig,\n production: devConfig\n};\n```\n\nbut how can I run the the migration, which the config is not JSON?\n\n```\nnode_modules/.bin/sequelize db:migrate --config config/config.js\n```\n\n========================================\n\nTop Answer:\n- Rename `config.json` to `config.js` and call your environment variables inside.\n\n```\nmodule.exports = {\n development: {\n username: process.env.DB_USER,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_NAME,\n host: process.env.DB_HOST,\n dialect: 'postgres',\n logging: false,\n },\n test: {\n username: process.env.DB_USER,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_NAME,\n host: process.env.DB_HOST,\n dialect: 'postgres',\n logging: false,\n },\n production: {\n username: process.env.DB_USER,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_NAME,\n host: process.env.DB_HOST,\n dialect: 'postgres',\n logging: false,\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000,\n },\n },\n};\n```\n\n- Create a `.sequelizerc` file with the following:\n\n```\n'use strict';\n\nrequire('dotenv').config(); // don't forget to require dotenv\nconst path = require('path');\n\nmodule.exports = {\n 'config': path.resolve('config', 'config.js'),\n 'models-path': path.resolve('models'),\n 'seeders-path': path.resolve('seeders'),\n 'migrations-path': path.resolve('migrations'),\n};\n```\n\n- Run `sequelize db:migrate`\n\n========================================\n\nCode:\n```text\n{\n \"development\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"database\": \"test\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"postgres\"\n  },\n  ....\n}\n```\n\n```text\nrequire('dotenv').config({ silent: env === 'production'})\n\nconst devConfig = {\n  dialect: 'postgres',\n  host: process.env.DB_HOST || 'localhost',\n  port: process.env.DB_PORT || 5432,\n  database: process.env.DB_NAME || '',\n  username: process.env.DB_USER || 'postgres',\n  password: process.env.DB_PASSWORD || '',\n  migrationStorageTableName: 'migrations'\n};\n\nmodule.exports = {\n  development: devConfig,\n  production: devConfig\n};\n```\n\n```text\nnode_modules/.bin/sequelize db:migrate --config config/config.js\n```\n\n```text\nconfig/config.js\n```\n\n```text\n.sequelizerc\n```\n\n```js\nconst path = require('path')\n\nmodule.exports = {\n  config: path.resolve('config', 'config.js')\n}\n```\n\n```text\n.sequelizerc\n```\n\n```text\ndotenv -e path/to/.env sequelize db:migrate\n```\n\n```text\nmodule.exports = {\n  development: {\n    username: process.env.DB_USER,\n    password: process.env.DB_PASSWORD,\n    database: process.env.DB_NAME,\n    host: process.env.DB_HOST,\n    dialect: 'postgres',\n    logging: false,\n  },\n  test: {\n    username: process.env.DB_USER,\n    password: process.env.DB_PASSWORD,\n    database: process.env.DB_NAME,\n    host: process.env.DB_HOST,\n    dialect: 'postgres',\n    logging: false,\n  },\n  production: {\n    username: process.env.DB_USER,\n    password: process.env.DB_PASSWORD,\n    database: process.env.DB_NAME,\n    host: process.env.DB_HOST,\n    dialect: 'postgres',\n    logging: false,\n    pool: {\n      max: 5,\n      min: 0,\n      acquire: 30000,\n      idle: 10000,\n    },\n  },\n};\n```\n\n```text\n'use strict';\n\nrequire('dotenv').config();    // don't forget to require dotenv\nconst path = require('path');\n\nmodule.exports = {\n  'config': path.resolve('config', 'config.js'),\n  'models-path': path.resolve('models'),\n  'seeders-path': path.resolve('seeders'),\n  'migrations-path': path.resolve('migrations'),\n};\n```\n\n```text\nconfig.json\n```\n\n```text\nconfig.js\n```\n\n```text\n.sequelizerc\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nsequelize db:migrate --env production\n```\n\n========================================\n\nComments:\n- A slight variation is to install dotenv-cli as a dev dependency. Then you can run `npx dotenv -e .env sequelize db:migrate` locally.\n- thanks for the answer, just wanted to point out that it's not explicitly mentioned in the latest version of the docs, it's implied. It's not even available when you run `npx sequelize-cli --help`","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":244,"estimatedTokens":1204}}179{"id":"stack-44070808","source":"stackoverflow","questionId":44070808,"title":"hasMany called with something that's not an instance of Sequelize.Model","tags":["node.js","postgresql","sequelize.js"],"text":"Title: hasMany called with something that's not an instance of Sequelize.Model\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nas you guys can see my issue is related to the title description, i created a User Model, and a Foto Model in sequelize, basicly a user can shoot many fotos, but each foto can be related to just 1 user.\n\n**My User model**\n\n```\n\"use strict\";\nvar sequelize = require('./index');\nvar bcrypt = require('bcrypt-nodejs');\nvar Foto = require('./Foto');\n\nmodule.exports = function (sequelize, DataTypes) {\n var User = sequelize.define(\"User\", {\n username: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n validate: {\n isUnique: function (value, next) {\n var self = this;\n User.find({ where: { username: value } })\n .then(function (user) {\n // reject if a different user wants to use the same username\n if (user && self.id !== user.id) {\n return next('username already in use!');\n }\n return next();\n })\n .catch(function (err) {\n return next(err);\n });\n }\n }\n },\n\n email: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n validate: {\n isUnique: function (value, next) {\n var self = this;\n User.find({ where: { email: value } })\n .then(function (user) {\n // reject if a different user wants to use the same email\n if (user && self.id !== user.id) {\n return next('Email already in use!');\n }\n return next();\n })\n .catch(function (err) {\n return next(err);\n });\n }\n }\n },\n\n typeOfUser: {\n type: DataTypes.INTEGER,\n allowNull:true,\n defaultValue:null\n },\n\n country: {\n type: DataTypes.STRING,\n allowNull:true,\n defaultValue:null\n },\n\n birthDate:{\n type: DataTypes.DATEONLY,\n allowNull:true,\n defaultValue:null\n },\n\n reports: {\n type: DataTypes.INTEGER,\n defaultValue: 0\n },\n\n points: {\n type: DataTypes.INTEGER,\n defaultValue: 0\n },\n\n password: {\n type: DataTypes.STRING,\n allowNull:false\n },\n\n numberFotos: {\n type: DataTypes.INTEGER,\n defaultValue: 0\n }\n }, {\n classMethods: {\n generateHash: function (password) {\n return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);\n },\n\n },\n instanceMethods: {\n validPassword: function (password) {\n return bcrypt.compareSync(password, this.password);\n }\n }\n\n });\n\n User.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})\n\n return Foto;\n}\n```\n\n**My foto model**\n\n```\n\"use strict\";\nvar sequelize = require('./index');\nvar bcrypt = require('bcrypt-nodejs');\nvar User = require('./User');\n\nmodule.exports = function (sequelize, DataTypes) {\n var Foto = sequelize.define(\"Foto\", {\n reports: {\n type: DataTypes.INTEGER,\n defaultValue: 0\n },\n image: {\n type: DataTypes.STRING,\n allowNull: false\n },\n date: {\n type: DataTypes.DATE,\n allowNull:true\n },\n position: {\n type: DataTypes.RANGE,\n allowNull: true\n }\n });\n\n Foto.belongsTo(User, {foreignKey: 'userId'});\n\n return Foto;\n}\n```\n\n========================================\n\nTop Answer:\nYou can define relations for both models in **one file**. It doesn't throw any errors that way.\n\nIn your Foto.js, you can try:\n\n```\n...\n\nFoto.belongsTo(User);\nUser.hasMany(Foto);\n\nreturn Foto;\n```\n\n========================================\n\nCode:\n```text\n\"use strict\";\nvar sequelize = require('./index');\nvar bcrypt = require('bcrypt-nodejs');\nvar Foto = require('./Foto');\n\nmodule.exports = function (sequelize, DataTypes) {\n  var User = sequelize.define(\"User\", {\n    username: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true,\n      validate: {\n        isUnique: function (value, next) {\n          var self = this;\n          User.find({ where: { username: value } })\n            .then(function (user) {\n              // reject if a different user wants to use the same username\n              if (user && self.id !== user.id) {\n                return next('username already in use!');\n              }\n              return next();\n            })\n            .catch(function (err) {\n              return next(err);\n            });\n        }\n      }\n    },\n\n    email: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true,\n      validate: {\n        isUnique: function (value, next) {\n          var self = this;\n          User.find({ where: { email: value } })\n            .then(function (user) {\n              // reject if a different user wants to use the same email\n              if (user && self.id !== user.id) {\n                return next('Email already in use!');\n              }\n              return next();\n            })\n            .catch(function (err) {\n              return next(err);\n            });\n        }\n      }\n    },\n\n    typeOfUser: {\n      type: DataTypes.INTEGER,\n      allowNull:true,\n      defaultValue:null\n    },\n\n    country: {\n      type: DataTypes.STRING,\n      allowNull:true,\n      defaultValue:null\n    },\n\n    birthDate:{\n      type: DataTypes.DATEONLY,\n      allowNull:true,\n      defaultValue:null\n    },\n\n    reports: {\n      type: DataTypes.INTEGER,\n      defaultValue: 0\n    },\n\n    points: {\n      type: DataTypes.INTEGER,\n      defaultValue: 0\n    },\n\n    password: {\n      type: DataTypes.STRING,\n      allowNull:false\n    },\n\n    numberFotos: {\n      type: DataTypes.INTEGER,\n      defaultValue: 0\n    }\n  }, {\n      classMethods: {\n        generateHash: function (password) {\n          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);\n        },\n\n      },\n      instanceMethods: {\n        validPassword: function (password) {\n          return bcrypt.compareSync(password, this.password);\n        }\n      }\n\n\n    });\n\n  User.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})\n\n  return Foto;\n}\n```\n\n```text\n\"use strict\";\nvar sequelize = require('./index');\nvar bcrypt = require('bcrypt-nodejs');\nvar User = require('./User');\n\n\nmodule.exports = function (sequelize, DataTypes) {\n  var Foto = sequelize.define(\"Foto\", {\n    reports: {\n      type: DataTypes.INTEGER,\n      defaultValue: 0\n    },\n    image: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    date: {\n      type: DataTypes.DATE,\n      allowNull:true\n    },\n    position: {\n      type: DataTypes.RANGE,\n      allowNull: true\n    }\n  });\n\n  Foto.belongsTo(User, {foreignKey: 'userId'});\n\n  return Foto;\n}\n```\n\n```text\nFoto.belongsTo(User, {foreignKey: 'userId'});\n```\n\n```text\nUser.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})\n```\n\n```text\n...\n\nFoto.belongsTo(User);\nUser.hasMany(Foto);\n\nreturn Foto;\n```\n\n```text\nconst entities = {\n  A: require('./src/Entity/A'),\n  B: require('./src/Entity/B'),\n};\nentities.A.belongsToMany(entities.B, {through: 'AB'});\nentities.B.belongsToMany(entities.A, {through: 'AB'});\n```\n\n```text\nUser.hasMany(models.Foto ,{as: 'fotos', foreignKey: 'userId'})\n```\n\n```text\nextra-setup.js\n```\n\n```text\n'use strict'\nconst { Model } = require('sequelize')\nmodule.exports = (sequelize, DataTypes) => {\n  class User extends Model {\n    /**\n     * Helper method for defining associations.\n     * This method is not a part of Sequelize lifecycle.\n     * The `models/index` file will call this method automatically.\n     */\n    static associate({ PersonalDetail }) {\n      // define association here\n      this.hasMany(PersonalDetail, {\n        foreignKey: 'userId',\n        //as: 'personalDetails',\n      })\n    }\n  }\n  User.init(\n    {\n      uuid: {\n        type: DataTypes.UUID,\n        defaultValue: DataTypes.UUIDV4,\n      },\n  \n      moredata below: {\n        type: DataTypes.STRING,\n        allowNull: false,\n      },\n\n      //createdAt/updatedAt is defined in migration and updated automatically\n    },\n    {\n      sequelize,\n      tableName: 'users',\n      modelName: 'User',\n    }\n  )\n  return User\n}\n```\n\n```text\nstatic associate({ PersonalDetail })\n```\n\n```text\nconst company = sequelize.define(\"company\",{\n  id: {\n    type: DataTypes.INTEGER,\n    autoIncrement: true,\n    primaryKey: true,\n  },\n  companyName: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  }\n});\n\nexport default company;\n```\n\n```text\nconst Client = sequelize.define(\"client\", {\n  id: {\n    type: DataTypes.INTEGER,\n    autoIncrement: true,\n    primaryKey: true,\n  },\n  firstName: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  } \n});\n\nexport default Client;\n```\n\n```text\nconst clientCompany = sequelize.define(\"client_company\",{\n  id: {\n    type: DataTypes.INTEGER,\n    autoIncrement: true,\n    primaryKey: true,\n  },\n  companyId: {\n    type: DataTypes.INTEGER\n  },\n  clientId: {\n    type: DataTypes.INTEGER\n  }\n});\n\nexport default clientCompany;\n```\n\n```text\nimport Company from './company';\nimport Client from './client';\nimport ClientCompany from './clientCompany';\n\nCompany.belongsToMany(Client, { through : ClientCompany });\nClient.belongsToMany(Company, { through : ClientCompany });\n\nexport {\n  Company,\n  Client,\n  ClientCompany,\n};\n```\n\n```text\nimport { Client, Company } from '../../models';\n\nconst company = await Company.findOne({\n  where: { id: companyId },\n  include: Client,\n});\n```\n\n```text\nexports.User = sequelize.define(\n//\n)\n```\n\n```text\nconst { Collection } = require(\"../models/collection\");\nconst { User } = require(\"../models/user\");\n\n\nUser.hasMany(Collection, { foreignKey: \"userId\", as:\"collections\", });\nCollection.belongsTo(User, { foreignKey: \"userId\" })\n```\n\n========================================\n\nComments:\n- This issue is happens when there are circular dependency between the two models, like User model you put 'const Photo = require('./User')' and in Photo model you put 'const User= require('./Photo')', to resolve this there are two options: 1- define the belongTo and hasMany into one model. 2- define the relation in each model but inside a function and call this function in the index.js for example after requiring the two models like the solution posted in this github.com/sequelize/sequelize/issues/10395\n- My guy @AhmadZahabi ... Blessings to you!!! This fixed it for me.\n- hmmm thank you great answer, i just reated that association to get the user related to the foto\n- Can you please elaborate why I shouldn't use belongsTo in child table model?\n- Is it possible to add relation in both parent and child schema?\n- @KetavChotaliya 1. Is not that you \"can't\" use `belongsTo` , ideallyon a 1:N relationship you put ide foreign key on the dependent model. On this specific example the principal model is `User` because there can not be `Photos` without `User`. 2. Yes you can add the relation on both models.\n- Let's take one case, 1. I want to select a particular photo with his parent relation like user details in our case. At that time what to do? 2. If I can define the relation in both model then sequalize throw an error as discussed above.\n- @KetavChotaliya Please refer this article, Proper reference to relations medium.com/@eth3rnit3/&hellip;\n- I don't think one file for all models is a good approach, especially in medium sized projects.\n- by \"one file\" I meant, \"one of the model files\" that involve the relation between them.\n- This is exactly what was going on with me. Thanks for sharing your solution.\n- @Dorian, I can confirm that this solution works... but it's a bit frustrating to implement this (Don't get me wrong, I don't mean to offend you). For example, if you want to know about `EntityA`, you have to check `.&#47;src&#47;Entity&#47;A` and `index.js`. Wouldn't it be nice if you can put `EntityA`'s associations in `.&#47;src&#47;Entity&#47;A` too? On top of that, `index.js` can be quite huge if you have many entities with associations.\n- When I do that it says `hasOne is not a function`. This is so frustrating","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":501,"estimatedTokens":2858}}180{"id":"stack-29680359","source":"stackoverflow","questionId":29680359,"title":"How to use Sequelize belongsToMany associations?","tags":["javascript","sequelize.js","associations"],"text":"Title: How to use Sequelize belongsToMany associations?\nTags: javascript, sequelize.js, associations\nSource: Stack Overflow\n\nQuestion:\nI have projects and users.\n\nA user can have many projects.\n\nA project can have multiple users.\n\nI tried to model this with a belongsToMany association.\n\nOn my server I defined the associations like this:\n\n```\nuser.belongsToMany(project, {\n through: 'writer_of_project'\n foreign-key: 'user'\n as: 'projects'\n});\n\nproject.belongsToMany(user, {\n through: 'writer_of_project'\n foreign-key: 'project'\n as: 'writers'\n});\n```\n\nOn my client it looks like this:\n\n```\nuser: {\n id: 1,\n ...\n projects: [1,2,3]\n}\n\nproject: {\n id: 1,\n ...\n writers: [1,4,5]\n}\n```\n\nOn the server the association requires a third table to store the association and Sequelize doesn't seem to let me include the corresponding models from it.\n\nIf I run a `project.find(1)` with `include:[user]` I get\n\nuser is not associated with project!\n\nIf I try to put the project from the example above into the update method, the users attribute is simply ignored (I expected a project.setUsers(projectUpdate.users to happen in the background).\n\n**What is the right way to deal with the loading and updating of these associations?**\n\n========================================\n\nCode:\n```text\nuser.belongsToMany(project, {\n  through: 'writer_of_project'\n  foreign-key: 'user'\n  as: 'projects'\n});\n\nproject.belongsToMany(user, {\n  through: 'writer_of_project'\n  foreign-key: 'project'\n  as: 'writers'\n});\n```\n\n```text\nuser: {\n  id:     1,\n  ...\n  projects: [1,2,3]\n}\n\nproject: {\n  id:     1,\n  ...\n  writers: [1,4,5]\n}\n```\n\n```text\nproject.find(1)\n```\n\n```text\ninclude:[user]\n```\n\n```text\nproject.belongsToMany(user, {\n  through: 'writer_of_project'\n  foreign-key: 'project'\n  as: 'writers'\n});\n\nproject.find({\n  where: { id: 1 },\n  include: [ { model: User, as: 'writers' } ]\n});\n```\n\n```text\nProject.writersAssociation = project.belongsToMany(user, {\n  through: 'writer_of_project'\n  foreign-key: 'project'\n  as: 'writers'\n});\n\nproject.find({\n  where: { id: 1 },\n  include: [ project.writersAssociation ]\n});\n```\n\n```text\nas\n```\n\n========================================\n\nComments:\n- I find that if you set up your models with the sequelize-cli then association become easier to read as they are included within the model itself. It also allows you to use migrations which it a real bonus\n- In doing so will that create a writer_of_project model along with a corresponding table in the database? Sorry to piggy back on this but I'm concerned that my migration did not create a writer_of_project table within the db. Please advice....","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":129,"estimatedTokens":655}}181{"id":"stack-8390009","source":"stackoverflow","questionId":8390009,"title":"Sequelize how to find rows with multiple where clauses and timestamp > NOW()","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize how to find rows with multiple where clauses and timestamp > NOW()\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do I do this with Sequelize?\n\n```\nSELECT FROM sessions WHERE user_id = ? AND token = ? AND expires > NOW()\n```\n\nHere's what I'm trying to do (assume `Session` is a Sequelize model):\n\n```\nSession.find({\n where: {\n user_id: someNumber,\n token: someString,\n //expires > NOW() (how do I do this?)\n }\n}).on('success', function (s) { /* things and stuff */ });\n```\n\nThanks!\n\n========================================\n\nTop Answer:\nAnother method:\n\n```\nSession.find({\n where: {\n user_id: someNumber,\n token: someString,\n expires: {\n $gt: (new Date())\n }\n }\n}).on('success', function (s) { /* things and stuff */ });\n```\n\n========================================\n\nCode:\n```text\nSELECT FROM sessions WHERE user_id = ? AND token = ? AND expires > NOW()\n```\n\n```text\nSession.find({\n    where: {\n        user_id: someNumber,\n        token: someString,\n        //expires > NOW() (how do I do this?)\n    }\n}).on('success', function (s) { /* things and stuff */ });\n```\n\n```text\nSession\n```\n\n```text\nSession.find({\n  where: ['user_id=? and token=? and expires > NOW()', someNumber, someString]\n}).on('success', function (s) { /* things and stuff */ });\n```\n\n```text\nSession.find({\n  where: {\n    user_id: someNumber,\n    token: someString,\n    expires: {\n      $gt: (new Date())\n    }\n  }\n}).on('success', function (s) { /* things and stuff */ });\n```\n\n```text\nfilters[\"State\"] = {$and: [filters[\"State\"], {$not: this.filterSBM()}] };\n```\n\n```text\n{ $and: [{\"Key1\": \"Value1\"}, {\"Key2\": \"Value2\"}] }\n```\n\n========================================\n\nComments:\n- Ahh, my bad... I guess I didn't realize you could have more than one replacement using that method. Thanks!\n- I'm happy to change the accepted answer, but I don't have time to test this right now. Perhaps if @sdepold wants to chime in?","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":94,"estimatedTokens":485}}182{"id":"stack-30002321","source":"stackoverflow","questionId":30002321,"title":"What is the difference between .save and .create in Sequelizejs?","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: What is the difference between .save and .create in Sequelizejs?\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to Sequelize, and trying hard to understand how this very strange, new world of ORMs works. Once thing that I can't seem to understand is the difference between \".create\" and \".save\" in Sequelizejs. I have written test functions with both, and besides having slightly different syntax, they both seem to do exactly the same thing.\n\nThis is using the \".save\" method\n\n```\nmodels.User.build({\n username: req.body.username,\n password: req.body.password,\n first_name: req.body.firstName,\n last_name: req.body.lastName\n })\n .save()\n .then(function(task){\n // some function...\n })\n .catch(function(error){\n // some function...\n });\n```\n\nThis is using the \".create\" method\n\n```\nmodels.User.create({\n username: req.body.username,\n password: req.body.password,\n first_name: req.body.firstName,\n last_name: req.body.lastName\n }).then(function(data) {\n // some function...\n });\n```\n\nWhat am I not seeing here?\n\n========================================\n\nTop Answer:\nWhen used like that they mean the same thing. `.create()` is internally `.build()` and `.save()`.\n\nBut most importantly in your first example, `.build()` instantiates ActiveRecord which gains methods such as associations methods and all your getter and setter methods. The `.create()` method gives you back the ActiveRecord only after the creation is completed.\n\nSuppose your users are associated with a `picture`. Sometimes you use the build method to do this:\n\n```\nvar user = models.User.build({\n userName: req.body.userName\n})\n\n// start doing things with the user instance\n\nuser.hasPictures().then(function(hasPictures) {\n // does user have pictures?\n console.log(hasPictures)\n\n})\n```\n\nMore importantly, setter methods may be of more interest to you..\nSee https://sequelize.org/docs/v6/core-concepts/getters-setters-virtuals/\n\nSuppose you may have a `setter` method that does this:\n\n```\nconst User = sequelize.define('user', {\n username: DataTypes.STRING,\n nationality: DataTypes.STRING,\n name: {\n type: DataTypes.STRING,\n set([firstName, lastName]) {\n\n if (this.nationality === 'Chinese' || this.nationality === 'Korean' ) {\n return this.setDataValue('name', `${lastName} ${firstName}`)\n }\n\n // for all other nationalities, we default to having the first name in front.\n this.setDataValue('name', `${firstName} ${lastName}`)\n }\n }\n})\n```\n\nThen now with your `user` ActiveRecord, you can do:\n\n```\nconst user = User.build({ userName: 'parkJS' })\nuser.nationality = 'Korean'\nuser.setDataValue('name', ['Ji Sung', 'Park'])\nconsole.log(user.name) // outputs 'Park Ji Sung'\n\nconst user2 = User.build({ userName: 'davidb' })\nuser2.nationality = 'British'\nuser2.setDataValue('name', ['David', 'Beckham'])\nconsole.log(user2.name) // outputs 'David Beckham'\n\n// call any other setter methods here to complete the model.\n\n// then finally call .save()\nuser.save()\nuser2.save()\n```\n\n========================================\n\nCode:\n```text\nmodels.User.build({\n    username: req.body.username,\n    password: req.body.password,\n    first_name: req.body.firstName,\n    last_name: req.body.lastName\n  })\n  .save()\n  .then(function(task){\n    // some function...\n  })\n  .catch(function(error){\n    // some function...\n  });\n```\n\n```text\nmodels.User.create({\n    username: req.body.username,\n    password: req.body.password,\n    first_name: req.body.firstName,\n    last_name: req.body.lastName\n  }).then(function(data) {\n    // some function...\n  });\n```\n\n```text\nUser.build({ name: \"John\" }).save().then(function(newUser){\n    console.log(newUser.name); // John\n    // John is now in your db!\n}).catch(function(error){\n    // error\n});\n```\n\n```text\nUser.create({ name: \"John\"}).then(function(newUser){\n    console.log(newUser.name); // John\n    // John is now in your db!\n}).catch(function(error){\n    // error\n});\n```\n\n```text\nvar user = User.build({ name: \"John\"}); // nothing in your db yet\n\nuser.name = \"Doe\"; // still, nothing on your db\n\nuser.save().then(function(newUser){\n    console.log(newUser.name); // Doe\n    // Doe is now in your db!\n}).catch(function(error){\n    // error\n});\n```\n\n```text\nvar user = models.User.build({\n    userName: req.body.userName\n})\n\n// start doing things with the user instance\n\nuser.hasPictures().then(function(hasPictures) {\n    // does user have pictures?\n    console.log(hasPictures)\n\n})\n```\n\n```js\nconst User = sequelize.define('user', {\n  username: DataTypes.STRING,\n  nationality: DataTypes.STRING,\n  name: {\n    type: DataTypes.STRING,\n    set([firstName, lastName]) {\n\n      if (this.nationality === 'Chinese' || this.nationality === 'Korean' ) {\n        return this.setDataValue('name', `${lastName} ${firstName}`)\n      }\n\n      // for all other nationalities, we default to having the first name in front.\n      this.setDataValue('name', `${firstName} ${lastName}`)\n    }\n  }\n})\n```\n\n```text\nconst user = User.build({ userName: 'parkJS' })\nuser.nationality = 'Korean'\nuser.setDataValue('name', ['Ji Sung', 'Park'])\nconsole.log(user.name) // outputs 'Park Ji Sung'\n\nconst user2 = User.build({ userName: 'davidb' })\nuser2.nationality = 'British'\nuser2.setDataValue('name', ['David', 'Beckham'])\nconsole.log(user2.name) // outputs 'David Beckham'\n\n// call any other setter methods here to complete the model.\n\n// then finally call .save()\nuser.save()\nuser2.save()\n```\n\n```text\n.create()\n```\n\n```text\n.build()\n```\n\n```text\n.save()\n```\n\n```text\n.build()\n```\n\n```text\n.create()\n```\n\n```text\npicture\n```\n\n```text\nsetter\n```\n\n```text\nuser\n```\n\n========================================\n\nComments:\n- With create you don't need to call .save() :)\n- Apparently `build().save()` will do an update when `isNewRecord` is set to false, but `create()` will not do an update, regardless of the value of `isNewRecord`. (using Sequelize v3)\n- When you use `build`, the object will have a default values defined in the model.","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":257,"estimatedTokens":1487}}183{"id":"stack-42101128","source":"stackoverflow","questionId":42101128,"title":"Merging stack traces in rethrown errors","tags":["javascript","node.js","sequelize.js","stack-trace","winston"],"text":"Title: Merging stack traces in rethrown errors\nTags: javascript, node.js, sequelize.js, stack-trace, winston\nSource: Stack Overflow\n\nQuestion:\nI'm rethrowing here an error from Sequelize promise (Bluebird). In the first place, this was done to change error message, but as it appeared, this also produces more informative stack trace.\n\nIt is something like\n\n```\nsequelize.sync().catch(originalError => {\n const rethrownError = new Error(originalError.msg + ': ' + originalError.sql);\n throw rethrownError;\n});\n```\n\nWhere `originalError.stack` doesn't contain the line that caused the error but it holds important information that it originates in Sequelize and MySQL driver:\n\n```\nSequelizeDatabaseError: ER_KEY_COLUMN_DOES_NOT_EXITS: Key column 'NonExisting' doesn't exist in table\n at Query.formatError (...\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:175:14)\n at Query._callback (...\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:49:21)\n at Query.Sequence.end (...\\node_modules\\mysql\\lib\\protocol\\sequences\\Sequence.js:85:24)\n at Query.ErrorPacket (...\\node_modules\\mysql\\lib\\protocol\\sequences\\Query.js:94:8)\n at Protocol._parsePacket (...\\node_modules\\mysql\\lib\\protocol\\Protocol.js:280:23)\n at Parser.write (...\\node_modules\\mysql\\lib\\protocol\\Parser.js:74:12)\n at Protocol.write (...\\node_modules\\mysql\\lib\\protocol\\Protocol.js:39:16)\n at Socket. (...\\node_modules\\mysql\\lib\\Connection.js:109:28)\n at emitOne (events.js:96:13)\n at Socket.emit (events.js:188:7)\n at readableAddChunk (_stream_readable.js:176:18)\n at Socket.Readable.push (_stream_readable.js:134:10)\n at TCP.onread (net.js:548:20)\n```\n\n`rethrownError.stack` contains the point of interest (the first line in the stack) but everything else is a rubbish:\n\n```\nError: ER_KEY_COLUMN_DOES_NOT_EXITS: Key column 'NonExisting' doesn't exist in table\n at sequelize.sync.catch (...\\app.js:59:17)\n at tryCatcher (...\\node_modules\\bluebird\\js\\release\\util.js:16:23)\n at Promise._settlePromiseFromHandler (...\\node_modules\\bluebird\\js\\release\\promise.js:504:31)\n at Promise._settlePromise (...\\node_modules\\bluebird\\js\\release\\promise.js:561:18)\n at Promise._settlePromise0 (...\\node_modules\\bluebird\\js\\release\\promise.js:606:10)\n at Promise._settlePromises (...\\node_modules\\bluebird\\js\\release\\promise.js:681:18)\n at Async._drainQueue (...\\node_modules\\bluebird\\js\\release\\async.js:138:16)\n at Async._drainQueues (...\\node_modules\\bluebird\\js\\release\\async.js:148:10)\n at Immediate.Async.drainQueues (...\\node_modules\\bluebird\\js\\release\\async.js:17:14)\n at runCallback (timers.js:637:20)\n at tryOnImmediate (timers.js:610:5)\n at processImmediate [as _immediateCallback] (timers.js:582:5)\n```\n\nI would like to keep the information about both of them - and to designate the link between them, not just to add as two unrelated log entries.\n\nI've been thinking on logging them as a single error with concatenated stack, `rethrownError.stack += '\\n' + originalError.stack`. \n\nHow should these two errors be treated? Should their stack traces be joined? Is there a convention for merging error stacks in JavaScript (Node.js in particular)?\n\nThe intention is to keep the resulting error meaningful and to not upset existing tools that parse error stack traces (namely Stacktrace.js).\n\nThe projects under consideration use Winston logger or plain `console.error`, so the error is stringified at some point (in the example above it was logged via unhandled rejection handler).\n\n========================================\n\nTop Answer:\nAs far as I know, there is no built-in way to handle nested errors in Node.js. The only thing I can recommend you is to use the VError library. It is really useful when dealing with advanced error handling.\n\nYou can use `fullStack` to combine stack traces of many errors:\n\n```\nvar err1 = new VError('something bad happened');\nvar err2 = new VError(err1, 'something really bad happened here');\n\nconsole.log(VError.fullStack(err2));\n```\n\n========================================\n\nCode:\n```text\nsequelize.sync().catch(originalError => {\n  const rethrownError = new Error(originalError.msg + ': ' + originalError.sql);\n  throw rethrownError;\n});\n```\n\n```text\nSequelizeDatabaseError: ER_KEY_COLUMN_DOES_NOT_EXITS: Key column 'NonExisting' doesn't exist in table\n    at Query.formatError (...\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:175:14)\n    at Query._callback (...\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:49:21)\n    at Query.Sequence.end (...\\node_modules\\mysql\\lib\\protocol\\sequences\\Sequence.js:85:24)\n    at Query.ErrorPacket (...\\node_modules\\mysql\\lib\\protocol\\sequences\\Query.js:94:8)\n    at Protocol._parsePacket (...\\node_modules\\mysql\\lib\\protocol\\Protocol.js:280:23)\n    at Parser.write (...\\node_modules\\mysql\\lib\\protocol\\Parser.js:74:12)\n    at Protocol.write (...\\node_modules\\mysql\\lib\\protocol\\Protocol.js:39:16)\n    at Socket.<anonymous> (...\\node_modules\\mysql\\lib\\Connection.js:109:28)\n    at emitOne (events.js:96:13)\n    at Socket.emit (events.js:188:7)\n    at readableAddChunk (_stream_readable.js:176:18)\n    at Socket.Readable.push (_stream_readable.js:134:10)\n    at TCP.onread (net.js:548:20)\n```\n\n```text\nError: ER_KEY_COLUMN_DOES_NOT_EXITS: Key column 'NonExisting' doesn't exist in table\n    at sequelize.sync.catch (...\\app.js:59:17)\n    at tryCatcher (...\\node_modules\\bluebird\\js\\release\\util.js:16:23)\n    at Promise._settlePromiseFromHandler (...\\node_modules\\bluebird\\js\\release\\promise.js:504:31)\n    at Promise._settlePromise (...\\node_modules\\bluebird\\js\\release\\promise.js:561:18)\n    at Promise._settlePromise0 (...\\node_modules\\bluebird\\js\\release\\promise.js:606:10)\n    at Promise._settlePromises (...\\node_modules\\bluebird\\js\\release\\promise.js:681:18)\n    at Async._drainQueue (...\\node_modules\\bluebird\\js\\release\\async.js:138:16)\n    at Async._drainQueues (...\\node_modules\\bluebird\\js\\release\\async.js:148:10)\n    at Immediate.Async.drainQueues (...\\node_modules\\bluebird\\js\\release\\async.js:17:14)\n    at runCallback (timers.js:637:20)\n    at tryOnImmediate (timers.js:610:5)\n    at processImmediate [as _immediateCallback] (timers.js:582:5)\n```\n\n```text\noriginalError.stack\n```\n\n```text\nrethrownError.stack\n```\n\n```text\nrethrownError.stack += '\\n' + originalError.stack\n```\n\n```text\nconsole.error\n```\n\n```js\ntry {\n  // ···\n} catch (error) {\n  throw new Error(\n    `While processing ${filePath}`,\n    {\n      cause: error\n    }\n  );\n}\n```\n\n```text\nfunction fail() {\n  throw new RError({\n    name: 'BAR',\n    message: 'I messed up.'\n  })\n}\n\nfunction failFurther() {\n  try {\n    fail()\n  } catch (err) {\n    throw new RError({\n      name: 'FOO',\n      message: 'Something went wrong.',\n      cause: err\n    })\n  }\n}\n\ntry {\n  failFurther()\n} catch (err) {\n  console.error(err.why)\n  console.error(err.stacks)\n}\n```\n\n```text\nFOO: Something went wrong. <- BAR: I messed up.\nError\n    at failFurther (/Users/boris/Workspace/playground/es5/index.js:98:11)\n    at Object.<anonymous> (/Users/boris/Workspace/playground/es5/index.js:107:3)\n    at Module._compile (module.js:556:32)\n    at Object.Module._extensions..js (module.js:565:10)\n    at Module.load (module.js:473:32)\n    at tryModuleLoad (module.js:432:12)\n    at Function.Module._load (module.js:424:3)\n    at Module.runMain (module.js:590:10)\n    at run (bootstrap_node.js:394:7)\n<- Error\n    at fail (/Users/boris/Workspace/playground/es5/index.js:88:9)\n    at failFurther (/Users/boris/Workspace/playground/es5/index.js:96:5)\n    at Object.<anonymous> (/Users/boris/Workspace/playground/es5/index.js:107:3)\n    at Module._compile (module.js:556:32)\n    at Object.Module._extensions..js (module.js:565:10)\n    at Module.load (module.js:473:32)\n    at tryModuleLoad (module.js:432:12)\n    at Function.Module._load (module.js:424:3)\n    at Module.runMain (module.js:590:10)\n```\n\n```text\nError.prototype.cause\n```\n\n```text\nvar err1 = new VError('something bad happened');\nvar err2 = new VError(err1, 'something really bad happened here');\n\nconsole.log(VError.fullStack(err2));\n```\n\n```text\nfullStack\n```\n\n```text\nclass FullStackVError extends VError {\n  constructor(cause, ...args) {\n    super(cause, ...args);\n\n    let childFullStack;\n\n    if (cause instanceof VError) {\n      childFullStack = cause.stack;\n      cause.stack = cause._originalStack;\n    }\n\n    this._originalStack = this.stack;\n    this.stack = VError.fullStack(this);\n\n    if (cause instanceof VError) {\n      cause.stack = childFullStack;\n    }\n  }\n}\n```\n\n```text\nVError.fullStack\n```\n\n```text\nconsole.log(err2.stack);\n```\n\n```text\nconsole.log(VError.fullStack(err2));\n```\n\n========================================\n\nComments:\n- As someone who's used sequelize a fair bit: why are you rethrowing at all? The moment you hit `catch()` you should be handling the error in a way that does not lead to further throws.\n- @Mike'Pomax'Kamermans It is out of the scope of the question, but I originally did this to concat error `sql` prop to `msg`, I wasn't very happy to see in logs ER_KEY_COLUMN_DOES_NOT_EXITS that doesn't explain anything. But here I'm interested in the stack from rethrown error, `at sequelize.sync.catch...`. From original error, is not obvious at all where it has occured.\n- Preventing going down an XY Problem rabbit hole is never out of scope. As for the error from your comment: that is an incredibly clear MySQL error that tells you that you're using a column name for a table that doesn't *have* that column name. Nothing worth rethrowing errors there, you should just log the table name you tried to use and the set of columns you users, so you can verify against a MySQL `show create table {tablename}`\n- Thanks. Didn't know about this package and it obviously looks interesting in this context. Still not sure how it would be better to apply it to this situation. I've tried to use `MultiError`, it outputs `first of 2 errors...`, which is nice, but stack traces are still lost when the error is logged.\n- I have edited my response with more details about `fullStack` method.\n- Thanks, it helped.\n- Fwiw error.cause has already been supported in Node for a long time","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":260,"estimatedTokens":2518}}184{"id":"stack-58606137","source":"stackoverflow","questionId":58606137,"title":"Sequelize: escape string in a literal string","tags":["javascript","sql","sequelize.js","sql-injection"],"text":"Title: Sequelize: escape string in a literal string\nTags: javascript, sql, sequelize.js, sql-injection\nSource: Stack Overflow\n\nQuestion:\nI can use `literal` in Sequelize to manually build a SQL query part:\n\n```\nsequelize.literal(`\"foo\".bar ILIKE '%baz%'`)\n```\n\nBut if I want to add a var in this literal block, I now introduce SQL injection vulnerability:\n\n```\nsequelize.literal(`\"foo\".name ILIKE '%${myVar}%'`)\n```\n\nIs there a Sequelize way to protect variables in literal blocks?\n\n========================================\n\nTop Answer:\nYou may use `replacements` and `?` to avoid sql injections:\n\n```\nsequelize.query(`\"foo\".name ILIKE '%?%'`,\n { replacements: [myVar], type: sequelize.QueryTypes.SELECT }\n)\n```\n\n========================================\n\nCode:\n```text\nsequelize.literal(`\"foo\".bar ILIKE '%baz%'`)\n```\n\n```text\nsequelize.literal(`\"foo\".name ILIKE '%${myVar}%'`)\n```\n\n```text\nliteral\n```\n\n```text\nconst escapedSearch = sequelize.escape(`%${myVar}%`);\nsequelize.literal(`\"foo\".name ILIKE ${escapedSearch}`);\n```\n\n```text\nescape\n```\n\n```text\ndescription = {\n    $like: sequelize.literal(`${myVar} ESCAPE '\\\\'`)\n};\n```\n\n```text\nsequelize.query(`\"foo\".name ILIKE '%?%'`,\n  { replacements: [myVar], type: sequelize.QueryTypes.SELECT }\n)\n```\n\n```text\nreplacements\n```\n\n```text\n?\n```\n\n```text\nimport { sql } from '@sequelize/core';\n\nconst name = 'my name';\n\nconst users = await User.findAll({\n  where: { name: sql`${name}` },\n});\n```\n\n```text\nsql\n```\n\n========================================\n\nComments:\n- `sequelize.escape is not a function` tested as of 6.14.0.","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":92,"estimatedTokens":393}}185{"id":"stack-47755293","source":"stackoverflow","questionId":47755293,"title":"Sequelize - Rename column with index & constraint","tags":["migration","sequelize.js"],"text":"Title: Sequelize - Rename column with index & constraint\nTags: migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want create migration with Sequelize to rename column with camelCase to have a database with column in snake_case.\n\nI use Sequelize to create migration and use migration.\n\n```\nmodule.exports = {\n up: function(queryInterface, Sequelize) {\n return queryInterface.renameColumn('my_some_table', 'totoId', 'toto_id');\n },\n\n down: function(queryInterface, Sequelize) {\n //\n }\n};\n```\n\nBut... I have a unique constraint on this column (totoId) and name column, named **my_some_table_name_totoId_uindex**, and I also have an index on this column (totoId).\n\nHow I can force renaming column who have a unique constraint and one index?\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n      return queryInterface.renameColumn('my_some_table', 'totoId', 'toto_id');\n  },\n\n  down: function(queryInterface, Sequelize) {\n      //\n  }\n};\n```\n\n```text\n// 1) drop constraint\nqueryInterface.removeConstraint('my_some_table', 'my_constraint');\n\n// 2) rename column\nqueryInterface.renameColumn('my_some_table', 'totoId', 'toto_id');\n\n// 3) add constraint back\nqueryInterface.addConstraint('my_some_table', ['toto_id'], {\n    type: 'unique',\n    name: 'my_constraint'\n});\n```\n\n```text\nreturn queryInterface.sequelize.transaction(async (transaction) => {\n  await queryInterface.removeConstraint(\"my_some_table\", \"my_constraint\", {\n    transaction,\n  });\n  await queryInterface.renameColumn(\"my_some_table\", \"totoId\", \"toto_id\", {\n    transaction,\n  });\n  await queryInterface.addConstraint(\"my_some_table\", [\"toto_id\"], {\n    type: \"unique\",\n    name: \"my_constraint\",\n    transaction,\n  });\n});\n```\n\n```text\ntotoId\n```\n\n```text\ndown\n```\n\n========================================\n\nComments:\n- I think in PostgreSQL it just does a `ALTER TABLE` and works without any other conerns: postgresqltutorial.com/postgresql-tutorial/&hellip; SQLite likely still an issue. Maybe SQLite too? sqlite.org/lang_altertable.html Not sure.\n- I can't use SQL query directly :/\n- @pirmax you can just use the .query call directly in the migrations\n- \"Remember that migrations should be atomic operations. So you should create 3 migrations in that order.\" any reason not to use transactions and a single migration? Current docs exemplify it: sequelize.org/v5/manual/migrations.html\n- Actually, a transaction is even a better solution. I updated the answer to point it out.","metadata":{"transformedAt":"2026-08-18T18:33:34.352Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":86,"estimatedTokens":630}}186{"id":"stack-29313763","source":"stackoverflow","questionId":29313763,"title":"Accessing other models in a Sequelize model hook function","tags":["node.js","sequelize.js"],"text":"Title: Accessing other models in a Sequelize model hook function\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a model hook that automatically creates an associated record when the main model has been created. How can I access my other models within the hook function when my model file is structured as follows?\n\n```\n/**\n * Main Model\n */\nmodule.exports = function(sequelize, DataTypes) {\n\n var MainModel = sequelize.define('MainModel', {\n\n name: {\n type: DataTypes.STRING,\n }\n\n }, {\n\n classMethods: {\n associate: function(models) {\n\n MainModel.hasOne(models.OtherModel, {\n onDelete: 'cascade', hooks: true\n });\n\n }\n },\n\n hooks: {\n\n afterCreate: function(mainModel, next) {\n // ------------------------------------\n // How can I get to OtherModel here?\n // ------------------------------------\n }\n\n }\n\n });\n\n return MainModel;\n};\n```\n\n========================================\n\nTop Answer:\nYou can use `this.associations.OtherModel.target`.\n\n```\n/**\n * Main Model\n */\nmodule.exports = function(sequelize, DataTypes) {\n\n var MainModel = sequelize.define('MainModel', {\n\n name: {\n type: DataTypes.STRING,\n }\n\n }, {\n\n classMethods: {\n associate: function(models) {\n\n MainModel.hasOne(models.OtherModel, {\n onDelete: 'cascade', hooks: true\n });\n\n }\n },\n\n hooks: {\n\n afterCreate: function(mainModel, next) {\n /**\n * Check It!\n */\n this.associations.OtherModel.target.create({ MainModelId: mainModel.id })\n .then(function(otherModel) { return next(null, otherModel); })\n .catch(function(err) { return next(null); });\n }\n\n }\n\n });\n\n return MainModel;\n};\n```\n\n========================================\n\nCode:\n```text\n/**\n * Main Model\n */\nmodule.exports = function(sequelize, DataTypes) {\n\n  var MainModel = sequelize.define('MainModel', {\n\n    name: {\n      type: DataTypes.STRING,\n    }\n\n  }, {\n\n    classMethods: {\n      associate: function(models) {\n\n        MainModel.hasOne(models.OtherModel, {\n          onDelete: 'cascade', hooks: true\n        });\n\n      }\n    },\n\n    hooks: {\n\n      afterCreate: function(mainModel, next) {\n        // ------------------------------------\n        // How can I get to OtherModel here?\n        // ------------------------------------\n      }\n\n    }\n\n  });\n\n\n  return MainModel;\n};\n```\n\n```text\nsequelize.models.OtherModel\n```\n\n```text\n/**\n * Main Model\n */\nmodule.exports = function(sequelize, DataTypes) {\n\n  var MainModel = sequelize.define('MainModel', {\n\n    name: {\n      type: DataTypes.STRING,\n    }\n\n  }, {\n\n    classMethods: {\n      associate: function(models) {\n\n        MainModel.hasOne(models.OtherModel, {\n          onDelete: 'cascade', hooks: true\n        });\n\n      }\n    },\n\n    hooks: {\n\n      afterCreate: function(mainModel, next) {\n        /**\n         * Check It!\n         */\n        this.associations.OtherModel.target.create({ MainModelId: mainModel.id })\n        .then(function(otherModel) { return next(null, otherModel); })\n        .catch(function(err) { return next(null); });\n      }\n\n    }\n\n  });\n\n\n  return MainModel;\n};\n```\n\n```text\nthis.associations.OtherModel.target\n```\n\n========================================\n\nComments:\n- `sequelize` is not available.\n- `sequelize` should be available on `instance.sequelize` (`mainModel.sequelize` in the original question).\n- omg! thank you so much. you just saved me from an hour of confusion\n- the best practice is for check hasMany right ? so whenever the root have 3 child (hasMany) should change status column on root , may i right ?","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":198,"estimatedTokens":870}}187{"id":"stack-49890998","source":"stackoverflow","questionId":49890998,"title":"How to add column in Sequelize existing model?","tags":["node.js","database","orm","sequelize.js","sequelize-cli"],"text":"Title: How to add column in Sequelize existing model?\nTags: node.js, database, orm, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI have added a model and a migration file using this command \n\n```\nnode_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string\n```\n\nNow I wanted to add few more fields like gender and age in to the existing table(model). I changed model manually and fire this command \n\n```\nnode_modules/.bin/sequelize db:migrate\n```\n\nBut it is responding that \"No migrations were executed, database schema was already up to date.\n\"\n\n**User.js** \n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n var User = sequelize.define('User', {\n firstName: DataTypes.STRING,\n lastName: DataTypes.STRING,\n email: DataTypes.STRING\n }, {});\n User.associate = function(models) {\n // associations can be defined here\n };\n return User;\n};\n```\n\nThank you in advance :)\n\n========================================\n\nTop Answer:\nIn order to add new fields to the table,we should use migration skeleton as shown below.\n\n```\nsequelize migration:create --name Users\n```\n\nOpen the migration file and add the below codes\n\n```\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return [ queryInterface.addColumn(\n 'Users',\n 'gender',\n Sequelize.STRING\n ),\n queryInterface.addColumn(\n 'Users',\n 'age',\n Sequelize.STRING\n )];\n },\n\n down: function (queryInterface, Sequelize) {\n // logic for reverting the changes\n }\n};\n```\n\nThen just run the migration\n\n```\nnode_modules/.bin/sequelize db:migrate\n```\n\n**Note**: The passed **queryInterface** object can be used to modify the database. The **Sequelize** object stores the available data types such as STRING or INTEGER.\n\nFull list of methods in Query Interface\n\nI hope this will help you. If you have any issues let me know.\n\n========================================\n\nCode:\n```text\nnode_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string\n```\n\n```text\nnode_modules/.bin/sequelize db:migrate\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n  var User = sequelize.define('User', {\n    firstName: DataTypes.STRING,\n    lastName: DataTypes.STRING,\n    email: DataTypes.STRING\n  }, {});\n  User.associate = function(models) {\n    // associations can be defined here\n  };\n  return User;\n};\n```\n\n```text\nAdd altering commands here.\nReturn a promise to correctly handle asynchronicity.\n\nExample:\nreturn queryInterface.createTable('users', { id: Sequelize.INTEGER });\n```\n\n```text\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return Promise.all([\n      queryInterface.addColumn(\n        'Users',\n        'gender',\n         Sequelize.STRING\n       ),\n      queryInterface.addColumn(\n        'Users',\n        'age',\n        Sequelize.STRING\n      )\n    ]);\n  },\n\n  down: function (queryInterface, Sequelize) {\n    // logic for reverting the changes\n  }\n};\n```\n\n```text\nPromise.all\n```\n\n```text\nsequelize migration:create --name Users\n```\n\n```text\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return [ queryInterface.addColumn(\n              'Users',\n              'gender',\n               Sequelize.STRING\n             ),\n            queryInterface.addColumn(\n             'Users',\n             'age',\n             Sequelize.STRING\n          )];\n  },\n\n  down: function (queryInterface, Sequelize) {\n    // logic for reverting the changes\n  }\n};\n```\n\n```text\nnode_modules/.bin/sequelize db:migrate\n```\n\n```text\n**Promise.all**([queryInterface.addColumn(...)])\n```\n\n```text\ndb.sequelize.sync({ force: false, alter: true })\n```\n\n```text\nUser.sync({ alter: true })\n```\n\n```text\nalter\n```\n\n```bash\nnpx sequelize-cli migration:generate --name add_column_name_to_tablename\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    await queryInterface.addColumn('users', 'new_column', {\n      type: Sequelize.STRING,\n      allowNull: false,\n      defaultValue: ''\n    });\n\n    // Menempatkan kolom baru setelah kolom email\n    await queryInterface.sequelize.query('ALTER TABLE \"users\" ADD COLUMN \"new_column\" AFTER \"email\";');\n  },\n\n  down: async (queryInterface, Sequelize) => {\n    await queryInterface.removeColumn('users', 'new_column');\n  }\n};\n```\n\n```text\nnpx sequelize-cli db:migrate:undo\n```\n\n```text\nnpx sequelize-cli db:migrate\n```\n\n========================================\n\nComments:\n- can you attach the User.js file to the question?\n- I have added user.js file ! Please check\n- check the answer and let me know if you have difficulties\n- Link goes to a 404\n- \"Promise.all\" was missing in my case and throwing an exception. Thanks\n- I would recommend using a transaction to group both `addColumn` so if one fails, all rollsback gracefully, currently demonstrated in the docs: sequelize.org/v5/manual/migrations.html\n- is it will not reset data of all tables or specific table. if no what is purpose of migrations then ?\n- @JahangirHussain the purpose of migrations is that you can go up, but also down if needed. You also kinda have a history of structural db changes then","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":231,"estimatedTokens":1286}}188{"id":"stack-40703513","source":"stackoverflow","questionId":40703513,"title":"node js. Sequelize transactions","tags":["javascript","node.js","transactions","sequelize.js"],"text":"Title: node js. Sequelize transactions\nTags: javascript, node.js, transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 'Banks' table with 'money' field in my database,\n\nUsers can withdraw money periodically, but they can withdraw only if there is money > 0 in the bank.\n\nFirstly I should get the entity of bank, then check if(bank.money > amountToWithdraw) and then withdraw this amount.\n\nImagine the situation, when concurrent user try to withdraw some money.\nIn that moment when I check if(bank.money > amountToWithdraw) other user can perform withdraw operation and the real bank.money amount in the DB will be less.\n\nHow to apply transaction to finding bank operation(how to lock bank entity)?\n\n```\nmodels.sequelize.transaction(function (t) {\n\nreturn models.Banks.findOne({where: {\n money: {\n $gt: 0\n }\n }).then(function(bank){\n\n //in this moment other user finished the same operation\n// how to lock access for editing bank object by other users after //findOne method?\n\n bank.money -= amountToWithdraw;\n return bank.save({transaction: t});\n })\n})\n```\n\n========================================\n\nCode:\n```text\nmodels.sequelize.transaction(function (t) {\n\nreturn models.Banks.findOne({where: {\n    money: {\n      $gt: 0\n    }\n  }).then(function(bank){\n\n    //in this moment other user finished the same operation\n// how to lock access for editing bank object by other users after //findOne method?\n\n    bank.money -= amountToWithdraw;\n    return bank.save({transaction: t});\n  })\n})\n```\n\n```text\nmodels.sequelize.transaction(function (t) {\n\nreturn models.Banks.findOne({where: {\n       money: {\n         $gt: 0\n       }\n    }, lock: t.LOCK.UPDATE, transaction: t }).then(function(bank){\n\n    bank.money -= amountToWithdraw;\n    return bank.save({transaction: t});\n  })\n})\n```\n\n========================================\n\nComments:\n- You cannot understand how much TIME I've spent looking for a good solution. I think that documentation is not very clear about transaction usage. Your question saved my life!\n- How to use two rows, for example in one row I have quantity 10 and in other 20, I want to reduce 3 and give to other, so that new quantities will be 7 and 23 ?\n- Hi @drinchev, I am trying to implement transaction but getting error TypeError: Sequelize.transaction is not a function\n- First, you need to create a sequelize instance then you are able to access the transaction method. @AjendraPrasad","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":77,"estimatedTokens":606}}189{"id":"stack-42236837","source":"stackoverflow","questionId":42236837,"title":"How to perform a search with conditional where parameters using Sequelize","tags":["sql","node.js","sequelize.js"],"text":"Title: How to perform a search with conditional where parameters using Sequelize\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsually whenever I write a search query for SQL, I do something similar to this:\n\n```\nSELECT * FROM users u\nWHERE (@username IS NULL OR u.username like '%' + @username + '%')\nAND (@id IS NULL OR u.id = @id)\n```\n\nBasically this simulates a conditional WHERE clause. We only want to compare @searchParam to the column if @searchParam was provided.\n\nIs there a way to replicate this using Sequelize?\n\n**EDIT:** Here is my best attempt which fails:\n\n```\nmodels.user.findAll({\n where: {\n username: searchParams.username || models.sequelize.col('user.username'),\n id: searchParams.id || models.sequelize.col('user.id')\n }\n})\n```\n\n**UPDATE:** I found a way to do it, but it feels like a workaround. I'm certain there has to be a more elegant way. This works, but is ugly:\n\n```\nmodels.user.findAll({\n where: [\n '(? IS NULL OR \"user\".\"username\" LIKE ?) AND (? IS NULL OR \"user\".\"id\" = ?)',\n searchParams.username,\n `%${searchParams.username}%`,\n searchParams.id,\n searchParams.id\n ]\n})\n```\n\n========================================\n\nTop Answer:\nthat's pretty awesome. thank you. i use your ideas like that:\n\n```\napp.get('/', function (req, res) {\n ..\n let foo = await Foo.findAll(\n {\n offset: parseInt(req.query.offset | 0),\n limit: parseInt(req.query.limit | 10),\n where: getFooConditions(req),\n ...\n}\n\nfunction getFooConditions(req) {\n fooConditions = {};\n // Query param date\n if (req.query.date) {\n fooCondtions.start = {\n [Op.gte]: moment(parseInt(req.query.date)).utc().startOf('day'),\n [Op.lte]: moment(parseInt(req.query.date)).utc().endOf('day')\n }\n }\n // Query param name\n if (req.query.name) {\n fooCondtions.name = {\n [Op.like]: '%' + (req.query.name) + '%'\n }\n }\n // Query param id\n if (req.query.id) {\n fooCondtions.id = {\n [Op.equals]: '%' + (req.query.id) + '%'\n }\n }\n return fooConditions;\n}\n```\n\n========================================\n\nCode:\n```text\nSELECT * FROM users u\nWHERE (@username IS NULL OR u.username like '%' + @username + '%')\nAND (@id IS NULL OR u.id = @id)\n```\n\n```text\nmodels.user.findAll({\n  where: {\n    username: searchParams.username || models.sequelize.col('user.username'),\n    id: searchParams.id || models.sequelize.col('user.id')\n  }\n})\n```\n\n```text\nmodels.user.findAll({\n  where: [\n    '(? IS NULL OR \"user\".\"username\" LIKE ?) AND (? IS NULL OR \"user\".\"id\" = ?)',\n    searchParams.username,\n    `%${searchParams.username}%`,\n    searchParams.id,\n    searchParams.id\n  ]\n})\n```\n\n```text\nvar whereStatement = {};\nif(searchParams.id)\n    whereStatement.id = searchParams.id;\nif(searchParams.username)\n    whereStatement.username = {$like: '%' + searchParams.username + '%'};\nmodels.user.findAll({\n  where: whereStatement\n});\n```\n\n```text\nmodels.user.findAll({\n                where: {\n                    $and: [{\n                        $or: [{\n                            username: {\n                                $like: '%' + searchParams.username '%'\n                            }\n                        }, {\n                            username: null\n                        }]\n                    }, {\n                        $or: [{\n                                id: searchParams.id\n                        }, {\n                           id: null\n                        }]\n                    }]\n                }\n            })\n```\n\n```text\n$and\n```\n\n```text\n$or\n```\n\n```text\napp.get('/', function (req, res) {\n    ..\n    let foo = await Foo.findAll(\n    {\n        offset: parseInt(req.query.offset | 0),\n        limit: parseInt(req.query.limit | 10),\n        where: getFooConditions(req),\n    ...\n}\n\nfunction getFooConditions(req) {\n  fooConditions = {};\n  // Query param date\n  if (req.query.date) {\n    fooCondtions.start = {\n      [Op.gte]: moment(parseInt(req.query.date)).utc().startOf('day'),\n      [Op.lte]: moment(parseInt(req.query.date)).utc().endOf('day')\n    }\n  }\n  // Query param name\n  if (req.query.name) {\n    fooCondtions.name = {\n      [Op.like]: '%' + (req.query.name) + '%'\n    }\n  }\n  // Query param id\n  if (req.query.id) {\n    fooCondtions.id = {\n      [Op.equals]: '%' + (req.query.id) + '%'\n    }\n  }\n  return fooConditions;\n}\n```\n\n========================================\n\nComments:\n- This is not quite the same thing. Your example will return everything that equals searchParams.id or equals null. I'm wanting to return everything if searchParams.id is null, or everything that equals searchParams.id. See the difference?\n- Basically, what I can't figure out is how to check if searchParams.id is null. You could easily do this in a raw query, but I don't see a way to do it with the Sequelize operators.\n- Yeah, this really does seem to be the best way. I was hoping to avoid creating a long string of if checks, but it seems unavoidable at this point.\n- When my `whereStatement` object remains empty i get an error. What to do then? Sequelize 5.18.","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":197,"estimatedTokens":1244}}190{"id":"stack-42226351","source":"stackoverflow","questionId":42226351,"title":"Sequelize - Join with multiple column","tags":["node.js","sequelize.js","node-modules"],"text":"Title: Sequelize - Join with multiple column\nTags: node.js, sequelize.js, node-modules\nSource: Stack Overflow\n\nQuestion:\nI like to convert the following query into sequelize code\n\n```\nselect * from table_a \ninner join table_b \non table_a.column_1 = table_b.column_1\nand table_a.column_2 = table_b.column_2\n```\n\nI have tried many approaches and followed many provided solution but I am unable to achieve the desired query from sequelize code.\n\nThe max I achieve is following :\n\n```\nselect * from table_a \ninner join table_b \non table_a.column_1 = table_b.column_1\n```\n\nI want the second condition also.\n\n```\nand table_a.column_2 = table_b.column_2\n```\n\nany proper way to achieve it?\n\n========================================\n\nTop Answer:\nRegarding @TophatGordon 's doubt in accepted answer's comment: that if we need to have any associations set up in model or not.\n\nAlso went through the github issue raised back in 2012 that is still in **open** state.\n\nSo I was also in the same situation and trying to setup my own `ON` condition for left outer join.\n\nWhen I directly tried to use the `on: {...}` inside the `Table1.findAll(...include Table2 with ON condition...)`, it didn't work.\nIt threw an error:\n\n`EagerLoadingError [SequelizeEagerLoadingError]: Table2 is not associated to Table1!`\n\nMy use case was to match two non-primary-key columns from Table1 to two columns in Table2 in left outer join. I will show how and what I acheived:\n\nDon't get confused by table names and column names, as I had to change them from the original ones that I used.\n\nSO I had to create an association in Table1(Task) like:\n\n```\nTask.associate = (models) => { \n\nTask.hasOne(models.SubTask, {\n foreignKey: 'someId', // So the find query looks like this :\n\n```\nTask.findAll({\n where: whereCondition,\n // attributes: ['id','name','someId','someId2'],\n include: [{\n model: SubTask, as: 'subTask', // Resultant query:\n\n- One matching condition is taken from [foreignKey] = [sourceKey]\n\n- Second matching condition is obtained by `sequelize.where(...)` used in `scope:{...}`\n\n```\nselect\n \"Task\".\"id\",\n \"Task\".\"name\",\n \"Task\".\"some_id\" as \"someId\",\n \"Task\".\"some_id_2\" as \"someId2\"\nfrom\n \"task\" as \"Task\"\nleft outer join \"sub_task\" as \"subTask\" on\n \"Task\".\"some_id\" = \"subTask\".\"some_id\"\n and \"Task\".\"some_id_2\" = \"subTask\".\"some_id_2\";\n```\n\n### Another approach to achieve same as above to solve issues when using Table1 in include i.e. when Table1 appears as 2nd level table or is included from other table - say Table0\n\n```\nTask.associate = (models) => { \n\nTask.hasOne(models.SubTask, {\n foreignKey: 'someId', // \n // no constraints should be applied if sequelize will be creating tables and unique keys are not defined, \n //as it throws error of unique constraint \n constraints: false, \n });\n};\n```\n\nSo the find query from Table0 looks like this : *Also the foreignKey and sourceKey will not be considered as we will now use custom `on: {...}`*\n\n```\nTable0.findAll({\n where: whereCondition,\n // attributes: ['id','name','someId','someId2'],\n include: {\n model: Task, as: 'Table1AliasName', // if association has been defined as alias name \n include: [{\n model: SubTask, as: 'subTask', // subTask.some_id')\n ),\n sequelize.where(\n sequelize.col('Table1AliasName_OR_ModelName.some_id_2'),\n Op.eq, // '=',\n sequelize.col('Table1AliasName_OR_ModelName->subTask.some_id_2')\n ),\n ],\n },\n }],\n }\n});\n```\n\n### Skip below part if your tables are already created...\n\nSet constraints to false, as if sequelize tries to create the 2nd table(SubTask) it might throw error `(DatabaseError [SequelizeDatabaseError]: there is no unique constraint matching given keys for referenced table \"task\")` due to following query:\n\ncreate table if not exists \"sub_task\" (\"some_id\" INTEGER, \"some_id_2\"\nINTEGER references \"task\" (\"some_id\") on delete cascade on update\ncascade, \"data\" INTEGER);\n\nIf we set **constraint: false**, it creates this below query instead which will not throw unique constraint error as we are referencing non-primary column:\n\ncreate table if not exists \"sub_task\" (\"some_id\" INTEGER, \"some_id_2\" INTEGER, \"data\" INTEGER);\n\n========================================\n\nCode:\n```text\nselect * from table_a \ninner join table_b \non table_a.column_1 = table_b.column_1\nand table_a.column_2 = table_b.column_2\n```\n\n```text\nselect * from table_a \ninner join table_b \non table_a.column_1 = table_b.column_1\n```\n\n```text\nand table_a.column_2 = table_b.column_2\n```\n\n```text\nModelA.findAll({\n    include: [\n        {\n            model: ModelB,\n            on: {\n                col1: sequelize.where(sequelize.col(\"ModelA.col1\"), \"=\", sequelize.col(\"ModelB.col1\")),\n                col2: sequelize.where(sequelize.col(\"ModelA.col2\"), \"=\", sequelize.col(\"ModelB.col2\"))\n            },\n            attributes: [] // empty array means that no column from ModelB will be returned\n        }\n    ]\n}).then((modelAInstances) => {\n    // result...\n});\n```\n\n```text\non\n```\n\n```text\nJOIN\n```\n\n```text\nTask.associate = (models) => {    \n\nTask.hasOne(models.SubTask, {\n        foreignKey: 'someId', // <--- one of the column of table2 - SubTask: not a primary key here in my case; can be primary key also\n        sourceKey: 'someId', // <---  one of the column of table1 - Task: not a primary key here in my case; can be a primary key also\n        scope: {\n            [Op.and]: sequelize.where(sequelize.col(\"Task.some_id_2\"),\n                // '=',\n                Op.eq, // or you can use '=',\n                sequelize.col(\"subTask.some_id_2\")),\n        },\n        as: 'subTask',\n        // no constraints should be applied if sequelize will be creating tables and unique keys are not defined, \n        //as it throws error of unique constraint            \n        constraints: false, \n    });\n};\n```\n\n```text\nTask.findAll({\n    where: whereCondition,\n    // attributes: ['id','name','someId','someId2'],\n    include: [{\n        model: SubTask, as: 'subTask', // <-- model name and alias name as defined in association \n        attributes: [], // if no attributes needed from SubTask - empty array\n    },\n    ],\n});\n```\n\n```text\nselect\n  \"Task\".\"id\",\n  \"Task\".\"name\",\n  \"Task\".\"some_id\" as \"someId\",\n  \"Task\".\"some_id_2\" as \"someId2\"\nfrom\n  \"task\" as \"Task\"\nleft outer join \"sub_task\" as \"subTask\" on\n  \"Task\".\"some_id\" = \"subTask\".\"some_id\"\n  and \"Task\".\"some_id_2\" = \"subTask\".\"some_id_2\";\n```\n\n```text\nTask.associate = (models) => {    \n\nTask.hasOne(models.SubTask, {\n        foreignKey: 'someId', // <--- one of the column of table2 - SubTask: not a primary key here in my case; can be primary key also\n        sourceKey: 'someId', // <---  one of the column of table1 - Task: not a primary key here in my case; can be a primary key also\n        as: 'subTask',\n        // <-- removed scope -->\n        // no constraints should be applied if sequelize will be creating tables and unique keys are not defined, \n        //as it throws error of unique constraint            \n        constraints: false, \n    });\n};\n```\n\n```text\nTable0.findAll({\n    where: whereCondition,\n    // attributes: ['id','name','someId','someId2'],\n    include: {\n        model: Task, as: 'Table1AliasName', // if association has been defined as alias name \n        include: [{\n            model: SubTask, as: 'subTask', // <-- model name and alias name as defined in association \n            attributes: [], // if no attributes needed from SubTask - empty array\n            on: {\n                [Op.and]: [\n                    sequelize.where(\n                        sequelize.col('Table1AliasName_OR_ModelName.some_id'),\n                        Op.eq, // '=',\n                        sequelize.col('Table1AliasName_OR_ModelName->subTask.some_id')\n                    ),\n                    sequelize.where(\n                        sequelize.col('Table1AliasName_OR_ModelName.some_id_2'),\n                        Op.eq, // '=',\n                        sequelize.col('Table1AliasName_OR_ModelName->subTask.some_id_2')\n                    ),\n                ],\n            },\n        }],\n    }\n});\n```\n\n```text\nON\n```\n\n```text\non: {...}\n```\n\n```text\nTable1.findAll(...include Table2 with ON condition...)\n```\n\n```text\nEagerLoadingError [SequelizeEagerLoadingError]: Table2 is not associated to Table1!\n```\n\n```text\nsequelize.where(...)\n```\n\n```text\nscope:{...}\n```\n\n```text\non: {...}\n```\n\n```text\n(DatabaseError [SequelizeDatabaseError]: there is no unique constraint matching given keys for referenced table \"task\")\n```\n\n========================================\n\nComments:\n- Getting error : TypeError: Cannot read property 'indexOf' of undefined\n- What should I write in model file?\n- Does this require you to set up any associations on either of the models? I’m looking at doing something very similar. There are no FKs on the tables so not wanting to add any associations if possible. Thanks.\n- @TophatGordon I tried to make a solution for one of my use cases. Please check my answer here and see if that helps you.\n- Wow... this was REALLY timely, lol. I was just looking for how to accomplish this and BOOM it was answered 6 hours earlier. Thanks @Abhishek Shah!\n- @KyleFarris 2 months back I came to this same post and also the github issue , but there wasn't any specific answer that I got for the problem. And today here I am back with a solution, that might help atleast a little.\n- how does this work when `Task` is part of an `as`? e.g. `user->tasks` because `Task` is nested in an include?\n- @Jayen Can you refer the Table0.findAll part of the answer. Does that help?\n- yes, thanks. i ended up using `user->tasks` in `scope` instead of `where` as i have a few similar queries. using `separate:true` worked as well but for other reasons i couldn't use that.","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":308,"estimatedTokens":2427}}191{"id":"stack-55646233","source":"stackoverflow","questionId":55646233,"title":"Updating with calculated values in Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Updating with calculated values in Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to run an update query on my model using the previous value in one of the fields.\n\nThis updates the model (row id=4) the 'seq' field to 5.\n\n```\nModel.update({\n seq: 5\n },{\n where:{\n 'id':4,\n\n }\n });\n```\n\nNow how do I update the model to the previous value stored in the 'seq' field + 5 ?\n\n```\nModel.update({\n seq: 'seq' + 5\n },{\n where:{\n 'id':4,\n\n }\n });\n```\n\n========================================\n\nTop Answer:\nYou can do this by using increment\n\n```\nModel.increment(\n { seq: +5 },\n { where: { id: 4 } }\n );\n```\n\nand output:\n\n```\nUPDATE `Model` SET `seq`=`seq`+ 5 WHERE `id` = 4\n```\n\n========================================\n\nCode:\n```text\nModel.update({\n        seq: 5\n    },{\n        where:{\n            'id':4,\n\n        }\n    });\n```\n\n```text\nModel.update({\n            seq: 'seq' + 5\n        },{\n            where:{\n                'id':4,\n\n            }\n        });\n```\n\n```text\nModel.update(\n  { seq: sequelize.literal('seq + 5') },\n  { where: { id: model_id } }\n);\n```\n\n```text\nModel.increment('seq', { by: 5, where: { id: 'model_id' }});\n```\n\n```text\nincrement\n```\n\n```text\nModel.increment(\n        { seq: +5 },\n        { where: { id: 4 } }\n      );\n```\n\n```text\nUPDATE `Model` SET `seq`=`seq`+ 5 WHERE `id` = 4\n```\n\n```text\nUsers.increment('aa', { by: 5, where: { gender: 'female' } });\n```\n\n```text\nconst Inverses = sequelize.define('Inverses',\n  {\n    myValue: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n    },\n    inverse: {\n      type: DataTypes.INTEGER,\n    },\n    name: {\n      type: DataTypes.STRING,\n    },\n  },\n  { timestamps: false }\n);\nawait Inverses.sync({ force: true })\nasync function reset() {\n  await sequelize.truncate({ cascade: true })\n  await Inverses.create({ myValue: 2, inverse: -2, name: 'two' });\n  await Inverses.create({ myValue: 3, inverse: -3, name: 'three' });\n  await Inverses.create({ myValue: 5, inverse: -5, name: 'five' });\n}\n```\n\n```text\nawait Inverses.update(\n  { inverse: 0, },\n  { where: { myValue: { [Op.gt]: 2 } } },\n);\n```\n\n```text\n{ myValue: 2, inverse: -2, name: 'two'   },\n{ myValue: 3, inverse:  0, name: 'three' },\n{ myValue: 5, inverse:  0, name: 'five'  },\n```\n\n```text\nawait Inverses.update(\n  { inverse: sequelize.col('myValue'), },\n  { where: { myValue: { [Op.gt]: 2 } } },\n);\n```\n\n```text\n{ myValue: 2, inverse: -2, name: 'two'   },\n{ myValue: 3, inverse:  3, name: 'three' },\n{ myValue: 5, inverse:  5, name: 'five'  },\n```\n\n```text\nawait Inverses.update(\n  { inverse: sequelize.fn('1 + ', sequelize.col('myValue')), },\n  { where: { myValue: { [Op.gt]: 2 } } },\n);\n```\n\n```text\n{ myValue: 2, inverse: -2, name: 'two'   },\n{ myValue: 3, inverse:  4, name: 'three' },\n{ myValue: 5, inverse:  6, name: 'five'  },\n```\n\n```text\nawait Inverses.update(\n  { name: sequelize.fn('upper', sequelize.col('name')), },\n  { where: { myValue: { [Op.gt]: 2 } } },\n);\n```\n\n```text\n{ myValue: 2, inverse: -2, name: 'two'   },\n{ myValue: 3, inverse: -3, name: 'THREE' },\n{ myValue: 5, inverse: -5, name: 'FIVE'  },\n```\n\n```text\nawait Inverses.update(\n  { inverse: sequelize.where(sequelize.col('myValue'), '*', sequelize.col('inverse')), },\n  { where: { myValue: { [Op.gt]: 2 } } },\n);\n```\n\n```text\n{ myValue: 2, inverse:  -2, name: 'two'   },\n{ myValue: 3, inverse:  -9, name: 'three' },\n{ myValue: 5, inverse: -25, name: 'five'  },\n```\n\n```text\nawait Inverses.update(\n  { inverse: sequelize.literal('\"myValue\" * \"inverse\"'), },\n  { where: { myValue: { [Op.gt]: 2 } } },\n);\n```\n\n```text\n{ myValue: 2, inverse:  -2, name: 'two'   },\n{ myValue: 3, inverse:  -9, name: 'three' },\n{ myValue: 5, inverse: -25, name: 'five'  },\n```\n\n```text\nawait Inverses.update(\n  { inverse: sequelize.where(sequelize.col('myValue'), '*', -2), },\n  { where: { myValue: { [Op.gt]: 2 } } },\n);\n```\n\n```text\n{ myValue: 2, inverse:  -2, name: 'two'   },\n{ myValue: 3, inverse:  -6, name: 'three' },\n{ myValue: 5, inverse: -10, name: 'five'  },\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.14.0\",\n    \"sql-formatter\": \"4.0.2\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\nliteral\n```\n\n========================================\n\nComments:\n- Can this be used with upsert?","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":245,"estimatedTokens":1084}}192{"id":"stack-39651853","source":"stackoverflow","questionId":39651853,"title":"How to create join table with foreign keys with sequelize or sequelize-cli","tags":["node.js","join","foreign-keys","sequelize.js","sequelize-cli"],"text":"Title: How to create join table with foreign keys with sequelize or sequelize-cli\nTags: node.js, join, foreign-keys, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI'm creating models and migrations for two types, Player and Team that have many to many relationship. I'm using sequelize model:create, but don't see how to specify foreign keys or join tables.\n\n```\nsequelize model:create --name Player --attributes \"name:string\"\nsequelize model:create --name Team --attributes \"name:string\"\n```\n\nAfter the model is created, I add associations.\nIn Player:\n\n```\nPlayer.belongsToMany(models.Team, { through: 'PlayerTeam', foreignKey: 'playerId', otherKey: 'teamId' });\n```\n\nIn Team:\n\n```\nTeam.belongsToMany(models.Player, { through: 'PlayerTeam', foreignKey: 'teamId', otherKey: 'playerId' });\n```\n\nThen the migrations are run with\n\n```\nsequelize db:migrate\n```\n\nThere are tables for Player and Team but there's no join table (nor foreign keys) in the database. How can the foreign keys and join table be created? Is there a definitive guide on how to do this?\n\n========================================\n\nCode:\n```text\nsequelize model:create --name Player --attributes \"name:string\"\nsequelize model:create --name Team --attributes \"name:string\"\n```\n\n```text\nPlayer.belongsToMany(models.Team, { through: 'PlayerTeam', foreignKey: 'playerId', otherKey: 'teamId' });\n```\n\n```text\nTeam.belongsToMany(models.Player, { through: 'PlayerTeam', foreignKey: 'teamId', otherKey: 'playerId' });\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n    return queryInterface.createTable('PlayerTeam', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n    playerId: {\n      type: Sequelize.INTEGER,\n      allowNull: false,\n      references: {\n        model: 'Player',\n        key: 'id'\n      },\n      onUpdate: 'cascade',\n      onDelete: 'cascade'\n    },\n    teamId: {\n      type: Sequelize.INTEGER,\n      allowNull: false,\n      references: {\n        model: 'Team',\n        key: 'id'\n      },\n      onUpdate: 'cascade',\n      onDelete: 'cascade'\n    },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    }).then(() => {\n      // Create Unique CompoundIndex\n      let sql = `CREATE UNIQUE INDEX \"PlayerTeamCompoundIndex\"\n              ON public.\"PlayerTeam\"\n              USING btree\n              (\"playerId\", \"teamId\");\n            `;\n      return queryInterface.sequelize.query(sql, {raw: true});\n      });\n  },\n  down: function(queryInterface, Sequelize) {\n    return queryInterface.dropTable('PlayerTeam');\n  }\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":106,"estimatedTokens":695}}193{"id":"stack-49251948","source":"stackoverflow","questionId":49251948,"title":"Unable to execute the raw query in Sequelize migrations","tags":["node.js","express","sequelize.js"],"text":"Title: Unable to execute the raw query in Sequelize migrations\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to update my database using Sequelize migrations so I have tried to write a Sequelize migrations like this \n\n```\n'use strict';\nmodule.exports = {\n up: (queryInterface, Sequelize, migration) => {\n queryInterface.addColumn('coaching_class_entries', 'bill_cycle', {\n type: Sequelize.INTEGER(4),\n allowNull: false,\n defaultValue: '0',\n field: 'bill_cycle',\n after: 'fees'\n })\n .then(() => queryInterface.addColumn('coaching_classes', 'bill_plans', {\n type: Sequelize.JSON,\n allowNull: false,\n defaultValue: 'NULL',\n field: 'bill_plans',\n after: 'bill_cycle'\n }))\n .then(() =>\n migration.migrator.Sequelize.query('UPDATE coaching_classes SET bill_plans = JSON_ARRAY(JSON_OBJECT(\"cycle\", bill_cycle, \"fee\", fees));'));\n\n },\n\n down: (queryInterface, Sequelize) => {\n let migrations = [];\n\n migrations.push(queryInterface.removeColumn('coaching_class_entries', 'bill_cycle'))\n migrations.push(queryInterface.removeColumn('coaching_classes', 'bill_plans'))\n return Promise.all(migrations);\n\n }\n};\n```\n\nBut it is always giving me error in raw query line \n\n Cannot read property 'Sequelize' of undefined \n\nWhat is the correct syntax for this?\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = {\n  up: (queryInterface, Sequelize, migration) => {\n    queryInterface.addColumn('coaching_class_entries', 'bill_cycle', {\n      type: Sequelize.INTEGER(4),\n      allowNull: false,\n      defaultValue: '0',\n      field: 'bill_cycle',\n      after: 'fees'\n    })\n      .then(() => queryInterface.addColumn('coaching_classes', 'bill_plans', {\n        type: Sequelize.JSON,\n        allowNull: false,\n        defaultValue: 'NULL',\n        field: 'bill_plans',\n        after: 'bill_cycle'\n      }))\n      .then(() =>\n        migration.migrator.Sequelize.query('UPDATE coaching_classes  SET bill_plans = JSON_ARRAY(JSON_OBJECT(\"cycle\", bill_cycle, \"fee\", fees));'));\n\n  },\n\n  down: (queryInterface, Sequelize) => {\n    let migrations = [];\n\n    migrations.push(queryInterface.removeColumn('coaching_class_entries', 'bill_cycle'))\n    migrations.push(queryInterface.removeColumn('coaching_classes', 'bill_plans'))\n    return Promise.all(migrations);\n\n  }\n};\n```\n\n```text\nqueryInterface.sequelize.query\n```\n\n========================================\n\nComments:\n- I tried this and worked for me. The problem i am facing is it returns me the time field converted to `2019-10-01T08:00:00.000Z`, but i want just `2019-10-01 08:00:00`. What i have in Db for that column is `2019-10-01 08:00:00` I want same in result. Do you have any solution for this? If i run same query in mysqlworkbench, i get same result as it is stored in DB, but when .i use `queryInterface.sequelize.query` , i get other one.","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":92,"estimatedTokens":713}}194{"id":"stack-25954491","source":"stackoverflow","questionId":25954491,"title":"node-webkit Error: please install sqlite3 package manually","tags":["node.js","sqlite","node-webkit","sequelize.js"],"text":"Title: node-webkit Error: please install sqlite3 package manually\nTags: node.js, sqlite, node-webkit, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm working with `node-webkit`, `Sequelize` and `sqlite3`. Node runs the app with no problems, but when I run it from node-webkit it throws me this Error\n\n```\n\"Uncaught Error: The dialect sqlite is not supported. (Error: Please install sqlite3 package manually)\", source: /Users/mariowise/projects/node-webkit/requies-pos/node_modules/sequelize/lib/sequelize.js (176)\n```\n\nThis are my dependencies\n\n```\n\"dependencies\": {\n \"express\": \"~4.2.0\",\n \"static-favicon\": \"~1.0.0\",\n \"morgan\": \"~1.0.0\",\n \"cookie-parser\": \"~1.0.1\",\n \"body-parser\": \"~1.0.0\",\n \"debug\": \"~0.7.4\",\n \"jade\": \"~1.3.0\",\n \"nunjucks\": \"^1.0.5\",\n \"sqlite3\": \"~2.1.19\",\n \"config\": \"0.4.33\",\n \"sequelize\": \"~2.0.0-rc1\",\n \"sequelize-sqlite\": \"~1.7.0\"\n}\n```\n\n========================================\n\nCode:\n```text\n\"Uncaught Error: The dialect sqlite is not supported. (Error: Please install sqlite3 package manually)\", source: /Users/mariowise/projects/node-webkit/requies-pos/node_modules/sequelize/lib/sequelize.js (176)\n```\n\n```text\n\"dependencies\": {\n    \"express\": \"~4.2.0\",\n    \"static-favicon\": \"~1.0.0\",\n    \"morgan\": \"~1.0.0\",\n    \"cookie-parser\": \"~1.0.1\",\n    \"body-parser\": \"~1.0.0\",\n    \"debug\": \"~0.7.4\",\n    \"jade\": \"~1.3.0\",\n    \"nunjucks\": \"^1.0.5\",\n    \"sqlite3\": \"~2.1.19\",\n    \"config\": \"0.4.33\",\n    \"sequelize\": \"~2.0.0-rc1\",\n    \"sequelize-sqlite\": \"~1.7.0\"\n}\n```\n\n```text\nnode-webkit\n```\n\n```text\nSequelize\n```\n\n```text\nsqlite3\n```\n\n```text\nsqlite3\n```\n\n========================================\n\nComments:\n- Hmm, strange, i'm not familiar with node-webkit but sequelize just require's sqlite so it uses the regular npm lookup. You can remove sequelize-sqlite as a dependency by the way, just use sequelize and sqlite3\n- If helps someone, this worked for me with `node@0.12.3`. Some how i've installed `node@0.12.0-alpha2` and it was not working. So there you go. Sorry the late validation, but just today I had time to test this. Thank you very much Jeff.","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":75,"estimatedTokens":522}}195{"id":"stack-28787889","source":"stackoverflow","questionId":28787889,"title":"How can I set up Sequelize.js to stream data instead of a promise / callback?","tags":["mysql","node.js","sequelize.js"],"text":"Title: How can I set up Sequelize.js to stream data instead of a promise / callback?\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using `MySQL` and have a very large response (15,000+ rows). This takes.. well.. time. But I can start to process the first result right away. Can I set up a stream somehow with `sequelize`? If so, how?\n\n========================================\n\nTop Answer:\nAlso you can use `node-sequelize-stream` library.\n\n========================================\n\nCode:\n```text\nMySQL\n```\n\n```text\nsequelize\n```\n\n```text\nconnection.query(mySavedQuery).stream().pipe(...)\n```\n\n```text\nnode-sequelize-stream\n```\n\n```text\nexport async function* findAllPagination<M extends Model>(\n  model: ModelStatic<M>,\n  options: FindOptions<Attributes<M>>,\n  pageSize: number,\n) {\n  if (!options.order) {\n    throw new Error(`${model.name} has no order defined. Order is required to provide stable pagination`);\n  }\n  let offset = 0;\n  let count = 0;\n  do {\n    const result = await model.findAll({\n      ...options,\n      limit: pageSize,\n      offset,\n    });\n    yield result;\n    count = result.length;\n    offset += count;\n  } while (count === pageSize);\n}\n```\n\n```text\nconst loader = findAllPagination(MyModel, {\n  where: {\n    foo: 'bar',\n  },\n  order: [['id', 'DESC']],\n}, 1000);\nfor await (const features of loader) {\n  doThings(features)\n}\n```\n\n```text\norder\n```\n\n========================================\n\nComments:\n- Apparently this module is running multiple queries with offset and limit here. Streaming will be done in `O(n^2)` IO complexity.","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":397}}196{"id":"stack-61575312","source":"stackoverflow","questionId":61575312,"title":"sequelize migrations not running","tags":["node.js","orm","graphql","migration","sequelize.js"],"text":"Title: sequelize migrations not running\nTags: node.js, orm, graphql, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm having a weird issue with Sequelize I haven't encountered before, when I try to run my migrations nothing happens. I get the following output:\n\n```\nLoaded configuration file \"config\\config.json\"\nUsing environment \"development\"\n```\n\nAnd the program just exists back.\n\nI've checked my code multiple times over and everything checks out.\n\nModel code:\n\n```\nmodule.exports = {\nup: (queryInterface, Sequelize) => {\n return queryInterface.createTable(\"users\", {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n username: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n email: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false,\n validate: {\n notEmpty: true,\n isEmail: true\n }\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n notEmpty: true,\n len: [7, 42]\n }\n },\n createdAt: {\n type: Sequelize.DATE\n },\n updatedAt: {\n type: Sequelize.DATE\n }\n })\n},\ndown: (queryInterface, Sequelize) => {\n return queryInterface.dropTable(\"users\")\n}\n```\n\n}\n\nAnd here is a snippet from my model/index.js:\n\n```\nconst fs = require(\"fs\")\nconst path = require(\"path\")\nconst Sequelize = require(\"sequelize\")\n\nconst basename = path.basename(__filename)\nconst env = process.env.TEST_ENV || \"development\"\nconst config = require(`${__dirname}/../config/config.js`)[env]\nconst db = {}\n\nconsole.log('config', config)\n\nlet sequelize\nif (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config)\n} else {\n sequelize = new Sequelize(\n config.database,\n config.username,\n config.password,\n config\n )\n}\n```\n\nIt's almost like sequelize just isn't picking up any of migrations file. I'm not sure how I should troubleshoot this. Any help on this would be much appreciated.\n\n========================================\n\nTop Answer:\nUpdating `pg` fixed the issue on my end.\n\n```\nnpm install --save pg@latest\n```\n\n========================================\n\nCode:\n```text\nLoaded configuration file \"config\\config.json\"\nUsing environment \"development\"\n```\n\n```text\nmodule.exports = {\nup: (queryInterface, Sequelize) => {\n    return queryInterface.createTable(\"users\", {\n        id: {\n            allowNull: false,\n            autoIncrement: true,\n            primaryKey: true,\n            type: Sequelize.INTEGER\n        },\n        username: {\n            type: Sequelize.STRING,\n            unique: true,\n            allowNull: false,\n            validate: {\n                notEmpty: true\n            }\n        },\n        email: {\n            type: Sequelize.STRING,\n            unique: true,\n            allowNull: false,\n            validate: {\n                notEmpty: true,\n                isEmail: true\n            }\n        },\n        password: {\n            type: Sequelize.STRING,\n            allowNull: false,\n            validate: {\n                notEmpty: true,\n                len: [7, 42]\n            }\n        },\n        createdAt: {\n            type: Sequelize.DATE\n        },\n        updatedAt: {\n            type: Sequelize.DATE\n        }\n    })\n},\ndown: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable(\"users\")\n}\n```\n\n```text\nconst fs = require(\"fs\")\nconst path = require(\"path\")\nconst Sequelize = require(\"sequelize\")\n\nconst basename = path.basename(__filename)\nconst env = process.env.TEST_ENV || \"development\"\nconst config = require(`${__dirname}/../config/config.js`)[env]\nconst db = {}\n\nconsole.log('config', config)\n\nlet sequelize\nif (config.use_env_variable) {\n    sequelize = new Sequelize(process.env[config.use_env_variable], config)\n} else {\n    sequelize = new Sequelize(\n        config.database,\n        config.username,\n        config.password,\n        config\n    )\n}\n```\n\n```text\nsequelize db:migrate:all\n```\n\n```text\nnpm install --save pg@latest\n```\n\n```text\npg\n```\n\n```text\nnpm install pg@latest\n```\n\n========================================\n\nComments:\n- Did you ever figure out why version 14 doesn't work (and possible file an issue)?\n- No, nothing concrete but I think the issue was that the migrations were initially setup with Node 10.13.0 so when I tried to run them with 14 there was some sort of compatibility issue.\n- It seems like this was a compatibility issue between Node 14 and the pg library. Updating to pg@8.0.3 fixed the issue without needing to downgrade Node.\n- @bradley2w1dl Thanks,, having the same issue and npm install --save pg@latest fixed it for me.\n- that command doesn't exist at least in my CLI version 5.5.1\n- does not exist in verion 5 `sequelize db:migrate Run pending migrations`\n- Life saver. Thank you so much.","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":213,"estimatedTokens":1190}}197{"id":"stack-26021965","source":"stackoverflow","questionId":26021965,"title":"Sequelize with NodeJS can't join tables with limit","tags":["sql","node.js","sequelize.js"],"text":"Title: Sequelize with NodeJS can't join tables with limit\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement a simple query that should look like this:\n\n```\nselect * from property join entity_area on property.id=entity_area.entity_id and entity_area.area_id=1 where property.price>300000 limit 12\n```\n\nPretty straightforward: I want to get the joined result and then to limit to 12.\n\nIn Sequelize i'm using the following function:\n\n```\nreturn models.property.findAll(\n{\n where: [\"price>=?\", 300000],\n include: [\n {\n model:models.entity_area,\n where: { area_id:1 }\n }\n ],\n limit:12\n})\n```\n\nBut this code generates the following sql:\n\n```\nselect property.*, entity_area.* from (select * from property where property.price>300000 limit 12) join entity_area on property.id=entity_area.entity_id and entity_area.area_id=1\n```\n\nWhich has totally different logic from what i'm trying to do because in the generated sql it first gets any 12 results and then tries to join with entity_area, and of course the random 12 results don't necessarily match the entity_area, so i'm getting no results back.\n\nPlease suggest me a proper way of doing it. The property table is very massive, and i have to use the \"limit\" rather than getting all the results and slicing them in javascript. Also i wouldn't like to start using raw queries.\n\n========================================\n\nTop Answer:\n```\nmodels.property.findAll(\n{\n where: [...],\n include: [{...}],\n limit:12\n},\n{\n subQuery:false\n})\n```\n\n========================================\n\nCode:\n```text\nselect * from property join entity_area on property.id=entity_area.entity_id and entity_area.area_id=1 where property.price>300000 limit 12\n```\n\n```text\nreturn models.property.findAll(\n{\n    where: [\"price>=?\", 300000],\n    include: [\n    {\n        model:models.entity_area,\n        where: { area_id:1 }\n    }\n    ],\n    limit:12\n})\n```\n\n```text\nselect property.*, entity_area.* from (select * from property where property.price>300000 limit 12) join entity_area on property.id=entity_area.entity_id and entity_area.area_id=1\n```\n\n```text\nsubQuery = limit && (options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation) && options.subQuery !== false\n```\n\n```text\nreturn models.property.findAll(\n{\n    where: [\"price>=?\", 300000],\n    include: [\n    {\n        model:models.entity_area,\n        where: { area_id:1 }\n    }\n    ],\n    limit:12,\n    subQuery:false\n})\n```\n\n```text\nsubQuery = limit && (options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation) && options.subQuery !== false && options.doSubQuery===true\n```\n\n```text\nmodels.property.findAll(\n{\n    where: [...],\n    include: [{...}],\n    limit:12\n},\n{\n    subQuery:false\n})\n```\n\n```text\nUser.findAll(\n{\n  where: {\n    $Tasks$: null,\n  },\n  include: [\n    {\n      model: Task,\n      // required: false,\n    },\n  ],\n  limit: 3,\n  subQuery: false,\n})\n```\n\n```text\nsubQuery: false,\n```\n\n```text\nsubquery: false\n```\n\n========================================\n\nComments:\n- github.com/sequelize/sequelize/blob/master/lib/dialects/&hellip; Code looks a bit different these days so `options.subQuery = false` should simply work.\n- @MickHansen this solved my problem too, but I'm a bit concerned because this isn't in Sequelize's documentation. Is it safe to rely on that?\n- They fixed this problem in current version (@6.6.5). You need to use just `subquery: false` in options\n- Thanks a lot! This is the right answar. You saved me lot of work\n- One issue with this solution: if any of the associated models have a one-to-many relationship with the base model, then less results will be returned.\n- i have used subQuery: false but i think limit not working properly in my calse\n- It did work. but can someone pls explain why subQuery:false works ?\n- I'm not sure if this solution will behave as desired. If no subquery is used, then the limit effectively limits both users and tasks. Eg if the first user in the result set has three tasks, then only that user will be returned. And if a user has more than three tasks, then only three of his tasks will be included, and of course, no other users.","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":150,"estimatedTokens":1044}}198{"id":"stack-28056211","source":"stackoverflow","questionId":28056211,"title":"How to choose name of Foreign Key column using Sequelize and mySql?","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: How to choose name of Foreign Key column using Sequelize and mySql?\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize to model a mySql-database schema in my node-application. An extract of my model looks like this:\nI have a company-table and a department-table. A company can have multiple departments and a department belongs to only one company. I modeled this as follows:\n\nThe company-table:\n\n```\nmodule.exports = function(sequelize, DataTypes){\nreturn Company = sequelize.define('Company', {\n companyId: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true,\n unique: true \n },\n name: {\n type: DataTypes.STRING,\n allowNull: false\n }\n})}\n```\n\nThe department-table:\n\n```\nvar Company = require('./company');\n\nmodule.exports = function(sequelize,DataTypes) {\nreturn Department = sequelize.define('Department', {\n departmentId: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true,\n unique: true\n },\n name: {\n type: DataTypes.STRING,\n allowNull: false \n },\n companyId: {\n type: DataTypes.INTEGER,\n references: 'Companies',\n referencesKey: 'companyId',\n onDelete: 'cascade'\n }\n});}\n```\n\nTo actually store this schema in the database I use the following code:\n\n```\nvar db = require('../models/index');\ndb[\"Company\"].hasMany(db[\"Department\"], {as: 'departments'});\ndb[\"Department\"].belongsTo(db[\"Company\"], {foreignKey: 'companyId', foreignKeyConstraint: true});\n\nmodels.sequelize.sync().complete(function(err){\n //irrelevant for the problem\n});\n```\n\nThe problem is that this code creates 2 foreign keys in the department table. One on the field \"companyId\" (as expected) but also one on the field \"CompanyCompanyId\", a field that is automatically generated.\n\nHow can I make sure that only the foreign key I defined ('companyId') is used and created?\n\n========================================\n\nTop Answer:\nIn the version 4.4.0, there is a targetKey option for the belongsTo function.\n\n```\nconst User = this.sequelize.define('user', {/* attributes */})\nconst Company = this.sequelize.define('company', {/* attributes */});\n\nUser.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User\n```\n\nmore information on http://docs.sequelizejs.com/manual/tutorial/associations.html#target-keys\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes){\nreturn Company = sequelize.define('Company', {\n    companyId: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        allowNull: false,\n        autoIncrement: true,\n        unique: true            \n    },\n    name: {\n        type: DataTypes.STRING,\n        allowNull: false\n    }\n})}\n```\n\n```text\nvar Company = require('./company');\n\nmodule.exports = function(sequelize,DataTypes) {\nreturn Department = sequelize.define('Department', {\n    departmentId: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        allowNull: false,\n        autoIncrement: true,\n        unique: true\n    },\n    name: {\n        type: DataTypes.STRING,\n        allowNull: false            \n    },\n    companyId: {\n        type:           DataTypes.INTEGER,\n        references:     'Companies',\n        referencesKey:  'companyId',\n        onDelete:       'cascade'\n    }\n});}\n```\n\n```text\nvar db = require('../models/index');\ndb[\"Company\"].hasMany(db[\"Department\"], {as: 'departments'});\ndb[\"Department\"].belongsTo(db[\"Company\"], {foreignKey: 'companyId', foreignKeyConstraint: true});\n\nmodels.sequelize.sync().complete(function(err){\n    //irrelevant for the problem\n});\n```\n\n```text\nvar db = require('../models/index');\ndb[\"Company\"].hasMany(db[\"Department\"], {as: 'departments'});\ndb[\"Department\"].belongsTo(db[\"Company\"], {foreignKey: 'companyId', foreignKeyConstraint: true});\n```\n\n```text\nvar db = require('../models/index');\ndb[\"Company\"].hasMany(db[\"Department\"], { foreignKey: 'companyId'});\ndb[\"Department\"].belongsTo(db[\"Company\"], {foreignKey: 'companyId'});\n```\n\n```text\ncompanyId\n```\n\n```text\nDepartment\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsTo\n```\n\n```text\nconst User = this.sequelize.define('user', {/* attributes */})\nconst Company  = this.sequelize.define('company', {/* attributes */});\n\nUser.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User\n```\n\n```text\ncompanyId: {\n  type:           DataTypes.INTEGER,\n  references:     'Companies',\n  referencesKey:  'companyId'\n}\n```\n\n```text\ncompanyId: {\n  type: DataTypes.INTEGER,\n  references: {\n    model: 'Company',\n    key: 'companyId'\n  }\n}\n```\n\n========================================\n\nComments:\n- Thank you for your comment. I noticed that sequelize creates a foreignKey field for me. It is called \"CompanyCompanyId\", but I would like to be able to give it a name that I defined (i.e. \"companyId\" instead of \"CompanyCompanyId\"). Do you know how I can achieve this?\n- You can specify it using `as` in options. Ex. `db[\"Department\"].belongsTo(db[\"Company\"], {as: 'companyId', foreignKey: 'companyId', foreignKeyConstraint: true});`\n- Thanks for your input Nilesh but I managed to fix it otherwise. Check my own reply to know how I did it.\n- Yes, same foreignKey value on both sides of relationship solves the problem, thanks!\n- If you have additional options for the `foreignKey` (e.g. `allowNull: false`) then you can specify its name using `name`: `foreignKey: {name: 'companyId', allowNull: false}`.\n- Hi Simon am struggling to create foreign key can you help me?","metadata":{"transformedAt":"2026-08-18T18:33:34.353Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":201,"estimatedTokens":1386}}199{"id":"stack-32752840","source":"stackoverflow","questionId":32752840,"title":"Sequelize: Concat fields in WHERE LIKE clause","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize: Concat fields in WHERE LIKE clause\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using the sequelize ORM for a node.js project I am working on. One query I have, I need to perform a like operation on the concatenated result of multiple columns.\n\nFor instance, something like the following:\n\nSELECT * FROM People WHERE (CONCAT(firstname, ' ', lastname)) LIKE '%John Do%'.\n\nI am using the following syntax and would like to know if this is possible without having to resort to using RAW queries (which is nowhere else in my solution).\n\n```\nvar criteria = {\n include: [\n occupation\n ],\n where: {\n is_active: 1\n },\n nest: false\n };\n\n db.people.findAll(criteria, {}).then(function(people) {\n success(people);\n }).catch(function(err) {\n error(err);\n });\n```\n\nAny ideas?\n\n========================================\n\nTop Answer:\nInspired by @code-jaff but you need to concatenate a space string in between first and last names to make this work correctly. Otherwise it would only return for 'JohnDoe' and not for 'John Doe'. Here's the code.\n\n```\nSequelize.where(Sequelize.fn('concat', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {\n like: '% John Doe %'\n })\n```\n\nTo provide some context for people who might not understand where this would fit into your query, this is an example of the above code in a where or statement. req.body.query being the variable search term that you're POSTing.\n\n```\nUsers.findAll({\n where: {\n $or: [\n Sequelize.where(Sequelize.fn('concat', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {\n like: '%' + req.body.query + '%'\n }),\n { email: { $like: '%' + req.body.query + '%' } },\n { companyName: { $like: '%' + req.body.query + '%' } }\n ]\n }\n})\n```\n\n*Update for Sequelize 4.0*\n\nString based operators (`$like` and `$or` in the above example) have been deprecated in favour of symbol based operators. It's a good thing for security\n\nSee: http://docs.sequelizejs.com/manual/tutorial/querying.html#operators\n\nThese operators would be replaced with `[Sequelize.Op.like]` and `[Sequelize.Op.or]`. There are also other ways to configure it in your sequelize options highlighted in their documentation\n\n========================================\n\nCode:\n```text\nvar criteria = {\n        include: [\n            occupation\n        ],\n        where: {\n            is_active: 1\n        },\n        nest: false\n    };\n\n    db.people.findAll(criteria, {}).then(function(people) {\n        success(people);\n    }).catch(function(err) {\n        error(err);\n    });\n```\n\n```text\nvar criteria = {\n    where: Sequelize.where(Sequelize.fn(\"concat\", Sequelize.col(\"firstname\"), Sequelize.col(\"lastname\")), {\n        like: '%John Do%'\n    })\n}\n```\n\n```text\nSequelize.where(Sequelize.fn('concat', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {\n    like: '% John Doe %'\n  })\n```\n\n```text\nUsers.findAll({\n  where: {\n    $or: [\n      Sequelize.where(Sequelize.fn('concat', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {\n        like: '%' + req.body.query + '%'\n      }),\n        { email: { $like: '%' + req.body.query + '%' } },\n        { companyName: { $like: '%' + req.body.query + '%' } }\n    ]\n  }\n})\n```\n\n```text\n$like\n```\n\n```text\n$or\n```\n\n```text\n[Sequelize.Op.like]\n```\n\n```text\n[Sequelize.Op.or]\n```\n\n```text\nUsers.findAll({\n  where: {\n    [sequelize.Op.or]:{\n     namesQuery: sequelize.where(\n      sequelize.fn(\n        \"concat\",\n        sequelize.col(\"firstName\"),\n        \" \",\n        sequelize.col(\"lastName\")\n      ),\n      {\n        [sequelize.Op.like]: `%${req.body.query}%`,\n      }\n    ),\n    email: {[sequelize.Op.like]: `%${req.body.query}%`},\n    companyName: {[sequelize.Op.like]: `%${req.body.query}%`},\n  }\n})\n```\n\n```text\ndb.models.users.findOne({ \n            where: {\n                [db.sequelize.Op.and]: [\n                    db.sequelize.where(\n                        db.sequelize.fn('CONCAT', db.sequelize.col('first_name'), ' ', db.sequelize.col('last_name')), \n                        { like: `%${name}%` },\n                    ),\n                    { status: 'ACTIVE' },\n                ]\n            }\n        });\n```\n\n========================================\n\nComments:\n- I had to replace the `like` inside `Sequelize.where` with `[Sequelize.Op.like]` to get it work.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":172,"estimatedTokens":1076}}200{"id":"stack-35705622","source":"stackoverflow","questionId":35705622,"title":"Using loops and promises in transactions in Sequelize","tags":["javascript","node.js","express","promise","sequelize.js"],"text":"Title: Using loops and promises in transactions in Sequelize\nTags: javascript, node.js, express, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am currently building a Nodejs, Express, Sequelize (w. PostgreSQL) app, and have run into a few problems with using promises together with transactions and loops.\n\nI am trying to figure out how to use a for loops in a transaction. I am trying to loop through a list of members and create a new user in the database for each of them. \n\nI know the following code is wrong but it shows what I am trying to do.\n\nCan anyone point me in the right direction?\n\n```\nvar members = req.body.members;\n models.sequelize.transaction(function (t) {\n for (var i = 0; i < members.length; i++) {\n return models.User.create({'firstname':members[i], 'email':members[i], 'pending':true}, {transaction: t}).then(function(user) {\n return user.addInvitations([group], {transaction: t}).then(function(){}).catch(function(err){return next(err);});\n })\n };\n }).then(function (result) {\n console.log(\"YAY\");\n }).catch(function (err) {\n console.log(\"NO!!!\");\n return next(err);\n });\n```\n\n========================================\n\nTop Answer:\nYou'll need to use the built in looping constructs of bluebird which ships with sequelize:\n\n```\nvar members = req.body.members;\n models.sequelize.transaction(t => \n Promise.map(members, m => // create all users\n models.User.create({firstname: m, email: m, 'pending':true}, {transaction: t})\n ).map(user => // then for each user add the invitation\n user.addInvitations([group], {transaction: t}) // add invitations\n )).nodeify(next); // convert to node err-back syntax for express\n```\n\n========================================\n\nCode:\n```text\nvar members = req.body.members;\n        models.sequelize.transaction(function (t) {\n            for (var i = 0; i < members.length; i++) {\n                return models.User.create({'firstname':members[i], 'email':members[i], 'pending':true}, {transaction: t}).then(function(user) {\n                    return user.addInvitations([group], {transaction: t}).then(function(){}).catch(function(err){return next(err);});\n                })\n            };\n        }).then(function (result) {\n            console.log(\"YAY\");\n        }).catch(function (err) {\n            console.log(\"NO!!!\");\n            return next(err);\n        });\n```\n\n```text\nvar members = req.body.members;\n    models.sequelize.transaction(function (t) {\n        var promises = []\n        for (var i = 0; i < members.length; i++) {\n            var newPromise = models.User.create({'firstname':members[i], 'email':members[i], 'pending':true}, {transaction: t});\n           promises.push(newPromise);\n        };\n        return Promise.all(promises).then(function(users) {\n            var userPromises = [];\n            for (var i = 0; i < users.length; i++) {\n                userPromises.push(users[i].addInvitations([group], {transaction: t});\n            }\n            return Promise.all(userPromises);\n        });\n    }).then(function (result) {\n        console.log(\"YAY\");\n    }).catch(function (err) {\n        console.log(\"NO!!!\");\n        return next(err);\n    });\n```\n\n```text\nPromise.all\n```\n\n```text\ncatch\n```\n\n```text\n.then\n```\n\n```js\nvar members = req.body.members;\n    models.sequelize.transaction(t => \n      Promise.map(members, m => // create all users\n        models.User.create({firstname: m, email: m, 'pending':true}, {transaction: t})\n      ).map(user => // then for each user add the invitation\n         user.addInvitations([group], {transaction: t}) // add invitations\n    )).nodeify(next); // convert to node err-back syntax for express\n```\n\n```text\n// requiring...\nconst async = require('async');\n\n// exports...\ncreateAllAsync: (array, transaction) => {\n  return new Promise((resolve, reject) => {\n    var results = [];\n    async.forEachOf(array, (elem, index, callback) => {\n      results.push(models.Model.create(elem, {transaction}));\n      callback();\n    }, err => {\n      if (err) {\n        reject(err);\n      }\n      else {\n        resolve(results);\n      }\n    });\n  });\n}\n```\n\n```text\nasync function createMemeber(req) {\nlet members = req.body.members;\n  for (var i = 0; i < members.length; i++) {\n    // Must be defined inside loop but outside the try to reset for each new member;\n    let transaction = models.sequelize.transaction();\n    try { \n      // Start transaction block.\n      let user = await models.User.create({'firstname':members[i],  'email':members[i], 'pending':true}, {transaction});\n      await user.addInvitations([group], {transaction}));\n\n      // if successful commit the record. Else in the catch block rollback the record.\n      transaction.commit();\n      // End transaction block.\n      return user;\n    } catch (error) { \n      console.log(\"An unexpected error occurred creating user record: \", error);\n      transaction.rollback();\n      // Throw the error back to the caller and handle it there. i.e. the called express route.\n      throw error;\n    }\n  }\n}\n```\n\n```text\nconst array = ['one','two','three'];\nconst createdTransaction = sequelize.transaction();\n    \nconst promises = array.map(async item => {\n      await model.create({\n          name: item,\n      },\n      { transaction: createdTransaction },\n     );\n});\n\nPromise.all(promises).then(async values => {\n    await createdTransaction.commit();\n});\n```\n\n========================================\n\nComments:\n- Thanks for the answer, but I get an error telling me that I need to return a promise chain to the transaction. Tried adding \"return\" before each Promise.all but then I get *\"Unhandled rejection commit has been called on this transaction(fc7be023-1980-455e-9934-7816420daa2b), you can no longer use it\"*\n- Yeah it's missing a return and nothing is ever pushed to userPromises.\n- @BenjaminGruenbaum thanks I did this on mobile yesterday and never got a chance to come back and check it over I'll update after when I can\n- @BenjaminGruenbaum I am still getting the `Unhandled rejection commit has been called on this transaction` error even with a return\n- Also working and very elegant code. Could not get the `.nodeify(err);` to work though. It says err not defined. Have not used nodeify before, so I am probably missing something.\n- Should be nodeify(next) - sorry\n- Property 'map' does not exist on type 'PromiseConstructor'.\n- Welcome to Stack Overflow, thank you for offering an answer. Please review: stackoverflow.com/help/how-to-answer","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":184,"estimatedTokens":1613}}201{"id":"stack-42519583","source":"stackoverflow","questionId":42519583,"title":"How to update \"updatedAt\" manually?","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: How to update \"updatedAt\" manually?\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nBelow is the code I am using in Hooks to update the `updatedAt` column for two objects:\n\n```\nhooks: {\n afterUpdate: (group, options, callback) => {\n console.log(\"groudId \" + groupId + \" options \" + options)\n },\n afterCreate: (member, options, callback) => {\n return new Promise((resolve, reject) => {\n sequelize.models.Group.findOne({\n where: {\n id: member.group_id\n }\n }).then((group) => {\n if (group) {\n var date = new Date();\n console.log(\"BEFORE group.updatedAt \" + group.updatedAt)\n group.dataValues.updatedAt = new Date()\n console.log(\"CHANGED group.updatedAt \" + group.updatedAt)\n group.save().then((Group) => {\n if (Group) {\n console.log(\"UPDATED Group.updatedAt \" + Group.updatedAt)\n console.log(\"UPDATED group.updatedAt \" + group.updatedAt)\n resolve(Group)\n } else {\n console.log(\"NO GROUP Found\")\n return reject(group.id)\n }\n }).catch((error) => {\n return (error)\n })\n } else {\n return reject(id)\n }\n }).catch((error) => {\n return (reject)\n })\n })\n }\n```\n\nConsole Log:\n\n```\nBEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)\nCHANGED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)\nUPDATED Group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)\nUPDATED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)\nBEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)\nCHANGED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)\nUPDATED Group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)\nUPDATED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)\n```\n\nWhile the log, what I think, appears correct, why isn't the actual object in the DB updated to the new `updatedAt` value? Or is there an **easier** way to update an objects `updatedAt` column?\n\n========================================\n\nTop Answer:\nThe following worked for:\n\n```\ngroup.changed('updatedAt', true)\n```\n\nThis will mark the `updatedAt` column as dirty so it will be updated.\n\n========================================\n\nCode:\n```text\nhooks: {\n                afterUpdate: (group, options, callback) => {\n                    console.log(\"groudId \" + groupId + \" options \" + options)\n                },\n                afterCreate: (member, options, callback) => {\n                    return new Promise((resolve, reject) => {\n                        sequelize.models.Group.findOne({\n                            where: {\n                                id: member.group_id\n                            }\n                        }).then((group) => {\n                            if (group) {\n                                var date = new Date();\n                                console.log(\"BEFORE group.updatedAt \" + group.updatedAt)\n                                group.dataValues.updatedAt = new Date()\n                                console.log(\"CHANGED group.updatedAt \" + group.updatedAt)\n                                group.save().then((Group) => {\n                                    if (Group) {\n                                        console.log(\"UPDATED Group.updatedAt \" + Group.updatedAt)\n                                        console.log(\"UPDATED group.updatedAt \" + group.updatedAt)\n                                        resolve(Group)\n                                    } else {\n                                        console.log(\"NO GROUP Found\")\n                                        return reject(group.id)\n                                    }\n                                }).catch((error) => {\n                                    return (error)\n                                })\n                            } else {\n                                return reject(id)\n                            }\n                        }).catch((error) => {\n                            return (reject)\n                        })\n                    })\n                }\n```\n\n```text\nBEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)\nCHANGED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)\nUPDATED Group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)\nUPDATED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)\nBEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)\nCHANGED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)\nUPDATED Group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)\nUPDATED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)\n```\n\n```text\nupdatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\ngroup.changed('updatedAt', true)\n\nawait group.update({\n    updatedAt: new Date()\n})\n```\n\n```text\nconsole.log(\"BEFORE group.updatedAt \" + group.updatedAt)\ngroup.set('updatedAt', new Date())\nconsole.log(\"CHANGED group.updatedAt \" + group.updatedAt)\ngroup.save().then((Group) => { /* the other part of your code*/ })\n```\n\n```text\ninstance.set(key, value, [options])\n```\n\n```text\ngroup.changed('updatedAt', true)\n```\n\n```text\nupdatedAt\n```\n\n```text\nawait MyModel.update({ updatedAt }, { where: { id: instance.id }, silent: true });\n```\n\n```text\nawait MyModel.update({ updatedAt: new Date() }, { where: { id: instance.id }})\n```\n\n```text\ngroup.changed('updatedAt', true)\ngroup.changed('exampleProperty', true)\nawait group.save({ silent: false })\n```\n\n```js\nvar query = sequelize.getQueryInterface().queryGenerator.updateQuery(\n      'YOUR_TABLE',\n      { updated_at: sequelize.literal('CURRENT_TIMESTAMP') },\n      { id: 1 },\n      { returning: false },\n);\n\nsequelize.query(query);\n```\n\n```js\nawait sequelize.query(\"UPDATE groups SET updatedAt = :date WHERE id = :id\", {\n  replacements: { date: new Date(2012, 7, 22, 2, 30, 0, 0), id: group.id },\n});\n```\n\n========================================\n\nComments:\n- Thanks, I tried that, but that also doesn't work. In fact it wont update at all. Here is the log: `BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST) CHANGED group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST) UPDATED Group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST) UPDATED group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)`\n- Did you do anything else to get this to work? Any time I do this, it won't update unless I include some other field in addition to `updatedAt`.\n- Ditto, looks like this alone does not work.\n- v6 sequelize appears to work the same way. Must add an additional field in order for to actually set `updatedAt`. Interestingly, if you wanted to manually change `createdAt`, this is not the case.\n- if you don't want to use the \"new Date()\" (afraid of db <> api TZ, etc) then you can also just use `1` instead of \"new Date()\" e.g. this `group.changed('updatedAt', true); await group.update({ updatedAt: 1 })` The value will be overridden anyway so it's just important to include \"a value\" for it.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":203,"estimatedTokens":1695}}202{"id":"stack-43523203","source":"stackoverflow","questionId":43523203,"title":"Two foreign Key of same table in one table in sequelize","tags":["node.js","sequelize.js"],"text":"Title: Two foreign Key of same table in one table in sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nmy team member model :-\n\n```\nvar teamMember = {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n level: DataTypes.INTEGER,\n supervisorId: {\n type: DataTypes.INTEGER,\n references: {\n model: \"employees\",\n key: \"id\"\n }\n },\n employeeId: {\n type: DataTypes.INTEGER,\n unique: true,\n references: {\n model: \"employees\",\n key: \"id\"\n }\n }\n```\n\nand there is employee model\n\nmapping:-\n\n```\ndb.employee.hasOne(db.teamMember);\ndb.teamMember.belongsTo(db.employee);\n```\n\nmy query function \n\n```\ndb.teamMember.findOne({\n where: { employeeId: req.employee.id },\n include: [db.employee]\n\n })\n .then(teamMember => {\n if (!teamMember) {\n throw ('no teamMember found');\n }\n consol.log(teamMember)\n })\n```\n\nmy **teamMember** table is like=\n\nid------employeeId------supervisorId \n\n2 ----------- 4 ------------- 5 \n\nProblem is -: so when i m asking for row in teamMember whose employeeId is 4. that should be include with supervisorId(JOIN) and it returns row with employee included of 4 (id) . i want employee of 5th id .\n\n**Both supervisorId and employeeId are reffer to employee table.**\n\n========================================\n\nCode:\n```text\nvar teamMember = {\n    id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    level: DataTypes.INTEGER,\n    supervisorId: {\n        type: DataTypes.INTEGER,\n        references: {\n            model: \"employees\",\n            key: \"id\"\n        }\n    },\n    employeeId: {\n        type: DataTypes.INTEGER,\n        unique: true,\n        references: {\n            model: \"employees\",\n            key: \"id\"\n        }\n    }\n```\n\n```text\ndb.employee.hasOne(db.teamMember);\ndb.teamMember.belongsTo(db.employee);\n```\n\n```text\ndb.teamMember.findOne({\n        where: { employeeId: req.employee.id },\n        include: [db.employee]\n\n    })\n    .then(teamMember => {\n        if (!teamMember) {\n            throw ('no teamMember found');\n        }\n       consol.log(teamMember)\n    })\n```\n\n```text\ndb.teamMember.belongsTo(db.employee, {as: 'SupervisorId'});\ndb.teamMember.belongsTo(db.employee, {as: 'RegularEmployeeId'});\n```\n\n```text\ninclude: [{\n    model: db.employee,\n    as: 'SupervisorId\n}]\n```\n\n========================================\n\nComments:\n- only we need belongsTo for include ? their is no need of hasMany , hasOne ?? by the way your answer works .Thanks\n- On your particular case belongTo is enough. Depending on your database schema you will need hasMany, hasOne, etc.\n- what about the migration file, will this need to be created?\n- Thanks man, in addition to this answer, you can add the key, for example: {as: ''MyOwnName', foreignKey: 'supervisorId'}","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":133,"estimatedTokens":696}}203{"id":"stack-51950129","source":"stackoverflow","questionId":51950129,"title":"Execute raw query in migration - Sequelize 3.30","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Execute raw query in migration - Sequelize 3.30\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to execute a raw query in my migrations `up` and `down` functions. \n\nWhen I try to do: `Sequelize.query`, it says `ERROR: Sequelize.query is not a function`.\n\nThis is my migration skeleton file:\n\n```\n'use strict';\n\nmodule.exports = {\n\n up: (queryInterface, Sequelize, migration) => {\n return Sequelize.query(...); //ERROR: Sequelize.query is not a Function\n },\n\n down: (queryInterface, Sequelize) => {\n return Sequelize.query(...); //ERROR: Sequelize.query is not a Function\n }\n\n};\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = {\n\n  up: (queryInterface, Sequelize, migration) => {\n     return Sequelize.query(...);   //ERROR: Sequelize.query is not a Function\n  },\n\n  down: (queryInterface, Sequelize) => {\n     return Sequelize.query(...);  //ERROR: Sequelize.query is not a Function\n  }\n\n};\n```\n\n```text\nup\n```\n\n```text\ndown\n```\n\n```text\nSequelize.query\n```\n\n```text\nERROR: Sequelize.query is not a function\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n\n  up: (queryInterface, Sequelize, migration) => {\n     return queryInterface.sequelize.query(...);\n  },\n\n  down: (queryInterface, Sequelize) => {\n     return queryInterface.sequelize.query(...);\n  }\n\n};\n```\n\n```text\nquery()\n```\n\n```text\nSequelize\n```\n\n```text\nqueryInterface\n```\n\n```text\nqueryInterface.sequelize\n```\n\n========================================\n\nComments:\n- `Sequelize` => is this variable `require('sequelize')`?","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":98,"estimatedTokens":392}}204{"id":"stack-37638476","source":"stackoverflow","questionId":37638476,"title":"Sequelize query is giving TypeError: undefined is not a function","tags":["node.js","sequelize.js"],"text":"Title: Sequelize query is giving TypeError: undefined is not a function\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using express and sequelize for my node application. On the controller file, I have the following:\n\n```\nvar models = require('../models'),\n Property = models.property,\n Sequelize = require('sequelize');\n\nmodule.exports = function(req, res){\n Sequelize.query(\"SELECT * FROM 'property'\", { type:Sequelize.QueryTypes.SELECT})\n .then(function(properties) {\n res.json(properties)\n })\n}\n```\n\nI can use model.findAll fine but when I try to use raw query, I'm getting the TypeError: undefined is not a function. Can you point what I'm doing wrong in this code?\n\n========================================\n\nTop Answer:\nYou can use\n\n```\nconst sql = \"select * from ...\"\n\n model.sequelize.query(sql, { type: model.sequelize.QueryTypes.SELECT })\n.then(function (rows) {\n ... do a job on the query here... \n })\n```\n\n========================================\n\nCode:\n```text\nvar models          = require('../models'),\n    Property        = models.property,\n    Sequelize       = require('sequelize');\n\nmodule.exports = function(req, res){\n  Sequelize.query(\"SELECT * FROM 'property'\", { type:Sequelize.QueryTypes.SELECT})\n   .then(function(properties) {\n      res.json(properties)\n  })\n}\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('database', 'username', 'password');\n\nsequelize.query(\"SELECT * FROM 'property'\", { type:Sequelize.QueryTypes.SELECT})\n   .then(function(properties) {\n      res.json(properties)\n  })\n```\n\n```text\nquery()\n```\n\n```text\nSequelize\n```\n\n```text\nconst sql = \"select * from ...\"\n\n model.sequelize.query(sql, { type: model.sequelize.QueryTypes.SELECT })\n.then(function (rows) {\n    ... do a job on the query here...   \n })\n```\n\n```text\nconst sqlFile = fs.readFileSync(file, {encoding: \"UTF-8\"});\n\nawait queryInterface.sequelize.query(sqlFile, {          \n            raw: true,\n            type: Sequelize.QueryTypes.RAW\n          });\n```\n\n```text\nconst sqlFile = fs.readFileSync(file, {encoding: \"UTF-8\"}).replace('`', '\\`');\n```\n\n```text\nError importing:  sql.trim is not a function\n```\n\n========================================\n\nComments:\n- The typeerror is gone but now I'm getting this: Unhandled rejection SequelizeDatabaseError: syntax error at or near \"'property'\". Any thoughts?\n- @iMad sure, remove the single quotes around the `property`.\n- still not a function in the seeder/migration up() method. How is that supposed to work?\n- Thank you for this - just hit this today. Finding good examples of `queryInterface.sequelize.query` within a migration has been difficult.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":103,"estimatedTokens":666}}205{"id":"stack-45690000","source":"stackoverflow","questionId":45690000,"title":"Cannot rollback a Sequelize transaction","tags":["javascript","node.js","postgresql","express","sequelize.js"],"text":"Title: Cannot rollback a Sequelize transaction\nTags: javascript, node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement OAuth2, but I'm stuck with *Sequelize* transactions.\n\nGetting error:\n\n```\nExecuting (9edf48f7-5823-4b4f-b444-faa4c1896831): START TRANSACTION;\nExecuting (9edf48f7-5823-4b4f-b444-faa4c1896831): COMMIT;\nUnhandled rejection Error: commit has been called on this\n transaction(9edf48f7-5823-4b4f-b444-faa4c1896831), you can no longer\n use it. (The rejected query is attached as the 'sql' property of\n this error)\n```\n\nThe following is the relevant JavaScript code:\n\n```\nat.save({transaction: t}).then(() => {\n rt.save({transaction: t}).then(() => {\n t.commit();\n return done(false, accessToken, refreshToken, {\n expires_at: expires,\n scope: scope});\n }).error(function(\n err) {\n t.rollback();\n return done(err);\n });\n }).error(function(err) {\n t.rollback();\n return done(err);\n });\n```\n\nI'm using Sequelize 4.x.x with Postgres\n\n========================================\n\nCode:\n```bash\nExecuting (9edf48f7-5823-4b4f-b444-faa4c1896831): START TRANSACTION;\nExecuting (9edf48f7-5823-4b4f-b444-faa4c1896831): COMMIT;\nUnhandled rejection Error: commit has been called on this\n    transaction(9edf48f7-5823-4b4f-b444-faa4c1896831), you can no longer\n    use it. (The rejected query is attached as the 'sql' property of\n    this error)\n```\n\n```js\nat.save({transaction: t}).then(() => {\n                rt.save({transaction: t}).then(() => {\n                    t.commit();\n                    return done(false, accessToken, refreshToken, {\n                        expires_at: expires,\n                        scope: scope});\n                }).error(function(\n                    err) {\n                    t.rollback();\n                    return done(err);\n                });\n            }).error(function(err) {\n                t.rollback();\n                return done(err);\n            });\n```\n\n```text\nreturn sequelize.transaction(t => {\n  return at.save({ transaction: t })\n    .then(() => {\n      return rt.save({ transaction: t })\n        .then(() => {\n          return t.commit() // Commit also returns a promise, you will want that to finish too\n            .then(() => {\n              return done();\n            });\n        });\n    });\n});\n```\n\n```text\nt.commit()\n```\n\n========================================\n\nComments:\n- Mine was using async and was missing an await as per this issue on the Sequelize github: github.com/sequelize/sequelize/issues/7525\n- For me a `forEach()` caused the transaction to automatically commit. Inside the forEach() I had a async. method. Can somebody explain this?","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":94,"estimatedTokens":666}}206{"id":"stack-42719750","source":"stackoverflow","questionId":42719750,"title":"Sequelize relation with WHERE IN (\"ARRAY\")","tags":["sequelize.js"],"text":"Title: Sequelize relation with WHERE IN (\"ARRAY\")\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to define a relationships in sequelize where multiple foreign keys are stored as an array in one field. Basically a belongsToMany but instead of an relation table all ids are stored comma separated in one field. Query would be with `WHERE IN('1,5,7')`.\n\n========================================\n\nTop Answer:\nTo get sequelize query result with where condition for given array with using `**Op.in**` code to find result with in array as\n\n```\nvar Sequelize = require('sequelize');\nvar Op = Sequelize.Op;\nvar arrayofTaskId = ['123', '456', '789'];\nTasks.findAll({\n where: {\n task_id: {\n [Op.in]: arrayofTaskId\n }\n }\n}).then(function(result) {\n return res.json(result)\n});\n```\n\n========================================\n\nCode:\n```text\nWHERE IN('1,5,7')\n```\n\n```js\nconst User = sequelize.define('User', {\n    categories: DataTypes.ARRAY(DataTypes.INTEGER)\n}, {\n    instanceMethods: {\n        getCategories: function(){\n            return Category.findAll({\n                where: {\n                    id: { $in: this.get('categories') }\n                }\n            }).then(categories => {\n                // if user's categories was [1, 2, 4]\n                // it would return categories with id=1, id=2 and id=4\n                return categories;\n            });\n        },\n        setCategories: function(ids){\n            return this.setDataValues('categories', ids).save().then(self => {\n                return self;\n            });\n        }\n    }\n});\n```\n\n```text\ninstanceMethods\n```\n\n```text\nARRAY\n```\n\n```text\ncategories\n```\n\n```text\nhook\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar Op = Sequelize.Op;\nvar arrayofTaskId = ['123', '456', '789'];\nTasks.findAll({\n  where: {\n    task_id: {\n      [Op.in]: arrayofTaskId\n    }\n  }\n}).then(function(result) {\n  return res.json(result)\n});\n```\n\n```text\n**Op.in**\n```\n\n========================================\n\nComments:\n- Thank you for this. A question, however: should it not be `this.setDataValue()`? **notice the use of a singular form*\n- where is that `this` come from?\n- @AlanYong I guess it's from Model class","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":100,"estimatedTokens":548}}207{"id":"stack-38082938","source":"stackoverflow","questionId":38082938,"title":"Sequelize hasMany Join association","tags":["node.js","sqlite","join","sequelize.js","relationships"],"text":"Title: Sequelize hasMany Join association\nTags: node.js, sqlite, join, sequelize.js, relationships\nSource: Stack Overflow\n\nQuestion:\nI'm expanding my application and I need to join two models I had previously created with Sequelize, they are as follows:\n\n**Meal**\n\n```\nsequelize.define('meal', {\n mealId: {\n type: DataTypes.INTEGER, \n primaryKey: true,\n autoIncrement: true\n },\n quantity: {\n type: DataTypes.DECIMAL,\n allowNull: false\n },\n period: {\n type: DataTypes.INTEGER,\n allowNull: false\n }\n})\n```\n\n**Food**\n\n```\nsequelize.define('food', {\n idFood: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n nameFood: {\n type: DataTypes.STRING,\n allowNull: false\n }\n})\n```\n\nI added the following relationship:\n\n```\ndb.food.hasMany(db.meal, {as : 'Food', foreignKey : 'idFood'});\n```\n\nThis line adds an idFood column on Meal\n\nQuickly explaining what is going on, **Food** is a table with many foods (duh) like Bread, Rice, Beans, etc. **Meal** is a table that identifies which food the user has chosen with their details.\n\nTherefore, my understanding was that **Meal** had many **Food** (as I added before) but **Food** didn't require any relationship with **Meal**, since it just holds data and isn't changed after I first populate it. But when I tried to join them with:\n\n```\ndb.meal.findAll({ include : [db.food] }).then(function (meals) {\n console.log(JSON.stringify(meals));\n});\n```\n\nI got the following error:\n\n```\nUnhandled rejection Error: food is not associated to meal!\n```\n\nCan anyone explain what I should do? I think it has to do with the relationships, but I couldn't find on the documentation any good explanation as to what I should do.\n\nThank you!\n\nEdit: Reading the documentation (again), the example makes sense, but I don't think the example is applicable on my situation, because on their example, User has a Task, and Task belongs to User. But on my case, Food doesn't belong to a Meal, because many Meals can have the same Food in different amounts (or for different users).\n\n========================================\n\nTop Answer:\nIf you are using an alias on the association (`{ as: 'Food' }`) you need to use it on the include statement as well.\n\nSo it'd be like that:\n\n```\ndb.meal.findAll({ \n include : [{\n model: db.food,\n as: 'Food'\n }]\n}).then(function (meals) {\n console.log(JSON.stringify(meals));\n});\n```\n\n If an association is aliased (using the as option), you must specify\n this alias when including the model. Notice how the user's Tools are aliased as Instruments above. In order to get that right you have to specify the model you want to load, as well as the alias\n\nMore information here.\n\n========================================\n\nCode:\n```text\nsequelize.define('meal', {\n    mealId: {\n        type: DataTypes.INTEGER, \n        primaryKey: true,\n        autoIncrement: true\n    },\n    quantity: {\n        type: DataTypes.DECIMAL,\n        allowNull: false\n    },\n    period: {\n        type: DataTypes.INTEGER,\n        allowNull: false\n    }\n})\n```\n\n```text\nsequelize.define('food', {\n    idFood: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    nameFood: {\n        type: DataTypes.STRING,\n        allowNull: false\n    }\n})\n```\n\n```text\ndb.food.hasMany(db.meal, {as : 'Food', foreignKey : 'idFood'});\n```\n\n```text\ndb.meal.findAll({ include : [db.food] }).then(function (meals) {\n    console.log(JSON.stringify(meals));\n});\n```\n\n```text\nUnhandled rejection Error: food is not associated to meal!\n```\n\n```text\ndb.food.hasMany(db.meal, {as : 'Food', foreignKey : 'idFood'});\n```\n\n```text\ndb.meal.belongsTo(db.food, {foreignKey : 'idFood'});\n```\n\n```text\ndb.meal.findAll({ include : [db.food] }).then(function (meals) {\n    console.log(JSON.stringify(meals)); <-- each array element of meals should have an attribute `food`\n});\n```\n\n```text\nmeal.idFood\n```\n\n```text\ndb.meal.findAll({ \n  include : [{\n    model: db.food,\n    as: 'Food'\n  }]\n}).then(function (meals) {\n  console.log(JSON.stringify(meals));\n});\n```\n\n```text\n{ as: 'Food' }\n```\n\n```text\nDonor.hasMany(Donation, {\n  foreignKey: \"donorId\",\n  onDelete: \"cascade\",\n});\nDonation.belongsTo(Donor, { foreignKey: \"donorId\" });\n```\n\n========================================\n\nComments:\n- Still gives me the error: Unhandled rejection Error: food (Food) is not associated to meal!\n- Reading the documentation (again), the example makes sense, but I don't think it the example is applicable on my situation, because on their example, User has a Task, and Task belongs to User. But on my case, Food doesn't belong to a Meal, because many Meals can have the same Food in different amounts (or for different users). How can I get around that?\n- @leofontes in your situation you need to implement many-to-many relationship, a meal can have many foods, and one food can be used in multiple meals, so that makes sense. documentation to implement this kind of relationship.\n- Excelent! This gave me the result I wanted, just one final question.. I'm printing the JSON.stringify(meals) and it shows every part of the data, but what if I wanted to access some of those values by themselves, how could I do it?\n- Like access each food?\n- Thanks, I spent a complete day unsuccessfully before I found this answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":195,"estimatedTokens":1314}}208{"id":"stack-37723420","source":"stackoverflow","questionId":37723420,"title":"Convert datetime to date of a column in where condition using sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: Convert datetime to date of a column in where condition using sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nOkay,\n\nI want to convert column datetime to date while querying.\n\nCan anyone help me out with sequelize query of below given query ?\n\n```\nselect * from ev_events where DATE(event_date) <= '2016-10-10'\n```\n\n========================================\n\nTop Answer:\n```\nsequelize.and(\n {id: '111'},\n sequelize.where(\n sequelize.fn('date', sequelize.col('event_date')), \n '<=', '2016-10-10'\n )\n)\n```\n\n========================================\n\nCode:\n```text\nselect * from ev_events where DATE(event_date) <= '2016-10-10'\n```\n\n```text\nEvent.findAll({\n  where: sequelize.where(sequelize.fn('date', sequelize.col('event_date')), '<=', '2016-10-10')\n})\n```\n\n```text\nsequelize.fn\n```\n\n```text\nsequelize.and(\n  {id: '111'},\n  sequelize.where(\n    sequelize.fn('date', sequelize.col('event_date')), \n    '<=', '2016-10-10'\n  )\n)\n```\n\n========================================\n\nComments:\n- Yeah this is the way to do it. This is how i did it sequelize.where(sequelize.cast(mods.sequelize.col('event_dat&zwnj;&#8203;e'), 'DATE'), '>=', from_date). But thanks for the help :)\n- How do you do with this type of query to add a AND something_id = 45 ?\n- @Sachacr You can do that by `{ where: { [Sequelize.Op.and]: [ { id: 45 }, Sequelize.where('date', '=', '2018-05-13') ] } }`\n- @KeyurSakaria 's answer in comment worked for me(I only had to remove mods.). The accepted answer didn't work for me. I got error - 'date' is not a function.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":62,"estimatedTokens":392}}209{"id":"stack-28258694","source":"stackoverflow","questionId":28258694,"title":"Sequelize: insert in bulk","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize: insert in bulk\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Node.js, MySQL and Sequelize. I'd like to insert some 10k rows into a table at once. The table has custom `primaryKey` field, that is being set manually. The data are downloaded from web and are overlapping.\n\nI'd like to have a version of `bulkCreate` that wouldn't fail if any of the rows in data have unique keys that are already present in the table. Such kind of things is done in MySQL via `INSERT ... ON DUPLICATE KEY UPDATE` construct.\n\nHow do I do it in Sequelize?\n\n========================================\n\nTop Answer:\nYuri's answer will ignore duplicates... there is an option for `updateOnDuplicate`:\n\n Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated.\n\nhttp://docs.sequelizejs.com/en/latest/api/model/#bulkcreaterecords-options-promisearrayinstance\n\n========================================\n\nCode:\n```text\nprimaryKey\n```\n\n```text\nbulkCreate\n```\n\n```text\nINSERT ... ON DUPLICATE KEY UPDATE\n```\n\n```text\nbulkCreate([...], { ignoreDuplicates: true })\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\nProductAttribute.bulkCreate(arrayToUpsert, {updateOnDuplicate: ['id', 'attributeValue'] })\n```\n\n```text\nmodel.bulkCreate(dataToUpdate, { updateOnDuplicate: [\"user_id\", \"token\", \"created_at\"] })\n```\n\n========================================\n\nComments:\n- This is mysql only unfortunately, does not work on postgres\n- bulkCreate always insert a single record i am not getting solution . and on second insertion attempt it gives error of unique\n- Soo.. im using `v5` and i just spent an hour or so debugging why my bulkCreate was not working. The data you pass into bulkCreate needs to be an array of plain js objects.. not an array of sequelize models. I had a server response.. i was make modifications and using bulkCreate to perform a bulkUpdate.... you need to run `row.get({plain:true})` on your data to bring it back down to plain js objects.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":57,"estimatedTokens":514}}210{"id":"stack-35665263","source":"stackoverflow","questionId":35665263,"title":"How do I query for two columns to be equal using Sequelize?","tags":["postgresql","sequelize.js"],"text":"Title: How do I query for two columns to be equal using Sequelize?\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\ndb.WorkbookQuestion.count({\n where: {\n QuestionId: dbQuestion.id,\n AnswerSelectedId: db.sequelize.col('CorrectAnswerId')\n }\n});\n```\n\nThe query generates this SQL: `SELECT count(*) AS \"count\" FROM \"WorkbookQuestions\" AS \"WorkbookQuestion\" WHERE \"WorkbookQuestion\".\"QuestionId\" = 1103 AND \"CorrectAnswerId\";`\n\nHow do I get it to be more like `AnswerSelectedId = CorrectAnswerId`?\n\n========================================\n\nTop Answer:\nI was stuck on this for a while today until I found this answer. I also found another way of doing the same query so will leave another answer here.\n\n```\ndb.WorkbookQuestion.count({\n where: {\n CorrectAnswerId: {\n $col: 'AnswerSelectedId'\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\ndb.WorkbookQuestion.count({\n  where: {\n    QuestionId: dbQuestion.id,\n    AnswerSelectedId: db.sequelize.col('CorrectAnswerId')\n  }\n});\n```\n\n```text\nSELECT count(*) AS \"count\" FROM \"WorkbookQuestions\" AS \"WorkbookQuestion\" WHERE \"WorkbookQuestion\".\"QuestionId\" = 1103 AND \"CorrectAnswerId\";\n```\n\n```text\nAnswerSelectedId = CorrectAnswerId\n```\n\n```text\ndb.WorkbookQuestion.count({\n  where: sequelize.where(\n    db.sequelize.col('CorrectAnswerId'),\n    db.sequelize.col('AnswerSelectedId')\n  )\n});\n```\n\n```text\nsequelize.where()\n```\n\n```text\ndb.WorkbookQuestion.count({\n  where: {\n    CorrectAnswerId: {\n        $col: 'AnswerSelectedId'\n    }\n  }\n});\n```\n\n```text\nconst { Op } = require('sequelize');\n\ndb.WorkbookQuestion.count({\n  where: {\n    QuestionId: dbQuestion.id,\n    CorrectAnswerId: {\n        [Op.eq]: sequelize.col('AnswerSelectedId')\n    }\n  }\n});\n```\n\n========================================\n\nComments:\n- What if I want to have multiple clauses?\n- @Shamoon have you tried to put the conditions into an array? Something like: `where: [sequelize.where(..), sequelize.where(..)]`. Not tested - will actually experiment if this is not going to work. Thanks.\n- Using `where: [sequelize.where(..), sequelize.where(..)]` causes a `sql.replace is not a function` error.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":95,"estimatedTokens":538}}211{"id":"stack-46388378","source":"stackoverflow","questionId":46388378,"title":"How to seed uuidv4 with sequelize","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: How to seed uuidv4 with sequelize\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am trying to seed a uuid using sequilize generateUUID\n but i get this error `Seed file failed with error: sequelize.Utils.generateUUID is not a function TypeError: sequelize.Utils.generateUUID is not a function`\n\nhow do i seed a UUID?\n\n```\nreturn queryInterface.bulkInsert('companies', [{\n id: sequelize.Utils.generateUUID(),\n name: 'Testing',\n updated_at: new Date(),\n created_at: new Date()\n }]);\n```\n\n========================================\n\nTop Answer:\nSince it's included in the `DataTypes` package, would make sense to use what is already available as Matt suggested. You can use it in this way:\n\n```\n{\n ...,\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV4,\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nreturn queryInterface.bulkInsert('companies', [{\n        id: sequelize.Utils.generateUUID(),\n        name: 'Testing',\n        updated_at: new Date(),\n        created_at: new Date()\n    }]);\n```\n\n```text\nSeed file failed with error: sequelize.Utils.generateUUID is not a function TypeError: sequelize.Utils.generateUUID is not a function\n```\n\n```text\nnpm install uuid\n```\n\n```text\nconst uuidv4 = require('uuid/v4');\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.bulkInsert('yourTableName', [\n      {\n        id: uuidv4()\n      }],\n {});\n```\n\n```text\n{\n    ...,\n    type: DataTypes.UUID,\n    defaultValue: DataTypes.UUIDV4,\n    ...\n}\n```\n\n```text\nDataTypes\n```\n\n```text\nconst { v4: uuidv4 } = require('uuid');\n\nreturn queryInterface.bulkInsert('companies', [{\n    id: uuidv4(),\n    name: 'Testing',\n    updated_at: new Date(),\n    created_at: new Date()\n}]);\n```\n\n```text\nnpm install uuid\n```\n\n========================================\n\nComments:\n- Sequelize does use `uuid` under the hood so the package should already be available. Sequelize doesn't expose the `uuidv4` method in a useful way though.\n- Now getting `DeprecationWarning: Deep requiring like 'const uuidv4 = require('uuid&#47;v4');' is deprecated as of uuid@7.x. Please require the top-level module when using the Node.js CommonJS module or use ECMAScript Modules when bundling for the browser. See https:&#47;&#47;github.com&#47;uuidjs&#47;uuid#deep-requires-now-deprecated for more information.` And when I switch to the recommended import syntax I get a different error.\n- Wow! Changing the key from \"default\" to \"defaultValue\" solved it for me. Thanks\n- Nice, This is far good in comparison to the above answers as sequelize have it all required for this to achieve.\n- I thought, the link is to Sequelize documentation\n- Nah... it's uuid documentation... I have updated the answer to clarify that.. thanks for pointing it out.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":102,"estimatedTokens":698}}212{"id":"stack-22633618","source":"stackoverflow","questionId":22633618,"title":"sequelize migrations in heroku","tags":["node.js","heroku","migration","sequelize.js"],"text":"Title: sequelize migrations in heroku\nTags: node.js, heroku, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nCan somebody please give me some complete examples for sequelize migrations for nodejs as the actual documentation itself doesn't give the complete example of how it is to be done.\n\nor may be give a complete example of some other module that can be used and best practise of how to be use in heroku?\n\nThanks\n\n========================================\n\nTop Answer:\nYou can use the Procfile and put this at the top.\n\n```\nrelease: npx sequelize-cli db:migrate\n```\n\nThen you will need a .sequelizerc file to define where your migrations are.\n\nAnd for the config you can use this for ssl.\n\n```\nproduction: {\n use_env_variable: 'DATABASE_URL',\n dialect: 'postgres',\n protocol: 'postgres',\n ssl: true,\n dialectOptions: {\n ssl: {\n require: true,\n rejectUnauthorized: false,\n },\n },\n}\n```\n\n========================================\n\nCode:\n```text\nsequelize -i\n```\n\n```text\n{\n  \"development\": {\n  \"username\": \"postgres\",\n  \"password\": \"password\",\n  \"database\": \"dbname\",\n  \"host\": \"100.0.0.0\",\n  \"dialect\":\"postgres\",\n  \"protocol\":\"postgres\",\n  \"port\":\"xxxx\"\n },\n  \"staging\": {\n  \"username\": \"dbusername\",\n  \"password\": \"dbpassword\",\n  \"database\": \"db\",\n  \"host\": \"host\",\n  \"dialect\":\"postgres\",\n  \"protocol\":\"postgres\",\n  \"port\":\"xxxx\"\n  },\n  \"production\": {\n  \"username\": \"dbusername\",\n  \"password\": \"dbpassword\",\n  \"database\": \"db\",\n  \"host\": \"dbhost\",\n  \"dialect\":\"postgres\",\n  \"protocol\":\"postgres\",\n  \"port\":\"xxxx\"\n  }\n}\n```\n\n```text\nheroku config --app production-app-name\n```\n\n```text\nheroku run sequelize db:migrate --env production -m --app production-app-name.\n```\n\n```text\n\"production\": {\n  \"use_env_variable\": \"DATABASE_URL\"\n}\n```\n\n```text\n...\n\"scripts\": {\n  ...\n  \"build\": \"sequelize db:migrate --env production && <other stuff to do before run the app>\"\n}\n...\n```\n\n```text\nrelease: npx sequelize-cli db:migrate\n```\n\n```text\nproduction: {\n use_env_variable: 'DATABASE_URL',\n dialect: 'postgres',\n protocol: 'postgres',\n ssl: true,\n dialectOptions: {\n   ssl: {\n    require: true,\n    rejectUnauthorized: false,\n   },\n },\n}\n```\n\n```bash\nheroku run npx sequelize-cli db:migrate --config sequelize-config.js --app your-app --env production\n```\n\n========================================\n\nComments:\n- When doing this, I get an SSL error, where do you add the ssl=true option ?\n- Unfortunately, this means that you have to run that command every time you deploy changes with new migrations.\n- it didn't worked for me :(\n- project is built first then zipped and deployed. You can see this process when you check the deployment logs\n- Here's the full command we needed to use, since we have multiple environments: \"heroku run --app our-app-testing npx sequelize-cli db:migrate\" This is what we use. Doesn't help that as infrequent as we migrate, the command is forgotten every time and we have to look it up. Definitely recommend recording this url or command in a spot that is easy to remember where you put it.","metadata":{"transformedAt":"2026-08-18T18:33:34.354Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":132,"estimatedTokens":756}}213{"id":"stack-45563842","source":"stackoverflow","questionId":45563842,"title":"Set raw = true on Sequelize Model.create","tags":["node.js","orm","sequelize.js"],"text":"Title: Set raw = true on Sequelize Model.create\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to be able to receive the plain raw object after calling `Model.create` on Sequelize, the object itself that was created, no metadata or any other things. Just like the `{raw: true}` option in `Model.find`.\n\nI've already seen this answer:\nSetting all queries to raw = true sequelize,\nand no, `Model.create({name: 'test'}, {raw: true})` doesn't work.\n\nThanks\n\n========================================\n\nTop Answer:\n```\nModel.create(modelObject)\n.then((resultEntity) => {\n const dataObj = resultEntity.get({plain:true})\n}\n```\n\nLike mentioned before or if you want to keep with async/await syntax go for:\n\n```\nconst myResultVar = (await Model.create(modelObject)).get({plain:true})\n```\n\nBasically the same thing just not leaving the async/await syntax behind :)\n\n========================================\n\nCode:\n```text\nModel.create\n```\n\n```text\n{raw: true}\n```\n\n```text\nModel.find\n```\n\n```text\nModel.create({name: 'test'}, {raw: true})\n```\n\n```text\nModel.create(modelObject)\n.then((resultEntity) => {\n    const dataObj = resultEntity.get({plain:true})\n}\n```\n\n```text\n.get()\n```\n\n```text\n.create()\n```\n\n```text\n.findAll()\n```\n\n```text\n{raw: true}\n```\n\n```text\n{raw: true}\n```\n\n```text\nModel.create(modelObject)\n.then((resultEntity) => {\n    const dataObj = resultEntity.get({plain:true})\n}\n```\n\n```text\nconst myResultVar = (await Model.create(modelObject)).get({plain:true})\n```\n\n```text\n{raw: true}\n```\n\n```text\n{plain: true}\n```\n\n```text\n.... new Sequelize('dbUrl',{query:{raw:true, plain:true}, logging: false});\n```\n\n```text\nlet newRecord = await models.movies.create({...data for new row});\nnewRecord = newRecord.toJSON();\n```\n\n```text\n.then(response => (response.get({plain: true}))\n```\n\n========================================\n\nComments:\n- Use `model.toObject` function: http://mongoosejs.com/docs/api.html#document_Document-toObje&zwnj;&#8203;ct\n- thank you alexmac. but that's for mongoose, but I found a similar method for sequelize `model.get`, which I posted as answer. thnx\n- thanks Kevin, found a built-in solution, and posted as answer\n- I noticed that `.toJSON()` returns the entire object? Do you know how to pair this with `attributes` to filter what is returned?\n- Why Sequelize don't implement {raw: true} for create?!\n- Hi :) You don't need to repeat other answers. Your alternative option is good enough to be written as an answer on its own.\n- Please don't post code-only answers. Future readers will be grateful to see explained *why* this answers the question instead of having to infer it from the code. Also, since this is an old question, please explain how it complements the other answers. TBH this only looks like a repetition of some of them.","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":119,"estimatedTokens":698}}214{"id":"stack-40462446","source":"stackoverflow","questionId":40462446,"title":"How to select case query in sequelize?","tags":["javascript","sql","node.js","postgresql","sequelize.js"],"text":"Title: How to select case query in sequelize?\nTags: javascript, sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a sql query:\n\n```\nSELECT field1, field2,\n CASE\n WHEN field1=1 THEN 'a'\n ELSE 'b'\n END \n AS field3\nFROM test\n```\n\nand I want to implement it with `sequelizejs` , \n\n```\nconst params = {\n attributes: //DO SELECT CASE,\n};\n\nyield Model.findAll(params);\n```\n\nCan anyone help me? Thank you.\n\n========================================\n\nCode:\n```text\nSELECT field1, field2,\n  CASE\n    WHEN field1=1 THEN 'a'\n    ELSE 'b'\n  END \n  AS field3\nFROM test\n```\n\n```text\nconst params = {\n  attributes: //DO SELECT CASE,\n};\n\nyield Model.findAll(params);\n```\n\n```text\nsequelizejs\n```\n\n```text\nModel.findAll({\n  attributes: [[models.sequelize.literal('CASE WHEN \"field1\" = true THEN 55 ELSE 23 END'), 'field3']]\n}\n```\n\n```text\nModel.findAll({\n  attributes: { include: [[models.sequelize.literal('CASE WHEN \"field1\" = true THEN 55 ELSE 23 END'), 'field3']]}\n}\n```\n\n```text\nSELECT CASE WHEN \"field1\" THEN 55 ELSE 23 END AS \"field3\" FROM \"models\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":69,"estimatedTokens":268}}215{"id":"stack-35974514","source":"stackoverflow","questionId":35974514,"title":"Sequelize Association Error Cannot read property 'getTableName' of undefined","tags":["node.js","sequelize.js"],"text":"Title: Sequelize Association Error Cannot read property 'getTableName' of undefined\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am running into an issue where I get an error message, `Unhandled rejection TypeError: Cannot read property 'getTableName' of undefined` when I try to associate a table into my query. I have a one-to-one relationship between the tables and am not sure if this is causing the error or if it is somewhere else where I am associating the two tables.\n\nHere is my query:\n\n```\nappRoutes.route('/settings')\n\n .get(function(req, res, organization){\n models.DiscoverySource.findAll({\n where: { \n organizationId: req.user.organizationId\n },\n include: [{\n model: models.Organization, through: { attributes: ['organizationName', 'admin', 'discoverySource']}\n }]\n }).then(function(organization, discoverySource){\n res.render('pages/app/settings.hbs',{\n user: req.user,\n organization: organization,\n discoverySource: discoverySource\n });\n })\n\n })\n```\n\nHere is the models.DiscoverySource model:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\nvar DiscoverySource = sequelize.define('discovery_source', {\n discoverySourceId: {\n type: DataTypes.INTEGER,\n field: 'discovery_source_id',\n autoIncrement: true,\n primaryKey: true\n },\n discoverySource: {\n type: DataTypes.STRING,\n field: 'discovery_source_name'\n },\n organizationId: {\n type: DataTypes.TEXT,\n field: 'organization_id'\n },\n},{\n freezeTableName: true,\n classMethods: {\n associate: function(db) {\n DiscoverySource.belongsTo(db.Organization, {foreignKey: 'organization_id'});\n },\n },\n});\n return DiscoverySource;\n}\n```\n\nHere is my models.Organization model:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\nvar Organization = sequelize.define('organization', {\n organizationId: {\n type: DataTypes.INTEGER,\n field: 'organization_id',\n autoIncrement: true,\n primaryKey: true\n },\n organizationName: {\n type: DataTypes.STRING,\n field: 'organization_name'\n },\n admin: DataTypes.STRING\n},{\n freezeTableName: true,\n classMethods: {\n associate: function(db) {\n Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });\n },\n }\n});\n return Organization;\n}\n```\n\n========================================\n\nTop Answer:\nIn my case removing\n\n```\nthrough: { attributes: [] }\n```\n\nsolved the problem.\n\n========================================\n\nCode:\n```text\nappRoutes.route('/settings')\n\n    .get(function(req, res, organization){\n        models.DiscoverySource.findAll({\n            where: { \n                organizationId: req.user.organizationId\n            },\n            include: [{\n                model: models.Organization, through: { attributes: ['organizationName', 'admin', 'discoverySource']}\n            }]\n        }).then(function(organization, discoverySource){\n            res.render('pages/app/settings.hbs',{\n                user: req.user,\n                organization: organization,\n                discoverySource: discoverySource\n            });\n        })\n\n    })\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\nvar DiscoverySource = sequelize.define('discovery_source', {\n    discoverySourceId: {\n        type: DataTypes.INTEGER,\n        field: 'discovery_source_id',\n        autoIncrement: true,\n        primaryKey: true\n    },\n    discoverySource: {\n        type: DataTypes.STRING,\n        field: 'discovery_source_name'\n    },\n    organizationId: {\n        type: DataTypes.TEXT,\n        field: 'organization_id'\n    },\n},{\n    freezeTableName: true,\n    classMethods: {\n        associate: function(db) {\n            DiscoverySource.belongsTo(db.Organization, {foreignKey: 'organization_id'});\n        },\n    },\n});\n    return DiscoverySource;\n}\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\nvar Organization = sequelize.define('organization', {\n    organizationId: {\n        type: DataTypes.INTEGER,\n        field: 'organization_id',\n        autoIncrement: true,\n        primaryKey: true\n    },\n    organizationName: {\n        type: DataTypes.STRING,\n        field: 'organization_name'\n    },\n    admin: DataTypes.STRING\n},{\n    freezeTableName: true,\n    classMethods: {\n        associate: function(db) {\n            Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });\n        },\n    }\n});\n    return Organization;\n}\n```\n\n```text\nUnhandled rejection TypeError: Cannot read property 'getTableName' of undefined\n```\n\n```text\nmodels.DiscoverySource.findAll({\n    attributes: ['discoverySource'],\n    where: { \n        organizationId: req.user.organizationId\n    },\n    include: [{\n        model: models.Organization,\n        attributes: ['organizationName', 'admin']\n    }]\n})\n```\n\n```text\n[options.include[].through]\n```\n\n```text\nBelongs-To-Many\n```\n\n```text\nBelong-To\n```\n\n```text\nDiscoverySource\n```\n\n```text\nOrganization\n```\n\n```text\nmodels.DiscoverySource.findAll({\n    attributes: ['discoverySource'],\n    where: { \n        organizationId: req.user.organizationId\n    },\n    include: {\n        model: models.Organization,\n        //rest of the code, if any\n    }\n})\n```\n\n```text\n5.22.3\n```\n\n```text\nthrough: { attributes: [] }\n```\n\n```text\nmodels.DiscoverySource.findAll({\n            where: { \n                organizationId: req.user.organizationId\n            },\n            include: [{\n                model: models.Organization, \n                attributes: ['organizationName', 'admin', 'discoverySource']\n            }]\n```\n\n========================================\n\nComments:\n- For anyone facing this, the same error is yield whenever you pass anything different than an array as the `options.include[]` parameter\n- Yeah this worked for me, I still don't understand why though\n- Worked for me too, Thanks man P.S: Sequelize lacks documentation, lots of documentation\n- If you are using an association where the foreign key is a column on the table itself (one-to-one, or one-to-many, although not always the case), then you do not require a `through` table (by default). `through: { attributes: [] }` defines what attributes you want to include from the through table (Such as on a many to many relationship), and as such, will throw an error when being specified on a query/association without a through table.","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":261,"estimatedTokens":1557}}216{"id":"stack-28433139","source":"stackoverflow","questionId":28433139,"title":"sequelize js with big integers","tags":["mysql","node.js","sequelize.js","bigint"],"text":"Title: sequelize js with big integers\nTags: mysql, node.js, sequelize.js, bigint\nSource: Stack Overflow\n\nQuestion:\nI have an application written in Node JS and uses the Sequelize js ORM library to access my database which is MySql.\n\nMy problem is that I have a column in my db which is BIGINT and when the value of it is large I get wrong values when I retrieve it.\n\nfor example when the value in database is: `10205918797953057` I get `10205918797953056` when I get it using sequelize.\n\nI tried using `big-integer` library but I had no luck.\n\nany advice is welcomed.\n\nP.S: I can't change the datatype to VARCHAR.\n\n========================================\n\nTop Answer:\nThe answer by Jan Aagaard Meier is correct and works, But there are few things to consider.\n\nAccording to Sequelize Docs (connection-options):\n\n`supportBigNumbers`: When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option (Default: false).\n\n`bigNumberStrings`: Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: `false`). Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String objects only when they cannot be accurately represented with JavaScript Number objects(which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects. This option is ignored if `supportBigNumbers` is disabled.\n\nSo, in some cases, to handle the returned value correctly, using both\n`bigNumberStrings` and `supportBigNumbers` might be a better option\nthat **guarantees a string value in return**.\n\n========================================\n\nCode:\n```text\n10205918797953057\n```\n\n```text\n10205918797953056\n```\n\n```text\nbig-integer\n```\n\n```text\nnew Sequelize(..., {\n  dialect: 'mysql',\n  dialectOptions: {\n    supportBigNumbers: true\n  }\n});\n```\n\n```text\nsupportBigNumbers\n```\n\n```text\nbigNumberStrings\n```\n\n```text\nsupportBigNumbers\n```\n\n```text\nbigNumberStrings\n```\n\n```text\nsupportBigNumbers\n```\n\n```text\nbigNumberStrings\n```\n\n```text\nfalse\n```\n\n```text\nsupportBigNumbers\n```\n\n```text\nbigNumberStrings\n```\n\n```text\nsupportBigNumbers\n```\n\n```text\nbigNumberStrings\n```\n\n```text\nsupportBigNumbers\n```\n\n========================================\n\nComments:\n- could it be `DataTypes.BIGINT` as here\n- the column is defined in Mysql and in Sequelize as `BIGINT`\n- Thanks a lot mate that saved the day.","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":110,"estimatedTokens":624}}217{"id":"stack-40886293","source":"stackoverflow","questionId":40886293,"title":"How to connect Node Sequelize to Amazon RDS MySQL with Multi-AZ probably","tags":["mysql","node.js","amazon-web-services","sequelize.js","amazon-rds"],"text":"Title: How to connect Node Sequelize to Amazon RDS MySQL with Multi-AZ probably\nTags: mysql, node.js, amazon-web-services, sequelize.js, amazon-rds\nSource: Stack Overflow\n\nQuestion:\nI'm using an Amazon RDS hosted MySQL with Multi-AZ Support. Just could not find any information on how to connect Sequelize to Amazon RDS properly so that Sequelize is handling fail-overs etc. accordingly?\n\nI'm just using the following config, but do not know if this is enough or recommended?\n\n```\nsequelizeConfig = {\n logging: false,\n pool: { maxConnections: 5, maxIdleTime: 30},\n sequelizeConfig[dialectOptions] = {\n ssl: 'Amazon RDS'\n }\n}\n```\n\nUsing Amazon RDS with Multi-AZ I consider the following is important:\n\n- Try reconnecting if connection got lost, until it is available again\n\n- Don't cache mysql server ip address too long (Amazon suggests less than 1 min)\n\nAmazon Docs are not writing anything about connection handling and pooling.\n\n========================================\n\nTop Answer:\nThe previous answer didn't work for me, after some research, this options object did:\n\n```\nvar options = {\n host: settings.database.host,\n port: settings.database.port,\n logging: console.log,\n maxConcurrentQueries: 100,\n dialect: 'mysql',\n ssl: 'Amazon RDS',\n pool: { maxConnections: 5, maxIdleTime: 30 },\n language: 'en',\n}\n```\n\nI'm running a RDS MySQL and a EC2 instance in the same default VPC, this options object worked when connecting a node app from that EC2 with the RDS using sequelize.\n\n========================================\n\nCode:\n```text\nsequelizeConfig = {\n  logging: false,\n  pool: { maxConnections: 5, maxIdleTime: 30},\n  sequelizeConfig[dialectOptions] = {\n    ssl: 'Amazon RDS'\n  }\n}\n```\n\n```text\nvar config = require(__dirname + '/../config/config.json')[env];\n // your config file will be in your directory\n var sequelize = new Sequelize(config.database, config.username, config.password, {\n    host: '****.****.us-west-1.rds.amazonaws.com',\n    port: 5432,\n    logging: console.log,\n    maxConcurrentQueries: 100,\n    dialect: 'postgres',\n    dialectOptions: {\n        ssl:'Amazon RDS'\n    },\n    pool: { maxConnections: 5, maxIdleTime: 30},\n    language: 'en'\n})\n```\n\n```text\nvar options = {\n  host: settings.database.host,\n  port: settings.database.port,\n  logging: console.log,\n  maxConcurrentQueries: 100,\n  dialect: 'mysql',\n  ssl: 'Amazon RDS',\n  pool: { maxConnections: 5, maxIdleTime: 30 },\n  language: 'en',\n}\n```\n\n```text\nvar options = {\n  host: settings.database.host,\n  port: settings.database.port,\n  logging: console.log,\n  dialect: 'mysql',\n  \"dialectOptions\": {\n        \"ssl\": {\n            \"ca\": fs.readFileSync('./eu-central-1-bundle.pem')\n        }\n    }\n}\n```\n\n```text\nssl: 'Amazon RDS'\n```\n\n========================================\n\nComments:\n- Did you get Node Sequelize.js to work with Amazon RDS MySQL?\n- Yes, but just sequelize, not sequelize-cli with migrations. Just use the regular SQL settings via environment variables plus the above settings as described in the aws docs\n- I see. Bummer. We started a EC2 instance and connect RDS via Security Group.\n- can you provide an additional example for iam authentication please?\n- Thx for the fast reply anyways!\n- What do you put in the ssl? Just the string Amazon RDS??\n- Yes, I believe. I did it a year ago.\n- Worked for me, Except I used `dialect: 'mysql'` instead of postgres\n- @Manuel You have to create an auth token which you pass as password: docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/RDS/Signer.h&zwnj;&#8203;tml\n- I'm using sequelize 6.33.0 and node 18.17.1 and setting dialectOptions.ssl to 'Amazon RDS' results in an error. So this no longer works.\n- Can confirm @Mike Lane is right. It’s an error using ‘Amazon RDS’ now.\n- FYI `maxConcurrentQueries` has not been used since 2014: github.com/sequelize/sequelize/issues/2405\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- \"Some digging\" where? edit your question to include supporting details.","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":125,"estimatedTokens":1045}}218{"id":"stack-45070595","source":"stackoverflow","questionId":45070595,"title":"Sequelize exclude belongs-to-many mapping object","tags":["sequelize.js"],"text":"Title: Sequelize exclude belongs-to-many mapping object\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way when making a SequelizeJS query on an object, and including a relation which has a belongs-to-many association, to have the included property not return the association mapping object with the result?\n\ni.e.:\n\n```\nUsers.findAll({include: [{model: Role, as: 'roles'}]})\n\n//yields objects of the following form\nuser: {\n username: 'test',\n roles: [\n {\n name: 'user',\n UserRoles: {userId: 1, roleId: 1} //<--I do not want this\n }\n ] \n}\n```\n\n========================================\n\nTop Answer:\nYou can try specifying the `attributes` property.\n\nSo to include fields say a,b,c you add\n\n```\nattributes: ['a', 'b','c']\n```\n\nTo exclude them\n\n```\nattributes:{exclude:['a', 'b','c']}\n```\n\nSo findAll looks like\n\n```\nModel.someModel.findAll({\n where: // some condition\n include: // some other model\n attributes: // some fields\n})\n```\n\nYou can also specify attributes within the include clause\n\n========================================\n\nCode:\n```text\nUsers.findAll({include: [{model: Role, as: 'roles'}]})\n\n//yields objects of the following form\nuser: {\n    username: 'test',\n    roles: [\n        {\n           name: 'user',\n           UserRoles: {userId: 1, roleId: 1} //<--I do not want this\n        }\n    ]        \n}\n```\n\n```text\nUsers.findAll({\n    include: [\n        {\n            model: Role, \n            as: 'roles',\n            through: {attributes: []} //<-- this line will prevent mapping object from being added\n        }\n    ]\n});\n```\n\n```text\nattributes: ['a', 'b','c']\n```\n\n```text\nattributes:{exclude:['a', 'b','c']}\n```\n\n```text\nModel.someModel.findAll({\n  where: // some condition\n  include: // some other model\n  attributes: // some fields\n})\n```\n\n```text\nattributes\n```\n\n```js\nexport const getAllUsers = async (req, res) => {\n    try {\n        const users = await User.findAll({\n            include: [\n                {\n                    model: Enrollment,\n                    as: 'enrollments',\n                    attributes:{exclude:['city']}\n                }\n            ],\n            attributes: { exclude: ['password', 'refresh_token',] }\n        })\n        res.json(succesResponse(users))\n    } catch (error) {\n        res.json(errorResonse(error))\n    }\n}\n```\n\n========================================\n\nComments:\n- tried your response and it didn't exclude the UserRoles joining object\n- for now i just use a map and delete the UserRoles object from the result before sending to the client.\n- On Stack Overflow, the **how** is important, but much of the site's quality level comes from people going out of their way to explain **why**. While a *code-only* answer get the person who asked the question past whatever hurdle they might be facing, it doesn't do them or future visitors much good in the long run. See Is there any benefit in code-only answers?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":130,"estimatedTokens":795}}219{"id":"stack-27157687","source":"stackoverflow","questionId":27157687,"title":"Is it possible to do a subquery with Sequelize.js?","tags":["mysql","sequelize.js"],"text":"Title: Is it possible to do a subquery with Sequelize.js?\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a query that looks like:\n\n```\nselect es.EssayId, (esmax.WordCount - esmin.WordCount)\nfrom (select es.EssayId, min(es.EssayDate) as mined, max(es.EssayDate) as maxed\n from EssayStats es\n group by es.EssayId\n ) es join\n EssayStats esmin\n on es.EssayId = esmin.EssayId and es.mined = esmin.EssayDate join\n EssayStats esmax\n on es.EssayId = esmax.EssayId and es.maxed = esmax.EssayDate;\n```\n\nIs it possible to write this with Sequelize.js ORM? I know I can just use a `query` directly, but I'm wondering if it's possible to construct.\n\n========================================\n\nTop Answer:\nan example for subquery\n\n```\nModelA.findAll({\n where: {\n $or: [\n {'$B.someColumn$' : someCondition},\n {'$C.someOtherColumn$' : someOtherCondition}\n ]\n },\n include: [{\n model: ModelB,\n required: false, //true or false for required \n where:{id:$id}\n\n }, {\n model: ModelC,\n required: false, //true or false for required \n where:{id:$id}\n }]\n});\n```\n\ni hope useful :D\n\n========================================\n\nCode:\n```text\nselect es.EssayId, (esmax.WordCount - esmin.WordCount)\nfrom (select es.EssayId, min(es.EssayDate) as mined, max(es.EssayDate) as maxed\n      from EssayStats es\n      group by es.EssayId\n     ) es join\n     EssayStats esmin\n     on es.EssayId = esmin.EssayId and es.mined = esmin.EssayDate join\n     EssayStats esmax\n     on es.EssayId = esmax.EssayId and es.maxed = esmax.EssayDate;\n```\n\n```text\nquery\n```\n\n```text\nEssayStats\n    EssayId\n    EssayDate\n    WordCount\n```\n\n```text\nreturn EssayStat.findAll({\n    attributes: [\n        [sequelize.literal('((SELECT wordCount FROM \"EssayStats\" WHERE \"EssayId\" = \"EssayStat\".\"EssayId\" EssayStat BY \"createdAt\" DESC LIMIT 1) - (SELECT wordCount FROM \"EssayStats\" WHERE \"EssayId\" = \"EssayStat\".\"EssayId\" EssayStat BY \"createdAt\" ASC LIMIT 1))'), 'difference'],\n        'EssayId'\n    ],\n    group: ['EssayId']\n});\n```\n\n```text\nsequelize.query\n```\n\n```text\nafterCreate\n```\n\n```text\nModelA.findAll({\n    where: {\n        $or: [\n            {'$B.someColumn$' : someCondition},\n            {'$C.someOtherColumn$' : someOtherCondition}\n        ]\n    },\n    include: [{\n        model: ModelB,\n        required: false,  //true or false for required \n        where:{id:$id}\n\n    }, {\n        model: ModelC,\n        required: false, //true or false for required \n        where:{id:$id}\n    }]\n});\n```\n\n========================================\n\nComments:\n- I don't think so. Eager loading may be the closest thing. Here's an example where Sequelize generates a sub-query via eager loading, because of an artificial `limit`.\n- I don't know anything about `Sequelize.js`. Is it possible to compose something like `EssayStats t1 LEFT JOIN EssayStats t2 ON t1.EssayId = t2.EssayId AND t1.EssayDate < t2.EssayDate` using its ORM? If the answer is `YES` then you can write the query without subqueries and without `GROUP BY`. You need to join the table to itself three times though, once with `INNER JOIN` and two times with `LEFT JOIN`.\n- Hi @Derit, here I want some alias name for Model A, Model B join output and again join that output with model C. Is there any way to do it. Ex: select uid,col1,col2,col3 from( select A.id as uid,col1,col2,col3 from A inner join B in A.id = B.mid where somecondition ) as 't' inner join users as u on t.uid = u.id","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":120,"estimatedTokens":853}}220{"id":"stack-68304477","source":"stackoverflow","questionId":68304477,"title":"Sequelize - run migration with es6 and modules","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize - run migration with es6 and modules\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm not sure if I'm doing something wrong or what. I feel like I'm running a modern, fairly common stack. But I cannot get the new Sequelize v6 to work nicely with my setup. I am on Node v14.17, Sequelize v6.6.2 and in my package.json I have `\"type\": \"module\"`. I finally figured out how to get my models automatically imported with a lot of googling and tinkering. So now I am trying to add a field to a model using the migration tool. I created the migration file in the migrations folder.\n\nThat looks like this:\n\n```\n'use strict';\n\nmodule.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n * Add altering commands here.\n *\n * Example:\n * await queryInterface.createTable('users', { id: Sequelize.INTEGER });\n */\n return Promise.all([\n queryInterface.addColumn(\n 'Customers', // table name\n 'include_core_items', // new field name\n {\n type: Sequelize.Boolean,\n allowNull: false,\n defaultValue: true,\n after: 'customer_name',\n }\n ),\n ]);\n },\n\n down: async (queryInterface, Sequelize) => {\n /**\n * Add reverting commands here.\n *\n * Example:\n * await queryInterface.dropTable('users');\n */\n return Promise.all([\n queryInterface.removeColumn('Customers', 'include_core_items'),\n ]);\n },\n};\n```\n\nAnd then I am trying to run the migration with: `npx sequelize-cli db:migrate` and I get the following errors:\n`ERROR: Error reading \"config\\config.js\". Error: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\\...\\config\\config.js require() of ES modules is not supported. require() of C:\\...\\config\\config.js from C:\\Users\\...\\AppData\\Roaming\\npm-cache\\_npx\\12576\\node_modules\\sequelize-cli\\lib\\helpers\\config-helper.js is an ES module file as it is a .js file whose nearest pare nt package.json contains \"type\": \"module\" which defines all .js files in that package scope as ES modules. Instead rename config.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from C:\\...\\package.json.`\n\nI have tried renaming the config to .cjs and then get the error: `ERROR: Dialect needs to be explicitly supplied as of v4.0.0` so I don't think it is correctly reading in the ENV variables or something.\n\nconfig.[c]js\n\n```\n// seed command: sequelize seed:create --name PermissionData\n// import dotenv from 'dotenv';\n// dotenv.config();\n\nimport 'dotenv/config.js';\n\nconst username = process.env.NAME;\nconst password = process.env.PASSWORD;\nconst database = process.env.DATABASE;\nconst host = process.env.HOST;\nconst port = process.env.DB_PORT;\nconst dialect = process.env.DIALECT;\nconst node_env = process.env.NODE_ENV;\nconst session_secret = process.env.SESSION_SECRET;\nconst base_url = process.env.BASE_URL;\nconst client_url = process.env.CLIENT_APP_LOC;\nconst secure_cookie = process.env.SECURE_COOKIE;\n\nconst config = {\n dev: {\n username,\n password,\n database,\n host,\n port,\n dialect,\n logging: true,\n session_secret,\n base_url,\n client_url,\n secure_cookie,\n },\n testing: {\n username,\n password,\n database,\n host,\n port,\n dialect,\n logging: true,\n session_secret,\n base_url,\n client_url,\n secure_cookie,\n },\n production: {\n username,\n password,\n database,\n host,\n port,\n dialect,\n logging: true,\n session_secret,\n base_url,\n client_url,\n secure_cookie,\n },\n};\n\nexport default config[node_env];\n```\n\n========================================\n\nCode:\n```js\n'use strict';\n\nmodule.exports = {\n    up: async (queryInterface, Sequelize) => {\n        /**\n         * Add altering commands here.\n         *\n         * Example:\n         * await queryInterface.createTable('users', { id: Sequelize.INTEGER });\n         */\n        return Promise.all([\n            queryInterface.addColumn(\n                'Customers', // table name\n                'include_core_items', // new field name\n                {\n                    type: Sequelize.Boolean,\n                    allowNull: false,\n                    defaultValue: true,\n                    after: 'customer_name',\n                }\n            ),\n        ]);\n    },\n\n    down: async (queryInterface, Sequelize) => {\n        /**\n         * Add reverting commands here.\n         *\n         * Example:\n         * await queryInterface.dropTable('users');\n         */\n        return Promise.all([\n            queryInterface.removeColumn('Customers', 'include_core_items'),\n        ]);\n    },\n};\n```\n\n```js\n// seed command: sequelize seed:create --name PermissionData\n// import dotenv from 'dotenv';\n// dotenv.config();\n\nimport 'dotenv/config.js';\n\nconst username = process.env.NAME;\nconst password = process.env.PASSWORD;\nconst database = process.env.DATABASE;\nconst host = process.env.HOST;\nconst port = process.env.DB_PORT;\nconst dialect = process.env.DIALECT;\nconst node_env = process.env.NODE_ENV;\nconst session_secret = process.env.SESSION_SECRET;\nconst base_url = process.env.BASE_URL;\nconst client_url = process.env.CLIENT_APP_LOC;\nconst secure_cookie = process.env.SECURE_COOKIE;\n\nconst config = {\n    dev: {\n        username,\n        password,\n        database,\n        host,\n        port,\n        dialect,\n        logging: true,\n        session_secret,\n        base_url,\n        client_url,\n        secure_cookie,\n    },\n    testing: {\n        username,\n        password,\n        database,\n        host,\n        port,\n        dialect,\n        logging: true,\n        session_secret,\n        base_url,\n        client_url,\n        secure_cookie,\n    },\n    production: {\n        username,\n        password,\n        database,\n        host,\n        port,\n        dialect,\n        logging: true,\n        session_secret,\n        base_url,\n        client_url,\n        secure_cookie,\n    },\n};\n\nexport default config[node_env];\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\nnpx sequelize-cli db:migrate\n```\n\n```text\nERROR: Error reading \"config\\config.js\". Error: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\\...\\config\\config.js require() of ES modules is not supported. require() of C:\\...\\config\\config.js from C:\\Users\\...\\AppData\\Roaming\\npm-cache\\_npx\\12576\\node_modules\\sequelize-cli\\lib\\helpers\\config-helper.js is an ES module file as it is a .js file whose nearest pare nt package.json contains \"type\": \"module\" which defines all .js files in that package scope as ES modules. Instead rename config.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from C:\\...\\package.json.\n```\n\n```text\nERROR: Dialect needs to be explicitly supplied as of v4.0.0\n```\n\n```text\nrequire(\"babel-register\");\n\nconst path = require('path');\n\nmodule.exports = {\n  'config': path.resolve('config', 'config.json'),\n  'models-path': path.resolve('models'),\n  'seeders-path': path.resolve('seeders'),\n  'migrations-path': path.resolve('migrations')\n}\n```\n\n```text\nnpm i --save-dev babel-register\n```\n\n```text\n.sequelizerc\n```\n\n```text\n.sequelizerc\n```\n\n```text\nconfig.js\n```\n\n========================================\n\nComments:\n- Similar question answered here stackoverflow.com/a/69801750/1704845\n- Finally got around to digging in and working on this and it worked for me! I did have to add a `package.json` file in my config folder with `{ \"type\": \"commonjs\" }` to finally get it to work. And I had to change all of my imports to this: `import * as config from '..&#47;config&#47;config.js';`\n- If anyone comes here and has the same issue, just an FYI, I also had to add a `package.json` file to my migrations folder with the contents `{ \"type\": \"commonjs\" }` to get the migrations to work correctly. What a mess!\n- adding package.json file in migrations folder with only having { \"type\": \"commonjs\" } worked for me too.\n- It should be noticed that the question specifies that type is set to module, i.e es6.\n- I used a `config.cjs` file instead of `config.js`.\n- I am not able to run seeders, migration are working fine. For seeder I am getting `ERROR: require() of ES Module &#47;Users&#47;tinkeshwarsingh&#47;Sites&#47;Open&#47;node-latest-sequelize&#47;data&zwnj;&#8203;base&#47;seeders&#47;2022071&zwnj;&#8203;7130025-initial-admi&zwnj;&#8203;n-user.js not supported. Instead change the require of 20220717130025-initial-admin-user.js in null to a dynamic import() which is available in all CommonJS modules.`\n- if you are using @babel/core ^7.0.0 you need to use @babel/register in this solution fyi","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":281,"estimatedTokens":2091}}221{"id":"stack-42414024","source":"stackoverflow","questionId":42414024,"title":"Sequelize update","tags":["node.js","sequelize.js"],"text":"Title: Sequelize update\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to update a model in Sequelize using the following code:\n\n```\nexports.updateItem = function(item) {\n return new Promise((fulfill, reject) => {\n models.TimesheetItem.update(item,{where: {id: item.id}})\n .then(fulfill)\n .catch(console.dir);\n });\n};\n```\n\nWhere item is the result of doing models.TimeSheetItem.find()\n\nThe call never executes the .then and instead passes an empty object to the .catch.\n\nI've looked over the documentation and it seems that this is the way to update a row, but I can't get it to work. What am I doing wrong?\n\nThank you!\n\n========================================\n\nTop Answer:\n```\n{ error: type \"where\" does not exist}\n```\n\nJust an update to the solution, Sequelize now gives the error above when you include the 'where' option(as shown below). So take it out and it should work perfectly.\n\n```\nexports.updateItem = function(item){\n models.TimesheetItem.update(item, { id: item.id }).then((result) => {\n // here result will be [ 1 ], if the id column is unique in your table\n // the problem is that you can't return updated instance, you would have to retrieve it from database once again\n return result;\n }).catch(e => {\n console.log(e);\n });\n};\n```\n\n========================================\n\nCode:\n```text\nexports.updateItem = function(item) {\n    return new Promise((fulfill, reject) => {\n        models.TimesheetItem.update(item,{where: {id: item.id}})\n                            .then(fulfill)\n                            .catch(console.dir);\n     });\n};\n```\n\n```text\nlet updateValues = { name: 'changed name' };\nmodels.Model.update(updateValues, { where: { id: 1 } }).then((result) => {\n    // here your result is simply an array with number of affected rows\n    console.log(result);\n    // [ 1 ]\n});\n```\n\n```text\nlet updateValues = { name: 'changed name' };\ninstance.update(updateValues).then((self) => {\n    // here self is your instance, but updated\n});\n```\n\n```text\nexports.updateItem = function(item){\n    return item.update(values).then((self) => {\n        return self;\n    }).catch(e => {\n        console.log(e);\n    });\n};\n```\n\n```text\nexports.updateItem = function(item){\n    models.TimesheetItem.update(item, { where: { id: item.id } }).then((result) => {\n        // here result will be [ 1 ], if the id column is unique in your table\n        // the problem is that you can't return updated instance, you would have to retrieve it from database once again\n        return result;\n    }).catch(e => {\n        console.log(e);\n    });\n};\n```\n\n```text\nexports.updateItem = function(item) {\n    return models.TimesheetItem.findById(item.id).then((itemInstance) => {\n        return itemIstance.update(item).then((self) => {\n            return self;\n        });\n    }).catch(e => {\n        console.log(e);\n    });\n}\n```\n\n```text\nupdate\n```\n\n```text\nvalues\n```\n\n```text\noptions\n```\n\n```text\nwhere\n```\n\n```text\nModel.update()\n```\n\n```text\nwhere\n```\n\n```text\ninstance.update()\n```\n\n```text\nupdate()\n```\n\n```text\nitem\n```\n\n```text\nitem\n```\n\n```text\nModel.update()\n```\n\n```text\nTimesheetItem\n```\n\n```text\nid = item.id\n```\n\n```text\ninstance.update()\n```\n\n```text\nPromise\n```\n\n```text\nupdate()\n```\n\n```text\n{ error: type \"where\" does not exist}\n```\n\n```text\nexports.updateItem = function(item){\n    models.TimesheetItem.update(item, { id: item.id  }).then((result) => {\n        // here result will be [ 1 ], if the id column is unique in your table\n        // the problem is that you can't return updated instance, you would have to retrieve it from database once again\n        return result;\n    }).catch(e => {\n        console.log(e);\n    });\n};\n```\n\n========================================\n\nComments:\n- Wonderful answer, you explained it perfectly. Many thanks!\n- you didn't add the where clause `{ where: { id: args.id } }`, you only added `{ id: args.id }`","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":194,"estimatedTokens":972}}222{"id":"stack-12156206","source":"stackoverflow","questionId":12156206,"title":"Sequelize select distinct rows","tags":["node.js","sequelize.js"],"text":"Title: Sequelize select distinct rows\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to select distinct rows from a table using sequelize.js? \nI looked through the documentation but the \"finder methods\" do not specify a way to accomplish this task.\n\n========================================\n\nTop Answer:\nAssuming you want to apply DISTINCT to the following query:\n\n```\nTuple.findAll({attributes: ['key', 'value']});\n```\n\nthen this is a (hackish) way to achieve what you want without having to write the whole query yourself:\n\n```\nTuple.findAll({attributes: [[Sequelize.literal('DISTINCT `key`'), 'key'], 'value']});\n```\n\n(Tested with Sequelize v2.1.0)\n\nEdit 2015-06-08: Still works with Sequelize v3.1.1\n\n========================================\n\nCode:\n```text\nsequelize.query('sql goes here', null, { raw: plain }).success(function(data){\n    console.log(data)\n})\n```\n\n```text\nsequelize.query('sql goes here', { raw: true }).then(function(data){\n        console.log(data);\n    });\n```\n\n```text\nthen\n```\n\n```text\nsuccess\n```\n\n```text\nSequelize.query\n```\n\n```text\nsql\n```\n\n```text\noptions\n```\n\n```text\nraw\n```\n\n```text\ntrue/false\n```\n\n```text\nplain\n```\n\n```text\nvar query = \"SELECT <%= attributes %> FROM <%= table %>\"\n```\n\n```text\nvar query = \"SELECT \" + ((options.distinct)? 'DISTINCT ':'') +\"<%= attributes %> FROM <%= table %>\",\n```\n\n```text\ndistinct: true\n```\n\n```text\nmainQueryItems.push('SELECT ');\n    if (options.distinct) {\n        mainQueryItems.push('DISTINCT ');\n    }\n    mainQueryItems.push(mainAttributes.join(', ') + ' FROM ' + options.table);\n```\n\n```text\nTuple.findAll({attributes: ['key', 'value']});\n```\n\n```text\nTuple.findAll({attributes: [[Sequelize.literal('DISTINCT `key`'), 'key'], 'value']});\n```\n\n```text\nMyModel.aggregate('teh_field', 'DISTINCT', { plain: false }).then(...)\n// Resolves to: [ { DISTINCT: value1 }, { DISTINCT: value2 }, ... ]\n```\n\n```text\nMyModel.aggregate('teh_field', 'DISTINCT', { plain: false })\n    .map(function (row) { return row.DISTINCT })\n    .then(function (tehValueList) {\n        // tehValueList = [ value1, value2, ... ]\n    })\n;\n```\n\n```text\nmyModel.findAll({\n  attributes: [[sequelize.fn('DISTINCT', sequelize.col('col_name')), 'alias_name']],\n  where:{}\n}).then(data => {}).....\n```\n\n```text\nModel.findAll({Attributes: ['col_name1', 'col_name2'], group: ['col_name1', 'col_name2']});\n```\n\n========================================\n\nComments:\n- Ok. I get that :) Probably in next versions, a bool option {distinct: true} can be added (false being default).\n- yep not sure if it will be in the next version but we should add it\n- stackoverflow.com/a/30070249/1353897 is the most elegant solution\n- (... Do not do this. It will be overwritten the next time you update the package.)\n- NOTE : This solution does not work with `findAndCountAll` method.\n- alias_name doesn't work for me when its different then col_name\n- how to define `ORDER BY expressions` for this?\n- u know what if hace a \"distinct\" in attributes? `Model.findAll({Attributes: [[Sequelize.fn('DISTINCT', Sequelize.col('id')), 'id'], 'col_name2'], group: ['id', 'col_name2']});`","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":138,"estimatedTokens":783}}223{"id":"stack-45398851","source":"stackoverflow","questionId":45398851,"title":"How to make a field required in Sequelize?","tags":["mysql","node.js","postgresql","sequelize.js"],"text":"Title: How to make a field required in Sequelize?\nTags: mysql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet's say I want to make the firstname field required in sequelize, in mongoose I can just say required: true on that field but how do I do that in Sequelize?\n\n========================================\n\nTop Answer:\nTo responde to Dmitry question: you can define a custom validation error under the field definition :\n\n```\nfoo: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n notNull: { msg: \"foo is required\" },\n },\n}\n```\n\nmore info here\n\n========================================\n\nCode:\n```text\nconst YourTable = sequelize.define('your_table', {\n  firstname: {\n    type: Sequelize.STRING,\n\n    // This will require the firstname be present\n    allowNull: false,\n\n    // If you want to also have a length restriction, add the next line\n    len: [2,50], // only allow values with length between 2 and 50\n       // That is 'Al' will be accepted and so will 'Rigoberto Fernando Luis María'. \n       // But '' or 'J' won't be good enough\n\n     // If you use sequelize transforms, this will remove spaces on both ends\n     // of the string also\n     trim: true,\n  },\n  // All the other fields (columns)\n});\n```\n\n```text\nrequired: true\n```\n\n```text\nallowNull: false\n```\n\n```text\nfoo: {\n  type: Sequelize.STRING,\n  allowNull: false,\n  validate: {\n    notNull: { msg: \"foo is required\" },\n  },\n}\n```\n\n========================================\n\nComments:\n- How I can set, say \"[Fieldname] is required?\" message for required fields?","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":70,"estimatedTokens":391}}224{"id":"stack-51965298","source":"stackoverflow","questionId":51965298,"title":"How to get results from multiple level associations in sequelize?","tags":["mysql","sequelize.js"],"text":"Title: How to get results from multiple level associations in sequelize?\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 3 models Country, City and Office\n\nThey are associated with each other. \nOffice Belongs To City, City Belongs to Country. \nNow what I want to do is get Office that are within specific Country. \nI have tried below but it does not work.\n\n```\nOffice.findAll({\n where: {'$Country.id$': 1},\n include: [\n { \n model: City,\n as: 'city',\n include: [{model: Country, as: 'country'}]\n }\n ]\n});\n```\n\nCountry\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n let Country = sequelize.define('Country', {\n id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},\n code: {type: DataTypes.STRING, allowNull: false, unique: true },\n name: DataTypes.STRING\n });\n Country.associate = (models) => {\n Country.hasMany(models.City, {as: 'cities'});\n };\n return Country;\n}\n```\n\nCity \n\n```\nmodule.exports = (sequelize, DataTypes) => {\n let City = sequelize.define('City', {\n id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},\n name: {type: DataTypes.STRING, allowNull: false, unique: true},\n });\n\n City.associate = (models) => {\n City.belongsTo(models.Country, {as: 'country'});\n City.hasMany(models.Office, {as: 'offices'});\n };\n\n return City;\n}\n```\n\nOffice\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n let Office= sequelize.define('Office', {\n id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},\n name: DataTypes.STRING,\n details: DataTypes.TEXT,\n latitude: DataTypes.DECIMAL(10, 8),\n longitude: DataTypes.DECIMAL(11, 8),\n });\n\n Office.associate = (models) => {\n Office.belongsTo(models.City, {as: 'city'});\n };\n\n return Office;\n};\n```\n\n========================================\n\nTop Answer:\nYou can query from Country directly from include , and use `required : true` , try this :\n\n```\nOffice.findAll({\n include: [\n { \n model: City,\n as: 'city',\n required : true , <----- Make sure will create inner join\n include: [\n {\n model: Country, \n as: 'country' ,\n required : true , // <----- Make sure will create inner join\n where : { 'id' : 1 } // <-------- Here\n }]\n }\n ]\n});\n```\n\n========================================\n\nCode:\n```text\nOffice.findAll({\n  where: {'$Country.id$': 1},\n  include: [\n    { \n      model: City,\n      as: 'city',\n      include: [{model: Country, as: 'country'}]\n    }\n  ]\n});\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    let Country = sequelize.define('Country', {\n        id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},\n        code: {type: DataTypes.STRING, allowNull: false, unique: true },\n        name: DataTypes.STRING\n    });\n    Country.associate = (models) => {\n        Country.hasMany(models.City, {as: 'cities'});\n    };\n    return Country;\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    let City = sequelize.define('City', {\n        id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},\n        name: {type: DataTypes.STRING, allowNull: false, unique: true},\n    });\n\n    City.associate = (models) => {\n        City.belongsTo(models.Country, {as: 'country'});\n        City.hasMany(models.Office, {as: 'offices'});\n    };\n\n    return City;\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  let Office= sequelize.define('Office', {\n    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},\n    name: DataTypes.STRING,\n    details: DataTypes.TEXT,\n    latitude: DataTypes.DECIMAL(10, 8),\n    longitude: DataTypes.DECIMAL(11, 8),\n  });\n\n  Office.associate = (models) => {\n    Office.belongsTo(models.City, {as: 'city'});\n  };\n\n  return Office;\n};\n```\n\n```text\nconst where = {\n    'city.country.id': 1\n};\n\nOffice.findAll({ where, include: [{ all: true, nested: true }]});\n```\n\n```text\nSELECT\n    `Office`.`id`,\n    `Office`.`name`,\n    `Office`.`details`,\n    `Office`.`latitude`,\n    `Office`.`longitude`,\n    `Office`.`createdAt`,\n    `Office`.`updatedAt`,\n    `Office`.`cityId`,\n    `Office`.`CityId`,\n    `city`.`id` AS `city.id`,\n    `city`.`name` AS `city.name`,\n    `city`.`createdAt` AS `city.createdAt`,\n    `city`.`updatedAt` AS `city.updatedAt`,\n    `city`.`CountryId` AS `city.CountryId`,\n    `city`.`countryId` AS `city.countryId`,\n    `city->country`.`id` AS `city.country.id`,\n    `city->country`.`code` AS `city.country.code`,\n    `city->country`.`name` AS `city.country.name`,\n    `city->country`.`createdAt` AS `city.country.createdAt`,\n    `city->country`.`updatedAt` AS `city.country.updatedAt`\nFROM\n    `Offices` AS `Office`\n    LEFT OUTER JOIN `Cities` AS `city` ON `Office`.`cityId` = `city`.`id`\n    LEFT OUTER JOIN `Countries` AS `city->country` ON `city`.`countryId` = `city->country`.`id`\nWHERE\n    `Office`.`city.country.id` = 1;\n```\n\n```text\nOffice.findAll({\n  include: [\n    { \n      model: City,\n      as: 'city',\n      required : true , <----- Make sure will create inner join\n      include: [\n            {\n                model: Country, \n                as: 'country' ,\n                required : true , // <----- Make sure will create inner join\n                where : { 'id' : 1 } // <-------- Here\n            }]\n    }\n  ]\n});\n```\n\n```text\nrequired : true\n```\n\n========================================\n\nComments:\n- This worked for me! The other answer was a little confusing with my model.","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":232,"estimatedTokens":1333}}225{"id":"stack-35882816","source":"stackoverflow","questionId":35882816,"title":"How to disable only_full_group_by in MySQL or Sequelize","tags":["mysql","sequelize.js"],"text":"Title: How to disable only_full_group_by in MySQL or Sequelize\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn Sequelize, how would I do the equivalent of `SET sql_mode=''` to avoid getting the following error?\n\n `SequelizeDatabaseError: ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'assets.group_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by`\n\nOr, alternatively, how do I change the default configuration of MySQL such that the `sql_mode` is always `''`?\n\nThanks!\n\n========================================\n\nTop Answer:\nGet the existing sql_mode and remove only the `ONLY_FULL_GROUP_BY` value rather than making it completely empty.\n\n```\nSELECT @@sql_mode; -- Get the current sql_mode\n```\n\nYou might get a result as follows;\n\n```\nONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\n```\n\nNow remove the `ONLY_FULL_GROUP_BY` from the result and update the sql_mode\n\n```\nSET GLOBAL sql_mode=\"STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\";\nSET SESSION sql_mode=\"STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\";\n```\n\nNow you are done.\n\nNote that SET GLOBAL is to update the global setting which will not take effect until you restart the mysql server or service.\nSET SESSION will immediately take this effect on your current session even without restarting mysql server. Therefore, you can use either one or both depending on your requirement.\n\nAlternatively, instead of disabling this setting, from MySQL 5.7 onwards, you can simply modify the query by using `ANY_VALUE` function on whichever the field is throwing error. For example `ANY_VALUE(assets.group_id)` as mentioned in the error message you have posted.\n\n========================================\n\nCode:\n```text\nSET sql_mode=''\n```\n\n```text\nSequelizeDatabaseError: ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'assets.group_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n```\n\n```text\nsql_mode\n```\n\n```text\n''\n```\n\n```text\nSET GLOBAL sql_mode = '';\n```\n\n```text\nSELECT @@sql_mode; -- Get the current sql_mode\n```\n\n```text\nONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\n```\n\n```text\nSET GLOBAL sql_mode=\"STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\";\nSET SESSION sql_mode=\"STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\";\n```\n\n```text\nONLY_FULL_GROUP_BY\n```\n\n```text\nONLY_FULL_GROUP_BY\n```\n\n```text\nANY_VALUE\n```\n\n```text\nANY_VALUE(assets.group_id)\n```\n\n========================================\n\nComments:\n- Great! This seems to have done it! Thanks so much. I will accept this answer once I am allowed to. (Apparently you responded much faster than stackoverflow allows me to accept)\n- Thanks it helps me as it was working perfect before a day today itself it's giving me an error may i know the reason?\n- I always get a permission error: MySQL said: Documentation #1227 - Access denied; you need (at least one of) the SUPER or SYSTEM_VARIABLES_ADMIN privilege(s) for this operation –\n- The ANY_VALUE(assets.group_id) workaround was perfect. Good hack\n- I always get a permission error: MySQL said: Documentation #1227 - Access denied; you need (at least one of) the SUPER or SYSTEM_VARIABLES_ADMIN privilege(s) for this operation","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":102,"estimatedTokens":883}}226{"id":"stack-23361022","source":"stackoverflow","questionId":23361022,"title":"Sequelize in NodeJS : Inner JOIN implementation Failure","tags":["mysql","node.js","join","orm","sequelize.js"],"text":"Title: Sequelize in NodeJS : Inner JOIN implementation Failure\nTags: mysql, node.js, join, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have three tables contractors, projects and jointable for these two is projects_contractors and i created models and wrote a relation like below,\n\n```\nContractor.hasMany(Project, {joinTableName: 'projects_contractors'})\n Project.hasMany(Contractor, {joinTableName: 'projects_contractors'})\n```\n\nI want to access this Contractor based projects means inner JOIN.\n\nCore query : \n select c.id,c.name,p.id,p.name from contractors c inner join projects_contractors pc on c.id=pc.contractor_id inner join projects p on p.id = pc.project_id\n\nI was failed in implementing the below code. \"required\" is a keyword which used for inner JOIN but not working if we keep.\n\n```\nContractor.findAll({ include: [Project, {required: false}]}).success(function(list){\n console.log(\"hi\")\n res.send(204)\n })\n```\n\nIf not keeping required it will creates a left outer JOIN on projects and contractors. Suggest me with a sample example for the above senario.\n\n========================================\n\nCode:\n```text\nContractor.hasMany(Project, {joinTableName: 'projects_contractors'})\n    Project.hasMany(Contractor, {joinTableName: 'projects_contractors'})\n```\n\n```text\nContractor.findAll({ include: [Project, {required: false}]}).success(function(list){\n       console.log(\"hi\")\n         res.send(204)\n     })\n```\n\n```text\nContractor.findAll({ include: [{model: Project, required: true}]})\n```\n\n========================================\n\nComments:\n- Have you tried `required: true`?\n- @MickHansen : Yes, I tried, but showing below error: Include malformed. Expected attributes: daoFactory, as!","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":429}}227{"id":"stack-46608382","source":"stackoverflow","questionId":46608382,"title":"Sequelize Deprecated Error Message","tags":["node.js","sequelize.js"],"text":"Title: Sequelize Deprecated Error Message\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm very new to Node and I'm getting my head around how ORM and Sequelize works. I've been on the Sequelize website and copied the connection string and altered it to work with my database. When I execute the file, it seems to execute OK creating the table in my database however I get the error \"String based operators are now deprecated.Please use Symbol based operators for better security ....node_modules/sequelize/lib/sequelize.js:236:13\" I understand why the operators have been deprecated, however as I've installed this as a new package and used the connection string from the documentation, thus avoiding using any illegal operators am I right in assuming this error message is for info only and not reflected in the code I have just used.\n\nI include my for app file that is bringing up the error, is it the password that maybe causing this.\n\n```\nconst express = require('express');\nconst app = express();\n\nconst Sequelize = require('sequelize');\n\nconst db = new Sequelize('myDBName', 'mYuSeRnAmE', 'mYpAsSw!ORd$', {\nhost: 'mySqlserverName',\n dialect: 'mssql',\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n },\n\n});\n\nvar Article = db.define('Article', {\n title: Sequelize.STRING,\n body: Sequelize.TEXT\n});\n\ndb.sync();\n\nmodule.exports = app;\n```\n\n**** Edit ****\n\nI've figured it out, I'll leave this answer up just incase someone else runs into the problem. You need to include { operatorsAliases: false } to get rid of the error message in the connection.\n\n========================================\n\nTop Answer:\nUpdating to version:\n\n```\n\"sequelize\": \"^5.8.6\"\n```\n\nand removing `operatorsAliases` param from \n\n```\nnew Sequelize()\n```\n\nremoved depreciation warning\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst app = express();\n\nconst Sequelize = require('sequelize');\n\nconst db = new Sequelize('myDBName', 'mYuSeRnAmE', 'mYpAsSw!ORd$', {\nhost: 'mySqlserverName',\n  dialect: 'mssql',\n\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  },\n\n});\n\n\nvar Article = db.define('Article', {\n    title: Sequelize.STRING,\n    body: Sequelize.TEXT\n});\n\ndb.sync();\n\nmodule.exports = app;\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst sequelize = new Sequelize(\n  DB_NAME,\n  USERNAME, \n  PASSWORD,\n  {\n    host: HOSTNAME,\n    dialect: 'mysql',\n    logging: false,\n    freezeTableName: true,\n    operatorsAliases: false\n  }\n)\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst Op = Sequelize.Op\nconst sequelize = new Sequelize(\n  DB_NAME,\n  USERNAME, \n  PASSWORD,\n  {\n    host: HOSTNAME,\n    dialect: 'mysql',\n    logging: false,\n    freezeTableName: true,\n    operatorsAliases: {\n      $and: Op.and,\n      $or: Op.or,\n      $eq: Op.eq,\n      $gt: Op.gt,\n      $lt: Op.lt,\n      $lte: Op.lte,\n      $like: Op.like\n    }\n  }\n)\n```\n\n```text\nconst sequelize = new Sequelize({\n  username: process.env.DBUSERNAME,\n  host: process.env.DBHOST,\n  database: process.env.DBNAME,\n  password: process.env.DBPASSWORD,\n  dialect: 'postgres',\n  define: {\n    timestamps: false,\n  },\n  operatorsAliases: false,\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  },\n\n});\n```\n\n```text\n\"sequelize\": \"^5.8.6\"\n```\n\n```text\nnew Sequelize()\n```\n\n```text\noperatorsAliases\n```\n\n========================================\n\nComments:\n- Instead of editing your solution into your question, you should write an **actual answer** below. Otherwise, users are probably going to glance over your edit and not see it. Considering user3139574's answer is the same, maybe even just accept and upvote that as the correct answer.\n- See also: DeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed\n- BartusZak is correct. As of Version 5, the operatorAliases will cause a warning: \"DeprecationWarning: String based operators are deprecated. Please use Symbol based operatorys for better security...\" When you remove operatorAliases from the options, the warning goes away.\n- This is a no-op with v5 and should be removed.","metadata":{"transformedAt":"2026-08-18T18:33:34.355Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":170,"estimatedTokens":1029}}228{"id":"stack-25565212","source":"stackoverflow","questionId":25565212,"title":"How to define array of objects in Sequelize.js?","tags":["javascript","sequelize.js"],"text":"Title: How to define array of objects in Sequelize.js?\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I define an array of objects field in Sequelize.js model? \n\nI need something like this\n\n```\n{\n \"profiles\" : [\n {\n \"profile_id\": 10,\n \"profile_pictures\" : [\"pic1.jpg\",\"pic2.jpg\",\"pic3.jpg\"],\n \"profile_used_id\" : 12\n },\n ... // more profiles\n ]\n}\n```\n\nI checked the docs, but couldn't find a relevant data type, am I missing something here ?\n\n========================================\n\nTop Answer:\nI can think currently of 2 solutions (and a 3rd one if you are using PostgreSQL).\n\nWe have a relational database working behind, so do its principles apply also for Sequelize which is a ORM for relational databases. The easiest would be to create another table or entity and associate them as a 1:n relationship.\nFor that matter add a new model in Sequelize and define its associations like described here: http://sequelizejs.com/articles/getting-started#associations\nYou might have then 2 tables. One profile table having N pictures.\n\nIf its just a filename or url you could serialise a Javascript array to a JSON string like:\n\n// before save\n\nvar mypics = [\"pic1.jpg\",\"pic2.jpg\"];\nprofile.pictures = JSON.stringify( mypics );\nprofile.save()\n\n// after load before use\n\nvar profile = Profile.get(1)\npictures = JSON.parse(profile.pictures);\n\nIf you use PostgreSQL you could use the Array Datatype for this field, see:\nhttp://www.postgresql.org/docs/8.4/static/arrays.html\n\nor the JSON Datatype:\n\nhttp://www.postgresql.org/docs/9.3/interactive/datatype-json.html\n\nGo for 1 if your Picture object is or will be more complex in the feature. Or if you want to query by filename.\nGo for 2 if you dont do any data filtering or complex data in the future.\n\nGo for 3? I think its best to stick to Sequelize abstraction and not use custom data types even its possible in that case. Maybe you better stick to 1 or 2.\n\n========================================\n\nCode:\n```text\n{\n    \"profiles\" : [\n        {\n            \"profile_id\": 10,\n            \"profile_pictures\" : [\"pic1.jpg\",\"pic2.jpg\",\"pic3.jpg\"],\n            \"profile_used_id\" : 12\n        },\n        ... // more profiles\n    ]\n}\n```\n\n```text\nvar MyModel = sequelize.define('MyModel', {\n    myArrayField: { \n        type: DataTypes.STRING, \n        get: function() {\n            return JSON.parse(this.getDataValue('myArrayField'));\n        }, \n        set: function(val) {\n            return this.setDataValue('myArrayField', JSON.stringify(val));\n        }\n    }\n}\n```\n\n========================================\n\nComments:\n- So Let's say I use Postgres, I would define the array of Objects like Sequelize.ARRAY(Sequelize.JSON) right?\n- Sequelize.ARRAY(Sequelize.JSON) does not work\n- with defaultValue: '[]'\n- with type: DataTypes.STRING","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":95,"estimatedTokens":702}}229{"id":"stack-48397401","source":"stackoverflow","questionId":48397401,"title":"Sequelize 'Dialect needs to be explicitly supplied as of v4.0.0'","tags":["node.js","error-handling","sequelize.js"],"text":"Title: Sequelize 'Dialect needs to be explicitly supplied as of v4.0.0'\nTags: node.js, error-handling, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to run third party application in node.js environment but Sequelize throws 'Dialect needs to be explicitly supplied as of v4.0.0'\nI've found similar topic here Dialect needs to be explicitly supplied as of v4.0.0 but 'export NODE_ENV=development' doesn't work and I can not find Sequelize config file.\nHow can I fix this error?\n\nHere is code:\n\n```\nconst Sequelize = require('sequelize');\n\nconst scheme = require('./scheme');\n\nconst Op = Sequelize.Op;\n\nconst sequelize = new Sequelize(null, null, {\n\ndialect: 'sqlite',\nstorage: 'db.sqlite3',\n\noperatorsAliases: { $and: Op.and },\n\nlogging: false\n});\n\nscheme(sequelize);\nsequelize.sync();\n\nmodule.exports.sequelize = sequelize;\nmodule.exports.models = sequelize.models;\n```\n\n========================================\n\nTop Answer:\nNode cannot find your environment to load in the config file.\n\nYou can easily fix by running this \n\n```\nexport NODE_ENV=development; npx sequelize db:migrate\n```\n\nThis should export to NODE_ENV the environment needed to run it.\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\n\nconst scheme = require('./scheme');\n\nconst Op = Sequelize.Op;\n\nconst sequelize = new Sequelize(null, null, {\n\ndialect: 'sqlite',\nstorage: 'db.sqlite3',\n\noperatorsAliases: { $and: Op.and },\n\nlogging: false\n});\n\nscheme(sequelize);\nsequelize.sync();\n\nmodule.exports.sequelize = sequelize;\nmodule.exports.models = sequelize.models;\n```\n\n```text\nconst sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  dialect: // pick one of 'mysql','sqlite','postgres','mssql',\n});\n```\n\n```text\n'use strict';\n\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst db = {};\n\nconst DB = 'users';\nconst USER = 'user';\nconst PASSWORD = 'password';\nconst HOST = 'host';\nconst DIALECT = 'postgres';\nconst PORT = 5432;\n\nconst CONNECTION = new Sequelize(\n    DB,\n    USER, \n    PASSWORD, \n    {\n        host: HOST,\n        dialect: DIALECT,\n        port: PORT,\n    }\n)\n\nmodule.exports.CONNECTION = CONNECTION;\n```\n\n```text\nexport NODE_ENV=development; npx sequelize db:migrate\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n  'config': path.resolve('config', 'database.json'),\n  'models-path': path.resolve('db', 'models'),\n  'seeders-path': path.resolve('db', 'seeders'),\n  'migrations-path': path.resolve('db', 'migrations')\n};\n```\n\n========================================\n\nComments:\n- Yes, and you have passed two parameters before the options for dialect. Where as three are required. See my post","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":129,"estimatedTokens":677}}230{"id":"stack-49467654","source":"stackoverflow","questionId":49467654,"title":"What methods/mixins sequelize adds to the models when an association is made?","tags":["javascript","orm","sequelize.js","associations","prototype"],"text":"Title: What methods/mixins sequelize adds to the models when an association is made?\nTags: javascript, orm, sequelize.js, associations, prototype\nSource: Stack Overflow\n\nQuestion:\nEdit: Some time after I wrote this Q&A, I've made improvements to the Sequelize documentation itself, regarding multiple topics, including this one. For those interested, the original Q&A is kept below, but I recommend just reading the new documentation instead:\n\n- Basic Tutorial on Associations\n\n- Advanced Tutorial on Associations\n\n- HasOne API Reference\n\n- HasMany API Reference\n\n- BelongsTo API Reference\n\n- BelongsToMany API Reference\n\n### Original Question\n\nWhile going through the sequelize docs, more specifically the documentations about associations *(edit: warning: this link points to an old version of the documentation)*, I see that the guide casually shows the reader methods such as `setTasks()`, `addTask()`, `setProject()`, that seem to be automatically created by sequelize for all model instances with respect to the created associations.\n\nI couldn't find detailed information on what methods are available, and whether they are created with the singular version or plural version (since there is both `setTasks()` and `setProject()`, for example), and what exactly are the parameters they expect, and such. The docs apparently just casually mention them inside the examples...\n\n**So, what methods/mixins sequelize adds to the models when an association is made?** And what are the parameters and return values, i.e. what's the documentation for those methods? Or, at least, where can I find them?\n\n========================================\n\nTop Answer:\nTo get a listing of the added methods try:\n\n```\nconst model = %yourSequelizeModel%\n for (let assoc of Object.keys(model.associations)) {\n for (let accessor of Object.keys(model.associations[assoc].accessors)) {\n console.log(model.name + '.' + model.associations[assoc].accessors[accessor]+'()');\n }\n }\n```\n\nCredit goes to https://gist.github.com/Ivan-Feofanov/eefe489a2131f3ec43cfa3c7feb36490\n\nTo adjust the association names use \"as\" option:\n\n```\nModel.hasOne(models.series_promotions, { as: 'seriesPromotions' });\n```\n\nwhich changed the association method name from:\n\n```\nseries.getSeries_promotion()\nseries.setSeries_promotion()\nseries.createSeries_promotion()\n```\n\nto\n\n```\nseries.getSeriesPromotions()\nseries.setSeriesPromotions()\nseries.createSeriesPromotions()\n```\n\nbased on the snippet above.\n\n========================================\n\nCode:\n```text\nsetTasks()\n```\n\n```text\naddTask()\n```\n\n```text\nsetProject()\n```\n\n```text\nsetTasks()\n```\n\n```text\nsetProject()\n```\n\n```text\n// Assuming that the models Person, Hypothesis and Person_Hypothesis are already defined\nPerson.belongsToMany(Hypothesis, { through: Person_Hypothesis });\nHypothesis.belongsToMany(Person, { through: Person_Hypothesis });\n```\n\n```text\nthis.accessors = {\n    get: 'get' + plural,\n    set: 'set' + plural,\n    addMultiple: 'add' + plural,\n    add: 'add' + singular,\n    create: 'create' + singular,\n    remove: 'remove' + singular,\n    removeMultiple: 'remove' + plural,\n    hasSingle: 'has' + singular,\n    hasAll: 'has' + plural,\n    count: 'count' + plural\n};\n```\n\n```text\nthis.accessors = {\n      get: 'get' + singular,\n      set: 'set' + singular,\n      create: 'create' + singular\n  };\n```\n\n```text\nthis.accessors = {\n      get: 'get' + singular,\n      set: 'set' + singular,\n      create: 'create' + singular\n  };\n```\n\n```text\nthis.accessors = {\n      get: 'get' + plural,\n      set: 'set' + plural,\n      addMultiple: 'add' + plural,\n      add: 'add' + singular,\n      create: 'create' + singular,\n      remove: 'remove' + singular,\n      removeMultiple: 'remove' + plural,\n      hasSingle: 'has' + singular,\n      hasAll: 'has' + plural,\n      count: 'count' + plural\n  };\n```\n\n```text\nPerson\n```\n\n```text\nHypothesis\n```\n\n```text\nPeople\n```\n\n```text\nHypotheses\n```\n\n```text\nadd\n```\n\n```text\naddHypothesis()\n```\n\n```text\naddHypotheses()\n```\n\n```text\ncountHypotheses()\n```\n\n```text\ncreateHypothesis()\n```\n\n```text\ngetHypotheses()\n```\n\n```text\nhasHypothesis()\n```\n\n```text\nhasHypotheses()\n```\n\n```text\nremoveHypothesis()\n```\n\n```text\nremoveHypotheses()\n```\n\n```text\nsetHypotheses()\n```\n\n```text\naddPerson()\n```\n\n```text\naddPeople()\n```\n\n```text\ncountPeople()\n```\n\n```text\ncreatePerson()\n```\n\n```text\ngetPeople()\n```\n\n```text\nhasPerson()\n```\n\n```text\nhasPeople()\n```\n\n```text\nremovePerson()\n```\n\n```text\nremovePeople()\n```\n\n```text\nsetPeople()\n```\n\n```text\naddPerson()\n```\n\n```text\naddPeople()\n```\n\n```text\nadd\n```\n\n```text\naddMultiple\n```\n\n```text\nremove()\n```\n\n```text\nremoveMultiple()\n```\n\n```text\nhasSingle()\n```\n\n```text\nhasAll()\n```\n\n```text\nconst model = %yourSequelizeModel%\n    for (let assoc of Object.keys(model.associations)) {\n      for (let accessor of Object.keys(model.associations[assoc].accessors)) {\n        console.log(model.name + '.' + model.associations[assoc].accessors[accessor]+'()');\n      }\n    }\n```\n\n```text\nModel.hasOne(models.series_promotions, { as: 'seriesPromotions' });\n```\n\n```text\nseries.getSeries_promotion()\nseries.setSeries_promotion()\nseries.createSeries_promotion()\n```\n\n```text\nseries.getSeriesPromotions()\nseries.setSeriesPromotions()\nseries.createSeriesPromotions()\n```\n\n========================================\n\nComments:\n- Do you know if these methods use any kind of performance optimizations? Like would `personInstance.getHypotheses()` be faster than defining an instance method on the person model that does a `findAll` to get their hypotheses?\n- @DanMandel - sorry to take so long. I am not 100% sure, but looks like there isn't really any performance optimizations when compared to a `findAll`. I checked the source code, and the `get` method actually calls `findAll` internally, after preparing the options / where clauses: here and here\n- You are my hero. Working with sqlz association mixins is easily the most aggravating thing about sqlz.\n- Very explanatory asnwer. Thank you. Do you know if there's any way to check what the exact plural version of my model will be? Sometimes it can get complicated and the set methods simply do not work. I had to rename my model. It would be nice if I could name my model whatever I wanted, and if I could check how inflection named my add, set methods etc.\n- @EsterVojkollari Thank you very much! I did this Q&A exactly because it took me a while to understand this part of sequelize. For your question, I suggest using npm's runkit and running `inflection.pluralize(yourString)`.\n- You answered your own question but used the second person: > The documentation about associations you linked, ... ;)\n- @DeeZone Tried to make it even more subtle ;)\n- Is there a way to know if any of the sequelize mixins/methods like get, set, add, remove have completed or failed. Also do they support transactions, so I can roll back a record creation that precedes any of these method's\n- @NathanielBabalola if they fail they will throw an error. Yes they support transactions. In the API reference you should see the transaction option listed.\n- Ooh I checked and I didn't see it\n- @Pedro A I have a situation where on a table I used a different field apart from `id` as PRIMARY KEY. So when I used `set` to create the relationship on the through table, so while using the node debugger in vs code, I saw that Sequelize was trying to create the association by linking it to `id` field, but this id field wasn't referenced from the through table so it isn't a FOREIGN KEY. Is there a way to tell Sequelize the correct field it should link to instead of automatically assuming it's the `id` field\n- @PedroA i posted the full question here, i would be grateful if you can help me out, stackoverflow.com/questions/66221799/&hellip;\n- For anyone looking for the updated link to Sequelize docs, the updated link is here: sequelize.org/api/v6/class/src/associations/&hellip;\n- @plutownium Thank you for the heads up. I've updated the question and the answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":47,"totalLines":316,"estimatedTokens":1993}}231{"id":"stack-37544147","source":"stackoverflow","questionId":37544147,"title":"Nodejs sequelize how to get last insert id","tags":["javascript","node.js","sequelize.js"],"text":"Title: Nodejs sequelize how to get last insert id\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize with nodejs to insert a row in a table,now i want that last inserted id,i want some thing like \"mysql_insert_id()\", here is my code:\n\n```\nfunction registerAgent(agent_data,request_key,res,next)\n{\n models.agent.create({creator_id: agent_data.userid }, { fields: [ 'creator_id'] }).then(function(user) {\n console.log(user);\n }); \n};\n```\n\n========================================\n\nCode:\n```text\nfunction registerAgent(agent_data,request_key,res,next)\n{\n  models.agent.create({creator_id: agent_data.userid },  { fields: [ 'creator_id'] }).then(function(user) {\n      console.log(user);\n    }); \n};\n```\n\n```text\nfunction registerAgent(agent_data,request_key,res,next)\n{\n  models.agent.create({creator_id: agent_data.userid },  { fields: [ 'creator_id'] }).then(function(user) {\n      console.log(user.id);\n    }); \n};\n```\n\n========================================\n\nComments:\n- Actually i forgot to add \"autoIncrement: true\" in my model that's why it was giving null. Thanks its working now :)\n- OK, it's my glad to help.","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":42,"estimatedTokens":291}}232{"id":"stack-37121882","source":"stackoverflow","questionId":37121882,"title":"Sequelize: Naming collision between attribute 'playlist' and association 'playlist'?","tags":["javascript","node.js","sequelize.js","mariadb"],"text":"Title: Sequelize: Naming collision between attribute 'playlist' and association 'playlist'?\nTags: javascript, node.js, sequelize.js, mariadb\nSource: Stack Overflow\n\nQuestion:\nI am using node.js, Sequelize and MariaDB and I am running into the following error, which I am not sure how to resolve?\n\n Error: Naming collision between attribute 'playlist' and association\n 'playlist' on model playlist_entry. To remedy this, change either foreignKey\n or as in your association definition\n\nMy Javascript:\n\n```\nEntities = function (settings, context) {\n\n sequelize = context.sequelize;\n\n var entities = {\n\n Playlist: this.sequelize.define('playlist', {\n name: Sequelize.STRING,\n description: Sequelize.STRING\n }), \n\n PlaylistEntry: this.sequelize.define('playlist_entry', {\n playlist: Sequelize.INTEGER\n //track: Sequelize.INTEGER\n })\n\n }; \n\n entities.PlaylistEntry.belongsTo(\n entities.Playlist,\n { foreignKey: { name: 'fk_playlist' }});\n\n return entities; \n}\n```\n\nMy tables:\n\n```\nCREATE TABLE `playlist` (\n `id` int(11) unsigned NOT NULL,\n `name` varchar(255) NOT NULL,\n `description` varchar(255) DEFAULT NULL,\n `createdAt` timestamp NULL DEFAULT NULL,\n `updatedAt` timestamp NULL DEFAULT NULL,\n `external_id` int(11) DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `id` (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nCREATE TABLE `playlist_entry` (\n `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n `playlist` int(11) unsigned DEFAULT NULL,\n `track` int(11) unsigned DEFAULT NULL,\n `createdAt` timestamp NULL DEFAULT NULL,\n `updatedat` timestamp NULL DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `track_idx` (`track`),\n KEY `playlist_idx` (`playlist`),\n CONSTRAINT `fk_playlist` FOREIGN KEY (`playlist`) REFERENCES `playlist` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION\n) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;\n```\n\n========================================\n\nCode:\n```text\nEntities = function (settings, context) {\n\n    sequelize = context.sequelize;\n\n    var entities = {\n\n        Playlist: this.sequelize.define('playlist', {\n            name: Sequelize.STRING,\n            description: Sequelize.STRING\n        }),     \n\n        PlaylistEntry: this.sequelize.define('playlist_entry', {\n            playlist: Sequelize.INTEGER\n            //track: Sequelize.INTEGER\n        })\n\n    };  \n\n     entities.PlaylistEntry.belongsTo(\n         entities.Playlist,\n         { foreignKey: { name: 'fk_playlist' }});\n\n    return entities;                    \n}\n```\n\n```text\nCREATE TABLE `playlist` (\n  `id` int(11) unsigned NOT NULL,\n  `name` varchar(255) NOT NULL,\n  `description` varchar(255) DEFAULT NULL,\n  `createdAt` timestamp NULL DEFAULT NULL,\n  `updatedAt` timestamp NULL DEFAULT NULL,\n  `external_id` int(11) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `id` (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nCREATE TABLE `playlist_entry` (\n  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n  `playlist` int(11) unsigned DEFAULT NULL,\n  `track` int(11) unsigned DEFAULT NULL,\n  `createdAt` timestamp NULL DEFAULT NULL,\n  `updatedat` timestamp NULL DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `track_idx` (`track`),\n  KEY `playlist_idx` (`playlist`),\n  CONSTRAINT `fk_playlist` FOREIGN KEY (`playlist`) REFERENCES `playlist` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION\n) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const session = sequelize.define('session', {\n    menteeId: DataTypes.INTEGER,\n  }, {});\n\n  session.associate = (models) => {\n    session.belongsTo(models.user, {\n      foreignKey: 'menteeId',\n      as: 'menteeId',\n      onDelete: 'CASCADE',\n    });\n  };\n  return session;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const session = sequelize.define('session', {\n    menteeId: DataTypes.INTEGER,\n  }, {});\n\n  session.associate = (models) => {\n    session.belongsTo(models.user, {\n      foreignKey: 'menteeId',\n      as: 'MenteeId', // Changes applied here\n      onDelete: 'CASCADE',\n    });\n  };\n  return session;\n};\n```\n\n```text\nentities.PlaylistEntry.belongsTo(\n    entities.Playlist,\n    { \n    foreignKey: { name: 'fk_playlist' },\n    as: 'PlayListAlias', // Appropriate name\n    },\n);\n```\n\n```text\ncolumn name\n```\n\n```text\nreference name\n```\n\n```text\ncolumn name\n```\n\n```text\nmenteeId\n```\n\n```text\nalias name\n```\n\n```text\nmenteeId\n```\n\n```text\nalias name\n```\n\n========================================\n\nComments:\n- You can specify an alias for the relationship with the key \"as\". docs.sequelizejs.com/en/latest/docs/associations\n- Thanks, that helps: `entities.PlaylistEntry.belongsTo(entities.Playlist, { as: 'Playlist', foreignKey: { name: 'fk_playlist' }});`.\n- well but if you put the same name, isnt it the same?\n- True, but now Sequelize doesn't complain about the collision. Maybe a question of case? Would you recommend an alternative nomenclature here?\n- Nah, if it works its good I guess. Never had such a problem, though I remembered the documentation hence the suggestion.","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":202,"estimatedTokens":1249}}233{"id":"stack-42677071","source":"stackoverflow","questionId":42677071,"title":"Sequelize migration add \"IF NOT EXISTS\" to addIndex and addColumn","tags":["postgresql","sequelize.js"],"text":"Title: Sequelize migration add \"IF NOT EXISTS\" to addIndex and addColumn\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**Is there a way to force Sequelize.js to add `IF NOT EXISTS` to the Postgres SQL created by the `queryInterface.addColumn` and `queryInterface.addIndex` methods?** \n\nAccording to the Postgres Docs this is supported for Alter Table Add Column as well as Create Index\n\nI have looked through the Sequelize.js docs without any luck, and I have tried to go through the code to figure out how the SQL is generated, but I have not had any luck yet.\n\n### A bit of background, or \"Why\"\n\nI am trying to create a migration strategy for an existing postgres instance, and I have currently created a Sequelize migration set which migrates from \"nothing\" to the current schema. Now I would like to simply get this up and running on my production server where all of the data already exists such that the next time I create a migration, I can run it.\n\nAll of this works well for every `queryInterface.createTable` because the `IF NOT EXISTS` is automatically added.\n\n========================================\n\nTop Answer:\nI had a similar issue, except in my case I was only interested in addColumn IF NOT EXIST.\n\nYou can achieve this with a two step solution, using `queryInterface.describeTable`.\nGiven the table name the function will return the table definition which contains all the existing columns. If the column you need to add does not exist then call the `queryInterface.addColumn` function.\n\n```\nconst tableName = 'your_table_name';\n\nqueryInterface.describeTable(tableName)\n .then(tableDefinition => {\n if (tableDefinition.yourColumnName) {\n return Promise.resolve();\n }\n\n return queryInterface.addColumn(\n tableName,\n 'your_column_name',\n { type: Sequelize.STRING } // or a different column\n );\n });\n```\n\n========================================\n\nCode:\n```text\nIF NOT EXISTS\n```\n\n```text\nqueryInterface.addColumn\n```\n\n```text\nqueryInterface.addIndex\n```\n\n```text\nqueryInterface.createTable\n```\n\n```text\nIF NOT EXISTS\n```\n\n```text\nlet query = `ALTER TABLE ${quotedTable} ADD COLUMN ${quotedKey} ${definition};`;\n```\n\n```text\nqueryInterface.sequelize.query(...);\n```\n\n```text\naddColumn\n```\n\n```text\nqueryGenerator\n```\n\n```text\naddColumnQuery\n```\n\n```text\ntable\n```\n\n```text\nkey\n```\n\n```text\ndataType\n```\n\n```text\nIF NOT EXISTS\n```\n\n```text\naddIndex\n```\n\n```text\nconst tableName = 'your_table_name';\n\nqueryInterface.describeTable(tableName)\n  .then(tableDefinition => {\n    if (tableDefinition.yourColumnName) {\n      return Promise.resolve();\n    }\n\n    return queryInterface.addColumn(\n      tableName,\n      'your_column_name',\n      { type: Sequelize.STRING } // or a different column\n    );\n  });\n```\n\n```text\nqueryInterface.describeTable\n```\n\n```text\nqueryInterface.addColumn\n```\n\n```text\nreturn queryInterface.describeTable(tableName).then(tableDefinition => {\n            if (!tableDefinition[columnName]){\n                return queryInterface.addColumn(tableName, columnName, {\n                    type: Sequelize.JSON\n                });\n            } else {\n                return Promise.resolve(true);\n            }\n        });\n```\n\n```text\nif (!tableDefinition.yourColumnName)\n```\n\n```text\nmodule.exports = {\n  /**\n   * @description Up.\n   * @param {QueryInterface} queryInterface\n   * @return Promise<void>\n   */\n  up: async (queryInterface) => {\n    const tableDefinition =  await queryInterface.describeTable('group');\n    const promises = [];\n\n    return queryInterface.sequelize.transaction((transaction) => {\n      if (!tableDefinition.column1) {\n        promises.push(queryInterface.addColumn(\n          'group',\n          'column1',\n          {\n            type: queryInterface.sequelize.Sequelize.STRING,\n            allowNull: true,\n          },\n          {transaction},\n        ));\n      }\n\n      if (!tableDefinition.oauth2_token_expire_at) {\n        promises.push(queryInterface.addColumn(\n          'group',\n          'column2',\n          {\n            type: queryInterface.sequelize.Sequelize.DATE,\n            allowNull: true,\n          },\n          {transaction},\n        ));\n      }\n\n      return Promise.all(promises);\n    });\n  },\n  /**\n   * @description Down.\n   * @param {QueryInterface} queryInterface\n   * @return Promise<void>\n   */\n  down: (queryInterface) => {\n    ...\n  },\n};\n```\n\n========================================\n\nComments:\n- Yeah, I found that code looking through the repo myself. I am considering creating a PR on the repo to enable this functionality, however what I ended up doing is to manually update the `SequelizeMeta` to fake the running of the migrations.\n- @Cort3z did you ever end up doing a PR for this?\n- @Simon I never did. Was a fire-and-forget job for me. I don't quite remember, but I might have manually updated my database with PSequel, or some other db management tool.\n- @Cort3z Yeah, I just ended up going with a raw query that checks for existing indexes. Thanks for following up!","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":203,"estimatedTokens":1248}}234{"id":"stack-13002873","source":"stackoverflow","questionId":13002873,"title":"sequelize fetching associations on find (1.6)","tags":["node.js","sequelize.js"],"text":"Title: sequelize fetching associations on find (1.6)\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nsequelize 1.6 has the following in the changelog:\n\n [FEATURE] added association prefetching for find and findAll\n\nThe question is HOW? \n\nI have the following models defined:\n\n```\nvar self = {\n Medium: client.define(\"Medium\", {\n name: Sequelize.STRING,\n description: Sequelize.TEXT\n },\n\n User: client.define(\"User\", {\n firstName: Sequelize.STRING,\n lastName: Sequelize.STRING,\n email: Sequelize.STRING,\n aboutArt: Sequelize.TEXT,\n bio: Sequelize.TEXT,\n password: Sequelize.STRING,\n description: Sequelize.TEXT\n }\n};\nself.User.hasMany(self.Medium, { as: 'Media' });\nself.Medium.hasMany(self.User);\n\nfor(var key in self){\n var model = self[key];\n model.sync();\n}\n```\n\nlater when i fetch a user like this:\n\n```\nUser.find(id)\n .success(function(record) {\n //record has no media!\n })\n```\n\nthe User instance does not have a list media. How do i auto fetch associations?\n\n========================================\n\nTop Answer:\nsdepold actually wrote the code, but I believe the syntax he settled on for include is:\n\n```\nUser.find({ where: {id: id}, include: ['Media'] }).success(function(user){ \n console.log(user.media)\n})\n```\n\n========================================\n\nCode:\n```text\nvar self = {\n    Medium: client.define(\"Medium\", {\n        name: Sequelize.STRING,\n        description: Sequelize.TEXT\n    },\n\n    User: client.define(\"User\", {\n        firstName: Sequelize.STRING,\n        lastName: Sequelize.STRING,\n        email: Sequelize.STRING,\n        aboutArt: Sequelize.TEXT,\n        bio: Sequelize.TEXT,\n        password: Sequelize.STRING,\n        description: Sequelize.TEXT\n    }\n};\nself.User.hasMany(self.Medium, { as: 'Media' });\nself.Medium.hasMany(self.User);\n\nfor(var key in self){\n    var model = self[key];\n    model.sync();\n}\n```\n\n```text\nUser.find(id)\n    .success(function(record) {\n        //record has no media!\n    })\n```\n\n```text\nUser.find({ where: {id: id}, include: [Media] }).success(function(user){ \n  console.log(user.media)\n})\n```\n\n```text\nUser.find({ where: {id: id}, include: ['Media'] }).success(function(user){ \n  console.log(user.media)\n})\n```\n\n```text\nUser.find({ where: {id: id}, include: ['Media'] }).success(function(user){ \n  console.log(user.media)\n})\n```\n\n========================================\n\nComments:\n- Oh yeah! That is what I am talking about. Thanks @sdepold!\n- Is there a way to use the field name instead? That would be very useful, especially considering that you can have separate fields reference the same table.\n- I can't seem to get this to work: `Item.hasOne(Item, { foreignKey: 'parentAid', as: 'Parent' })`. It says `Error: Item is not associated to Item!`, even though I got: `Item.hasOne(Item, { foreignKey: 'parentAid', as: 'Parent' })`","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":121,"estimatedTokens":703}}235{"id":"stack-35029052","source":"stackoverflow","questionId":35029052,"title":"Sequelize throwing 'id must be unique' on create","tags":["node.js","sequelize.js"],"text":"Title: Sequelize throwing 'id must be unique' on create\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nnew to Sequelize library. From my understanding, 'id' is created automatically by sequelize (and thats what I see in the database). However when I go to 'create' an object it will throw this error:\n\n```\n{ [SequelizeUniqueConstraintError: Validation error]\n name: 'SequelizeUniqueConstraintError',\n message: 'Validation error',\n errors: \n [ { message: 'id must be unique',\n type: 'unique violation',\n path: 'id',\n value: '1' } ],\n fields: { id: '1' } }\n```\n\nThe offending code:\n\n```\ndb.Account.create({\n email: req.body.email,\n password: req.body.password,\n allowEmail: req.body.allowEmail,\n provider: 'local',\n role: 'user'\n })\n```\n\nNotice ID is not specified anywhere, neither is it specified in my model definition. Also the query it generates runs fine if I run it in postgres admin:\n\n```\nINSERT INTO \"Accounts\" (\"id\",\"email\",\"role\",\"verifyCode\",\"provider\",\"cheaterScore\",\"isBanned\",\"allowEmail\",\"updatedAt\",\"createdAt\") VALUES (DEFAULT,'cat69232@gmail.com','user','','local',0,false,false,'2016-01-27 04:31:54.350 +00:00','2016-01-27 04:31:54.350 +00:00') RETURNING *;\n```\n\nAny ideas to what I could be missing here?\n\nedit: \n\npostgres version: 9.5\nstack trace starts here: \n/node_modules/sequelize/lib/dialects/postgres/query.js:326\n\n========================================\n\nTop Answer:\nTLDR: use:\n\n```\nawait sequelize.query(`ALTER SEQUENCE \"SharedLogs_id_seq\" RESTART WITH ${maxId};`);\n```\n\nHere is my typescript full migration code which makes bulk insert and alters postgres sequence accordingly:\n\n```\nimport {Migration, MigrationParams} from '../../types/db.migrations';\nimport {SharedLogRecord/* , SharedStateRecord*/} from '../../types/db';\nimport fs from 'fs';\n\ntype SharedLogRecordFromSqlite = SharedLogRecord & {\n updatedAt: string;\n deletedAt: string;\n};\n\nexport const up: Migration = async ({context: queryInterface}: MigrationParams) => {\n const data: SharedLogRecordFromSqlite[] = JSON.parse(fs.readFileSync(__dirname + '/20_shared_logs.json', 'utf8'));\n\n let maxId: number = 0;\n data.forEach((record: SharedLogRecordFromSqlite) => {\n delete record.updatedAt;\n delete record.deletedAt;\n\n if (record.id > maxId) maxId = record.id;\n });\n maxId++;\n\n await queryInterface.bulkInsert('SharedLogs', data);\n\n await queryInterface.sequelize.query(`ALTER SEQUENCE \"SharedLogs_id_seq\" RESTART WITH ${maxId};`); // {};\n\nmodule.exports = {up, down};\n```\n\nPlease see: https://stackoverflow.com/a/8750984/10099510\n\n========================================\n\nCode:\n```text\n{ [SequelizeUniqueConstraintError: Validation error]\n  name: 'SequelizeUniqueConstraintError',\n  message: 'Validation error',\n  errors: \n   [ { message: 'id must be unique',\n       type: 'unique violation',\n       path: 'id',\n       value: '1' } ],\n  fields: { id: '1' } }\n```\n\n```text\ndb.Account.create({\n    email: req.body.email,\n    password: req.body.password,\n    allowEmail: req.body.allowEmail,\n    provider: 'local',\n    role: 'user'\n  })\n```\n\n```text\nINSERT INTO \"Accounts\" (\"id\",\"email\",\"role\",\"verifyCode\",\"provider\",\"cheaterScore\",\"isBanned\",\"allowEmail\",\"updatedAt\",\"createdAt\") VALUES (DEFAULT,'cat69232@gmail.com','user','','local',0,false,false,'2016-01-27 04:31:54.350 +00:00','2016-01-27 04:31:54.350 +00:00') RETURNING *;\n```\n\n```js\nawait sequelize.query(`ALTER SEQUENCE \"SharedLogs_id_seq\" RESTART WITH ${maxId};`);\n```\n\n```js\nimport {Migration, MigrationParams} from '../../types/db.migrations';\nimport {SharedLogRecord/* , SharedStateRecord*/} from '../../types/db';\nimport fs from 'fs';\n\ntype SharedLogRecordFromSqlite = SharedLogRecord & {\n  updatedAt: string;\n  deletedAt: string;\n};\n\nexport const up: Migration = async ({context: queryInterface}: MigrationParams) => {\n  const data: SharedLogRecordFromSqlite[] = JSON.parse(fs.readFileSync(__dirname + '/20_shared_logs.json', 'utf8'));\n\n  let maxId: number = 0;\n  data.forEach((record: SharedLogRecordFromSqlite) => {\n    delete record.updatedAt;\n    delete record.deletedAt;\n\n    if (record.id > maxId) maxId = record.id;\n  });\n  maxId++;\n\n  await queryInterface.bulkInsert('SharedLogs', data);\n\n  await queryInterface.sequelize.query(`ALTER SEQUENCE \"SharedLogs_id_seq\" RESTART WITH ${maxId};`); // <--- key line\n};\n\nexport const down: Migration = async () => {};\n\nmodule.exports = {up, down};\n```\n\n========================================\n\nComments:\n- id: {type:DataTypes.INTEGER,primaryKey: true,autoIncrement: true}, Do you have something like above in your model definition.\n- I didn't at first, but I tried adding it too just in case. Either way same result, (and it creates the tables too). I also have sync({force: true}) on.\n- I have the same problem - doing a bulk insert (auto-setting up a test DB with pre-filling of data) and upon the first try of `SomeModel.create()` I get his error. Any next try works fine. So, I guess it's the Postgres problem you mention. I checked out the post you linked to, but from what I got as information there - I could not fix my problem. The ID columns in my models are `BIGSERIAL`, so I don't see where the problem comes from. Any ideas?","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":158,"estimatedTokens":1289}}236{"id":"stack-33313569","source":"stackoverflow","questionId":33313569,"title":"sequelize .create is not a function error","tags":["node.js","express","sequelize.js"],"text":"Title: sequelize .create is not a function error\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting `Unhandled rejection TypeError: feed.create is not a function` error and I can't understand why it occurs. What's the problem here?\n\nHere's my code. I'm probably not doing something very fundamental here since I can't reach feed variable in routes/index.js.\n\nIf I add module.exports = feed; to my models file, I can reach it, but I have more than one models, so if I add additional models below the feed, they override it.\n\ndb.js\n\n```\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('mydatabase', 'root', 'root', {\n host: 'localhost',\n dialect: 'mysql',\n port: 8889,\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n },\n define: {\n timestamps: false\n }\n});\n\nvar db = {};\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\nmodule.exports = db;\n```\n\nmodels.js\n\n```\nvar db = require('./db'),\n sequelize = db.sequelize,\n Sequelize = db.Sequelize;\n\nvar feed = sequelize.define('feeds', {\n subscriber_id: Sequelize.INTEGER,\n activity_id: Sequelize.INTEGER\n},\n{\n tableName: 'feeds',\n freezeTableName: true\n});\n```\n\nroutes/index.js\n\n```\nvar express = require('express');\nvar router = express.Router();\nvar models = require('../models');\n\nrouter.get('/addfeed', function(req,res) {\n sequelize.sync().then(function () {\n return feed.create({\n subscriber_id: 5008,\n activity_id : 116\n });\n }).then(function (jane) {\n res.sendStatus(jane);\n });\n});\n```\n\n========================================\n\nTop Answer:\nJust use\n\n```\nconst { User } = require(\"../models\");\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('mydatabase', 'root', 'root', {\n    host: 'localhost',\n    dialect: 'mysql',\n    port: 8889,\n\n    pool: {\n        max: 5,\n        min: 0,\n        idle: 10000\n    },\n    define: {\n        timestamps: false\n    }\n});\n\nvar db = {};\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\nmodule.exports = db;\n```\n\n```text\nvar db = require('./db'),\n    sequelize = db.sequelize,\n    Sequelize = db.Sequelize;\n\nvar feed = sequelize.define('feeds', {\n    subscriber_id: Sequelize.INTEGER,\n    activity_id: Sequelize.INTEGER\n},\n{\n    tableName: 'feeds',\n    freezeTableName: true\n});\n```\n\n```text\nvar express = require('express');\nvar router = express.Router();\nvar models = require('../models');\n\nrouter.get('/addfeed', function(req,res) {\n    sequelize.sync().then(function () {\n        return feed.create({\n            subscriber_id: 5008,\n            activity_id : 116\n        });\n    }).then(function (jane) {\n        res.sendStatus(jane);\n    });\n});\n```\n\n```text\nUnhandled rejection TypeError: feed.create is not a function\n```\n\n```text\nvar sequelize = new Sequelize('DBNAME', 'root', 'root', { \n  host: \"localhost\",           \n  dialect: 'sqlite',           \n\n  pool:{\n    max: 5, \n    min: 0,\n    idle: 10000                \n  },\n\n  storage: \"SOME_DB_PATH\"\n}); \n\n// load models                 \nvar models = [                 \n  'Users',            \n];\nmodels.forEach(function(model) {\n  module.exports[model] = sequelize.import(__dirname + '/' + model);\n});\n```\n\n```text\nvar Sequelize = require(\"sequelize\");\n\nmodule.exports=function(sequelize, DataTypes){ \n  return Users = sequelize.define(\"Users\", {\n    id: {\n      type: DataTypes.INTEGER, \n      field: \"id\",             \n      autoIncrement: !0,       \n      primaryKey: !0\n    },\n    firstName: {               \n      type: DataTypes.STRING,  \n      field: \"first_name\"      \n    },\n    lastName: {                \n      type: DataTypes.STRING,  \n      field: \"last_name\"       \n    },\n  }, {\n    freezeTableName: true, // Model tableName will be the same as the model name\n    classMethods:{\n\n      }\n    },\n    instanceMethods:{\n\n      }\n    }\n  });\n};\n```\n\n```text\nmodule.exports\n```\n\n```text\nsequelize.import\n```\n\n```text\nvar Users = require(\"MODELS_FOLDER_PATH\").Users;\n```\n\n```text\nconst User = sequelize.import('../models/users');\n```\n\n```text\nimport User from '../models/users';\n```\n\n```js\nconst { User } = require(\"../models\");\n```\n\n```text\n'use strict'\nmodule.exports = (sequelize, DataTypes, Model) => {\n    class User extends Model {\n        /**\n         * Helper method for defining associations.\n         * This method is not a part of Sequelize lifecycle.\n         * The `models/index` file will call this method automatically.\n         */\n        static associate(models) {\n            // define association here\n        }\n    };\n    User.init({\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false\n        },\n        phone_number: {\n            type: DataTypes.STRING(20)\n        },\n        otp: {\n            type: DataTypes.INTEGER(4).UNSIGNED\n        },{\n        sequelize,\n        modelName: 'User',\n    });\n    return User;\n};\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = require('../config/db').sequelize;\n\n// Bring in Model\nconst User = require('../models/user')(sequelize, Sequelize.DataTypes,\n     Sequelize.Model);\n// your code...\n// User.create(), User.find() whatever\n```\n\n```text\nconst sequelize = new Sequelize();\n... //your code\n...\nmodule.exports = {\nsequelize: sequelize\n}\n```\n\n```text\nv6\n```\n\n```text\nsequelize.import\n```\n\n```text\nsequelize\n```\n\n```text\nDataTypes\n```\n\n```text\nModel\n```\n\n```text\nsequelize\n```\n\n```text\nSequelize\n```\n\n```text\nsequelize\n```\n\n```text\nconst sequelize = new Sequelize()\n```\n\n```text\nconst { Feed } = require(\"../models/Feed.js\");\n```\n\n```text\nconst { Feed } = require(\"../models\");\n```\n\n========================================\n\nComments:\n- I have followed this i am getting error `Cannot read property 'all' of undefined`\n- `const {User} = require('#models&#47;user.js');` resolves the issue","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":323,"estimatedTokens":1448}}237{"id":"stack-14653913","source":"stackoverflow","questionId":14653913,"title":"Rename node.js sequelize timestamp columns","tags":["javascript","mysql","node.js","orm","sequelize.js"],"text":"Title: Rename node.js sequelize timestamp columns\nTags: javascript, mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've just started using sequelize but I'm having a small issue mapping an existing database.\n\nBy default sequelize creates two datatime columns named createdAt and updatedAt, does anyone know if its possible to rename the columns to something else. For example...\n\n```\nproducts: sequelize.define('products', {\n timestamps: false,\n product_id: {\n type: Sequelize.INTEGER, \n primaryKey: true, \n autoIncrement: true\n },\n product_name: Sequelize.STRING,\n product_description: Sequelize.TEXT,\n product_created: Sequelize.DATE,\n product_updated: Sequelize.DATE\n}),\n```\n\nThat would still automagically amend the product_created/product_updated columns on creates and updates.\n\n========================================\n\nTop Answer:\nsadly this is not yet possible. Can you please open an issue on github. I guess this is pretty easy to implement. \n\nThanks :)\n\n========================================\n\nCode:\n```text\nproducts: sequelize.define('products', {\n    timestamps: false,\n    product_id: {\n        type: Sequelize.INTEGER, \n        primaryKey: true, \n        autoIncrement: true\n    },\n    product_name: Sequelize.STRING,\n    product_description: Sequelize.TEXT,\n    product_created: Sequelize.DATE,\n    product_updated: Sequelize.DATE\n}),\n```\n\n```js\nproducts: sequelize.define('products', {\n    timestamps: false,\n    product_id: {\n        type: Sequelize.INTEGER, \n        primaryKey: true, \n        autoIncrement: true\n    },\n    product_name: Sequelize.STRING,\n    product_description: Sequelize.TEXT,\n    product_created: Sequelize.DATE,\n    product_updated: Sequelize.DATE\n}, {\n  updatedAt: 'product_updated',\n  createdAt: 'product_created'\n});\n```\n\n========================================\n\nComments:\n- Maybe this? `renameColumn(tableName, attrNameBefore, attrNameAfter) This methods allows renaming attributes. migration.renameColumn('Person', 'signature', 'sig')`\n- Good news, sadly the project i was working on at the time is well out of the door, but good to know for the future!\n- @OliverRidgway I know its not kind to the previous guy, but could you mark this answer as correct answer for future ref?\n- Sure, poor Sascha, gave us sequelize and now we're taking reputation off him!\n- @OliverRidgway if only there was a way to transfer reputation... I am ashamed of myself.","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":77,"estimatedTokens":605}}238{"id":"stack-39621568","source":"stackoverflow","questionId":39621568,"title":"My models for DB using Sequelize don't doing migration","tags":["node.js","postgresql","sequelize.js","sequelize-cli"],"text":"Title: My models for DB using Sequelize don't doing migration\nTags: node.js, postgresql, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI've two models:\n\n**user.js**\n\n\r\n\r\n\n```\n'use strict'\r\nmodule.exports = function(sequelize, DataTypes) {\r\n var User = sequelize.define('User', {\r\n gid: {\r\n type: DataTypes.INTEGER,\r\n allowNull: false,\r\n primaryKey: true,\r\n autoIncrement: true\r\n },\r\n email: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n },\r\n password: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n },\r\n newsletters: {\r\n type: 'NUMERIC',\r\n allowNull: false,\r\n defaultValue: '1'\r\n },\r\n status: {\r\n type: 'NUMERIC',\r\n allowNull: false,\r\n defaultValue: '1'\r\n },\r\n date_verified: {\r\n type: DataTypes.TIME,\r\n allowNull: true\r\n },\r\n date_created: {\r\n type: DataTypes.TIME,\r\n allowNull: false,\r\n defaultValue: sequelize.fn('now')\r\n },\r\n date_updated: {\r\n type: DataTypes.TIME,\r\n allowNull: false,\r\n defaultValue: sequelize.fn('now')\r\n }\r\n },{\r\n tableName: 'user'\r\n },{\r\n classMethods:{\r\n associate: function(models){\r\n User.belongsTo(models.User);\r\n }\r\n }\r\n });\r\n\r\n User.schema(\"security\");\r\n\r\n return User;\r\n};\n```\n\n\r\n\r\n\r\n\n**role.js**\n\n\r\n\r\n\n```\n'use strict'\r\nmodule.exports = function(sequelize, DataTypes) {\r\n var Role = sequelize.define('Role', {\r\n gid: {\r\n type: DataTypes.INTEGER,\r\n allowNull: false,\r\n primaryKey: true,\r\n autoIncrement: true\r\n },\r\n name: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n },\r\n status: {\r\n type: 'NUMERIC',\r\n allowNull: false,\r\n defaultValue: '1'\r\n },\r\n date_created: {\r\n type: DataTypes.TIME,\r\n allowNull: false,\r\n defaultValue: sequelize.fn('now')\r\n },\r\n date_updated: {\r\n type: DataTypes.TIME,\r\n allowNull: false,\r\n defaultValue: sequelize.fn('now')\r\n }\r\n },{\r\n tableName: 'role'\r\n },{\r\n classMethods:{\r\n associate: function(models){\r\n Role.hasMany(models.User);\r\n }\r\n }\r\n });\r\n\r\n Role.schema(\"security\");\r\n\r\n return Role;\r\n};\n```\n\n\r\n\r\n\r\n\nAnd index.js in the same **\"models\"** folder, that is generated automatically for Sequelize. \n\nI only changed the config.json with my connection variables, and connects succefully.\n\nBut, when I put in console\n\n```\nnode_modules/.bin/sequelize db:migrate\n```\n\nShows me this:\n\n```\nSequelize [Node: 4.4.4, CLI: 2.1.0, ORM: 3.12.2, pg: ^4.4.3]\n\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\nUsing gulpfile c:\\Users\\Ulises\\MVO-app\\server\\node_modules\\sequelize-cli\\lib\\gulpfile.js\nStarting 'db:migrate'...\nFinished 'db:migrate' after 180 ms\nNo migrations were executed, database schema was already up to date.\n```\n\nAnd in my DB don't create the models\n\n========================================\n\nTop Answer:\nPlease check in your database, table `SequelizeMeta`, and remove record which corresponding name with file migration. Sequelize will log migration into this table, and when run migration again, it cannot re-run migration file.\n\n========================================\n\nCode:\n```js\n'use strict'\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define('User', {\n    gid: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    email: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    password: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    newsletters: {\n      type: 'NUMERIC',\n      allowNull: false,\n      defaultValue: '1'\n    },\n    status: {\n      type: 'NUMERIC',\n      allowNull: false,\n      defaultValue: '1'\n    },\n    date_verified: {\n      type: DataTypes.TIME,\n      allowNull: true\n    },\n    date_created: {\n      type: DataTypes.TIME,\n      allowNull: false,\n      defaultValue: sequelize.fn('now')\n    },\n    date_updated: {\n      type: DataTypes.TIME,\n      allowNull: false,\n      defaultValue: sequelize.fn('now')\n    }\n  },{\n    tableName: 'user'\n  },{\n    classMethods:{\n      associate: function(models){\n        User.belongsTo(models.User);\n      }\n    }\n  });\n\n  User.schema(\"security\");\n\n  return User;\n};\n```\n\n```js\n'use strict'\nmodule.exports = function(sequelize, DataTypes) {\n  var Role = sequelize.define('Role', {\n    gid: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    status: {\n      type: 'NUMERIC',\n      allowNull: false,\n      defaultValue: '1'\n    },\n    date_created: {\n      type: DataTypes.TIME,\n      allowNull: false,\n      defaultValue: sequelize.fn('now')\n    },\n    date_updated: {\n      type: DataTypes.TIME,\n      allowNull: false,\n      defaultValue: sequelize.fn('now')\n    }\n  },{\n    tableName: 'role'\n  },{\n    classMethods:{\n      associate: function(models){\n        Role.hasMany(models.User);\n      }\n    }\n  });\n\n  Role.schema(\"security\");\n\n  return Role;\n};\n```\n\n```text\nnode_modules/.bin/sequelize db:migrate\n```\n\n```text\nSequelize [Node: 4.4.4, CLI: 2.1.0, ORM: 3.12.2, pg: ^4.4.3]\n\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\nUsing gulpfile c:\\Users\\Ulises\\MVO-app\\server\\node_modules\\sequelize-cli\\lib\\gulpfile.js\nStarting 'db:migrate'...\nFinished 'db:migrate' after 180 ms\nNo migrations were executed, database schema was already up to date.\n```\n\n```text\n$ npx sequelize-cli db:migrate\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nyarn migrate\n```\n\n```text\nsequelize db:migrate:undo:all &&  sequelize db:migrate && sequelize db:seed:all && node grantsSeeders.js\n```\n\n```text\nsequelize db:migrate:undo:all &&  sequelize db:migrate\n```\n\n```text\nsequelize db:migrate:undo:all\n```\n\n```text\n/** @type {import('sequelize-cli').Migration} */\n    module.exports = {\n      async up(queryInterface, Sequelize) {\n        await queryInterface.addColumn('UserModels', 'status', {\n          type: Sequelize.STRING,\n          allowNull: true,\n          unique: false\n        })\n      },\n\n      async down(queryInterface, Sequelize) {\n        await queryInterface.removeColumn('UserModels', 'status')\n      }\n    };\n```\n\n```text\nnpx sequelize db:generate --name TABLE_NAME_OPERATION\n```\n\n```text\nuserModel-add-email-column\n```\n\n```text\nnpx seqeulize db:migrate\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":331,"estimatedTokens":1535}}239{"id":"stack-32659318","source":"stackoverflow","questionId":32659318,"title":"Sequelize find soft deleted rows","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize find soft deleted rows\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get some rows from database that are soft deleted AND some that are not, but it's not working for me.\n\n```\nModel.findAll({\n 'where': {\n cond: 'xxx'\n },\n include: [Model2],\n paranoid: false\n}).then(function (rows) {\n // do something\n}).catch(function (err) {\n // do something\n});\n```\n\nHow can I do it?\n\n========================================\n\nCode:\n```text\nModel.findAll({\n    'where': {\n        cond: 'xxx'\n    },\n    include: [Model2],\n    paranoid: false\n}).then(function (rows) {\n    // do something\n}).catch(function (err) {\n    // do something\n});\n```\n\n```text\nModel.findAll({\n    'where': {\n        cond: 'xxx'\n    },\n    include: [{\n        model: Model2,\n        paranoid: false\n    }], \n    paranoid: false\n}).then(function (rows) {\n    // do something\n}).catch(function (err) {\n    // do something\n});\n```\n\n```text\nModel\n```\n\n```text\nModel2\n```\n\n```text\nModel2\n```\n\n```text\nparanoid: false\n```\n\n```text\ninclude\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":76,"estimatedTokens":264}}240{"id":"stack-51957860","source":"stackoverflow","questionId":51957860,"title":"Referencing a composite primary key in a Sequelize.js seed model","tags":["database","postgresql","sequelize.js"],"text":"Title: Referencing a composite primary key in a Sequelize.js seed model\nTags: database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to reference composite primary keys in Sequelize?\n\nI'm working on a web-app that helps organize kitchen waste. The restaurant organizes its weeks and months into 'periods' where the first week of September would be '9.1'. For every period, I need to create a new batch of ingredient objects that can keep track of what their prices and quantities were for that period. I figure it would be best to make the period primary keys their combined month and week, as that will be unique in the database.\nI may add year on later, but that doesn't change my problem.\n\nThe database I'm working with is Postgres.\n\nThis is my period table model in my sequelize seed file:\n\n```\n.then(() => queryInterface.createTable('periods', {\n month: {\n type: Sequelize.INTEGER,\n validate: {\n max: 12,\n min: 1\n },\n unique: \"monthWeekConstraint\",\n primaryKey: true\n },\n week: {\n type: Sequelize.INTEGER,\n validate: {\n max: 4,\n min: 1\n },\n unique: \"monthWeekConstraint\",\n primaryKey: true\n },\n createdAt: {\n type: Sequelize.DATE\n },\n updtedAt: {\n type: Sequelize.DATE\n }\n }))\n```\n\nI'd like to reference the periods stored in the above table in my periodItems table, which I have (incorrectly) looking like:\n\n```\n.then(() => queryInterface.createTable('periodItems', {\n periodMonth: {\n type: Sequelize.INTEGER,\n references: {model: 'periods', key: 'monthWeekConstraint'}\n },\n periodWeek: {\n type: Sequelize.INTEGER,\n references: {model: 'periods', key: 'monthWeekConstraint'}\n },\n day: {\n type: Sequelize.INTEGER,\n validate: {\n min: 1,\n max: 7\n }\n },\n...other irrelevant fields...\n}))\n```\n\nI'm definitely new to databases, so I apologize if I'm way off. I've gotten a few other tables doing what I'd like, but I've been stuck on this problem for a few days.\n\n========================================\n\nTop Answer:\n```\nmodel/product.js:\nconst Product = sequelize.define(\"product\", {\n sku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },\n title: { type: Sequelize.STRING, allowNull: false },\n availability: {\n type: Sequelize.STRING,\n allowNull: false,\n defaultValue: false,\n }\n});\n\nmodel/Attribute.js:\nconst Attribute = sequelize.define(\"attribute\", {\n key: { type: Sequelize.STRING, allowNull: false, primaryKey: true },\n productSku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },\n value: { type: Sequelize.STRING, allowNull: false },\n});\n\nAfter importing to app.js:\nproduct.hasMany(attribute, { foreignKey: \"productSku\", sourceKey: \"sku\" });\nattribute.belongsTo(product, { foreignKey: \"productSku\", targetKey: \"sku\" });\n\nExplanation:\nProduct.sku is exported as foreign key to Attibute.productSku. Attribute table has a composite foreign (key + productSku), and a ForeignKey(productSku) from product.sku;\n```\n\n========================================\n\nCode:\n```text\n.then(() => queryInterface.createTable('periods', {\n      month: {\n        type: Sequelize.INTEGER,\n        validate: {\n          max: 12,\n          min: 1\n        },\n        unique: \"monthWeekConstraint\",\n        primaryKey: true\n      },\n      week: {\n        type: Sequelize.INTEGER,\n        validate: {\n          max: 4,\n          min: 1\n        },\n        unique: \"monthWeekConstraint\",\n        primaryKey: true\n      },\n      createdAt: {\n        type: Sequelize.DATE\n      },\n      updtedAt: {\n        type: Sequelize.DATE\n      }\n    }))\n```\n\n```text\n.then(() => queryInterface.createTable('periodItems', {\n  periodMonth: {\n    type: Sequelize.INTEGER,\n    references: {model: 'periods', key: 'monthWeekConstraint'}\n  },\n  periodWeek: {\n    type: Sequelize.INTEGER,\n    references: {model: 'periods', key: 'monthWeekConstraint'}\n  },\n  day: {\n    type: Sequelize.INTEGER,\n    validate: {\n      min: 1,\n      max: 7\n    }\n  },\n...other irrelevant fields...\n}))\n```\n\n```text\nprimaryKey: true\n```\n\n```text\nmodel/product.js:\nconst Product = sequelize.define(\"product\", {\n  sku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },\n  title: { type: Sequelize.STRING, allowNull: false },\n  availability: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    defaultValue: false,\n  }\n});\n\nmodel/Attribute.js:\nconst Attribute = sequelize.define(\"attribute\", {\n  key: { type: Sequelize.STRING, allowNull: false, primaryKey: true },\n  productSku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },\n  value: { type: Sequelize.STRING, allowNull: false },\n});\n\n\nAfter importing to app.js:\nproduct.hasMany(attribute, { foreignKey: \"productSku\", sourceKey: \"sku\" });\nattribute.belongsTo(product, { foreignKey: \"productSku\", targetKey: \"sku\" });\n\n\nExplanation:\nProduct.sku is exported as foreign key to Attibute.productSku. Attribute table has a composite foreign (key + productSku), and a ForeignKey(productSku) from product.sku;\n```\n\n========================================\n\nComments:\n- is this still the case?\n- Hi @Prof, I believe so, given the Github issue linked above is still open and active. AFAICT the only way around it is to use single primary key column on all target tables, and restrict yourself to using single column foreign keys. The downside is that this does not allow for many complex constraint enforcement scenarios that a composite foreign key would handle.\n- ahh that is a shame. in the end I opted for a surrogate key with uniqueness over the foriegn keys.\n- I wonder why would one want a composite foreign key?..\n- @x-yuri I've used it frequently to ensure data integrity. This can reduce possible wrong associations that could result from other applications that uses the same database or from migrations. So if an application does something wrong, data won't be corrupted. But there might be other scenarios as well.\n- @robsch Could you possibly be more specific? Like, say, we have users and posts. And in posts we have a foreign key consisting of user_first_name and user_last_name, in place of user_id? Or user_id + user_first_name + user_last_name? Which doesn't sound good to me because they might point to different users, and first_name + last name is not necessarily unique.\n- @x-yuri I'd say in case of two tables it would't make sense. Have a look at this or that. I think it gets useful if you have a group of relate tables (models) where entries should not get mixed up. But it might be possible to avoid that - not sure, I'm not an db expert.\n- @robsch Have you possibly missed that the question is about composite *foreign* keys, not composite *primary* keys? Composite primary keys are okay in join tables. However, Ruby on Rails, for one, by default adds the `id` column to such tables (`has_many :through`) and makes it the primary key. And I'm not sure if it's easy to avoid that. But I don't see any significant downside to this. Some even say it may come in handy down the road...\n- ...As for composite foreign keys... I don't remember an ORM that supports them. And although theoretically they might be useful in some cases, I fail to come up with one. One of your links gives an idea for a case, but it's arguably easier done with a single column primary key. I'd say, if you need a composite foreign key, it's best to add an `id` column to the join table, make it the primary key, and reference it.\n- is this properly supporting composite foreign keys? Is this a new feature added by sequelize?","metadata":{"transformedAt":"2026-08-18T18:33:34.356Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":197,"estimatedTokens":1850}}241{"id":"stack-48957191","source":"stackoverflow","questionId":48957191,"title":"How do I ORM additional columns on a join table in sequelize?","tags":["javascript","sequelize.js"],"text":"Title: How do I ORM additional columns on a join table in sequelize?\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using node v9.5, sequelize v4.33 (postgres dialect).\n\nI have two first-class models: `Driver` (specific people) and `Car` (generic make+model combinations). Thus far, they've been connected by a many-to-many join table. Now I want to start tracking additional properties on that join table, but am having trouble declaring these relationships so they actually work.\n\n```\nconst Driver = sqlz.define('Driver', {\n id: { primaryKey: true, type: DataTypes.UUID },\n name: DataTypes.string\n})\n\nconst Car = sqlz.define('Car', {\n id: { primaryKey: true, type: DataTypes.UUID },\n make: DataTypes.string,\n model: DataTypes.string\n})\n\n// old associations; worked great when requirements were simpler\nDriver.belongsToMany(Car, {\n through: 'DriverCar',\n as: 'carList',\n foreignKey: 'driverId'\n})\n\nCar.belongsToMany(Driver, {\n through: 'DriverCar',\n as: 'driverList',\n foreignKey: 'carId'\n})\n```\n\nNow I want to begin tracking more information about the relationship between a car and its driver, like the color of that specific car.\n\nStep 1: I update the migration script, adding a new column to the join table like so:\n\n```\nqueryInterface.createTable( 'DriverCar', {\n driverId: {\n type: sqlz.UUID,\n allowNull: false,\n primaryKey: true,\n references: {\n model: 'Driver',\n key: 'id'\n }\n },\n carId: {\n type: sqlz.UUID,\n allowNull: false,\n primaryKey: true,\n references: {\n model: 'Car',\n key: 'id'\n }\n },\n createdAt: {\n type: sqlz.DATE,\n allowNull: false\n },\n updatedAt: {\n type: sqlz.DATE,\n allowNull: false\n },\n\n // new column for join table\n color: {\n type: Sequelize.STRING\n }\n})\n```\n\nStep 2: I define a new sqlz model for `DriverCar`:\n\n```\nconst DriverCar = sqlz.define('DriverCar', {\n color: DataTypes.string\n})\n```\n\n(I assume I only need to define the interesting properties, and that `driverId` and `carId` will still be inferred from the associations that will be defined.)\n\nStep 3: I need to update the associations that exist among `Driver`, `Car`, and `DriverCar`.\n\nThis is where I'm stuck. I have attempted updating the existing associations, like so:\n\n```\nDriver.belongsToMany(Car, {\n through: DriverCar, // NOTE: no longer a string, but a reference to new DriverCar model\n as: 'carList',\n foreignKey: 'driverId'\n})\n\nCar.belongsToMany(Driver, {\n through: DriverCar, // NOTE: no longer a string, but a reference to new DriverCar model\n as: 'driverList',\n foreignKey: 'carId'\n})\n```\n\nThis executes without error, but the new `color` property is not fetched from the join table when I try `driver.getCarList()`. (Sqlz is configured to log every SQL statement, and I have verified that no properties from the join table are being requested.)\n\nSo, instead, I tried spelling out this relationship more explicitly, by associating `Driver` to `DriverCar`, and then `Car` to `DriverCar`:\n\n```\n// Driver -> Car\nDriver.hasMany(DriverCar, {\n as: 'carList',\n foreignKey: 'driverId'\n})\n\n// Car -> Driver\nCar.hasMany(DriverCar, {\n foreignKey: 'carId'\n})\n```\n\nI also tell sqlz that `DriverCar` won't have a standard row id:\n\n```\nDriverCar.removeAttribute('id')\n```\n\nAt this point, requesting a Driver's carList (`driver.getCarList()`) seems to work, because I can see join table props being fetched in SQL. But saving fails:\n\n```\ndriverModel.setCarList([ carModel1 ])\n\nUPDATE DriverCar\nSET \"driverId\"='a-uuid',\"updatedAt\"='2018-02-23 22:01:02.126 +00:00'\nWHERE \"undefined\" in (NULL)\n```\n\nThe error:\n\n```\nSequelizeDatabaseError: column \"undefined\" does not exist\n```\n\nI assume this error is occurring because sqzl doesn't understand the proper way to identify rows in the join table, because I've failed to establish the necessary associations. And frankly, I'm not confident I've done this correctly; I'm new to ORMs, but I was expecting I'd need to specify 4 assocations:\n\n- `Driver` -> `DriverCar`\n\n- `DriverCar` -> `Car`\n\n- `Car` -> `DriverCar`\n\n- `DriverCar` -> `Driver`\n\nTo recap: I have 2 first-class entities, joined in a many-to-many relationship. I'm trying to add data to the relationship, have discovered that the ORM requires defining those associations differently, and am having trouble articulating the new associations.\n\n========================================\n\nCode:\n```text\nconst Driver = sqlz.define('Driver', {\n    id: { primaryKey: true, type: DataTypes.UUID },\n    name: DataTypes.string\n})\n\nconst Car = sqlz.define('Car', {\n    id: { primaryKey: true, type: DataTypes.UUID },\n    make: DataTypes.string,\n    model: DataTypes.string\n})\n\n// old associations; worked great when requirements were simpler\nDriver.belongsToMany(Car, {\n    through: 'DriverCar',\n    as: 'carList',\n    foreignKey: 'driverId'\n})\n\nCar.belongsToMany(Driver, {\n    through: 'DriverCar',\n    as: 'driverList',\n    foreignKey: 'carId'\n})\n```\n\n```text\nqueryInterface.createTable( 'DriverCar', {\n    driverId: {\n        type: sqlz.UUID,\n        allowNull: false,\n        primaryKey: true,\n        references: {\n            model: 'Driver',\n            key: 'id'\n        }\n    },\n    carId: {\n        type: sqlz.UUID,\n        allowNull: false,\n        primaryKey: true,\n        references: {\n            model: 'Car',\n            key: 'id'\n        }\n    },\n    createdAt: {\n        type: sqlz.DATE,\n        allowNull: false\n    },\n    updatedAt: {\n        type: sqlz.DATE,\n        allowNull: false\n    },\n\n    // new column for join table\n    color: {\n      type: Sequelize.STRING\n    }\n})\n```\n\n```text\nconst DriverCar = sqlz.define('DriverCar', {\n    color: DataTypes.string\n})\n```\n\n```text\nDriver.belongsToMany(Car, {\n    through: DriverCar, // NOTE: no longer a string, but a reference to new DriverCar model\n    as: 'carList',\n    foreignKey: 'driverId'\n})\n\nCar.belongsToMany(Driver, {\n    through: DriverCar, // NOTE: no longer a string, but a reference to new DriverCar model\n    as: 'driverList',\n    foreignKey: 'carId'\n})\n```\n\n```text\n// Driver -> Car\nDriver.hasMany(DriverCar, {\n    as: 'carList',\n    foreignKey: 'driverId'\n})\n\n// Car -> Driver\nCar.hasMany(DriverCar, {\n    foreignKey: 'carId'\n})\n```\n\n```text\nDriverCar.removeAttribute('id')\n```\n\n```text\ndriverModel.setCarList([ carModel1 ])\n\nUPDATE DriverCar\nSET \"driverId\"='a-uuid',\"updatedAt\"='2018-02-23 22:01:02.126 +00:00'\nWHERE \"undefined\" in (NULL)\n```\n\n```text\nSequelizeDatabaseError: column \"undefined\" does not exist\n```\n\n```text\nDriver\n```\n\n```text\nCar\n```\n\n```text\nDriverCar\n```\n\n```text\ndriverId\n```\n\n```text\ncarId\n```\n\n```text\nDriver\n```\n\n```text\nCar\n```\n\n```text\nDriverCar\n```\n\n```text\ncolor\n```\n\n```text\ndriver.getCarList()\n```\n\n```text\nDriver\n```\n\n```text\nDriverCar\n```\n\n```text\nCar\n```\n\n```text\nDriverCar\n```\n\n```text\nDriverCar\n```\n\n```text\ndriver.getCarList()\n```\n\n```text\nDriver\n```\n\n```text\nDriverCar\n```\n\n```text\nDriverCar\n```\n\n```text\nCar\n```\n\n```text\nCar\n```\n\n```text\nDriverCar\n```\n\n```text\nDriverCar\n```\n\n```text\nDriver\n```\n\n```text\nconst Sequelize = require(\"sequelize\");\nconst sequelize = new Sequelize({ dialect: 'sqlite', storage: 'db.sqlite' });\n\nconst Driver = sequelize.define(\"Driver\", {\n    name: Sequelize.STRING\n});\nconst Car = sequelize.define(\"Car\", {\n    make: Sequelize.STRING,\n    model: Sequelize.STRING\n});\nconst DriverCar = sequelize.define(\"DriverCar\", {\n    color: Sequelize.STRING\n});\nDriver.belongsToMany(Car, { through: DriverCar, foreignKey: \"driverId\" });\nCar.belongsToMany(Driver, { through: DriverCar, foreignKey: \"carId\" });\n\nvar car, driver;\n\nsequelize.sync({ force: true })\n    .then(() => {\n        // Create a driver\n        return Driver.create({ name: \"name test\" });\n    })\n    .then(created => {\n        // Store the driver created above in the 'driver' variable\n        driver = created;\n\n        // Create a car\n        return Car.create({ make: \"make test\", model: \"model test\" });\n    })\n    .then(created => {\n        // Store the car created above in the 'car' variable\n        car = created;\n\n        // Now we want to define that car is related to driver.\n        // Option 1:\n        return car.addDriver(driver, { through: { color: \"black\" }});\n\n        // Option 2:\n        // return driver.setCars([car], { through: { color: \"black\" }});\n\n        // Option 3:\n        // return DriverCar.create({\n        //     driverId: driver.id,\n        //     carId: car.id,\n        //     color: \"black\"\n        // });\n    })\n    .then(() => {\n        // Now we get the things back from the DB.\n\n        // This works:\n        return Driver.findAll({ include: [Car] });\n\n        // This also works:\n        // return car.getDrivers();\n\n        // This also works:\n        // return driver.getCars();\n    })\n    .then(result => {\n        // Log the query result in a readable way\n        console.log(JSON.stringify(result.map(x => x.toJSON()), null, 4));\n    });\n```\n\n```text\n[\n    {\n        \"id\": 1,\n        \"name\": \"name test\",\n        \"createdAt\": \"2018-03-11T03:04:28.657Z\",\n        \"updatedAt\": \"2018-03-11T03:04:28.657Z\",\n        \"Cars\": [\n            {\n                \"id\": 1,\n                \"make\": \"make test\",\n                \"model\": \"model test\",\n                \"createdAt\": \"2018-03-11T03:04:28.802Z\",\n                \"updatedAt\": \"2018-03-11T03:04:28.802Z\",\n                \"DriverCar\": {\n                    \"color\": \"black\",\n                    \"createdAt\": \"2018-03-11T03:04:28.961Z\",\n                    \"updatedAt\": \"2018-03-11T03:04:28.961Z\",\n                    \"driverId\": 1,\n                    \"carId\": 1\n                }\n            }\n        ]\n    }\n]\n```\n\n```text\ncarList\n```\n\n```text\ndriverList\n```\n\n```text\n.setCarList()\n```\n\n```text\n.setDriverList()\n```\n\n```text\n.addCarList()\n```\n\n```text\n.addDriverList()\n```\n\n```text\n.removeCarList()\n```\n\n```text\n.removeDriverList()\n```\n\n```text\n.setCars()\n```\n\n```text\n.setDrivers()\n```\n\n```text\n.addCar()\n```\n\n```text\n.removeCar()\n```\n\n```text\nnpm install sequelize sqlite3\n```\n\n```text\ncolor\n```\n\n```text\nCar\n```\n\n```text\nDriver\n```\n\n========================================\n\nComments:\n- This is one of the things where sequelize doesn't shine much. Still you should be able to find Driver and include Cars and it should bring all the fields. Do it in the query (using include) instead of using the magic method\n- @yBrodsky: Thanks for the tip. I believe I know what you mean by \"instead of using the magic method,\" but I'll have to do some more research to cash out your suggestion.\n- I should add, this issue on sequelize suggests the `include` approach won't work: github.com/sequelize/sequelize/issues/9094\n- Still no luck here. If anyone finds this, I'd still appreciate help.\n- pastebin.com/qT9D4KXE This doesn't work?\n- This seems pretty solid. I am going to need time to study it. Thank you.\n- @Tom - no problem, take your time. If you need further clarification/help, feel free to comment (:\n- I take your point about the aliases making for odd auto-generated method names. I'm new to sqlz, and it has been hard to find a complete list of the mixins that are automatically added to classes for each kind of association, which has frustrated the task of choosing names. All I know for sure is that I do not under any circumstances want it to be \"intelligently\" pluralizing words. If you have a good reference for those mixins (the source scatters them about), I'd like to take another crack at the plurals.\n- @Tom - Sorry to take so long to reply. For the plural things you said, see my questions & answers here and here. But I suggest that you attack your problem in parts. First, forget about the aliases, see if you can make your code work without any aliases. Then, after you're done with that, put your aliases again and see what happens. If you need further help, please let me know. If you make it work, let me know as well and if I was helpful, click the green checkmark :)\n- Sorry for the delay. I got stuff working soon after your response, but needed time to compare my fix to your answer to see if anything was omitted; your answer is complete! Thanks very much!\n- @PedroA I have a related question regarding the creation of such many-to-many records with extra fields on the junction table. I wonder if there is a way to create all 3 at once trough some specific data structure and includes mixture? My question is here: stackoverflow.com/questions/52784472/&hellip; Thanks!\n- @bluehipy Hello, I will take a look tomorrow :)\n- do not use `sequelize.sync({ force: true })` on a production db with data in it, use a migration file instead\n- Dude, there was a production with a polymorphic relationship. And thanks to your help, I completed the missing piece. Cheers 🍷\n- @HyopeR Nice!! Cheers :)","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":50,"totalLines":540,"estimatedTokens":3156}}242{"id":"stack-31361608","source":"stackoverflow","questionId":31361608,"title":"Programmatic default value for Sequelize model","tags":["sequelize.js"],"text":"Title: Programmatic default value for Sequelize model\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I create a default value that is generated programmatically upon creation of a new instance of a Sequelize model? I've read how to do this somewhere, but can't find it anywhere. I thought this had something to do with `classMethods`, but I can't figure out what that method should be called.\n\nFor example:\n\n```\nsequelize.define('Account', {\n name: DataTypes.STRING\n}, {\n classMethods: {\n something: function (instance) {\n instance.name = 'account12345';\n }\n }\n});\n\nmodels.account.create(function (account) {\n console.log(account.name); // Echos \"account12345\" or whatever I\n});\n```\n\nIf you could point me in the right direction, it would be greatly appreciated.\n\n========================================\n\nCode:\n```text\nsequelize.define('Account', {\n  name: DataTypes.STRING\n}, {\n  classMethods: {\n    something: function (instance) {\n      instance.name = 'account12345';\n    }\n  }\n});\n\nmodels.account.create(function (account) {\n  console.log(account.name); // Echos \"account12345\" or whatever I\n});\n```\n\n```text\nclassMethods\n```\n\n```text\nsequelize.define('model', {\n  uuid: {\n    type: DataTypes.UUID,\n    defaultValue: function() {\n      return generateMyId()\n    },\n    primaryKey: true\n  }\n})\n```\n\n========================================\n\nComments:\n- @MuhammadUmer you have to make sure it's unique by yourself.\n- @cattail How about if I'm adding a column, therefore the instance is already available. Can I get set the value of a different column as the `defaultValue`?","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":67,"estimatedTokens":398}}243{"id":"stack-52096692","source":"stackoverflow","questionId":52096692,"title":"Change sequelize timezone","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: Change sequelize timezone\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to make restful app in nodejs\n\nServer: centos 7 64x\nDatabase: postgresql\nAdditional: express, sequelize\nTable: datetime with timezone\n\nWhen I selecting rows with sequelize from database, created_at column gives me wrong time. 5 hour added to datetime.\n\nI change timezone configuration of centos to +5 (Tashkent/Asia)\nAlso change postgresql timezone configuration to +5\nDatetime is correct in database when shows.\n\nBut when I select it converts to like this\n\n\"createdAt\": \"2018-08-12T17:57:20.508Z\"\n\nIn database column shows this\n\n2018-08-12 22:57:20.508+05\n\nconfig.json\n\n```\n\"development\": {\n \"username\": \"postgres\",\n \"password\": \"postgres\",\n \"database\": \"zablet\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"postgres\",\n \"timezone\": \"Tashkent/Ashgabat\",\n \"define\": {\n \"charset\": \"utf8\",\n \"dialectOptions\": {\n \"collate\": \"utf8_general_ci\"\n },\n \"freezeTableName\": true\n }\n}\n```\n\nindex.js\n\n```\n'use strict';\nvar fs = require('fs');\nvar path = require('path');\n\nvar Sequelize = require('sequelize');\nvar basename = path.basename(__filename);\nvar env = process.env.NODE_ENV || 'development';\nvar config = require('../config/config.json')[env];\nvar db = {};\nif (config.use_env_variable) {\n var sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\nfs\n .readdirSync(__dirname)\n .filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n .forEach(file => {\n var model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\nmodule.exports = db;\n```\n\nupdated config.json\n\n```\n{\n \"development\": {\n \"username\": \"postgres\",\n \"password\": \"postgres\",\n \"database\": \"postgres\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"postgres\",\n \"define\": {\n \"charset\": \"utf8\",\n \"dialectOptions\": {\n \"collate\": \"utf8_general_ci\"\n },\n \"freezeTableName\": true\n },\n \"dialectOptions\": {\n \"useUTC\": false\n },\n \"timezone\": \"+05:00\"\n}\n}\n```\n\nHow can I select rows from database in correct timezone format?\n\n========================================\n\nTop Answer:\nUse in Config JSON\n\n```\n\"production\": {\n \"username\": \"xyz\",\n \"password\": \"\",\n \"database\": \"dbname\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"mysql\",\n \"port\": 123,\n \"dialectOptions\": {\n \"useUTC\": false \n },\n \"timezone\": \"+05:30\"\n}\n```\n\n========================================\n\nCode:\n```text\n\"development\": {\n    \"username\": \"postgres\",\n    \"password\": \"postgres\",\n    \"database\": \"zablet\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"postgres\",\n    \"timezone\": \"Tashkent/Ashgabat\",\n    \"define\": {\n        \"charset\": \"utf8\",\n        \"dialectOptions\": {\n            \"collate\": \"utf8_general_ci\"\n        },\n        \"freezeTableName\": true\n    }\n}\n```\n\n```text\n'use strict';\nvar fs = require('fs');\nvar path = require('path');\n\nvar Sequelize = require('sequelize');\nvar basename = path.basename(__filename);\nvar env = process.env.NODE_ENV || 'development';\nvar config = require('../config/config.json')[env];\nvar db = {};\nif (config.use_env_variable) {\n    var sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n    var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\nfs\n    .readdirSync(__dirname)\n    .filter(file => {\n        return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n    })\n    .forEach(file => {\n        var model = sequelize['import'](path.join(__dirname, file));\n        db[model.name] = model;\n    });\nObject.keys(db).forEach(modelName => {\n    if (db[modelName].associate) {\n        db[modelName].associate(db);\n    }\n});\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\nmodule.exports = db;\n```\n\n```text\n{\n    \"development\": {\n    \"username\": \"postgres\",\n    \"password\": \"postgres\",\n    \"database\": \"postgres\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"postgres\",\n    \"define\": {\n        \"charset\": \"utf8\",\n        \"dialectOptions\": {\n            \"collate\": \"utf8_general_ci\"\n        },\n        \"freezeTableName\": true\n    },\n    \"dialectOptions\": {\n        \"useUTC\": false\n    },\n    \"timezone\": \"+05:00\"\n}\n}\n```\n\n```text\ndevelopment: {\n    username: 'postgres',\n    password: 'postgres',\n    database: 'YOUR_DATABASE_NAME',\n    host: '127.0.0.1',\n    port: 5432,\n    dialect: 'postgres',\n    dialectOptions: {\n      useUTC: false, // for reading from database\n    },\n    timezone: '+05:30', // for writing to database\n  },\n```\n\n```text\ndialectOptions:{useUTC:false},timezone:\"+05:30\"\n```\n\n```text\nconst sequelize = new Sequelize(\"DB\",'USER','PWD',{host:'127.0.0.1',dialect:\"mysql\",operatorsAliases:0,timezone:\"+05:30\"})\n```\n\n```text\n\"production\": {\n    \"username\": \"xyz\",\n    \"password\": \"\",\n    \"database\": \"dbname\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\",\n    \"port\": 123,\n    \"dialectOptions\": {\n      \"useUTC\": false \n    },\n    \"timezone\": \"+05:30\"\n}\n```\n\n========================================\n\nComments:\n- If you are building REST API, you better store dates in UTC in the database and then do a conversion in the client. Why? Imagine that your API has users from different timezones... that's it, your API just got inadequate.\n- What you are seeing I am using this one. and it works fine for me\n- you wan't see saved data in required timzezone. to do that you have to set timezone at database options. If you will query after above configuration it always return results corrospondin to your timezone query.\n- Nope. Maybe I left something another configuration?\n- can you define dialectOption like which i defined\n- I put it below define in updated question. Maybe problem in postgresql?\n- @RahulSharma, If I save with time zone GMT-8 for example, shouldn't I see a different time in my phpmyadmin db ?\n- Your answer could be improved by adding more information on what the code does and how it helps the OP.","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":256,"estimatedTokens":1534}}244{"id":"stack-20156045","source":"stackoverflow","questionId":20156045,"title":"Get values from associated table with Sequelize.js","tags":["sequelize.js"],"text":"Title: Get values from associated table with Sequelize.js\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\nteam table match table\n=========== ================================\ntid= name mid= date =home_team=away_team\n============= ================================\n01 = denver 01 =10.11.13 = 01 = 04\n02 = minesota 02 =11.11.13 = 02 = 03\n03 = orlando 03 =11.11.13 = 04 = 02\n04 = portland 04 =12.11.13 = 03 = 01\n```\n\nI have a classical SQL JOIN problem - filled the match data and can't get the names of home and away teams that located in another table. \n\n```\nvar Team = sequelize.define('Team', { ... });\nvar Match = sequelize.define('Match',{ .. });\n\nTeam.hasOne(Match, {foreignKey: 'home_team', as: 'Home'})\nTeam.hasOne(Match, {foreignKey: 'away_team', as: 'Away'});\n```\n\nAs i understood from Docs after creating `as: 'Home` and `as: 'Away` i receive some \ngetters and setters like `Match.getHome` but i'm confused. how can i used it \n\n```\nMatch.find({where: {id: 1}}).success(function(match) {\n console.log(match);\n});\n```\n\n========================================\n\nCode:\n```text\nteam table               match table\n===========     ================================\ntid= name       mid=   date =home_team=away_team\n=============   ================================\n01 = denver     01 =10.11.13 =   01    =   04\n02 = minesota   02 =11.11.13 =   02    =   03\n03 = orlando    03 =11.11.13 =   04    =   02\n04 = portland   04 =12.11.13 =   03    =   01\n```\n\n```text\nvar Team = sequelize.define('Team', { ... });\nvar Match = sequelize.define('Match',{ .. });\n\nTeam.hasOne(Match, {foreignKey: 'home_team', as: 'Home'})\nTeam.hasOne(Match, {foreignKey: 'away_team', as: 'Away'});\n```\n\n```text\nMatch.find({where: {id: 1}}).success(function(match) {\n    console.log(match);\n});\n```\n\n```text\nas: 'Home\n```\n\n```text\nas: 'Away\n```\n\n```text\nMatch.getHome\n```\n\n```text\nMatch.belongsTo(Team, {foreignKey: 'home_team', as: 'Home'});\nMatch.belongsTo(Team, {foreignKey: 'away_team', as: 'Away'});\n```\n\n```text\nMatch.find({where: {mid: 1}}).success(function(match) {\n    match.getHome().success(function(home_team) {\n\n    });\n});\n```\n\n```text\nMatch.find({\n    where: { mid: 1 }, \n    include: [\n        { model: Team, as: 'Home'}\n    ]\n}).success(function(match) {\n    // Here you can access the home team data in match.home\n});\n```\n\n```text\nMatch.find({\n    where: { mid: 1 }, \n    include: [\n        { model: Team, as: 'Home'}\n        { model: Team, as: 'Away'}\n    ]\n}).success(function(match) {\n    // Here you can access the home team data in match.home and away team in match.away\n});\n```\n\n========================================\n\nComments:\n- Thanks a lot. I'm very confused with all of these `.hasOne()` and `.belongsTo()`\n- You are not the only one, we often get questions about those. There is a TODO in the docs to make the types of assocations clearer, you can add your voice there if you want to github.com/sequelize/sequelize-doc/issues/80 (I am a sequelize maintainer, that's why I know the associations so well :) )\n- I'm not really sure what you mean by that last comment? Could you perhaps update your question with the result you want to achieve?\n- perfect answer, I almost give up and this show related table, thank you","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":118,"estimatedTokens":807}}245{"id":"stack-47396796","source":"stackoverflow","questionId":47396796,"title":"How to use CASE WHEN expression in Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: How to use CASE WHEN expression in Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing Sequelize ORM for Node.js, how do you use CASE/WHEN expression in a select statement?\n\nI do not see any reference or examples to use the SQL expression CASE according to Sequelize Documentation . Is this possible?\n\nHere's my example:\n\n**SQL**\n\n```\nSELECT userId, Status, \n MAX(CASE Type WHEN 'Employee' THEN Rate ELSE 0 END) AS \"Employee\",\n MAX(CASE Type WHEN 'School' THEN Rate ELSE 0 END) AS \"School\",\n MAX(CASE Type WHEN 'Public' THEN Rate ELSE 0 END) AS \"Public\",\n MAX(CASE Type WHEN 'Other' THEN Rate ELSE 0 END) AS \"Other\"\nFROM Database.dbo.invoice\nWHERE Status IN ('Included', 'Excluded')\nGROUP BY userId, Status\n```\n\n**Sequelize** \n\n```\nvar query = {\n attributes: ['userId'], // need to include Rate (as Employee, School, Public, Other for each CASE/WHEN)\n /*\n MAX(CASE Type WHEN 'Employee' THEN Rate ELSE 0 END) AS \"Employee\",\n MAX(CASE Type WHEN 'School' THEN Rate ELSE 0 END) AS \"School\",\n MAX(CASE Type WHEN 'Public' THEN Rate ELSE 0 END) AS \"Public\",\n MAX(CASE Type WHEN 'Other' THEN Rate ELSE 0 END) AS \"Other\"\n*/\n where: {\n user: userId,\n Type: ['Employee', 'School', 'Public', 'Other'],\n },\n group: ['userId'],\n raw: true\n};\nmodels.invoice.findAll(query).then(result => {\n console.log(result);\n});\n```\n\n**Database Structure**\n\n```\n+--------+------+----------+\n| userId | Rate | Type |\n+--------+------+----------+\n| 1 | 2.00 | Employee |\n+--------+------+----------+\n| 1 | 3.50 | School |\n+--------+------+----------+\n| 1 | 4.00 | Public |\n+--------+------+----------+\n| 1 | 2.50 | Other |\n+--------+------+----------+\n| 2 | 3.75 | Employee |\n+--------+------+----------+\n| 2 | 4.25 | School |\n+--------+------+----------+\n| 2 | 2.00 | Public |\n+--------+------+----------+\n| 2 | 3.00 | Other |\n+--------+------+----------+\n```\n\n**Desired Result:**\n\n```\n+--------+----------+--------+--------+-------+\n| userId | Employee | School | Public | Other |\n+--------+----------+--------+--------+-------+\n| 1 | 2.00 | 3.50 | 4.00 | 2.50 |\n+--------+----------+--------+--------+-------+\n| 2 | 3.75 | 4.25 | 2.00 | 3.00 |\n+--------+----------+--------+--------+-------+\n```\n\n========================================\n\nCode:\n```text\nSELECT userId, Status, \n  MAX(CASE Type WHEN 'Employee' THEN Rate ELSE 0 END) AS \"Employee\",\n  MAX(CASE Type WHEN 'School' THEN Rate ELSE 0 END) AS \"School\",\n  MAX(CASE Type WHEN 'Public' THEN Rate ELSE 0 END) AS \"Public\",\n  MAX(CASE Type WHEN 'Other' THEN Rate ELSE 0 END) AS \"Other\"\nFROM Database.dbo.invoice\nWHERE Status IN ('Included', 'Excluded')\nGROUP BY userId,  Status\n```\n\n```text\nvar query = {\n  attributes: ['userId'], // need to include Rate (as Employee, School, Public, Other for each CASE/WHEN)\n  /*\n    MAX(CASE Type WHEN 'Employee' THEN Rate ELSE 0 END) AS \"Employee\",\n    MAX(CASE Type WHEN 'School' THEN Rate ELSE 0 END) AS \"School\",\n    MAX(CASE Type WHEN 'Public' THEN Rate ELSE 0 END) AS \"Public\",\n    MAX(CASE Type WHEN 'Other' THEN Rate ELSE 0 END) AS \"Other\"\n*/\n  where: {\n    user: userId,\n    Type: ['Employee', 'School', 'Public', 'Other'],\n  },\n  group: ['userId'],\n  raw: true\n};\nmodels.invoice.findAll(query).then(result => {\n  console.log(result);\n});\n```\n\n```text\n+--------+------+----------+\n| userId | Rate | Type     |\n+--------+------+----------+\n| 1      | 2.00 | Employee |\n+--------+------+----------+\n| 1      | 3.50 | School   |\n+--------+------+----------+\n| 1      | 4.00 | Public   |\n+--------+------+----------+\n| 1      | 2.50 | Other    |\n+--------+------+----------+\n| 2      | 3.75 | Employee |\n+--------+------+----------+\n| 2      | 4.25 | School   |\n+--------+------+----------+\n| 2      | 2.00 | Public   |\n+--------+------+----------+\n| 2      | 3.00 | Other    |\n+--------+------+----------+\n```\n\n```text\n+--------+----------+--------+--------+-------+\n| userId | Employee | School | Public | Other |\n+--------+----------+--------+--------+-------+\n| 1      | 2.00     | 3.50   | 4.00   | 2.50  |\n+--------+----------+--------+--------+-------+\n| 2      | 3.75     | 4.25   | 2.00   | 3.00  |\n+--------+----------+--------+--------+-------+\n```\n\n```text\nvar query = {\n  attributes: [\n    'userId',\n    [Sequelize.literal(`MAX(CASE Type WHEN 'Employee' THEN Rate ELSE 0 END)`), 'Employee'],\n    [Sequelize.literal(`MAX(CASE Type WHEN 'School' THEN Rate ELSE 0 END)`), 'School'],\n    [Sequelize.literal(`MAX(CASE Type WHEN 'Public' THEN Rate ELSE 0 END)`), 'Public'],\n    [Sequelize.literal(`MAX(CASE Type WHEN 'Other' THEN Rate ELSE 0 END)`), 'Other'],\n  ],\n  where: {\n    user: userId,\n    Type: ['Employee', 'School', 'Public', 'Other'],\n  },\n  group: ['userId'],\n  raw: true\n};\nmodels.invoice.findAll(query).then(result => {\n  console.log(result);\n});\n```\n\n```text\nattributes\n```\n\n========================================\n\nComments:\n- Can you please let me know what Type: ['Employee', 'School', 'Public', 'Other'] means ?","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":179,"estimatedTokens":1235}}246{"id":"stack-61153275","source":"stackoverflow","questionId":61153275,"title":"SequelizeConnectionError: The server does not support SSL connections","tags":["node.js","postgresql","express","ssl","sequelize.js"],"text":"Title: SequelizeConnectionError: The server does not support SSL connections\nTags: node.js, postgresql, express, ssl, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect my project with PostgreSQL but show this error. Please help me\nI have installed Postgres.app and for GUI PgAdmin.\n\n```\nUnhandled rejection SequelizeConnectionError: The server does not support SSL connections\n at /Users/inamur/Documents/Project/project-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:186:20\n at Connection.connectingErrorHandler (/Users/inamur/Documents/Project/project-api/node_modules/pg/lib/client.js:203:14)\n at Connection.emit (events.js:223:5)\n at Connection.EventEmitter.emit (domain.js:475:20)\n at Socket. (/Users/inamur/Documents/Project/project-api/node_modules/pg/lib/connection.js:90:21)\n at Object.onceWrapper (events.js:313:26)\n at Socket.emit (events.js:223:5)\n at Socket.EventEmitter.emit (domain.js:475:20)\n at addChunk (_stream_readable.js:309:12)\n at readableAddChunk (_stream_readable.js:290:11)\n at Socket.Readable.push (_stream_readable.js:224:10)\n at TCP.onStreamRead (internal/stream_base_commons.js:181:23)\n```\n\nThis is my .env file\n\n```\nJWT_SECRET='UserNews'\nDB_LINK='postgres://root:root@localhost:5432/SCROLL001?ssl=true'\n```\n\nThis is connection file.\n\n```\nconst sequelize = new Sequelize(process.env.DB_LINK, {\n dialect: 'postgres',\n protocol: 'postgres',\n dialectOptions: {\n ssl: {\n require: 'true'\n }\n }\n});\n```\n\n========================================\n\nTop Answer:\nIt is recommended to use SSL for connections in production applications. You can continue to use an SSL connection using while circumventing it locally using:\n\n```\nconst sequelize = new Sequelize(process.env.DB_LINK, {\n dialect: 'postgres',\n protocol: 'postgres',\n ssl: process.env.DB_ENABLE_SSL,\n dialectOptions: {\n ssl: process.env.DB_ENABLE_SSL && {\n require: true\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nUnhandled rejection SequelizeConnectionError: The server does not support SSL connections\n        at /Users/inamur/Documents/Project/project-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:186:20\n        at Connection.connectingErrorHandler (/Users/inamur/Documents/Project/project-api/node_modules/pg/lib/client.js:203:14)\n        at Connection.emit (events.js:223:5)\n        at Connection.EventEmitter.emit (domain.js:475:20)\n        at Socket.<anonymous> (/Users/inamur/Documents/Project/project-api/node_modules/pg/lib/connection.js:90:21)\n        at Object.onceWrapper (events.js:313:26)\n        at Socket.emit (events.js:223:5)\n        at Socket.EventEmitter.emit (domain.js:475:20)\n        at addChunk (_stream_readable.js:309:12)\n        at readableAddChunk (_stream_readable.js:290:11)\n        at Socket.Readable.push (_stream_readable.js:224:10)\n        at TCP.onStreamRead (internal/stream_base_commons.js:181:23)\n```\n\n```text\nJWT_SECRET='UserNews'\nDB_LINK='postgres://root:root@localhost:5432/SCROLL001?ssl=true'\n```\n\n```text\nconst sequelize = new Sequelize(process.env.DB_LINK, {\n  dialect: 'postgres',\n  protocol: 'postgres',\n  dialectOptions: {\n    ssl: {\n      require: 'true'\n    }\n  }\n});\n```\n\n```text\nconst sequelize = new Sequelize(process.env.DB_LINK, {\n  dialect: 'postgres',\n  protocol: 'postgres',\n  dialectOptions: {}, //removed ssl\n});\n```\n\n```text\nDB_LINK='postgres://root:root@localhost:5432/SCROLL001'\n```\n\n```text\nconst sequelize = new Sequelize(process.env.DB_LINK, {\n  dialect: 'postgres',\n  protocol: 'postgres',\n  dialectOptions: {\n    ssl: true,\n    native:true\n  }\n});\n```\n\n```js\nconst sequelize = new Sequelize(process.env.DB_LINK, {\n  dialect: 'postgres',\n  protocol: 'postgres',\n  ssl: process.env.DB_ENABLE_SSL,\n  dialectOptions: {\n    ssl: process.env.DB_ENABLE_SSL && {\n      require: true\n    }\n  }\n});\n```\n\n```text\nconst sequelize = new Sequelize(\n    process.env.DB_LINK,\n    {\n        dialect: 'postgres',\n        dialectoptions: {\n            ssl: true\n        }\n    }\n)\n```\n\n```text\ndialectoptions\n```\n\n```text\n?sslmode=require\n```\n\n```text\nDB_LINK\n```\n\n```text\npostgres://root:root@localhost:5432/SCROLL001?sslmode=require\n```\n\n```js\ndialectOptions: {\n  supportBigNumbers: true,\n  ssl: {\n    rejectUnauthorized: false, // Trust the self-signed certificate\n  }\n}\n```\n\n```js\nconst sequelize = new Sequelize(process.env.DB_LINK, {\n  dialect: 'postgres',\n  protocol: 'postgres',\n  dialectOptions: {\n    supportBigNumbers: true,\n    ssl: {\n      rejectUnauthorized: false, // Trust the self-signed certificate\n    }\n  }\n});\n```\n\n```text\nrejectUnauthorized\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- Does your DB require SSL connections>\n- @PrabhjotSinghKainth Yes\n- Thanks for your effort, but it does not work for me\n- Can someone please specify what's the difference btw ssl: false and giving it like this mentioned here { } - empty object :)\n- I would also like to know the answer here to @AshutoshTiwari 's question. Why is it necessary to pass an empty object to dialectOptions rather than specifying false?","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":201,"estimatedTokens":1270}}247{"id":"stack-50841912","source":"stackoverflow","questionId":50841912,"title":"Sequelize.js - \"is not associated to\"","tags":["javascript","node.js","database","sequelize.js"],"text":"Title: Sequelize.js - \"is not associated to\"\nTags: javascript, node.js, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have some issue with getting full data from db. \nThat are my models: \n\n**User**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('user', {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n field: 'ID'\n },\n password: {\n type: DataTypes.STRING(255),\n allowNull: false,\n field: 'password'\n },\n email: {\n type: DataTypes.STRING(255),\n allowNull: false,\n unique: true,\n field: 'email'\n },\n roleId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'role',\n key: 'ID'\n },\n field: 'role_id'\n }\n }, {\n timestamps: false,\n tableName: 'user'\n });\n};\n```\n\n**Role**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('role', {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n field: 'ID'\n },\n name: {\n type: DataTypes.STRING(255),\n allowNull: false,\n unique: true,\n field: 'name'\n },\n description: {\n type: DataTypes.STRING(255),\n allowNull: false,\n field: 'description'\n },\n permission: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n field: 'permission'\n }\n}, {\n timestamps: false,\n tableName: 'role',\n});};\n```\n\nI want to get object of one specific user including all role content. \nSomethink like \n\n```\n{\n id: 4,\n password: 'xxx',\n email: 'adsads@saas.com',\n role: {\n id: 2,\n name: 'admin'\n description: 'ipsum ssaffa',\n permission: 30\n }\n}\n```\n\nSo I'm using: \n\n```\nUser.findOne( { where: { id: req.userId }, include: [ Role ] } ).then( user =>{...});\n```\n\nbut I get in the result err.message: \"role is not associated to user\" \n\nAnd the simple question - what's wrong ? :) \n\n*to handle models I'm using sequelize-cli\n\n========================================\n\nTop Answer:\nYou have to declare associations between your Models. If using Sequelize CLI make sure the static method **associate** is being called. Example:\n\n/models.index.js\n\n```\nconst Category = require('./Category');\nconst Product = require('./Product');\nconst ProductTag = require('./ProductTag');\nconst Tag = require('./Tag');\n\nCategory.associate({Product});\nProduct.associate({Category,Tag});\nTag.associate({Product});\n\nmodule.exports={Category,Product,ProductTag,Tag};\n```\n\nand then the association in Category.js\n\n```\n'use strict';\nconst {Model,DataTypes} = require('sequelize');\nconst sequelize = require('../config/connection.js');\n\n class Category extends Model {\n /**\n * Helper method for defining associations.\n * This method is not a part of Sequelize lifecycle.\n * The `models/index` file will call this method.\n */\n static associate({Product}) {\n // define association here\n console.log('Category associated with: Product');\n this.hasMany(Product, {\n foreignKey: 'category_id',\n onDelete: 'CASCADE'\n });\n }\n }\n\n Category.init({\n category_id: {type: DataTypes.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},\n category_name: {type: DataTypes.STRING, allowNull: false}\n }, {\n sequelize,\n timestamps: false,\n freezeTableName: true,\n underscored: true,\n modelName: \"Category\",\n });\n\nmodule.exports = Category;\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    return sequelize.define('user', {\n        id: {\n            type: DataTypes.INTEGER(11),\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true,\n            field: 'ID'\n        },\n        password: {\n            type: DataTypes.STRING(255),\n            allowNull: false,\n            field: 'password'\n        },\n        email: {\n            type: DataTypes.STRING(255),\n            allowNull: false,\n            unique: true,\n            field: 'email'\n        },\n        roleId: {\n            type: DataTypes.INTEGER(11),\n            allowNull: false,\n            references: {\n                model: 'role',\n                key: 'ID'\n            },\n            field: 'role_id'\n        }\n    }, {\n        timestamps: false,\n        tableName: 'user'\n    });\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('role', {\n    id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true,\n        field: 'ID'\n    },\n    name: {\n        type: DataTypes.STRING(255),\n        allowNull: false,\n        unique: true,\n        field: 'name'\n    },\n    description: {\n        type: DataTypes.STRING(255),\n        allowNull: false,\n        field: 'description'\n    },\n    permission: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        field: 'permission'\n    }\n}, {\n    timestamps: false,\n    tableName: 'role',\n});};\n```\n\n```text\n{\n  id: 4,\n  password: 'xxx',\n  email: 'adsads@saas.com',\n  role: {\n     id: 2,\n     name: 'admin'\n     description: 'ipsum ssaffa',\n     permission: 30\n  }\n}\n```\n\n```text\nUser.findOne( { where: { id: req.userId }, include: [ Role ] } ).then( user =>{...});\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\nvar user =  sequelize.define('user', {\n    id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true,\n        field: 'ID'\n    },\n    password: {\n        type: DataTypes.STRING(255),\n        allowNull: false,\n        field: 'password'\n    },\n    email: {\n        type: DataTypes.STRING(255),\n        allowNull: false,\n        unique: true,\n        field: 'email'\n    },\n    roleId: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        references: {\n            model: 'role',\n            key: 'ID'\n        },\n        field: 'role_id'\n    }\n}, {\n    timestamps: false,\n    tableName: 'user'\n});\n    user.associate = function(models) {\n        user.hasOne(models.role, {foreignKey: 'id',sourceKey: 'roleId'});\n\n    }\n    return user;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var role = sequelize.define('role', {\n    id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true,\n        field: 'ID'\n    },\n    name: {\n        type: DataTypes.STRING(255),\n        allowNull: false,\n        unique: true,\n        field: 'name'\n    },\n    description: {\n        type: DataTypes.STRING(255),\n        allowNull: false,\n        field: 'description'\n    },\n    permission: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        field: 'permission'\n    }\n    }, {\n        timestamps: false,\n        tableName: 'role',\n    });\n    role.associate = function(models) {\n        user.belongsTo(models.role, {foreignKey: 'id'});\n\n    }\n    return role;\n};\n```\n\n```js\nconst Category  = require('./Category');\nconst Product = require('./Product');\nconst ProductTag = require('./ProductTag');\nconst Tag = require('./Tag');\n\nCategory.associate({Product});\nProduct.associate({Category,Tag});\nTag.associate({Product});\n\nmodule.exports={Category,Product,ProductTag,Tag};\n```\n\n```js\n'use strict';\nconst {Model,DataTypes} = require('sequelize');\nconst sequelize = require('../config/connection.js');\n\n    class Category extends Model {\n        /**\n         * Helper method for defining associations.\n         * This method is not a part of Sequelize lifecycle.\n         * The `models/index` file will call this method.\n         */\n        static associate({Product}) {\n            // define association here\n            console.log('Category associated with: Product');\n            this.hasMany(Product, {\n                foreignKey: 'category_id',\n                onDelete: 'CASCADE'\n            });\n        }\n    }\n\n    Category.init({\n        category_id: {type: DataTypes.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},\n        category_name: {type: DataTypes.STRING, allowNull: false}\n    }, {\n        sequelize,\n        timestamps: false,\n        freezeTableName: true,\n        underscored: true,\n        modelName: \"Category\",\n    });\n\nmodule.exports = Category;\n```\n\n========================================\n\nComments:\n- hmmmm, ok - so \"references\" key in user.roleId isn't enought ?\n- I don't think so, atleast associate is what i've been using to link models together for the latest version of sequelize.\n- Thanks! It works but you make little mistake :) Should be: In role: role.associate = ( models ) =>{ role.hasMany( models.user, { foreignKey: 'roleId', sourceKey: 'id' } ); }; In user: user.associate = ( models ) =>{ user.belongsTo( models.role, { foreignKey: `roleId`, targetKey: `id` } ); };\n- Hi @The4ECH. I tried following your comment ^ and feiii's answer, but I really can't make mine work. We have the very same structure of user and rols. Could you please your working setup?","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":392,"estimatedTokens":2203}}248{"id":"stack-30910248","source":"stackoverflow","questionId":30910248,"title":"cast uuid to varchar in postgres when I use sequelize","tags":["postgresql","uuid","sequelize.js"],"text":"Title: cast uuid to varchar in postgres when I use sequelize\nTags: postgresql, uuid, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table with a column named `_id` of which the type is `uuid`. I cast the type of `_id` from `uuid` to `varchar`, in order to select the records as follows:\n\n```\nSELECT \"_id\" FROM \"records\" WHERE \"_id\"::\"varchar\" LIKE '%1010%';\n```\n\nand it works well.\n\n```\n_id \n--------------------------------------\n 9a7a36d0-1010-11e5-a475-33082a4698d6\n(1 row)\n```\n\nI use sequelize as ORM for operation postgres. how to build the query condition in sequelize?\n\n========================================\n\nCode:\n```text\nSELECT \"_id\" FROM \"records\" WHERE \"_id\"::\"varchar\" LIKE '%1010%';\n```\n\n```text\n_id                  \n--------------------------------------\n 9a7a36d0-1010-11e5-a475-33082a4698d6\n(1 row)\n```\n\n```text\n_id\n```\n\n```text\nuuid\n```\n\n```text\n_id\n```\n\n```text\nuuid\n```\n\n```text\nvarchar\n```\n\n```text\n{where: ['_id::\"varchar\" like ?', '%1010%']},\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":59,"estimatedTokens":246}}249{"id":"stack-27273656","source":"stackoverflow","questionId":27273656,"title":"Can I specify the table when using sequelize.col?","tags":["sequelize.js"],"text":"Title: Can I specify the table when using sequelize.col?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy query looks something like\n\n```\n({\n attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'commitCount']],\n include: [\n {\n model: global.mysqlDb.Commit,\n attributes: ['id'],\n where: {\n RepositoryId: req.params.repositoryId\n }\n }, {\n model: global.mysqlDb.SourceFile\n }\n ],\n group: ['SourceFileId']\n});\n```\n\nBut the `id` in the `sequelize.col` is ambiguous because it could be from any of the tables. Any way for me to specify the table name as well?\n\n========================================\n\nTop Answer:\nSequelize uses the lower case model name as the alias for your table name in your generated SQL query. If you have a model `Commit` and a table `commits`, for example, the fully qualified column name should be `sequelize.col('commit.id')`.\n\n*Note that commit is singular*\n\n========================================\n\nCode:\n```text\n({\n  attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'commitCount']],\n  include: [\n    {\n      model: global.mysqlDb.Commit,\n      attributes: ['id'],\n      where: {\n        RepositoryId: req.params.repositoryId\n      }\n    }, {\n      model: global.mysqlDb.SourceFile\n    }\n  ],\n  group: ['SourceFileId']\n});\n```\n\n```text\nid\n```\n\n```text\nsequelize.col\n```\n\n```text\nsequelize.col('table.column')\n```\n\n```text\nCommit\n```\n\n```text\ncommits\n```\n\n```text\nsequelize.col('commit.id')\n```\n\n========================================\n\nComments:\n- Do I use plural or singular `table` name?\n- Depending on whether your table name is pluralized or not :). Since it's just a string, sequelize will not change the casing\n- I had to pass the model name that I used with `sequelize.define` (not the table name) for this to work.","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":85,"estimatedTokens":443}}250{"id":"stack-29551941","source":"stackoverflow","questionId":29551941,"title":"Unique constraint across foreign keys in Sequelize model","tags":["sequelize.js"],"text":"Title: Unique constraint across foreign keys in Sequelize model\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a simple Sequelize model that is associated with other models.\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n var Votes = sequelize.define('Votes', {\n isUpVote: DataTypes.BOOLEAN\n }, {\n classMethods: {\n associate: function (models) {\n Votes.belongsTo(models.Track);\n Votes.belongsTo(models.User);\n }\n }\n });\n\n return Votes;\n}\n```\n\nSequelize will generate a table with an `id`, `TrackId`, `UserId` and `isUpVote`.\n\nI want to set a `UNIQUE` constraint across `TrackId` and `UserId` (i.e. a composite index ensuring that there is only one vote record for a given track and user).\n\nHow can this be done?\n\n========================================\n\nTop Answer:\nWhat ended up working for me was adding it under indexes, e.g.:\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n var Votes = sequelize.define('Votes', {\n isUpVote: DataTypes.BOOLEAN,\n }, {\n indexes: [\n {\n unique: true,\n fields: ['TrackId', 'UserId'],\n },\n ],\n classMethods: {\n associate: function (models) {\n Votes.belongsTo(models.Track);\n Votes.belongsTo(models.User);\n },\n },\n });\n\n return Votes;\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function (sequelize, DataTypes) {\n  var Votes = sequelize.define('Votes', {\n    isUpVote: DataTypes.BOOLEAN\n  }, {\n    classMethods: {\n      associate: function (models) {\n        Votes.belongsTo(models.Track);\n        Votes.belongsTo(models.User);\n      }\n    }\n  });\n\n  return Votes;\n}\n```\n\n```text\nid\n```\n\n```text\nTrackId\n```\n\n```text\nUserId\n```\n\n```text\nisUpVote\n```\n\n```text\nUNIQUE\n```\n\n```text\nTrackId\n```\n\n```text\nUserId\n```\n\n```text\nmodule.exports = function (sequelize, DataTypes) {\n   var Votes = sequelize.define('Votes', {\n      isUpVote: {\n          type: DataTypes.BOOLEAN,\n          unique: 'myCompositeIndexName'\n      },\n      TrackId: {\n          type: DataType.INTEGER\n          unique: 'myCompositeIndexName',\n      },\n      UserId: {\n          type: DataType.INTEGER\n          unique: 'myCompositeIndexName',\n      }\n   }, {\n       classMethods: {\n           associate: function (models) {\n               Votes.belongsTo(models.Track);\n               Votes.belongsTo(models.User);\n           }\n       }\n    });\n\n    return Votes;\n}\n```\n\n```text\nmodule.exports = function (sequelize, DataTypes) {\n  var Votes = sequelize.define('Votes', {\n    isUpVote: DataTypes.BOOLEAN,\n  }, {\n    indexes: [\n      {\n        unique: true,\n        fields: ['TrackId', 'UserId'],\n      },\n    ],\n    classMethods: {\n      associate: function (models) {\n        Votes.belongsTo(models.Track);\n        Votes.belongsTo(models.User);\n      },\n    },\n  });\n\n  return Votes;\n}\n```\n\n========================================\n\nComments:\n- How would you define a composite unique index on a join table in an n:many situation?\n- When I try, it throws: `SequelizeDatabaseError: foreign key constraint \"event_related_info__fkey\" cannot be implemented`\n- what if I want TrackId to appear in 2 different composite keys? example (TrackId, UserId), (TrackId, isUpVote)","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":163,"estimatedTokens":783}}251{"id":"stack-40202540","source":"stackoverflow","questionId":40202540,"title":"Order by in nested eager loading in sequelize not working","tags":["node.js","sequelize.js","eager-loading"],"text":"Title: Order by in nested eager loading in sequelize not working\nTags: node.js, sequelize.js, eager-loading\nSource: Stack Overflow\n\nQuestion:\ni have four model Tehsil, Ilr, Patwar, and Villages.\nand their association is\n\nTehsil -> 1:m -> Ilr -> 1:m -> Patwar -> 1:m -> Villages\n\ni want to to apply order by on all four of my models.\n\nQuery:\n\n```\nvar tehsilQuery = {\n include: [{\n model: Ilr,\n as: 'GirdawariKanoongo',\n include: [{\n model: Patwar,\n as: 'GirdawariPatwar',\n include: [{\n model: Villages,\n as: 'GirdawariVillages',\n }]\n }]\n }],\n order: [\n ['tehsil_name', 'ASC'],\n [ {model: Ilr, as: 'GirdawariKanoongo'}, 'kanoongo_name', 'ASC'],\n [ {model: Patwar, as: 'GirdawariPatwar'}, 'patwar_area', 'ASC'],\n [ {model: Villages, as: 'GirdawariVillages'}, 'village_name', 'ASC'],\n ]\n};\nreturn Tehsils.findAll(tehsilQuery);\n\n[Error: 'girdawari_patwar' in order / group clause is not valid association]\n```\n\norder by is working if i remove `Patwar` and `Villages`(lat two model) from `order`.\n\n========================================\n\nTop Answer:\nAnother working example with nested ordering:\n\n```\norder: [ \n [ { model: chapterModel, as: 'Chapters' }, 'createdAt', 'ASC'], \n [ { model: chapterModel, as: 'Chapters' }, \n { model: partModel, as: 'Parts' }, 'createdAt', 'ASC'] \n],\n```\n\nwhere part and chapter have M:1 relation.\n\n========================================\n\nCode:\n```text\nvar tehsilQuery = {\n    include: [{\n        model: Ilr,\n        as: 'GirdawariKanoongo',\n        include: [{\n            model: Patwar,\n            as: 'GirdawariPatwar',\n            include: [{\n                model: Villages,\n                as: 'GirdawariVillages',\n            }]\n        }]\n    }],\n    order: [\n        ['tehsil_name', 'ASC'],\n        [ {model: Ilr, as: 'GirdawariKanoongo'}, 'kanoongo_name', 'ASC'],\n        [ {model: Patwar, as: 'GirdawariPatwar'}, 'patwar_area', 'ASC'],\n        [ {model: Villages, as: 'GirdawariVillages'}, 'village_name', 'ASC'],\n    ]\n};\nreturn Tehsils.findAll(tehsilQuery);\n\n[Error: 'girdawari_patwar' in order / group clause is not valid association]\n```\n\n```text\nPatwar\n```\n\n```text\nVillages\n```\n\n```text\norder\n```\n\n```text\norder: [\n        'tehsil_name',\n        'GirdawariKanoongo.kanoongo_name',\n        'GirdawariKanoongo.GirdawariPatwar.patwar_area',\n        'GirdawariKanoongo.GirdawariPatwar.GirdawariVillages.village_name' \n       ]\n```\n\n```text\norder\n```\n\n```text\nas\n```\n\n```text\ncolumn_name\n```\n\n```text\norder\n```\n\n```text\norder: [  \n  [ { model: chapterModel, as: 'Chapters' }, 'createdAt', 'ASC'], \n  [ { model: chapterModel, as: 'Chapters' }, \n    { model: partModel, as: 'Parts' }, 'createdAt', 'ASC'] \n],\n```\n\n```text\norder: [  \n    [ { model: survey, as: 'survey' }, 'subjectId', 'ASC'], \n    [ { model: survey, as: 'survey' }, \n      { model: question, as: 'question' }, 'id', 'ASC'] \n]\n```\n\n```text\ninclude\n```\n\n```text\nordering\n```\n\n```text\nfindAll\n```\n\n```text\nsurveySet.findAll\n```\n\n```text\norder: [\n    ['tehsil_name', 'ASC'],\n    [ {model: Ilr, as: 'GirdawariKanoongo'}, 'kanoongo_name', 'ASC'],\n    [ {model: Ilr, as: 'GirdawariKanoongo'}, {model: Patwar, as: 'GirdawariPatwar'}, 'patwar_area', 'ASC'],\n    [ {model: Ilr, as: 'GirdawariKanoongo'}, {model: Patwar, as: 'GirdawariPatwar'}, {model: Villages, as: 'GirdawariVillages'}, 'village_name', 'ASC'],\n]\n```\n\n========================================\n\nComments:\n- The underscore in the association name in the error suggests Sequelize is trying to auto-generate the association name, though I'm not sure why. Can you post the code where you set up your associations?\n- @TomJardine-McNamara here look i solved it, thanks for your time.\n- Thank you for this. I think the documentation is not at all clear about this. With the same example you posted, how would you order the models by two or more columns?\n- Hi @F_Bass, this is a bit old in my memory but this example sorts by 4 columns already, if you need more you can just append new orders in the `order` array and fit the order statement as you need.","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":171,"estimatedTokens":1003}}252{"id":"stack-29165644","source":"stackoverflow","questionId":29165644,"title":"Sequelize hasMany through another table","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize hasMany through another table\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nOkay so i have the following three `models`\n\n**Module:**\n\n```\nvar Module = sequelize.define('module', {\n id: DataTypes.INTEGER,\n name: DataTypes.STRING,\n description: DataTypes.STRING,\n category_id: DataTypes.STRING,\n module_type_id: DataTypes.STRING,\n gives_score: DataTypes.INTEGER,\n duration: DataTypes.STRING,\n price: DataTypes.STRING\n\n }, {\n freezeTableName: true}\n)\n```\n\n**Competence:**\n\n```\nCompetence = sequelize.define('competence', {\n id: DataTypes.INTEGER,\n name: DataTypes.STRING,\n organization_id: DataTypes.INTEGER,\n competence_type_id: DataTypes.INTEGER\n },{freezeTableName:true})\n```\n\n**Module_has_competence:**\n\n```\nModule_has_competence = sequelize.define('module_has_competence', {\n id: DataTypes.INTEGER,\n module_id: DataTypes.INTEGER,\n competence_id: DataTypes.INTEGER,\n score: DataTypes.STRING\n},{\n freezeTableName: true}\n})\n```\n\nAs you can see the relation between the tables are an `n:m`\n\nSo now i want to find all the `Competence` that a `Module` has:\n\nSo i created the following relationship:\n\n```\nModule.hasMany(Competence, {through: Module_has_competence, foreignKey: 'module_id'});\n```\n\nHowever when i try to run:\n\n```\nretrieveById: function (quote_id, onSuccess, onError) {\n Module.find({include: [{ all: true }],where: {id: quote_id}})\n .success(onSuccess).error(onError);\n }\n```\n\nit returns nothing. But if i delete the relationship it returns only the `Module`\n\nCan anyone tell me what i am doing wrong?\n\n**When i debug**\n\nWhen i debug it does not log any sql sadly it seems it is just ignoring the sql call ?\n\n========================================\n\nTop Answer:\nSteven's answer did not work for me but switching the foreign keys.\n\n```\nCompetence.belongsToMany(Module, {\n through: Module_has_competence,\n as: 'module',\n foreignKey: 'competence_id'\n});\nModule.belongsToMany(Competence, {\n through: Module_has_competence,\n as: 'competence',\n foreignKey: 'module_id'\n});\n```\n\n========================================\n\nCode:\n```text\nvar Module = sequelize.define('module', {\n        id: DataTypes.INTEGER,\n        name: DataTypes.STRING,\n        description: DataTypes.STRING,\n        category_id: DataTypes.STRING,\n        module_type_id: DataTypes.STRING,\n        gives_score: DataTypes.INTEGER,\n        duration: DataTypes.STRING,\n        price: DataTypes.STRING\n\n    }, {\n        freezeTableName: true}\n)\n```\n\n```text\nCompetence = sequelize.define('competence', {\n        id: DataTypes.INTEGER,\n        name: DataTypes.STRING,\n        organization_id: DataTypes.INTEGER,\n        competence_type_id: DataTypes.INTEGER\n    },{freezeTableName:true})\n```\n\n```text\nModule_has_competence = sequelize.define('module_has_competence', {\n    id: DataTypes.INTEGER,\n    module_id: DataTypes.INTEGER,\n    competence_id: DataTypes.INTEGER,\n    score: DataTypes.STRING\n},{\n    freezeTableName: true}\n})\n```\n\n```text\nModule.hasMany(Competence, {through: Module_has_competence, foreignKey: 'module_id'});\n```\n\n```text\nretrieveById: function (quote_id, onSuccess, onError) {\n                Module.find({include: [{ all: true }],where: {id: quote_id}})\n                    .success(onSuccess).error(onError);\n            }\n```\n\n```text\nmodels\n```\n\n```text\nn:m\n```\n\n```text\nCompetence\n```\n\n```text\nModule\n```\n\n```text\nModule\n```\n\n```text\nTrace: [TypeError: Cannot call method 'replace' of undefined]\n    at null.<anonymous> (/Users/sjlu/Development/29165644/app.js:61:13)\n    at tryCatch1 (/Users/sjlu/Development/29165644/node_modules/sequelize/node_modules/bluebird/js/main/util.js:45:21)\n    at Promise._callHandler (/Users/sjlu/Development/29165644/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:571:13)\n    at Promise._settlePromiseFromHandler (/Users/sjlu/Development/29165644/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:581:18)\n    at Promise._settlePromiseAt (/Users/sjlu/Development/29165644/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:713:18)\n    at Promise._settlePromiseAt (/Users/sjlu/Development/29165644/node_modules/sequelize/lib/promise.js:76:18)\n    at Promise._settlePromises (/Users/sjlu/Development/29165644/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:854:14)\n    at Async._consumeFunctionBuffer (/Users/sjlu/Development/29165644/node_modules/sequelize/node_modules/bluebird/js/main/async.js:85:12)\n    at Async.consumeFunctionBuffer (/Users/sjlu/Development/29165644/node_modules/sequelize/node_modules/bluebird/js/main/async.js:40:14)\n    at process._tickCallback (node.js:442:13)\n```\n\n```text\nCompetence.belongsToMany(Module, {\n    through: Module_has_competence,\n    as: 'module',\n    foreignKey: 'module_id'\n})\nModule.belongsToMany(Competence, {\n    through: Module_has_competence,\n    as: 'competence',\n    foreignKey: 'competence_id'\n})\n```\n\n```text\nSELECT `module`.`id`, \n         `module`.`name`, \n         `module`.`description`, \n         `module`.`category_id`, \n         `module`.`module_type_id`, \n         `module`.`gives_score`, \n         `module`.`duration`, \n         `module`.`price`, \n         `module`.`createdat`, \n         `module`.`updatedat`, \n         `competence`.`id`                                  AS `competence.id`, \n         `competence`.`name`                                AS `competence.name`, \n         `competence`.`organization_id`                     AS \n         `competence.organization_id`, \n         `competence`.`competence_type_id`                  AS \n         `competence.competence_type_id`, \n         `competence`.`createdat`                           AS \n         `competence.createdAt`, \n         `competence`.`updatedat`                           AS \n         `competence.updatedAt`, \n         `competence.module_has_competence`.`id`            AS \n         `competence.module_has_competence.id`, \n         `competence.module_has_competence`.`module_id`     AS \n         `competence.module_has_competence.module_id`, \n         `competence.module_has_competence`.`competence_id` AS \n         `competence.module_has_competence.competence_id`, \n         `competence.module_has_competence`.`score`         AS \n         `competence.module_has_competence.score`, \n         `competence.module_has_competence`.`createdat`     AS \n         `competence.module_has_competence.createdAt`, \n         `competence.module_has_competence`.`updatedat`     AS \n         `competence.module_has_competence.updatedAt` \n  FROM   `module` AS `module` \n         LEFT OUTER JOIN (`module_has_competence` AS \n                         `competence.module_has_competence` \n                          INNER JOIN `competence` AS `competence` \n                                  ON `competence`.`id` = \n  `competence.module_has_competence`.`module_id`) \n  ON `module`.`id` = \n  `competence.module_has_competence`.`competence_id` \n  WHERE  `module`.`id` = 1;\n```\n\n```text\n.hasMany()\n```\n\n```text\n.belongsToMany()\n```\n\n```text\n.hasMany\n```\n\n```text\nCompetence.belongsToMany(Module, {\n  through: Module_has_competence,\n  as: 'module',\n  foreignKey: 'competence_id'\n});\nModule.belongsToMany(Competence, {\n  through: Module_has_competence,\n  as: 'competence',\n  foreignKey: 'module_id'\n});\n```\n\n========================================\n\nComments:\n- Can you post the SQL queries produced by those statements? Also a state of you DB at that point would be helpful\n- @DanRocha Sure hang on please :D\n- @DanRocha Sadly it doesnt post any sql :s all my other functions does but this one does not :s\n- Are you sure you're reaching that code? Also try using findAll just to test if theres a problem with find\n- @dege the code is reachable because as as soon as i delete the line it collects the modules\n- it's weird not posting any sql :/\n- try to set {logging: true} on your Sequelize instance\n- and as @dege said, try using .findAll({include:[{all: true}]}) or .findAll({include:[Competence]}) to see if it works\n- What version of Sequelize are you using?\n- im using version 2.0.5","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":273,"estimatedTokens":2008}}253{"id":"stack-47021085","source":"stackoverflow","questionId":47021085,"title":"Sequelize Default Exclude","tags":["node.js","orm","sequelize.js"],"text":"Title: Sequelize Default Exclude\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table named `person`, I want a column to be excluded as default,\n\n```\nconst Person = sequelize.define('person',{\n secretColumn: Sequelize.STRING,\n //... and other columns\n});\n```\n\nI see that there is a feature called `Scope` in Sequelize:\nhttp://docs.sequelizejs.com/manual/tutorial/scopes.html\n\nI tried to exclude like this;\n\n```\nconst Person = sequelize.define('person',{\n secretColumn: Sequelize.STRING,\n //... and other columns\n}, {\n defaultScope: {\n exclude: ['secretColumn']\n }\n});\n```\n\nBut that does't work. Is there any other way to exclude a column by default?\n\n========================================\n\nCode:\n```text\nconst Person = sequelize.define('person',{\n  secretColumn: Sequelize.STRING,\n  //... and other columns\n});\n```\n\n```text\nconst Person = sequelize.define('person',{\n  secretColumn: Sequelize.STRING,\n  //... and other columns\n}, {\n  defaultScope: {\n    exclude: ['secretColumn']\n  }\n});\n```\n\n```text\nperson\n```\n\n```text\nScope\n```\n\n```text\nconst Person = sequelize.define('person',{\n  secretColumn: Sequelize.STRING,\n  //... and other columns\n}, {\n  defaultScope: {\n    attributes: { exclude: ['secretColumn'] }\n  }\n});\n```\n\n```text\nexclude\n```\n\n```text\nattributes\n```\n\n========================================\n\nComments:\n- Not sure why, but this isn't working for me. Is it okay to do this? defaultScope: { attributes: { exclude: ['token', 'access', 'password'] } }","metadata":{"transformedAt":"2026-08-18T18:33:34.357Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":84,"estimatedTokens":375}}254{"id":"stack-37761986","source":"stackoverflow","questionId":37761986,"title":"find records in sequelize seeds","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: find records in sequelize seeds\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI've been trying to write some seeds for my project, but I've ran into a bit of a snag.\n\nI've got a `many-to-many` relation with my `users` and `roles` table. So, when I'm seeding the database I need to add a record with correct ids into my join table. In order to do that I need to find user by `email` and role by `name` and get the `ids` and that's the problem. I can't find any good documentation on the sequelize site. I'm using the sequelize-cli for the seeding and migrating things. I get as a parameter a `queryInterface`, but I can't find any example or mention what this thing can actually do. Just some simple examples just got me through the migrating (somehow) and what I was able to find on google.\n\nI've resolved this by using a \"dirty trick\" I'd say...\n\n```\n// user_seeds.js\nup: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert(table, [{\n id: 1,\n name: 'John doe',\n email: 'john@doe.com',\n created_at,\n updated_at\n}], {});\n\n// roles_seeds.js\nup: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert(table, [{\n id: 1,\n name: 'admin',\n created_at,\n updated_at\n }, {\n id: 2,\n name: 'user',\n created_at,\n updated_at\n}]);\n\n//user_roles_seeds.js\nup: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert(table, [{\n employee_id: 1,\n role_id: 1\n }]);\n},\n```\n\nDon't like this solution since it may be troublesome in the future should I'd want to run the seeds again and forget about how this works. There should be a way for me to query the database using this `queryInterface`. I was wondering if one of you had ran into this issue and solved it, if so, please .\n\n========================================\n\nTop Answer:\nI can't add a comment, although this is an edit to the accepted answer here.\n\nAdd `plain: false` to the query options to return all matching entries. Sequelize doesn't seem to have a doc for `rawSelect`. But looking at the repo, it basically constructs a raw query from the params provided. For more info https://sequelize.org/master/manual/raw-queries.html\n\nSo it should look like this:\n\n```\nconst users = await queryInterface.rawSelect(\n 'Users',\n {\n where: {\n age: null,\n },\n plain: false,\n },\n ['id'],\n );\n```\n\n========================================\n\nCode:\n```text\n// user_seeds.js\nup: function (queryInterface, Sequelize) {\n  return queryInterface.bulkInsert(table, [{\n    id: 1,\n    name: 'John doe',\n    email: 'john@doe.com',\n    created_at,\n    updated_at\n}], {});\n\n// roles_seeds.js\nup: function (queryInterface, Sequelize) {\n  return queryInterface.bulkInsert(table, [{\n    id: 1,\n    name: 'admin',\n    created_at,\n    updated_at\n  }, {\n    id: 2,\n    name: 'user',\n    created_at,\n    updated_at\n}]);\n\n//user_roles_seeds.js\nup: function (queryInterface, Sequelize) {\n    return queryInterface.bulkInsert(table, [{\n    employee_id: 1,\n    role_id: 1\n  }]);\n},\n```\n\n```text\nmany-to-many\n```\n\n```text\nusers\n```\n\n```text\nroles\n```\n\n```text\nemail\n```\n\n```text\nname\n```\n\n```text\nids\n```\n\n```text\nqueryInterface\n```\n\n```text\nqueryInterface\n```\n\n```text\nasync up(queryInterface, Sequelize) {\n    const user = await queryInterface.rawSelect('User', {\n      where: {\n        name: 'John doe',\n      },\n    }, ['id']);\n\n    if(!user) {\n       // do bulkInsert stuff.\n    }\n  },\n```\n\n```text\nconst { User } = require('./models');\n\nup: function (queryInterface, Sequelize) {\n  return User.findOrCreate({\n    where: { email: 'john@doe.com' },\n    defaults: {\n      name: 'John Doe'\n    }\n  });\n```\n\n```text\nconst users = await queryInterface.rawSelect(\n      'Users',\n        {\n          where: {\n            age: null,\n          },\n          plain: false,\n        },\n        ['id'],\n      );\n```\n\n```text\nplain: false\n```\n\n```text\nrawSelect\n```\n\n========================================\n\nComments:\n- Did you resolve this??\n- In a way I did.\n- There is fundamentally no way to do non-raw querries BTW: github.com/sequelize/cli/issues/862\n- It's a good approach but when we use ES6 babel we have problems when using `import` in sequelize config, model etc..\n- This worked perfect for me thanks BenHu. Note that if you have a different seed file for each table then order of seeds is important (Sequelize CLI loads them in alphabetical order) - just rename them to reorder if needed.\n- I see that is a good approach but I dont know why it returns only one record. I would like to get all in a `where` condition. May you help me?\n- Thank you for this. I didn't find the doc for rawSelect either, and I was wondering why I was getting only one result for a similar query. plain false did the trick.","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":195,"estimatedTokens":1175}}255{"id":"stack-35073918","source":"stackoverflow","questionId":35073918,"title":"Sequelize grouping by date, disregarding hours/minutes/seconds","tags":["javascript","sql","node.js","postgresql","sequelize.js"],"text":"Title: Sequelize grouping by date, disregarding hours/minutes/seconds\nTags: javascript, sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHey so im trying to query from a database, using Sequelize (Node.js ORM for postgreSQL), im trying to group by date range, and keep a count of how many items where in that table.\n\nRight now the code i have is\n\n```\nTask.findAll({\n attributes: ['createdAt'],\n group: 'createdAt'\n })\n```\n\nBut as you can see the grouping only takes into account the exact date (including seconds) so the grouping is actually pointless since no matter what there will be no overlapping items with the exact same second count.\nSo i want it to just be group based on day, year and month.\n\nIm assuming that it will have to be something like sequelize.fn(...)\n\n========================================\n\nTop Answer:\nThe selected answer didn't work here.\n\nThis is what is working for me.\n\n```\nTask.findAll({\n attributes: [\n [Sequelize.literal(`DATE(\"createdAt\")`), 'date'],\n [Sequelize.literal(`COUNT(*)`), 'count']\n ],\n group: ['date'],\n})\n```\n\n========================================\n\nCode:\n```text\nTask.findAll({\n    attributes: ['createdAt'],\n    group: 'createdAt'\n  })\n```\n\n```text\nTask.findAll({\n  group: [sequelize.fn('date_trunc', 'day', sequelize.col('createdAt'))]\n})\n```\n\n```text\nsequelize.fn(...)\n```\n\n```text\ngroup:'DATE(date_added)' \n     or\n     group:'WEEK(date_added)'\n     or\n     group:'MONTH(date_added)'\n```\n\n```text\nTask.findAll({\n    attributes: [\n        [Sequelize.literal(`DATE(\"createdAt\")`), 'date'],\n        [Sequelize.literal(`COUNT(*)`), 'count']\n    ],\n    group: ['date'],\n})\n```\n\n```text\nModel.findAll({\n      attributes: [\n        /* add other attributes you may need from your table */\n        [sequelize.fn('DATE', sequelize.col('createdAt')), 'Date']\n      ],\n      group: [sequelize.fn('DATE', sequelize.col('createdAt')), 'Date']\n    })\n```\n\n```text\nModel.count({\n      where: {\n        createdAt: sequelize.where(\n          sequelize.fn(\"YEAR\", sequelize.col(\"createdAt\")),\n          \"2022\"\n        ),\n      },\n      attributes: [\n        [sequelize.fn(\"MONTH\", sequelize.col(\"createdAt\")), \"month\"],\n      ],\n      group: [\"month\"],\n    })\n      .then((result) => {\n        console.log(result);\n      })\n      .catch((error) => {\n        console.log(error);\n      });\n```\n\n```text\n[\n    {\n        \"month\": 8,\n        \"count\": 2\n    },\n    {\n        \"month\": 9,\n        \"count\": 1\n    }\n]\n```\n\n```text\ncount\n```\n\n```text\ngroup by\n```\n\n```text\nmonth\n```\n\n```text\nyear\n```\n\n========================================\n\nComments:\n- @repo glad to help! You can also upvote the answer for future viewers. I'm going to include the documentation of sequelize for the group property\n- @barbarity how do you do when you want to truncate with a specific timezone?\n- MariaDB wanted fieldname without quotes... ` [Sequelize.literal(`DATE(createdAt)`), 'date']`\n- @AnttiA very well. My answer was tested on PostgreSQL.\n- MySql also needs fieldname without quotes, but otherwise it works\n- Error: FUNCTION cms.date_trunc does not exist\n- This works for me, how can I have all months and count 0 if no data found.\n- @Donkagunila Whatever month is not returned, the frontend (or whoever is calling the API) should consider that 0 as default value. Or, you might need to write custom logic after, `.then((result) => {`","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":147,"estimatedTokens":844}}256{"id":"stack-42497254","source":"stackoverflow","questionId":42497254,"title":"Sequelize schema for PostgreSQL: How to accurately define a schema in a model?","tags":["node.js","postgresql","schema","sequelize.js","database-schema"],"text":"Title: Sequelize schema for PostgreSQL: How to accurately define a schema in a model?\nTags: node.js, postgresql, schema, sequelize.js, database-schema\nSource: Stack Overflow\n\nQuestion:\nI searched throughout the net and have not been able to determine how to add a schema to this sequelize model below. The following code does not kick back errors, however when I inspect the postgres DB, the only schema is the default one for public. \n\n```\n// The model definition is done in /path/to/models/project.js\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define(\"project\", {\n name: DataTypes.STRING,\n description: DataTypes.TEXT,\n },\n define: {\n schema: \"prefix\"\n },\n classMethods: {\n method1: function() {},\n method2: function() {}\n },\n instanceMethods: {\n method3: function() {}\n })\n```\n\nHow should the script be revised to accurately define a schema? \n\n**EDIT**\n\nIn my case, the final answer was \n\n```\ndatabase_name.sequelize.createSchema('prefix').then(() => {...});\n```\n\nin my ./models/index.js file the database object is as follows:\n\n```\ndatabase_name = {\n Sequelize: Sequelize,\n sequelize: sq,\n table_1: sq.import(__dirname + '/file_folder')\n };\n\nmodule.exports = database_name;\n```\n\n========================================\n\nTop Answer:\nI think you need to define the schema in the create table migration file like so:\n\n```\nqueryInterface.createTable(\n 'nameOfTheNewTable',\n {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n createdAt: {\n type: Sequelize.DATE\n },\n updatedAt: {\n type: Sequelize.DATE\n },\n attr1: Sequelize.STRING,\n attr2: Sequelize.INTEGER,\n attr3: {\n type: Sequelize.BOOLEAN,\n defaultValue: false,\n allowNull: false\n },\n //foreign key usage\n attr4: {\n type: Sequelize.INTEGER,\n references: {\n model: 'another_table_name',\n key: 'id'\n },\n onUpdate: 'cascade',\n onDelete: 'cascade'\n }\n },\n {\n engine: 'MYISAM', // default: 'InnoDB'\n charset: 'latin1', // default: null\n schema: 'prefix' // default: public, PostgreSQL only.\n }\n```\n\n========================================\n\nCode:\n```text\n// The model definition is done in /path/to/models/project.js\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define(\"project\", {\n    name: DataTypes.STRING,\n    description: DataTypes.TEXT,\n  },\n    define: {\n        schema: \"prefix\"\n    },\n    classMethods: {\n      method1: function() {},\n      method2: function() {}\n  },\n    instanceMethods: {\n      method3: function() {}\n  })\n```\n\n```text\ndatabase_name.sequelize.createSchema('prefix').then(() => {...});\n```\n\n```text\ndatabase_name = {\n    Sequelize: Sequelize,\n    sequelize: sq,\n    table_1: sq.import(__dirname + '/file_folder')\n };\n\nmodule.exports = database_name;\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n    return sequelize.define(\"project\", {\n        name: DataTypes.STRING,\n        description: DataTypes.TEXT,\n    }, {\n        schema: 'prefix',\n        classMethods: {\n            method1: function() {},\n            method2: function() {}\n        },\n        instanceMethods: {\n            method3: function() {}\n        }\n    }\n}\n```\n\n```text\nsequelize.createSchema('prefix').then(() => {\n    // new schema is created\n});\n```\n\n```sql\nCREATE SCHEMA prefix;\n```\n\n```text\noptions\n```\n\n```text\nsequelize.define\n```\n\n```text\nschema\n```\n\n```text\nsequelize.createSchema()\n```\n\n```text\nsequelize.sync()\n```\n\n```text\nqueryInterface.createTable(\n  'nameOfTheNewTable',\n  {\n    id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    createdAt: {\n      type: Sequelize.DATE\n    },\n    updatedAt: {\n      type: Sequelize.DATE\n    },\n    attr1: Sequelize.STRING,\n    attr2: Sequelize.INTEGER,\n    attr3: {\n      type: Sequelize.BOOLEAN,\n      defaultValue: false,\n      allowNull: false\n    },\n    //foreign key usage\n    attr4: {\n        type: Sequelize.INTEGER,\n        references: {\n            model: 'another_table_name',\n            key: 'id'\n        },\n        onUpdate: 'cascade',\n        onDelete: 'cascade'\n    }\n  },\n  {\n    engine: 'MYISAM',                     // default: 'InnoDB'\n    charset: 'latin1',                    // default: null\n    schema: 'prefix'                      // default: public, PostgreSQL only.\n  }\n```\n\n```text\nconst User = sequelize.define('people', {\n        uuid: {\n            type: Sequelize.UUID,\n            defaultValue: Sequelize.UUIDV1,\n            primaryKey: true\n        },\n        username: Sequelize.STRING,\n        email: Sequelize.STRING,\n        birthday: Sequelize.DATE\n    }, {\n            schema: 'public',\n        });\n\n    sequelize.sync()\n        .then(() => User.create({\n            username: 'MartialDoane',\n            email: 'martial-doane@gmail.com',\n            birthday: new Date(1977, 6, 11)\n        }))\n        .then(jane => {\n            console.log(jane.toJSON());\n\n            res.send(jane);\n            res.status(200);\n        });\n```\n\n```js\n(async function () {\n  await sequelize.showAllSchemas({ logging: false }).then(async (data) => {\n        if (!data.includes('some_schema')) {\n         await sequelize.createSchema('some_schema');\n        }\n        if (!data.includes('some_schema2')) {\n         await sequelize.createSchema('some_schema2');\n       }\n  });\n}());\n```\n\n```js\n(async function () {\n  const allSchema: Array<string> = await sequelize\n    .showAllSchemas({ logging: false })\n    .then((data) => data.map((ele) => ele.toString()));\n  if (!allSchema.includes('some_schema')) {\n    await sequelize.createSchema('some_schema', { logging: false });\n  }\n})();\n```\n\n========================================\n\nComments:\n- This will change the default schema. The question is specific to changing the schema for a specific model.\n- This does not work. It kicks back \"schema does not exist\"\n- Do you use `sequelize.sync()` to synchronize the database or you use migrations?\n- Because you need to create a schema before defining models in it\n- I don't use migrations yet. Yes I use sequelize.sync() to synchronize the DB. Can I define it programmatically without going doing it through the CLI?\n- I have edited the answer to include the schema creation part\n- In my specific case, I had preformed the following: database_name.sequelize.createSchema('prefix').then(() => {...}); This was based on how I define the database in the index.js file.\n- this is not working for me.The DB have table under schema called public so I have added {schema: 'public'} in the model but the find query returns empty object","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":281,"estimatedTokens":1622}}257{"id":"stack-56412038","source":"stackoverflow","questionId":56412038,"title":"Sequelize with Postgresql order by with null values first","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize with Postgresql order by with null values first\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI would like to construct a sequelize query that returns rows in ascending order with NULL values first.\n\nI have a timestamp when an email is sent, which is NULL if an email has never been sent.\n\nHere's the Postgres query that does what I want:\n\n```\nSELECT quote, quote_id\nFROM quotes\nWHERE book_id = '${book_id}'\nORDER BY last_emailed ASC NULLS FIRST\nLIMIT 5\n```\n\nThe sequelize query I have is:\n\n```\nconst res = await Quote.findAll({\n attributes: ['quote', 'quote_id'],\n where: { book_id },\n order: [\n ['last_emailed', 'ASC']\n ],\n limit: 5,\n})\n```\n\nBut this returns all NULL values last. It otherwise does what I want\n\n========================================\n\nTop Answer:\nThe accepted answer didn't work for me but adding an extra line in the order array like this worked:\n\n```\nconst res = await Quote.findAll({\n attributes: ['quote', 'quote_id'],\n where: { book_id },\n order: [\n Sequelize.fn(\"isnull\", Sequelize.col(\"last_emailed\")),\n ['last_emailed', 'ASC']\n ],\n limit: 5,\n})\n```\n\n========================================\n\nCode:\n```text\nSELECT quote, quote_id\nFROM quotes\nWHERE book_id = '${book_id}'\nORDER BY last_emailed ASC NULLS FIRST\nLIMIT 5\n```\n\n```text\nconst res = await Quote.findAll({\n  attributes: ['quote', 'quote_id'],\n  where: { book_id },\n  order: [\n    ['last_emailed', 'ASC']\n  ],\n  limit: 5,\n})\n```\n\n```text\nconst res = await Quote.findAll({\n   attributes: ['quote', 'quote_id'],\n   where: { book_id },\n   order: [\n      ['last_emailed', 'ASC NULLS FIRST']\n   ],\n   limit: 5,\n})\n```\n\n```text\nNULLS FIRST\n```\n\n```text\nASC\n```\n\n```text\nconst res = await Quote.findAll({\n   attributes: ['quote', 'quote_id'],\n   where: { book_id },\n   order: [\n      Sequelize.fn(\"isnull\", Sequelize.col(\"last_emailed\")),\n      ['last_emailed', 'ASC']\n   ],\n   limit: 5,\n})\n```\n\n========================================\n\nComments:\n- Doesn't work for me with sequelize 6 & mysql","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":108,"estimatedTokens":505}}258{"id":"stack-28249394","source":"stackoverflow","questionId":28249394,"title":"Difference between findOrCreate() and upsert() in sequelize","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: Difference between findOrCreate() and upsert() in sequelize\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI was reading over the doc and it mentioned two ways of doing an upsert: `findOrCreate()` or `upsert()`. I read the descriptions, but I'm still not clear what the difference is. \n\nThe `upsert()` goes on to say:\n\n```\nNote that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.\n```\n\nDoes this mean `upsert()` explicitly requires I define an `id` UNIQUE primary field in my model? ie:\n\n```\nvar Something = sequelize.define(\"Something\", { id: { \n type: DataTypes.INTEGER, \n primaryKey: true, \n unique: true, \n allowNull: false}});\n```\n\nIf so, why does `findOrCreate()` not have that restriction?\n\nCan someone explain the use cases for when `findOrCreate()` and `upsert()` should be used, and why `upsert()` has the unique constraint requirement when `findOrCreate()` doesn't seem to need it?\n\n========================================\n\nTop Answer:\nthe key difference is Id field. In case of upsert you need the id field. But sometimes, you dont hv the id field. For example when creating a user from an external provider fields say fb, you will not have the id of the user record if it already exists. In this case you will have to use findOrCreate on one of the fields returned by fb like for example email. findOrCreate user where the email is the email returned from fb\n\n========================================\n\nCode:\n```text\nNote that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.\n```\n\n```text\nvar Something = sequelize.define(\"Something\", { id: { \n                    type: DataTypes.INTEGER, \n                    primaryKey: true, \n                    unique: true, \n                    allowNull: false}});\n```\n\n```text\nfindOrCreate()\n```\n\n```text\nupsert()\n```\n\n```text\nupsert()\n```\n\n```text\nupsert()\n```\n\n```text\nid\n```\n\n```text\nfindOrCreate()\n```\n\n```text\nfindOrCreate()\n```\n\n```text\nupsert()\n```\n\n```text\nupsert()\n```\n\n```text\nfindOrCreate()\n```\n\n```text\n.findOrCreate\n```\n\n```text\n.upsert\n```\n\n========================================\n\nComments:\n- Hey! Do you know what would happen when there is one Primary/Unique key and one Unique key at the same time in the collection? Is sequelize updates unique key or uses it as a part of select query?\n- This doesn't always have to be an id, it can be whatever you have set as a key on the table itself. Example: updating a user's information if it's unique by email. If email is a key on the table, then Sequelize can find and update based on that, not the id that exists for the record on the table.","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":100,"estimatedTokens":733}}259{"id":"stack-42882288","source":"stackoverflow","questionId":42882288,"title":"Sequelize insert into join table (many-to-many)","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: Sequelize insert into join table (many-to-many)\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI set up two models in sequelize that have a many-to-many relationship. Sequelize created the join table correctly, but I'm not able to insert into it. I've been poring over this section of the docs: http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations but I can't get anything to work based on their examples. They don't have a many-to-many example, unfortunately. \n\nNext I tried to use the setModel functions, and that's producing an error from deep in the sequelize code which I can't figure out. That code is below.\n\nMy two models are Coin and Ledger.\n\n```\nLedger.findById(22).then(ledger=>{\n var c1 = Coin.findById(1);\n var c2 = Coin.findById(2);\n ledger.setCoins([c1,c2]).then(sc=>{\n console.log(sc);\n });\n});\n```\n\nMy models are related to each other using this code:\n\n```\nLedger.belongsToMany(Coin,{ through: 'ledger_coin'});\nCoin.belongsToMany(Ledger, {through: 'ledger_coin'});\n```\n\nCan anyone give me some suggestions or point me on the right track for either using the `get` functions or the association options to write to the join table? I could write a custom function but I know there must be a way to do it.\n\n========================================\n\nTop Answer:\n### 2019+\n\nAfter Sequelize 5+, `findById()` is replaced by `findByPk()`\n\n```\nLedger.findByPk(22).then(ledger=>{\n ledger.setCoins([1,2]).then(sc=>{\n console.log(sc);\n });\n});\n```\n\n========================================\n\nCode:\n```text\nLedger.findById(22).then(ledger=>{\n    var c1 = Coin.findById(1);\n    var c2 = Coin.findById(2);\n    ledger.setCoins([c1,c2]).then(sc=>{\n        console.log(sc);\n    });\n});\n```\n\n```text\nLedger.belongsToMany(Coin,{ through: 'ledger_coin'});\nCoin.belongsToMany(Ledger, {through: 'ledger_coin'});\n```\n\n```text\nget\n```\n\n```text\nLedger.findById(22).then(ledger=>{\n    ledger.setCoins([1,2]).then(sc=>{\n        console.log(sc);\n    });\n});\n```\n\n```text\nsetCoins\n```\n\n```text\nLedger.findByPk(22).then(ledger=>{\n    ledger.setCoins([1,2]).then(sc=>{\n        console.log(sc);\n    });\n});\n```\n\n```text\nfindById()\n```\n\n```text\nfindByPk()\n```\n\n========================================\n\nComments:\n- Hi @fredrover, Did you find any better solution than setting the content\n- How this can be done in typescript? TS2339: Property 'setCoins' does not exist on type 'Ledger'.","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":100,"estimatedTokens":611}}260{"id":"stack-53965349","source":"stackoverflow","questionId":53965349,"title":"How can I bind a variable to sequelize literal?","tags":["javascript","node.js","sequelize.js"],"text":"Title: How can I bind a variable to sequelize literal?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have this subquery that is used to check the existence of a column related to the source model.\n\n```\nconst defaultingLoans = await Loan.findAll({\n where: {\n [Op.and]: database.sequelize.literal('EXISTS(SELECT * FROM \"Instalments\" WHERE \"Instalments\".\"loanId\" = \"Loan\".\"id\" AND \"Instalments\".\"status\" = 'pending')')\n }\n });\n```\n\nThe query works fine but the value `pending` ideally won't be fixed so I'll like to have a variable there that can be used to query for different status.\n\nHow can I replace the pending string with a variable. \n\nConcatenation didn't work here because Sequelize has a weird way of parsing concatenated SQL queries which result in an error. An example is here https://pastebin.com/u8tr4Xbt and I took a screenshot of the error here\n\n========================================\n\nTop Answer:\nYou can put your `bind` object right inside your query object:\n\n```\nlet status = 'Pending';\nconst defaultingLoans = await Loan.findAll({\n where: database.sequelize.literal('EXISTS(SELECT * FROM \"Instalments\" WHERE \"Instalments\".\"loanId\" = \"Loan\".\"id\" AND \"Instalments\".\"status\" = $status)'),\n bind: {status}\n});\n```\n\n========================================\n\nCode:\n```text\nconst defaultingLoans = await Loan.findAll({\n    where: {\n      [Op.and]: database.sequelize.literal('EXISTS(SELECT * FROM \"Instalments\" WHERE \"Instalments\".\"loanId\" = \"Loan\".\"id\" AND \"Instalments\".\"status\" = 'pending')')\n    }\n  });\n```\n\n```text\npending\n```\n\n```text\nconst defaultingLoans = amount => await Loan.findAll({\n  where: {\n    [Op.and]: database.sequelize.literal(`EXISTS(SELECT * FROM \"Instalments\" WHERE \"Instalments\".\"loanId\" = \"Loan\".\"id\" AND \"Instalments\".\"amount\" = ${amount})`)\n  }\n});\n```\n\n```text\nconst loans = defaultingLoans(2000);\n```\n\n```text\ndefaultingLoans\n```\n\n```text\namount\n```\n\n```text\nlet status = 'Pending';\nconst defaultingLoans = await Loan.findAll({\n    where: database.sequelize.literal('EXISTS(SELECT * FROM \"Instalments\" WHERE \"Instalments\".\"loanId\" = \"Loan\".\"id\" AND \"Instalments\".\"status\" = $status)'),\n    bind: {status}\n});\n```\n\n```text\nbind\n```\n\n========================================\n\nComments:\n- Are you familiar with concatenating variables to strings?\n- @Hydrothermal String concatenation doesn't work with sequelize literal\n- What makes you say that? `literal()` is being given a string as an argument. It doesn't matter how it's constructed. Just that it is a valid string. `literal('abc')` and `literal('ab'+ 'c')` would both pass the same string to the method\n- There seems to be a problem with the way sequelize parses concatenated SQL strings, take a look at the query: pastebin.com/u8tr4Xbt The image is the error gotten when I run that: imagebin.ca/v/4RbsQOAPaxvO\n- There seems to be a problem with the way sequelize parses concatenated SQL strings, take a look at the query: pastebin.com/u8tr4Xbt The image is the error gotten when I run that: imagebin.ca/v/4RbsQOAPaxvO\n- That's because `clause1` and `clause2` are strings - you need to include quotes around the concatenated values when using strings\n- Something like this database.sequelize.literal(`EXISTS(SELECT * FROM \"Instalments\" WHERE \"Instalments\".\"loanId\" = \"Loan\".\"id\" AND \"Instalments\".\"status\" IN (\"${clause1}\", \"${clause2}\"))`) yeah? Still gives me the same error.\n- If not, can you help a sample of what you're talking about, thanks.\n- I believe sequelize requires single quotes for strings, so try `('${clause1}', '${clause2}')`\n- This isn't exactly binding. It'll concatenate the param to the query string.\n- Be careful with SQL Injection in this cases if this is exposed to users. Amount could be `'2000; DELETE FROM \"Instalments\";'`","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":95,"estimatedTokens":944}}261{"id":"stack-48326311","source":"stackoverflow","questionId":48326311,"title":"Sequelize: overlapping - Checking if any value in array matches any value in the passed array","tags":["sql","node.js","database","postgresql","sequelize.js"],"text":"Title: Sequelize: overlapping - Checking if any value in array matches any value in the passed array\nTags: sql, node.js, database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing sequelize to check if the the db input property, which is array, has a given item.\nHave a Postgres database with data *Events*.\nWant to get one *Event* that will have any of these *weekDays*.\nType of *weekDays* is ARRAY(integer).\n\n```\nEvents.findOne({\n where: {\n weekDays: {\n $contains: [2, 3],\n },\n },\n});\n```\n\nTried to do with $contains, $any, or $like $any but all the time got the same error message.\n\n TypeError: values.map is not a function\n\nSincerely thanks\n\n========================================\n\nCode:\n```text\nEvents.findOne({\n  where: {\n    weekDays: {\n      $contains: [2, 3],\n    },\n  },\n});\n```\n\n```text\nEvents.findOne({\n  where: {\n    weekDays: {\n      [Sequelize.Op.overlap]: [2, 3],\n    },\n  },\n});\n```\n\n```text\nweekDays\n```\n\n```text\nSequelize.Op.overlap\n```\n\n========================================\n\nComments:\n- did you use `$in` clause? And I will recommend `$like` clause...\n- @AshishChoudhary tried with $in and $like as well, same error\n- Ok... use `findAll` instead of `findOne`\n- Again same error","metadata":{"transformedAt":"2026-08-18T18:33:34.358Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":305}}262{"id":"stack-42850631","source":"stackoverflow","questionId":42850631,"title":"Simple example of many-to-many relation using Sequelize","tags":["javascript","mysql","node.js","many-to-many","sequelize.js"],"text":"Title: Simple example of many-to-many relation using Sequelize\nTags: javascript, mysql, node.js, many-to-many, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a simple example of many-to-many relation between tables using Sequelize. However, this seems to be way trickier than I expected.\n\nThis is the code I have currently (the `./db.js` file exports the Sequelize connection instance).\n\n```\nconst Sequelize = require(\"sequelize\");\nconst sequelize = require(\"./db\");\n\nvar Mentee = sequelize.define('mentee', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING\n }\n});\n\nvar Question = sequelize.define('question', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n text: {\n type: Sequelize.STRING\n }\n});\n\nvar MenteeQuestion = sequelize.define('menteequestion', {\n// answer: {\n// type: Sequelize.STRING\n// }\n});\n\n// A mentee can answer several questions\nMentee.belongsToMany(Question, { as: \"Questions\", through: MenteeQuestion });\n\n// And a question can be answered by several mentees\nQuestion.belongsToMany(Mentee, { as: \"Mentees\", through: MenteeQuestion });\n\nlet currentQuestion = null;\nPromise.all([\n Mentee.sync({ force: true })\n , Question.sync({ force: true })\n , MenteeQuestion.sync({ force: true })\n]).then(() => {\n return Mentee.destroy({where: {}})\n}).then(() => {\n return Question.destroy({ where: {} })\n}).then(() => {\n return Question.create({\n text: \"What is 42?\"\n });\n}).then(question => {\n currentQuestion = question;\n return Mentee.create({\n name: \"Johnny\"\n })\n}).then(mentee => {\n console.log(\"Adding question\");\n return mentee.addQuestion(currentQuestion);\n}).then(() => {\n return MenteeQuestion.findAll({\n where: {}\n , include: [Mentee]\n })\n}).then(menteeQuestions => {\n return MenteeQuestion.findAll({\n where: {\n menteeId: 1\n }\n , include: [Mentee]\n })\n}).then(menteeQuestion => {\n console.log(menteeQuestion.toJSON());\n}).catch(e => {\n console.error(e);\n});\n```\n\nWhen running this I get:\n\nCannot add foreign key constraint\n\nI think that is because of the `id` type—however I have no idea why it appears and how we can fix it.\n\nAnother error which appeared when the previous one won't appear was:\n\nExecuting (default): *INSERT INTO `menteequestions` (`menteeId`,`questionId`,`createdAt`,`updatedAt`) VALUES (2,1,'2017-03-17 06:18:01','2017-03-17 06:18:01');*\n\nError: mentee is not associated to menteequestion!\n\nAlso, another error I get—I think it's because of `force:true` in `sync`—is:\n\n*DROP TABLE IF EXISTS `mentees`;*\n\nER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails\n\nHow to solve these?\n\nAgain, I only need a minimal example of many-to-many crud operations (in this case just insert and read), but this seems to be beyond my understanding. Was struggling for two days with this.\n\n========================================\n\nCode:\n```text\nconst Sequelize = require(\"sequelize\");\nconst sequelize = require(\"./db\");\n\nvar Mentee = sequelize.define('mentee', {\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    name: {\n        type: Sequelize.STRING\n    }\n});\n\nvar Question = sequelize.define('question', {\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    text: {\n        type: Sequelize.STRING\n    }\n});\n\nvar MenteeQuestion = sequelize.define('menteequestion', {\n//    answer: {\n//        type: Sequelize.STRING\n//    }\n});\n\n// A mentee can answer several questions\nMentee.belongsToMany(Question, { as: \"Questions\", through: MenteeQuestion });\n\n// And a question can be answered by several mentees\nQuestion.belongsToMany(Mentee, { as: \"Mentees\", through: MenteeQuestion });\n\nlet currentQuestion = null;\nPromise.all([\n    Mentee.sync({ force: true })\n  , Question.sync({ force: true })\n  , MenteeQuestion.sync({ force: true })\n]).then(() => {\n    return Mentee.destroy({where: {}})\n}).then(() => {\n    return Question.destroy({ where: {} })\n}).then(() => {\n    return Question.create({\n        text: \"What is 42?\"\n    });\n}).then(question => {\n    currentQuestion = question;\n    return Mentee.create({\n        name: \"Johnny\"\n    })\n}).then(mentee => {\n    console.log(\"Adding question\");\n    return mentee.addQuestion(currentQuestion);\n}).then(() => {\n    return MenteeQuestion.findAll({\n        where: {}\n      , include: [Mentee]\n    })\n}).then(menteeQuestions => {\n    return MenteeQuestion.findAll({\n        where: {\n            menteeId: 1\n        }\n      , include: [Mentee]\n    })\n}).then(menteeQuestion => {\n    console.log(menteeQuestion.toJSON());\n}).catch(e => {\n    console.error(e);\n});\n```\n\n```text\n./db.js\n```\n\n```text\nid\n```\n\n```text\nmenteequestions\n```\n\n```text\nmenteeId\n```\n\n```text\nquestionId\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nforce:true\n```\n\n```text\nsync\n```\n\n```text\nmentees\n```\n\n```text\nsequelize.Promise.mapSeries([\n    Mentee.sync({ force: true })\n  , Question.sync({ force: true })\n  , MenteeQuestion.sync({ force: true })\n], (model) => { return model.destroy({ where: {} }); }).then(() => {\n\n});\n```\n\n```text\nMenteeQuestion.belongsTo(Mentee, { foreignKey: 'menteeId' });\nMenteeQuestion.belongsTo(Question, { foreignKey: 'questionId' });\n```\n\n```text\nmenteeQuestions.forEach(menteeQuestion => {\n    console.log(menteeQuestion.toJSON());\n});\n```\n\n```text\nsync()\n```\n\n```text\nindex.js\n```\n\n```text\n/models\n```\n\n```text\nmentee.js\n```\n\n```text\nquestion.js\n```\n\n```text\nsequelize.import()\n```\n\n```text\nsequelize[modelName]\n```\n\n```text\nsequelize.question\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\ndeletedAt\n```\n\n```text\nsync()\n```\n\n```text\nsequelize.sync({ force: true })\n```\n\n```text\nseeds\n```\n\n```text\nsequelize-cli\n```\n\n```text\nproject_test\n```\n\n```text\nPromise.all()\n```\n\n```text\nsync\n```\n\n```text\nmapSeries\n```\n\n```text\nBluebird\n```\n\n```text\nsequelize.Promise\n```\n\n```text\nmentees\n```\n\n```text\nmenteequestion\n```\n\n```text\nmapSeries\n```\n\n```text\nModel.sync()\n```\n\n```text\nmodel.destroy()\n```\n\n```text\ncreate()\n```\n\n```text\nMentee\n```\n\n```text\nQuestion\n```\n\n```text\nMenteeQuestion\n```\n\n```text\nMentee\n```\n\n```text\nQuestion\n```\n\n```text\nbelongsToMany\n```\n\n```text\ninclude: [Mentee, Question]\n```\n\n```text\nMenteeQuestion\n```\n\n```text\ntoJSON()\n```\n\n```text\nfindAll\n```\n\n```text\nforEach()\n```\n\n========================================\n\nComments:\n- Thanks for the nice answer. I don't have my laptop with me right now, so I cannot test it. Can you update my code snippet as well and explain in the inline comments what you changed? Thanks again!\n- It worked—thanks a lot! I'll open a bounty as well! I'd be curious why in the docs they didn't mention about this, did they? What's the *good practice*? Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:34.360Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":52,"totalLines":408,"estimatedTokens":1690}}263{"id":"stack-36578795","source":"stackoverflow","questionId":36578795,"title":"SEQUELIZE: How to use EXTRACT MySQL function","tags":["mysql","sequelize.js"],"text":"Title: SEQUELIZE: How to use EXTRACT MySQL function\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet's say I'm trying to extract `YEAR_MONTH` from the records in the `user` table\n\nI can write:\n\n```\nSELECT EXTRACT(YEAR_MONTH FROM u.created_on)\nFROM user u;\n```\n\nI am struggling to understand how to write a sequelize query that involves more complex MySQL methods.\n\nI know I can use something like:\n\n`sequelize.fn('avg', sequelize.col('User.age')), 'avg_age']`\n\nfor simple MySQL methods that take only one parameter.\n\nThis has been the closest I can get:\n\n```\n[sequelize.fn('extract', ['YEAR', 'FROM'], \n sequelize.col('User.created_on')), 'created_year_month']\n```\n\nWhich results in the following SQL:\n\n```\nextract('YEAR_MONTH', 'FROM', `User`.`created_on`) AS `created_year_month`\n```\n\nas opposed to\n\n```\nSELECT EXTRACT(YEAR_MONTH FROM u.created_on)\nFROM user u;\n```\n\nI am at a loss as to how I can properly build this query.\n\n========================================\n\nTop Answer:\n```\nconst tasks = await Task.findAll({\n attributes: ['id',\n\n [ sequelize.literal('extract(year from \"Task\".\"created_at\"::timestamp)'), 'year']\n\n]})\n```\n\n========================================\n\nCode:\n```text\nSELECT EXTRACT(YEAR_MONTH FROM u.created_on)\nFROM user u;\n```\n\n```text\n[sequelize.fn('extract', ['YEAR', 'FROM'],   \n sequelize.col('User.created_on')), 'created_year_month']\n```\n\n```text\nextract('YEAR_MONTH', 'FROM', `User`.`created_on`) AS `created_year_month`\n```\n\n```text\nSELECT EXTRACT(YEAR_MONTH FROM u.created_on)\nFROM user u;\n```\n\n```text\nYEAR_MONTH\n```\n\n```text\nuser\n```\n\n```text\nsequelize.fn('avg', sequelize.col('User.age')), 'avg_age']\n```\n\n```text\nsequelize.literal('extract(YEAR_MONTH FROM `User`.`created_on`) AS created_year_month')\n```\n\n```text\nsequelize.literal()\n```\n\n```text\nconst tasks = await Task.findAll({\n  attributes: ['id',\n\n    [ sequelize.literal('extract(year from \"Task\".\"created_at\"::timestamp)'), 'year']\n\n]})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.360Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":106,"estimatedTokens":488}}264{"id":"stack-37395933","source":"stackoverflow","questionId":37395933,"title":"How to create a new Sequelize dialect, for example DB2","tags":["sequelize.js"],"text":"Title: How to create a new Sequelize dialect, for example DB2\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSequelize supports five flavours of DBMS. In my project, we have a legacy database located in an IBM DB2, which is not in that list. There exists a node driver for DB2, published by IBM.\n\n- Is there a documentation on how to create such a new dialect for Sequelize?\n\n- Is it encouraged?\n\n========================================\n\nTop Answer:\nDb2 is adding Sequelize support. You can see the progress/beta at this fork: https://github.com/ibmdb/sequelize\n\n(Depending when you read this, it may have been completed, so check the Sequelize website: http://docs.sequelizejs.com/)\n\nI've been told around Feb 2019 is when its first official non-beta release is planned. Ran a test on the Db2 on Cloud Lite/free plan and it worked fine for a basic test case.\n\n========================================\n\nCode:\n```text\nvar Dialect;\n  // Requiring the dialect in a switch-case to keep the\n  // require calls static. (Browserify fix)\n  switch (this.getDialect()){\n    case 'mariadb':\n      Dialect = require('./dialects/mariadb');\n      break;\n    case 'mssql':\n      Dialect = require('./dialects/mssql');\n      break;\n    case 'mysql':\n      Dialect = require('./dialects/mysql');\n      break;\n    case 'postgres':\n      Dialect = require('./dialects/postgres');\n      break;\n    case 'sqlite':\n      Dialect = require('./dialects/sqlite');\n      break;\n    default:\n      throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mariadb, mssql, mysql, postgres, and sqlite.');\n  }\n```\n\n========================================\n\nComments:\n- can you please describe how you use github.com/ibmdb/sequelize ?","metadata":{"transformedAt":"2026-08-18T18:33:34.360Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":52,"estimatedTokens":437}}265{"id":"stack-25310624","source":"stackoverflow","questionId":25310624,"title":"how to inject mock testing hapi with Server.inject","tags":["node.js","node-mysql","sequelize.js","hapi.js"],"text":"Title: how to inject mock testing hapi with Server.inject\nTags: node.js, node-mysql, sequelize.js, hapi.js\nSource: Stack Overflow\n\nQuestion:\nI want to test hapi routes with lab, I am using mysql database.\n\nThe problem using Server.inject to test the route is that i can't mock the database because I am not calling the file that contains the handler function, so how do I inject mock database in handler?\n\n========================================\n\nCode:\n```text\nvar db = require('db');\n\nmodule.exports.handleOne = function(request, reply) {\n    reply(db.findOne());\n}\n```\n\n```text\nvar Hapi = require('hapi'),\n    dbHandler = require('dbHandler')\n\nvar server = new Hapi.Server(); server.connection({ port: 3000 });\n\nserver.route({\n    method: 'GET',\n    path: '/',\n    handler: dbHandler.handleOne\n});\n```\n\n```text\nvar sinon = require('sinon'),\n    server = require('server'),\n    db = require('db');\n\nsinon.stub(db, 'findOne').returns({ one: 'fakeOne' });\n// now the real findOne won't be called until you call db.findOne.restore()\nserver.inject({ url: '/' }, function (res) {\n    expect(res.one).to.equal('fakeOne');\n});\n```\n\n```text\nrequire\n```\n\n```text\nrequire\n```\n\n========================================\n\nComments:\n- What is the specific problem you are having? `inject` should work. `inject` should be identical to a real request from a coding standpoint.\n- I want to fake database calls while testing endpoints.\n- did you get anywhere with this? looking to use hapijs for an API and will want to mock db calls for tests.\n- @Adamski see my answer below.\n- What do you mean by 'cached \"require\"'?\n- @MananVaghasiya see nodejs.org/api/globals.html#globals_require_cache . Once resolved, `require` will cache the object, and subsequent calls to `require` for a module will return the cached instance of said module.","metadata":{"transformedAt":"2026-08-18T18:33:34.360Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":62,"estimatedTokens":455}}266{"id":"stack-64682146","source":"stackoverflow","questionId":64682146,"title":"add extra column to sql query result with constant value","tags":["mysql","sql","database","string","sequelize.js"],"text":"Title: add extra column to sql query result with constant value\nTags: mysql, sql, database, string, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've a simple query which returns me list of ids..\n\neg. `select id from users;`\n\nthis returns me the list of ids, but I need another x column(not for the users table or any other table in db) with some constant value which I'll give. I can achieve that with Js or other language after querying the ids. But just need to know if there's any way to do it within the query itself.\n\ncurrent result:\n\n```\nid\n---\n1\n2\n3\n```\n\nexpected result:\n\n```\nid some_new_column \n--- ---\n1 abc\n2 abc\n3 abc\n```\n\nwhere `some_new_column` and `abc`, both should be provided in query.\n\nNot sure if this is even possible or not. Any leads/helps appreciated.\n\n========================================\n\nTop Answer:\nYou just select it:\n\n```\nselect id, 'abc' as new_column_value\nfrom t;\n```\n\n========================================\n\nCode:\n```text\nid\n---\n1\n2\n3\n```\n\n```text\nid      some_new_column         \n---          ---\n1            abc\n2            abc\n3            abc\n```\n\n```text\nselect id from users;\n```\n\n```text\nsome_new_column\n```\n\n```text\nabc\n```\n\n```text\nselect id, 'abc' as some_new_column from users\n```\n\n```text\nselect\n```\n\n```text\nselect id, 'abc' as new_column_value\nfrom t;\n```\n\n========================================\n\nComments:\n- `select id, some_new_column from users;`?\n- note that the single quotes are important, `\"abc\" as some_new_column` doesn't work","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":94,"estimatedTokens":374}}267{"id":"stack-53415686","source":"stackoverflow","questionId":53415686,"title":"Compare Timestamp with date in sequelize query","tags":["javascript","node.js","postgresql","sequelize.js","timestamp-with-timezone"],"text":"Title: Compare Timestamp with date in sequelize query\nTags: javascript, node.js, postgresql, sequelize.js, timestamp-with-timezone\nSource: Stack Overflow\n\nQuestion:\nI have `createdAt` column which stores value as `\"2018-11-07 15:03:16.532+00\"`.\nI want to write query like `select * from table_name where createdAt = input_date`, where my`input_date` is only date value like `2018-11-07`.\nHow do i write this query using **`Sequelize`**?\n\n========================================\n\nTop Answer:\nThe accepted answer should work fine, but if we have multiple conditions in where I am using this -\n\n```\nconst cashRegisterData = await cashRegisterMain.findAll({\n attributes: ['crmid', 'dateCreated', 'startDate', 'endDate', 'startAmount', 'finalAmount', 'status'],\n where: {\n createdBy: userId,\n [Op.and]: [\n sequelize.where(sequelize.fn('date', sequelize.col('dateCreated')), '>=', fromDate),\n sequelize.where(sequelize.fn('date', sequelize.col('dateCreated')), 'Generated Query:\n\n```\nSELECT `crmid`, `dateCreated`, `startDate`, `endDate`, `startAmount`, `finalAmount`, `status` FROM `cashRegisterMain` AS `cashRegisterMain` WHERE (date(`dateCreated`) >= '2020-11-20' AND date(`dateCreated`) <= '2020-11-20') AND `cashRegisterMain`.`createdBy` = 1 ORDER BY `cashRegisterMain`.`dateCreated` DESC;\n```\n\n========================================\n\nCode:\n```text\ncreatedAt\n```\n\n```text\n\"2018-11-07 15:03:16.532+00\"\n```\n\n```text\nselect * from table_name where createdAt = input_date\n```\n\n```text\ninput_date\n```\n\n```text\n2018-11-07\n```\n\n```text\nSequelize\n```\n\n```js\nTableName.findAll({\n  where: sequelize.where(sequelize.fn('date', sequelize.col('createdAt')), '=', '2018-11-07')\n})\n```\n\n```text\nsequelize.fn()\n```\n\n```text\nconst cashRegisterData = await cashRegisterMain.findAll({\n            attributes: ['crmid', 'dateCreated', 'startDate', 'endDate', 'startAmount', 'finalAmount', 'status'],\n            where: {\n                createdBy: userId,\n                [Op.and]: [\n                    sequelize.where(sequelize.fn('date', sequelize.col('dateCreated')), '>=', fromDate),\n                    sequelize.where(sequelize.fn('date', sequelize.col('dateCreated')), '<=', toDate),\n                ]\n            },\n            order: [['dateCreated', 'DESC']],\n        });\n```\n\n```text\nSELECT `crmid`, `dateCreated`, `startDate`, `endDate`, `startAmount`, `finalAmount`, `status` FROM `cashRegisterMain` AS `cashRegisterMain` WHERE (date(`dateCreated`) >= '2020-11-20' AND date(`dateCreated`) <= '2020-11-20') AND `cashRegisterMain`.`createdBy` = 1 ORDER BY `cashRegisterMain`.`dateCreated` DESC;\n```\n\n```text\nconst beginningOfDay = moment(dateToFetch, 'YYYY-MM-DD').startOf('day');\nconst endOfDay = moment(dateToFetch, 'YYYY-MM-DD').endOf('day');\n```\n\n```text\nconst args : any = mostRecent ? {  where: { user_uid }, order: [['log_timestamp', 'DESC']] } : { where: { user_uid, log_timestamp: {\n            [Op.gte]: beginningOfDay,\n            [Op.lte]: endOfDay,\n        }},\n    };\n```\n\n```text\nconst userMessages: IUserMessages = await models.message.findAll(args);\n```\n\n```text\nsequelize.fn()\n```\n\n```text\nsequelize.fn()\n```\n\n========================================\n\nComments:\n- Thank you so much, this working perfectly! It's still valid in 2023 and the best way to get data by year from timestamp column\n- Thank you. Awesome! Your tip solved my problem.","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":112,"estimatedTokens":838}}268{"id":"stack-27292521","source":"stackoverflow","questionId":27292521,"title":"Sequalizejs adding paranoid configuration to an existing table","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequalizejs adding paranoid configuration to an existing table\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI created a table without the paranoid option, and i now want to change that table's definition to use paranoid.\n\nI don't want to re-create the database since its already in production.\nhow can i do that using migrations?\n\nshould i use addColumn with deletedAt and just add the paranoid definition to the model, or is there a better way?\n\n========================================\n\nTop Answer:\nSmall update.\n\nAccording to the `sequelize` version `6.4.0`(what I am currently using), the migration looks like this:\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.addColumn(\n 'TABLE_NAME',\n 'deletedAt',\n {\n allowNull: true,\n type: Sequelize.DATE\n })\n },\n \n down: (queryInterface, Sequelize) => {\n return queryInterface.removeColumn('TABLE_NAME', 'deletedAt')\n }\n };\n```\n\nI mean that the `done` method is not required.\n\n========================================\n\nCode:\n```text\n\"use strict\";\n\nmodule.exports = {\n  up: function(migration, DataTypes, done) {\n    // add altering commands here, calling 'done' when finished\n\n      migration.addColumn(\n          'mytablename',\n          'deletedAt',\n          {\n              type: DataTypes.DATE,\n              allowNull: true,\n              validate: {\n              }\n          }\n      );\n    done();\n  },\n\n  down: function(migration, DataTypes, done) {\n    // add reverting commands here, calling 'done' when finished\n    migration.removeColumn('mytablename', 'deletedAt');\n    done();\n  }\n};\n```\n\n```text\nparanoid: true,\n```\n\n```js\nmodule.exports = {\n        up: (queryInterface, Sequelize) => {\n            return queryInterface.addColumn(\n                'TABLE_NAME',\n                'deletedAt',\n                {\n                    allowNull: true,\n                    type: Sequelize.DATE\n                })\n        },\n    \n        down: (queryInterface, Sequelize) => {\n            return queryInterface.removeColumn('TABLE_NAME', 'deletedAt')\n        }\n    };\n```\n\n```text\nsequelize\n```\n\n```text\n6.4.0\n```\n\n```text\ndone\n```\n\n========================================\n\nComments:\n- I'd say that was is the preferred solution\n- Notice that the down migration would \"restore\" all tables that have been deleted since the up migration was applied.\n- Also need to set `paranoid: true` in the model options parameter.","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":110,"estimatedTokens":611}}269{"id":"stack-26888457","source":"stackoverflow","questionId":26888457,"title":"How to undo soft delete in Sequelize.js","tags":["javascript","node.js","sequelize.js"],"text":"Title: How to undo soft delete in Sequelize.js\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize.js in paranoid mode in my node.js project and while the soft deletion works as expected in finding and deleting data, i'm having trouble finding a way to undelete soft deleted rows.\n\nI know I can get deleted rows by using as explained in the docs\n\n```\nModel.findAll({paranoid: false, where: {deletedAt: {ne: null}}})\n```\n\nbut paranoid: false isn't available when updating. \n\nIs undeleting soft deleted rows even possible in Sequelize or am I just missing something?\n\n========================================\n\nTop Answer:\nYou can use `instance.setDataValue('deletedAt', null)`:\n\n```\nvar Bluebird = require('bluebird');\nvar models = require('./models');\n\nmodels.sequelize.sync({ force: true })\n.then(function () {\n return models.User.create({ name: 'user' })\n})\n.then(function (user) {\n return user.destroy()\n})\n.then(function () {\n return models.sequelize.models.User.findAll({ paranoid: false });\n})\n.then(function (users) {\n var user = users[0];\n user.setDataValue('deletedAt', null);\n return user.save({ paranoid: false });\n}).then(function () {\n return models.sequelize.models.User.findAll();\n}).then(function (users) {\n console.log(users[0]);\n});\n```\n\nPlease note that this snippet uses Sequelize@v2\n\n========================================\n\nCode:\n```text\nModel.findAll({paranoid: false, where: {deletedAt: {ne: null}}})\n```\n\n```text\n{paranoid: false}\n```\n\n```text\nvar model = Model.findOne({ where: { something: 1 }, paranoid: false })\n```\n\n```text\nmodel.restore()\n```\n\n```text\nvar Bluebird  = require('bluebird');\nvar models    = require('./models');\n\nmodels.sequelize.sync({ force: true })\n.then(function () {\n  return models.User.create({ name: 'user' })\n})\n.then(function (user) {\n  return user.destroy()\n})\n.then(function () {\n  return models.sequelize.models.User.findAll({ paranoid: false });\n})\n.then(function (users) {\n  var user = users[0];\n  user.setDataValue('deletedAt', null);\n  return user.save({ paranoid: false });\n}).then(function () {\n  return models.sequelize.models.User.findAll();\n}).then(function (users) {\n  console.log(users[0]);\n});\n```\n\n```text\ninstance.setDataValue('deletedAt', null)\n```\n\n```text\nuser.setDataValue('deletedAt', null);\nuser.update({deletedAt:null}, callback);\n```\n\n```text\ndeletedAt\n```\n\n```text\nnull\n```\n\n```text\nModel.update( { deletedAt: null }, { where: {deletedAt: {ne: null} }, paranoid: false  });\n```\n\n```text\nparanoid: false\n```\n\n========================================\n\nComments:\n- That's the only way it worked, although i'd prefer to `setDataValue` since it would mean only one trip to the database in case of a restore+update\n- this should be accepted answer. It's the most 'canonical' using a provided API\n- Unfortunately this solution is not working. You must pass `paranoid: false` as described here: stackoverflow.com/a/54977491/2430555\n- your answer is useful for someone who just looks this, like me :D , so is that possible to get back data which we deleted? and find it by paranoid true?\n- Yes you can do that.\n- i was following above code, but not work, i tried deleted one data, and then cant get it back by method above, do u have idea??\n- @ZumDummi , you need to define the same thing in model also , read this : docs.sequelizejs.com/manual/&hellip;\n- yep i just try to change it, but it said `column \"deletedAt\" does not exist`, i want to create it now, but what type data for deletedAt column is?\n- Have to run model.sync() then\n- what is that for?\n- sync is not function :(\n- Read the doc carefully.\n- @VivekDoshi the link to the doc is broken.","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":134,"estimatedTokens":917}}270{"id":"stack-45389747","source":"stackoverflow","questionId":45389747,"title":"Sequelize hasMany, belongsTo, or both?","tags":["sql","node.js","postgresql","sequelize.js"],"text":"Title: Sequelize hasMany, belongsTo, or both?\nTags: sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to properly setup one-to-one or one-to-many relationship with sequelize and as a matter of fact it all seems to be working just fine if i use either one of `hasOne`/ `hasMany` or `belongsTo` in my model definition. \nFor example the following associations do create the `userId` field on their Targets:\n\n```\nUser.hasMany(Email, {\n as: 'emails',\n foreignKey: 'userId',\n })\n\n User.hasOne(Profile, {\n as: 'profile',\n foreignKey: 'userId',\n })\n```\n\nBut almost everywhere in official docs i see something like:\n\n```\nProjects.hasMany(Tasks);\n Tasks.belongsTo(Projects);\n```\n\ni.e. `hasMany` AND `belongsTo` are being used together.\n\nIs this really required or it is enough to use just one of them? Any further explanation would be really valuable. Thanks!\n\n========================================\n\nCode:\n```text\nUser.hasMany(Email, {\n        as: 'emails',\n        foreignKey: 'userId',\n    })\n\n    User.hasOne(Profile, {\n        as: 'profile',\n        foreignKey: 'userId',\n    })\n```\n\n```text\nProjects.hasMany(Tasks);\n   Tasks.belongsTo(Projects);\n```\n\n```text\nhasOne\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nuserId\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nProject.hasMany(Task);\nTask.belongsTo(Project);\n```\n\n```text\nconst Project = sequelize.define('project', {\n    name: Sequelize.STRING\n});\nconst Task =  sequelize.define('task', {\n    name: Sequelize.STRING\n});\nProject.hasMany(Task);\nTask.belongsTo(Project);\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS `projects`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `projects` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`projects`)\nExecuting (default): DROP TABLE IF EXISTS `tasks`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `projectId` INTEGER REFERENCES `projects` (`id`) ON DELETE SET NULL ON UPDATE CASCADE);\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsTo\n```\n\n```text\ncascading delete\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsTo\n```\n\n========================================\n\nComments:\n- afaik, it is also possible to get the cascade effect with hasOne/Many, i.e something like `Project.hasMany(Task, {onDelete: 'cascade'})` should do the job","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":127,"estimatedTokens":638}}271{"id":"stack-42101243","source":"stackoverflow","questionId":42101243,"title":"Sequelize: Error: Error: Table1 is not associated to Table2","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize: Error: Error: Table1 is not associated to Table2\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create the following associations using Sequelize but I keep getting the following error “Error: Error: customer is not associated to order!”. I have bi-directional associations according to what I found in the documentation. I am confused about what the problem could be because when I look into the database tables I can see the foreign keys.\n\nFor this example, I am trying to pull the order and customer associated with the particular order. Technically, I could do three separate db pull but that seems inefficient as opposed to joins.\n\n```\n'use strict';\n\nmodule.exports = function(sequelize, DataTypes) {\n var user = sequelize.define('user', {\n username: DataTypes.STRING(30), //remove\n password: DataTypes.STRING(255),\n emailaddress: DataTypes.STRING(255),\n firstname: DataTypes.STRING(30),\n middlename: DataTypes.STRING(30), //remove\n lastname: DataTypes.STRING(30),\n approve: DataTypes.BOOLEAN,\n roles: DataTypes.STRING(50),\n isactive: DataTypes.BOOLEAN\n }, {\n classMethods: {\n associate: function(models) {\n // associations can be defined here\n this.hasMany(models.order);\n }\n }\n });\n\n user.hook('afterCreate', function(usr, options) {\n //hash the password\n \n return user.update({ password: passwd }, {\n where: {\n id: usr.id\n }\n });\n });\n\n return user;\n};\n\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var order = sequelize.define('order', {\n ponumber: DataTypes.STRING(30), //remove\n orderdate: DataTypes.DATE,\n shippingmethod: DataTypes.STRING(30),\n shippingterms: DataTypes.STRING(30),\n deliverydate: DataTypes.DATE,\n paymentterms: DataTypes.STRING(30),\n overridediscount: DataTypes.BOOLEAN,\n shippingaddress: DataTypes.STRING(30),\n shippingcity: DataTypes.STRING(30),\n shippingstate: DataTypes.STRING(20),\n shippingzipcode: DataTypes.STRING(10),\n isactive: DataTypes.BOOLEAN\n }, {\n associate: function(models) {\n // associations can be defined here\n this.belongsTo(models.user);\n this.belongsTo(models.customer);\n }\n });\n \n order.hook('afterCreate', function(ord, options) {\n //generate po number\n \n return order.update({ ponumber: ponumbr }, {\n where: {\n id: ord.id\n }//,\n //transaction: options.transaction\n });\n });\n\n return order;\n};\n\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var customer = sequelize.define('customer', {\n customernumber: DataTypes.STRING(30), //remove\n customerspecificationid: DataTypes.INTEGER,\n customertypeid: DataTypes.INTEGER,\n sportid: DataTypes.INTEGER,\n customername: DataTypes.STRING(20), //remove\n address: DataTypes.STRING(30),\n city: DataTypes.STRING(30),\n state: DataTypes.STRING(30),\n zipcode: DataTypes.STRING(30),\n ordercomplete: DataTypes.BOOLEAN,\n isactive: DataTypes.BOOLEAN\n }, {\n associate: function(models) {\n // associations can be defined here\n this.hasMany(models.order);\n }\n });\n \n customer.hook('afterCreate', function(cust, options) {\n //generate the customer number\n\n return customer.update({ customernumber: custnumber }, {\n where: {\n id: cust.id\n }\n });\n });\n\n return customer;\n};\n\nHere is the constructor and method inside of a repository class I want to join \n\nconstructor(model){\n super(model.order);\n this.currentmodel = model;\n}\n\nfindById(id){\n let that = this;\n return new Promise(\n function(resolve, reject) {\n that.model.find({\n where: { id: id },\n include: [ that.currentmodel.customer, that.currentmodel.user ]\n })\n .then(function(order){\n resolve(order);\n })\n .catch(function(err){\n reject(err);\n })\n });\n}\n```\n\nI have reviewed the documentation and searched the internet looking for a fix to this issue but I am not finding any answers. What could I be missing?\n\nFor the example above, I am trying to retrieve the user and the customer tied to the order record via the primary key. All of the findBy scenarios I have found so far would be getting a list of orders tied to the customer and user. What do I need to change in order to retrieve the order and customer whose foreign keys are tied to this order?\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = function(sequelize, DataTypes) {\n  var user = sequelize.define('user', {\n    username: DataTypes.STRING(30), //remove\n    password: DataTypes.STRING(255),\n    emailaddress: DataTypes.STRING(255),\n    firstname: DataTypes.STRING(30),\n    middlename: DataTypes.STRING(30), //remove\n    lastname: DataTypes.STRING(30),\n    approve: DataTypes.BOOLEAN,\n    roles: DataTypes.STRING(50),\n    isactive: DataTypes.BOOLEAN\n  }, {\n    classMethods: {\n      associate: function(models) {\n        // associations can be defined here\n        this.hasMany(models.order);\n      }\n    }\n  });\n\n  user.hook('afterCreate', function(usr, options) {\n      //hash the password\n      \n      return user.update({ password: passwd }, {\n        where: {\n          id: usr.id\n        }\n      });\n  });\n\n  return user;\n};\n\n\n\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var order = sequelize.define('order', {\n    ponumber: DataTypes.STRING(30), //remove\n    orderdate: DataTypes.DATE,\n    shippingmethod: DataTypes.STRING(30),\n    shippingterms: DataTypes.STRING(30),\n    deliverydate: DataTypes.DATE,\n    paymentterms: DataTypes.STRING(30),\n    overridediscount: DataTypes.BOOLEAN,\n    shippingaddress: DataTypes.STRING(30),\n    shippingcity: DataTypes.STRING(30),\n    shippingstate: DataTypes.STRING(20),\n    shippingzipcode: DataTypes.STRING(10),\n    isactive: DataTypes.BOOLEAN\n  }, {\n      associate: function(models) {\n        // associations can be defined here\n        this.belongsTo(models.user);\n        this.belongsTo(models.customer);\n      }\n  });\n  \n  order.hook('afterCreate', function(ord, options) {\n      //generate po number\n      \n      return order.update({ ponumber: ponumbr }, {\n        where: {\n          id: ord.id\n        }//,\n        //transaction: options.transaction\n      });\n  });\n\n  return order;\n};\n\n\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var customer = sequelize.define('customer', {\n    customernumber: DataTypes.STRING(30), //remove\n    customerspecificationid: DataTypes.INTEGER,\n    customertypeid: DataTypes.INTEGER,\n    sportid: DataTypes.INTEGER,\n    customername: DataTypes.STRING(20), //remove\n    address: DataTypes.STRING(30),\n    city: DataTypes.STRING(30),\n    state: DataTypes.STRING(30),\n    zipcode: DataTypes.STRING(30),\n    ordercomplete: DataTypes.BOOLEAN,\n    isactive: DataTypes.BOOLEAN\n  }, {\n      associate: function(models) {\n          // associations can be defined here\n        this.hasMany(models.order);\n      }\n  });\n  \n  customer.hook('afterCreate', function(cust, options) {\n      //generate the customer number\n\n        return customer.update({ customernumber: custnumber }, {\n        where: {\n          id: cust.id\n        }\n      });\n  });\n\n  return customer;\n};\n\n\nHere is the constructor and method inside of a repository class I want to join \n\nconstructor(model){\n    super(model.order);\n    this.currentmodel = model;\n}\n\n\nfindById(id){\n    let that = this;\n    return new Promise(\n        function(resolve, reject) {\n            that.model.find({\n                where: { id: id },\n                include: [ that.currentmodel.customer, that.currentmodel.user ]\n            })\n            .then(function(order){\n                resolve(order);\n            })\n            .catch(function(err){\n                reject(err);\n            })\n    });\n}\n```\n\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var customer = sequelize.define('customer', {\n    customernumber: DataTypes.STRING(30), //remove\n    customerspecificationid: DataTypes.INTEGER,\n    customertypeid: DataTypes.INTEGER,\n    sportid: DataTypes.INTEGER,\n    customername: DataTypes.STRING(20), //remove\n    address: DataTypes.STRING(30),\n    city: DataTypes.STRING(30),\n    state: DataTypes.STRING(30),\n    zipcode: DataTypes.STRING(30),\n    ordercomplete: DataTypes.BOOLEAN,\n    isactive: DataTypes.BOOLEAN\n  }, {\n      associate: function(models) {\n          // associations can be defined here\n        models.customer.hasMany(models.order);\n      }\n  });\n\n  customer.hook('afterCreate', function(cust, options) {\n      //generate the customer number\n\n        return customer.update({ customernumber: custnumber }, {\n        where: {\n          id: cust.id\n        }\n      });\n  });\n\n  return customer;\n};\n\n\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var order = sequelize.define('order', {\n    ponumber: DataTypes.STRING(30), //remove\n    orderdate: DataTypes.DATE,\n    shippingmethod: DataTypes.STRING(30),\n    shippingterms: DataTypes.STRING(30),\n    deliverydate: DataTypes.DATE,\n    paymentterms: DataTypes.STRING(30),\n    overridediscount: DataTypes.BOOLEAN,\n    shippingaddress: DataTypes.STRING(30),\n    shippingcity: DataTypes.STRING(30),\n    shippingstate: DataTypes.STRING(20),\n    shippingzipcode: DataTypes.STRING(10),\n    isactive: DataTypes.BOOLEAN\n  }, {\n      associate: function(models) {\n        // associations can be defined here\n        models.order.belongsTo(models.user);\n        models.order.belongsTo(models.customer);\n      }\n  });\n\n  order.hook('afterCreate', function(ord, options) {\n      //generate po number\n\n      return order.update({ ponumber: ponumbr }, {\n        where: {\n          id: ord.id\n        }//,\n        //transaction: options.transaction\n      });\n  });\n\n  return order;\n};\n\n'use strict';\n\nmodule.exports = function(sequelize, DataTypes) {\n  var user = sequelize.define('user', {\n    username: DataTypes.STRING(30), //remove\n    password: DataTypes.STRING(255),\n    emailaddress: DataTypes.STRING(255),\n    firstname: DataTypes.STRING(30),\n    middlename: DataTypes.STRING(30), //remove\n    lastname: DataTypes.STRING(30),\n    approve: DataTypes.BOOLEAN,\n    roles: DataTypes.STRING(50),\n    isactive: DataTypes.BOOLEAN\n  }, {\n    classMethods: {\n      associate: function(models) {\n        // associations can be defined here\n        models.user.hasMany(models.order);\n      }\n    }\n  });\n\n  user.hook('afterCreate', function(usr, options) {\n      //hash the password\n\n      return user.update({ password: passwd }, {\n        where: {\n          id: usr.id\n        }\n      });\n  });\n\n  return user;\n};\n```\n\n```text\nvar fs        = require('fs')\n    , path      = require('path')\n    , Sequelize = require('sequelize')\n    , lodash    = require('lodash')\n    , sequelize = new Sequelize('sequelize_test', 'root', 'root')\n    , db        = {} \n\n  fs.readdirSync(__dirname)\n    .filter(function(file) {\n      return (file.indexOf('.') !== 0) && (file !== 'index.js')\n    })\n    .forEach(function(file) {\n      var model = sequelize.import(path.join(__dirname, file))\n      db[model.name] = model\n    })\n\n  Object.keys(db).forEach(function(modelName) {\n    if (db[modelName].options.hasOwnProperty('associate')) {\n      db[modelName].options.associate(db)\n    }\n  })\n  // sequelize.sync({force: true})\n  module.exports = lodash.extend({\n    sequelize: sequelize,\n    Sequelize: Sequelize\n  }, db)\n```\n\n```text\ndb.order.find({\n            where: { id: 0 },\n            include: [ db.customer, db.user ]\n        })\n        .then(function(order){\n            console.log(order)\n        })\n```\n\n========================================\n\nComments:\n- That did it. Thanks a million. One more question, if you don't mind. So far I have been adding the foreign keys by setting the property before I create or update the record, like '...id = '. Is there a preferred method for doing this, or is this approach acceptable?\n- I did get your question that clearly, but if you already have the ids of the model you want to associate and you can use your method for creating records using id for simple association like one to many or one to one","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":438,"estimatedTokens":2963}}272{"id":"stack-50977198","source":"stackoverflow","questionId":50977198,"title":"Is there a way to disable timestamp columns globally for all models?","tags":["node.js","sequelize.js"],"text":"Title: Is there a way to disable timestamp columns globally for all models?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo I can disable the timestamp columns for a particular model but is there a way to disable it for all models?\n\n```\nconst Contract = sequelize.define('Contract', {\n idContract: {\n type: Sequelize.INTEGER,\n primaryKey: true\n },\n AccountNo_Lender: {\n type: Sequelize.STRING\n }\n}, { timestamps: false });\n```\n\n========================================\n\nTop Answer:\nThe Sequelize constructor takes a define option which will change the default options for all defined models.\n\n```\nconst sequelize = new Sequelize(connectionURI, {\n define: {\n // The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created.\n // This was true by default, but now is false by default\n timestamps: false\n }\n});\n\n// Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created.\nclass Foo extends Model {}\nFoo.init({ /* ... */ }, { sequelize });\n\n// Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created.\nclass Bar extends Model {}\nBar.init({ /* ... */ }, { sequelize, timestamps: true });\n```\n\ndocs\n\n========================================\n\nCode:\n```text\nconst Contract = sequelize.define('Contract', {\n    idContract: {\n        type: Sequelize.INTEGER,\n        primaryKey: true\n    },\n    AccountNo_Lender: {\n        type: Sequelize.STRING\n    }\n}, { timestamps: false });\n```\n\n```text\nconst sequelize = new Sequelize('test', 'postgres', 'postgres', {\n  host: '127.0.0.1',\n  dialect: 'postgres',\n  define: {\n    timestamps: false\n  },\n});\n```\n\n```text\nsequelize\n```\n\n```text\ndefine\n```\n\n```text\nconst sequelize = new Sequelize(connectionURI, {\n  define: {\n    // The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created.\n    // This was true by default, but now is false by default\n    timestamps: false\n  }\n});\n\n// Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created.\nclass Foo extends Model {}\nFoo.init({ /* ... */ }, { sequelize });\n\n// Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created.\nclass Bar extends Model {}\nBar.init({ /* ... */ }, { sequelize, timestamps: true });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":94,"estimatedTokens":588}}273{"id":"stack-14332376","source":"stackoverflow","questionId":14332376,"title":"How to prevent Sequelize from inserting NULL for primary keys with Postgres","tags":["node.js","postgresql","sequelize.js"],"text":"Title: How to prevent Sequelize from inserting NULL for primary keys with Postgres\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have created a table in postgresql 9\n\n```\ncreate table stillbirth(id serial primary key, state varchar(100), count int not null, year int not null);\n```\n\ntrying to write a sample on node.js with sequelize 1.4.1 version. \n\nmapped the above table as \n\n```\nvar StillBirth = sequelize.define('stillbirth',\n{ id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},\nstate: Sequelize.STRING,\nyear: Sequelize.INTEGER,\ncount: Sequelize.INTEGER\n}, {timestamps: false, freezeTableName: true});\n```\n\nnow when i try to create a new instance of Stillbirth and save it, i get errors. \n\n/** new instance create code **/\n\n```\nStillBirth\n .build({state: objs[j].state, year: objs[j].year, count: objs[j].count})\n .save()\n .error(function(row){\n console.log('could not save the row ' + JSON.stringify(row));\n })\n .success(function(row){\n console.log('successfully saved ' + JSON.stringify(row));\n })\n```\n\nerror i get\n\n*Executing: INSERT INTO \"stillbirth\" (\"state\",\"year\",\"count\",\"id\") VALUES ('Andhra Pradesh',2004,11,NULL) RETURNING ;\ncould not save the row {\"length\":110,\"name\":\"error\",\"severity\":\"ERROR\",\"code\":\"23502\",\"file\":\"execMain.c\",\"line\":\"1359\",\"routine\":\"ExecConstraints\"}\n\nIf you look at the sql that its generating, it puts null for the primary key which should ideally be generated by the db. \n\nCan someone help me as to what am i missing here ?\n\n========================================\n\nTop Answer:\nTo expand on the answer from `sdepold`, as he recommended, you can `omitNull` to prevent sequelize from adding `null` values to the generated SQL. In general, this is good, and it also allows you to perform partial updates.\n\n```\nvar sequelize = new Sequelize('db', 'user', 'pw', {\n omitNull: true\n})\n```\n\nThere is one caveat, though. How do you set a column to `null` if that's legitimately what you want to do?? The answer is that you can pass `omitNull` as part of your save.\n\n```\nuser.address = null;\nuser.save({omitNull: false});\n```\n\nOR\n\n```\nuser.update({address: null}, {omitNull: false});\n```\n\n========================================\n\nCode:\n```text\ncreate table stillbirth(id serial primary key, state varchar(100), count int not null, year int not null);\n```\n\n```text\nvar StillBirth = sequelize.define('stillbirth',\n{ id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},\nstate: Sequelize.STRING,\nyear: Sequelize.INTEGER,\ncount: Sequelize.INTEGER\n}, {timestamps: false, freezeTableName: true});\n```\n\n```text\nStillBirth\n   .build({state: objs[j].state, year: objs[j].year, count: objs[j].count})\n   .save()\n   .error(function(row){\n         console.log('could not save the row ' + JSON.stringify(row));\n        })\n   .success(function(row){\n       console.log('successfully saved ' + JSON.stringify(row));\n   })\n```\n\n```text\nvar sequelize = new Sequelize('db', 'user', 'pw', {\n  omitNull: true\n})\n```\n\n```text\nomitNull\n```\n\n```text\ndisable inserting undefined values as NULL\n```\n\n```text\nStillBirth\n   .build({state: objs[j].state, year: objs[j].year, count: objs[j].count})\n   .save(['state','year','count'])\n   .error(function(row){\n         console.log('could not save the row ' + JSON.stringify(row));\n        })\n   .success(function(row){\n       console.log('successfully saved ' + JSON.stringify(row));\n   })\n```\n\n```js\nvar sequelize = new Sequelize('db', 'user', 'pw', {\n  omitNull: true\n})\n```\n\n```js\nuser.address = null;\nuser.save({omitNull: false});\n```\n\n```js\nuser.update({address: null}, {omitNull: false});\n```\n\n```text\nsdepold\n```\n\n```text\nomitNull\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\nomitNull\n```\n\n```text\nUser.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user => {\n  // let's assume the default of isAdmin is false:\n  console.log(user.get({\n    plain: true\n  })) // => { username: 'barfooz', isAdmin: false }\n})\n```\n\n========================================\n\nComments:\n- Thanks that worked with the 1.5.x version, surprisingly the NPM registry npmjs.org/package/sequelize doesnt mention anything about the 1.5.0 version.\n- The problem with this solution is that when you try to perform an update like this user.save({address:null}); it doesn't change the address in the DB. Is there any way to perform an update an set an attribute to null?\n- Given the rate their docs mutate, that link is long dead. Sure would like to know what's going on with this because it just started happening to me and I want to know why.\n- @lao, this is a global setting. You can always pass a local override: `user.save({address:null}, {omitNull: false})`","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":178,"estimatedTokens":1173}}274{"id":"stack-43717995","source":"stackoverflow","questionId":43717995,"title":"Sequelize include even if it's null","tags":["mysql","node.js","express","orm","sequelize.js"],"text":"Title: Sequelize include even if it's null\nTags: mysql, node.js, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize express with Node.js as the backend, some data from my sequelize I need to include to another table but some of these data is null so the whole result I’m getting is null.\n\n**Question:** how can I return some data if data it's available and return the other null if not data is there \n\n```\nrouter.get(\"/scheduled/:id\", function(req, res, next) {\n\n models.Order.findOne({\n\n where: {\n id: req.params.id\n },\n attributes: ['orderStatus', 'id', 'serviceId', 'orderDescription', 'orderScheduledDate'],\n include: [{\n model: models.User,\n attributes: ['firstName', 'phoneNumber']\n }]\n }).then(function(data) {\n\n res.status(200).send({\n data: data,\n serviceName: data[\"serviceId\"]\n });\n\n });\n\n});\n```\n\n**I want:** the result should return null if there is no user for the order and return order details and user when it is null.\n\n========================================\n\nTop Answer:\nYou can add attribute `required: false,` \n\n```\nconst result = await company.findAndCountAll({\n where: conditions,\n distinct: true,\n include: [\n media,\n {\n model: tag,\n where: tagCond,\n },\n { model: users, where: userCond, attributes: ['id'] },\n {\n model: category_company,\n as: 'categoryCompany',\n where: categoryCond,\n },\n { model: media, as: 'logoInfo' },\n { model: city, as: 'city' },\n {\n model: employee,\n as: 'employees',\n required: false,\n include: [{\n model: media,\n as: 'avatarInfo',\n }],\n where: {\n publish: {\n [Op.ne]: -1,\n },\n },\n },\n ],\n order: [['createdAt', 'DESC']],\n ...paginate({ currentPage: page, pageSize: limit }),\n });\n```\n\n========================================\n\nCode:\n```text\nrouter.get(\"/scheduled/:id\", function(req, res, next) {\n\n    models.Order.findOne({\n\n        where: {\n            id: req.params.id\n        },\n        attributes: ['orderStatus', 'id', 'serviceId', 'orderDescription', 'orderScheduledDate'],\n        include: [{\n            model: models.User,\n            attributes: ['firstName', 'phoneNumber']\n        }]\n    }).then(function(data) {\n\n        res.status(200).send({\n            data: data,\n            serviceName: data[\"serviceId\"]\n        });\n\n    });\n\n});\n```\n\n```text\nvar users  = require('./database/models').user;\n\n    models.Order.findOne({\n    where: {\n        id: req.params.id\n    },attributes: ['orderStatus','id','serviceId','orderDescription','orderScheduledDate'],\n    include: [\n        {model: users,required: false,\n        attributes: ['firstName','phoneNumber']\n        }\n    ]\n}).then(function(data) {\n\n    res.status(200).send({data : data,serviceName : data[\"serviceId\"]});\n\n});\n```\n\n```text\nwhere\n```\n\n```text\ninner join\n```\n\n```text\nrequired: false\n```\n\n```text\nconst result = await company.findAndCountAll({\n        where: conditions,\n        distinct: true,\n        include: [\n          media,\n          {\n            model: tag,\n            where: tagCond,\n          },\n          { model: users, where: userCond, attributes: ['id'] },\n          {\n            model: category_company,\n            as: 'categoryCompany',\n            where: categoryCond,\n          },\n          { model: media, as: 'logoInfo' },\n          { model: city, as: 'city' },\n          {\n            model: employee,\n            as: 'employees',\n            required: false,\n            include: [{\n              model: media,\n              as: 'avatarInfo',\n            }],\n            where: {\n              publish: {\n                [Op.ne]: -1,\n              },\n            },\n          },\n        ],\n        order: [['createdAt', 'DESC']],\n        ...paginate({ currentPage: page, pageSize: limit }),\n      });\n```\n\n```text\nrequired: false,\n```\n\n========================================\n\nComments:\n- many thnx bro , i just removed the where and now i can return the parent data , it's already relation so no need to do where.\n- My code was working perfectly fine yesterday until today my queries started returning the equivalent of `users: null` in the Sequelize instance when I hadn't changed *anything*. I set `required` and it started working again. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":185,"estimatedTokens":1036}}275{"id":"stack-25363782","source":"stackoverflow","questionId":25363782,"title":"How to have a self-referencing many-to-many association in Sequelize?","tags":["sequelize.js"],"text":"Title: How to have a self-referencing many-to-many association in Sequelize?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a model called `Task`, which can have many parent tasks (multiple ancestors) and/or child tasks.\n\nIf I were to model this without Sequelize, I'd have a table called `ParentTasks`, which would have a `ParentTaskId` and a `TaskId` to determine the relationship and a `Tasks` table with an `id` as the primary key.\n\nUsing Sequelize, is this possible? I've tried so many different permutations and combinations, but none lead to what I want.\n\nAny help would be appreciated.\n\nThanks.\n\n========================================\n\nTop Answer:\nWhat have you tried?\n\nHow about this:\n\n```\nvar Task = sequelize.define('Task', {\n name: Sequelize.STRING\n});\n\nTask.belongsToMany(Task, { as: 'children', foreignKey: 'ParentTaskId', through: 'ParentTasks' });\nTask.belongsToMany(Task, { as: 'parents', foreignKey: 'TaskId', through: 'ParentTasks' });\n```\n\nplease refer to https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html\n\n========================================\n\nCode:\n```text\nTask\n```\n\n```text\nParentTasks\n```\n\n```text\nParentTaskId\n```\n\n```text\nTaskId\n```\n\n```text\nTasks\n```\n\n```text\nid\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Users = sequelize.define('Users', {\n    id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      allowNull: false,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false\n    }\n  }, {\n    freezeTableName: true\n  });\n\n  Users.associate = function(models) {\n    Users.belongsToMany(models.Users, { through: models.UserUsers, as: 'Parents', foreignKey: 'parentId' });\n    Users.belongsToMany(models.Users, { through: models.UserUsers, as: 'Siblings', foreignKey: 'siblingId' });\n  };\n\n  return Users;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const UserUsers = sequelize.define('UserUsers', {\n  }, {\n    freezeTableName: true\n  });\n\n  UserUsers.associate = function(models) {\n    UserUsers.belongsTo(models.Users, { as: 'Parent', onDelete: 'CASCADE'});\n    UserUsers.belongsTo(models.Users, { as: 'Sibling', onDelete: 'CASCADE' });\n  };\n\n  return UserUsers;\n};\n```\n\n```text\nmodels.Users.findOne({ where: { name: 'name' } })\n.then(u1 => {\n  models.Users.findOne({ where: { name: 'name2'} })\n  .then(u2 => {\n    u2.addSibling(u1);\n    // or if you have a list of siblings you can use the function:\n    u2.addSiblings([u1, ...more siblings]);\n  });\n});\n```\n\n```text\nmodels.Users.findOne({ where: { name: 'name'} })\n.then(person => {\n  person.getSiblings()\n  .then(siblings => { console.log(siblings) });\n});\n```\n\n```text\nvar Task = sequelize.define('Task', {\n  name: Sequelize.STRING\n});\n\nTask.belongsToMany(Task, { as: 'children', foreignKey: 'ParentTaskId', through: 'ParentTasks' });\nTask.belongsToMany(Task, { as: 'parents', foreignKey: 'TaskId', through: 'ParentTasks' });\n```\n\n========================================\n\nComments:\n- Can you give me a code example?\n- When I open the given link there are lots of code examples on that page. Maybe YOU need to give any code example(s) of the code that is not working for you. It seems you ask a generic question, but have a very specific one in mind. I guess, most people at stackoverflow are not good at mind reading.\n- @Quicker You should usually post that here in case the page 404s. Which is has.\n- @Noah: 1,5 year the link was outdated - I deleted that comment with the link; just for others: there were/are those informaton at sequelizejs.com (use g***)\n- Hey, looks like the answer is out of date... I'm getting the following error: N:M associations are not supported with hasMany. Use belongsToMany instead","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":139,"estimatedTokens":937}}276{"id":"stack-67445513","source":"stackoverflow","questionId":67445513,"title":"Getting Error: Unknown authenticationOk message typeMessage { name: 'authenticationOk', length: 23 }","tags":["node.js","postgresql","sequelize.js","sequelize-cli","postgresql-13"],"text":"Title: Getting Error: Unknown authenticationOk message typeMessage { name: 'authenticationOk', length: 23 }\nTags: node.js, postgresql, sequelize.js, sequelize-cli, postgresql-13\nSource: Stack Overflow\n\nQuestion:\nI have installed Postgres 13 in windows 10.\nConfigured all the right credentials in the environment file of the project.\nThe project uses the below dependencies and it was created in ubuntu.\n\n```\n\"pg\": \"^7.4.3\",\n\"pg-hstore\": \"^2.3.2\",\n\"sequelize\": \"4.38.0\",\n\"sequelize-cli\": \"^6.2.0\"\n```\n\nI'm trying to set it up in windows.\nAnd getting the below error in windows 10.\n\n```\nError: Unknown authenticationOk message typeMessage { name: 'authenticationOk', length: 23 }\n```\n\nWhen I hit\n`npx sequelize db:migrate`\nin the terminal for migrating the tables in the database.\n\n========================================\n\nTop Answer:\nBased on the comment by @nanaya here\n\nYou can try to use `pg-native`, and set env to `NODE_PG_FORCE_NATIVE=1` before executing the migration.\n\n```\n$ npm i pg-native\n$ export NODE_PG_FORCE_NATIVE=1\n$ npx sequelize db:migrate\n```\n\n========================================\n\nCode:\n```text\n\"pg\": \"^7.4.3\",\n\"pg-hstore\": \"^2.3.2\",\n\"sequelize\": \"4.38.0\",\n\"sequelize-cli\": \"^6.2.0\"\n```\n\n```text\nError: Unknown authenticationOk message typeMessage { name: 'authenticationOk', length: 23 }\n```\n\n```text\nnpx sequelize db:migrate\n```\n\n```text\npg\n```\n\n```text\n\"^7.4.3\"\n```\n\n```text\n\"^8.7.1\"\n```\n\n```text\n$ npm i pg-native\n$ export NODE_PG_FORCE_NATIVE=1\n$ npx sequelize db:migrate\n```\n\n```text\npg-native\n```\n\n```text\nNODE_PG_FORCE_NATIVE=1\n```\n\n========================================\n\nComments:\n- Yes, the same solution worked for me.\n- This worked for me as well. The situation was different but the error was the same.","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":89,"estimatedTokens":436}}277{"id":"stack-33429383","source":"stackoverflow","questionId":33429383,"title":"Sequelize migration order of execution","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize migration order of execution\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI can't seem to find the answer to this anywhere. I understand how Sequelize migrations and seeder work, but I have not found anywhere that states if they execute in some particular order. So if I start with a database, make a bunch of migrations, and then decide to initialize a brand new database from the original start point, will it execute the migrations in the exact same order. \n\nI am using sequelize-cli to create migrations, so the file name does begin with a timestamp.\n\n========================================\n\nComments:\n- I am not sure this is always true though. For example, in OSX, 100migration.js will appear before 10migrations.js. The same argument is true for timestamps.\n- Timestamps always have the same number of characters unlike 10 vs 100. Sort order goes character by character until it reaches a character that isn't the same\n- See you on 21st November, 2286 :)","metadata":{"transformedAt":"2026-08-18T18:33:34.361Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":15,"estimatedTokens":253}}278{"id":"stack-41495110","source":"stackoverflow","questionId":41495110,"title":"DAO vs ORM - Concept explained in the context of Sequelize.js","tags":["javascript","orm","sequelize.js","dao"],"text":"Title: DAO vs ORM - Concept explained in the context of Sequelize.js\nTags: javascript, orm, sequelize.js, dao\nSource: Stack Overflow\n\nQuestion:\nI've been working with Sequelize.js recently and come across the term \"DAO\" pretty frequently. Coming from ActiveRecord (in Rails), the idea of an ORM seems pretty straight forward.\n\nCould someone explain to me what a DAO is? How does it differ from an ORM? How does it result in more modular code/prevent abstraction leaking?\n\nEdit: After reading things like: https://www.reddit.com/r/learnprogramming/comments/32a1fr/what_is_the_general_difference_between_dao_and_orm/\n\nIt feels/seems like a DAO could be thought of as a singular \"model\" - as in the context of ActiveRecord, my User instance would be considered a DAO in that it: \"***abstracts the implementation of a persistent data store away from the application and allows for simple interaction with it***\"?\n\n========================================\n\nTop Answer:\nI am not too familiar with ActiveRecord but yes, it sounds like your User instance is indeed a DAO.\n\nThe previous answer has some confusing aspects in it which I hope to clarify.\n\nAccording to Oracle's description of the DAO pattern it:\n\n- separates a data resource's client interface from its data access mechanisms\n\n- adapts a specific data resource's access API to a generic client interface\n\n**The DAO pattern allows data access mechanisms to change independently of the code that uses the data.**\n\nThat being said, manually executing a SQL statement using a language's SQL driver would almost never be referred to as a DAO. Firstly, it doesn't abstract the data access mechanism *enough* to be of any practical value. You couldn't, say, swap your DB for a NoSQL backend without having to reimplement ActiveRecord's `execute` method to map SQL queries into the new backend's API.\n\nThat being said, some practical examples:\n\n```\n// Cloudscape concrete DAO Factory implementation\nimport java.sql.*;\n\npublic class CloudscapeDAOFactory extends DAOFactory {\n public static final String DRIVER=\n \"COM.cloudscape.core.RmiJdbcDriver\";\n public static final String DBURL=\n \"jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB\";\n\n // method to create Cloudscape connections\n public static Connection createConnection() {\n // Use DRIVER and DBURL to create a connection\n // Recommend connection pool implementation/usage\n }\n public CustomerDAO getCustomerDAO() {\n // CloudscapeCustomerDAO implements CustomerDAO\n return new CloudscapeCustomerDAO();\n }\n public AccountDAO getAccountDAO() {\n // CloudscapeAccountDAO implements AccountDAO\n return new CloudscapeAccountDAO();\n }\n public OrderDAO getOrderDAO() {\n // CloudscapeOrderDAO implements OrderDAO\n return new CloudscapeOrderDAO();\n }\n ...\n}\n```\n\nAs shown, the DAO *factory* sets up any connections with the underlying DB. This configuration is abstracted from the client.\n\n```\n// Interface that all CustomerDAOs must support\npublic interface CustomerDAO {\n public int insertCustomer(...);\n public boolean deleteCustomer(...);\n public Customer findCustomer(...);\n public boolean updateCustomer(...);\n public RowSet selectCustomersRS(...);\n public Collection selectCustomersTO(...);\n ...\n}\n```\n\nAs you can see, the DAO is meant to provide an object with a narrow interface to control and abstract access to the data layer. At any time, one could reimplement `findCustomer` to query a NoSQL DB and the calling code wouldn't need to change. Thus **\"The DAO pattern allows data access mechanisms to change independently of the code that uses the data.\"**\n\nThe DAO illustrated above may use an ORM library in the implementation to map the DB objects into models of the calling code or the implementation may perform the mapping itself. In any case, if the interface were changed so that `findCustomer` returns a plain object and did no mapping, it would still be a DAO. **A DAO does not need an ORM** but often uses one.\n\nAn ORM can potentially perform all of its DB access using raw methods like the programming language's method for establishing TCP connections. So **An ORM does not need a DAO** but often uses one.\n\nThe fundamental feature of an ORM is that it *maps* DB objects into domain models. If an ORM library also handles communications with the DB, whether it uses a DAO or opens TCP connections to the DB, then **it is itself also a DAO**.\n\n========================================\n\nCode:\n```text\nresult = ActiveRecord::Base.connection.execute(\"select * from users limit 1\")\n```\n\n```text\n{\n  \"id\" => \"1234\",\n  \"email\" => \"fred@example.com\",\n  \"first_name\" => \"Fred\",\n  \"last_name\" => \"Flintstone\",\n}\n```\n\n```text\nActiveRecord::Base.connection.execute(\"update users set first_name = 'Bob' where id = 1234\")\n```\n\n```text\nuser = User.find(1234)\nuser.name = 'Bob'\nuser.save!\n```\n\n```text\n\"select * from users limit 1\"\n```\n\n```text\nAccess\n```\n\n```text\nData\n```\n\n```text\nObject\n```\n\n```text\nData Access Object\n```\n\n```text\nDAO\n```\n\n```text\nresult\n```\n\n```text\nUser\n```\n\n```text\nHash\n```\n\n```text\nfirst_name\n```\n\n```text\nBob\n```\n\n```text\nDAO\n```\n\n```text\nORM\n```\n\n```text\nORM\n```\n\n```text\nDAO\n```\n\n```text\nDAO\n```\n\n```text\nORM\n```\n\n```text\nORM\n```\n\n```text\nDAO\n```\n\n```text\nORM\n```\n\n```text\nObject Relational Mapper\n```\n\n```text\nMap\n```\n\n```text\nRelational\n```\n\n```text\nObjects\n```\n\n```text\nORM\n```\n\n```text\nDAO\n```\n\n```text\nDAO\n```\n\n```text\nORM\n```\n\n```text\nDAO\n```\n\n```text\n// Cloudscape concrete DAO Factory implementation\nimport java.sql.*;\n\npublic class CloudscapeDAOFactory extends DAOFactory {\n  public static final String DRIVER=\n    \"COM.cloudscape.core.RmiJdbcDriver\";\n  public static final String DBURL=\n    \"jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB\";\n\n  // method to create Cloudscape connections\n  public static Connection createConnection() {\n    // Use DRIVER and DBURL to create a connection\n    // Recommend connection pool implementation/usage\n  }\n  public CustomerDAO getCustomerDAO() {\n    // CloudscapeCustomerDAO implements CustomerDAO\n    return new CloudscapeCustomerDAO();\n  }\n  public AccountDAO getAccountDAO() {\n    // CloudscapeAccountDAO implements AccountDAO\n    return new CloudscapeAccountDAO();\n  }\n  public OrderDAO getOrderDAO() {\n    // CloudscapeOrderDAO implements OrderDAO\n    return new CloudscapeOrderDAO();\n  }\n  ...\n}\n```\n\n```text\n// Interface that all CustomerDAOs must support\npublic interface CustomerDAO {\n  public int insertCustomer(...);\n  public boolean deleteCustomer(...);\n  public Customer findCustomer(...);\n  public boolean updateCustomer(...);\n  public RowSet selectCustomersRS(...);\n  public Collection selectCustomersTO(...);\n  ...\n}\n```\n\n```text\nexecute\n```\n\n```text\nfindCustomer\n```\n\n```text\nfindCustomer\n```\n\n========================================\n\nComments:\n- \"Raw Queries\" is a specific example in which Sequelize.js mentions `DAO`: `&#47;&#47; Are you expecting a massive dataset from the DB, &#47;&#47; and don't want to spend the time building DAOs for each entry? &#47;&#47; You can pass an extra query option to get the raw data instead: Project.findAll({ where: { ... }, raw: true })`\n- Awesome response. Helped clarify a lot and confirmed some floating 'suspicions' in my mind. Thank you very much.\n- Pretty decent answer with a little more perspective to add. Say technology changes and you decide to use a data store that wasn’t a RDBMS that ActiveRecord can be used with. Your entire codebase is brittle because of how tightly coupled to the specific backend it is. A DAO is basically a factory, a facade, an abstraction to allow your application to work in conceptual models while leaving the concerns of storing, retrieving, and munging the backend to the DAO.","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":290,"estimatedTokens":1913}}279{"id":"stack-59111392","source":"stackoverflow","questionId":59111392,"title":"using findByPk and WHERE condition in sequelize","tags":["sequelize.js"],"text":"Title: using findByPk and WHERE condition in sequelize\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn Sequelize I´m using findByPk but I also need to pass another condition\n\n```\nconst options = {\n where: { role: 'admin' },\n};\n\nreturn models.User.findByPk(id, options)\n .then((user) => {...\n```\n\nBut this query is retuning all users even if the role is not admin. I checked the SQL generated and I see\nSELECT * from User WHERE id = 1 but I don´t see the AND role = 'admin'.\nhow to use findByPk and pass another condition?\n\nthank you\n\n========================================\n\nCode:\n```text\nconst options = {\n    where: { role: 'admin' },\n};\n\nreturn models.User.findByPk(id, options)\n    .then((user) => {...\n```\n\n```js\nreturn models.User.findOne({\n  where: {\n    id: id,\n    role: 'admin', \n  },\n})\n```\n\n```text\nfindOne\n```\n\n```text\nwhere\n```\n\n```text\noptions\n```\n\n```text\nfindByPk\n```\n\n```text\nfindOne\n```\n\n========================================\n\nComments:\n- Please don't forget to mark my answer as the accepted one if it helped you. Thanks!\n- @jknotek sorry I forgot. thanks for the reminder!\n- No problem, thank you!\n- This works.....","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":70,"estimatedTokens":287}}280{"id":"stack-19461500","source":"stackoverflow","questionId":19461500,"title":"node sequelize sort by multiple columns","tags":["javascript","node.js","sequelize.js"],"text":"Title: node sequelize sort by multiple columns\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nComing from a Ruby/Rails background, I'm used to this type of syntax:\n\n`Model.all.order('col1 + col2 + col3')`\n\nSo, given that col1, col2 and col3 are integers, for example, it would sort the results by the sum of those 3 columns.\n\nIs there a similar way to sort like this using sequelize?\n\n========================================\n\nTop Answer:\n```\norder: [\n ['created_at', 'desc'],\n ['id', 'desc']\n]\n```\n\nor\n\n```\norder: [\n [sequelize.literal('created_at, id'), 'desc']\n]\n```\n\n========================================\n\nCode:\n```text\nModel.all.order('col1 + col2 + col3')\n```\n\n```text\nModel.findAll({ order: [[{ raw: 'col1 + col2 + col3 DESC' }]]});\n```\n\n```text\nORDER BY col1 + col2 + col3 DESC\n```\n\n```text\nModel.findAll({ order: [[sequelize.fn('SUM', sequelize.col('col1'), sequelize.col('col2'), sequelize.col('col3')), 'DESC']]});\n```\n\n```text\nORDER BY SUM(`col1`, `col2`, `col3`) DESC\n```\n\n```text\norder: [\n   ['created_at', 'desc'],\n   ['id', 'desc']\n]\n```\n\n```text\norder: [\n   [sequelize.literal('created_at, id'), 'desc']\n]\n```\n\n```text\norder: [[ 'col1', sequelize.literal('+'), 'col2', 'DESC']]\n```\n\n```text\nORDER BY \"tableName\".\"col1\"+\"col2\" DESC\n```\n\n```text\nfunction sum(numeric, numeric) does not exists\n```\n\n```text\nsequelize.literal('+')\n```\n\n```text\nsequelize.col('col2')\n```\n\n```text\n'tableName', sequelize.literal('.'), 'columnName'\n```\n\n```text\n{model: 'model', as: 'alias'}\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":94,"estimatedTokens":380}}281{"id":"stack-36214221","source":"stackoverflow","questionId":36214221,"title":"findAll() from Sequelize doesn't get","tags":["javascript","mysql","sequelize.js"],"text":"Title: findAll() from Sequelize doesn't get\nTags: javascript, mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize with MySQL.\n\nWhen I run this code:\n\n```\nusuarioService.getAll = function () {\n Usuario.findAll().then(function (users) {\n //return users;\n console.dir(users);\n });\n}\n```\n\nInstead of get the user, I get:\n\nhttps://i.sstatic.net/uLhmN.png\n\nHelp me, please! I'm going crazy!\n\nThanks\n\n========================================\n\nTop Answer:\nYou are returning a user. \n\nThe first bit you see is the SQL query that Sequelize is executing for you. \n\nThe bit that says \n\n```\ndataValues: \n { usuario_id: 1,\n ... \n }\n```\n\nis your user. `findAll()` should give you an array with all of your users.\n\nIf you just want the dataValues returned you can just pass in `raw: true`.\n\n```\nusuarioService.getAll = function () {\n Usuario.findAll({ raw: true }).then(function (users) {\n //return users;\n console.dir(users);\n });\n}\n```\n\n========================================\n\nCode:\n```text\nusuarioService.getAll = function () {\n    Usuario.findAll().then(function (users) {\n        //return users;\n        console.dir(users);\n    });\n}\n```\n\n```text\nusuarioService.getAll = function (cb) {\n    Usuario.findAll().then(function (users) {\n        return cb(null, users);\n    }).catch(function(err) {\n        return cb(err);\n    });\n}\n```\n\n```text\nrouter.get('your_path', function(req, res, next) {\n    serv.getAll(function(err, users) {\n        if (err) {\n            // your err handling code\n        }\n        // users is now a valid js array\n        // could send it in res.json(users)\n    });\n});\n```\n\n```text\nusuarioService.getAll = function () {\n    return Usuario.findAll({ raw: true });\n}\n```\n\n```text\nrouter.get('your_path', function(req, res, next) {\n    serv.getAll().then(function(users) {\n        res.render('usuarios/index',{\n            users: users\n        })\n    }).catch(function(err) {\n        // your error handling code here\n    });\n});\n```\n\n```text\ninstance\n```\n\n```text\ninstance\n```\n\n```text\nget({plain: true})\n```\n\n```text\nusers[0].get({plain: true})\n```\n\n```text\nusers[0].get('nombre')\n```\n\n```text\nusers[0].nombre\n```\n\n```text\ndataValues: \n   { usuario_id: 1,\n    ... \n   }\n```\n\n```text\nusuarioService.getAll = function () {\n    Usuario.findAll({ raw: true }).then(function (users) {\n        //return users;\n        console.dir(users);\n    });\n}\n```\n\n```text\nfindAll()\n```\n\n```text\nraw: true\n```\n\n========================================\n\nComments:\n- Thank you very much. But for example, in my route js I have this: var users = serv.getAll(); res.render('usuarios/index', { users: users }); And I get TypeError: /home/gercho/develop/js/voley-manager/views/usuarios/index.j&zwnj;&#8203;ade:14 12| th 13| tbody > 14| - for user in users 15| tr 16| td= user.nombre 17| td= user.apellido Cannot read property 'length' of undefined\n- Note that any hooks you may have won't work if you use `{raw: true}`.. very unfortunate characteristic of Sequelize\n- If i use { raw: true } then it wont let me use where clause in the query... i just return whole database never executing where clause. User.findAll({ where: { 'email': body.username, isActive: 'Y' } } ).then( user => {}); returns user as undefined as there was no data retrieved\n- @gerchoG you could try the `{raw: true}` suggested in the other answer by @LT-. You could also just map the results `users = users.map(function(userInstance) { return userInstance.get({ plain: true})});`. Although, if you're doing something like this, I would highly recommend a library like lodash as it's much faster than native methods. You could just then do `users = _.map(users, function(userInstance) { return userInstance.get({plain: true})});`","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":162,"estimatedTokens":929}}282{"id":"stack-57722509","source":"stackoverflow","questionId":57722509,"title":"SequelizeAssociationError: You have used the alias in two separate associations. Aliased associations must have unique aliases","tags":["sequelize.js","sequelize-typescript"],"text":"Title: SequelizeAssociationError: You have used the alias in two separate associations. Aliased associations must have unique aliases\nTags: sequelize.js, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nOn Sequelize v5 When I configuring the associations between models I got error like this.\n\n```\n/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/base.js:106\n throw new AssociationError(`You have used the alias ${options.as} in two separate associations. ` +\n ^\nSequelizeAssociationError: You have used the alias originMenu in two separate associations. Aliased associations must have unique aliases.\n at new Association (/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/base.js:106:13)\n at new BelongsTo (/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/belongs-to.js:18:5)\n at Function. (/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/mixin.js:105:25)\n at Function.Model.(anonymous function) [as belongsTo] (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/model/model/model.js:116:28)\n at associations.forEach.association (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:54:52)\n at Array.forEach ()\n at models.forEach.model (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:48:26)\n at Array.forEach ()\n at Sequelize.associateModels (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:44:16)\n at Sequelize.addModels (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:36:14)\n at Object. (/home/aditya/project/apisrv/src/repositories/pg/index.ts:44:15)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n at Module.m._compile (/home/aditya/project/apisrv/node_modules/ts-node/src/index.ts:473:23)\n at Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n at Object.require.extensions.(anonymous function) [as .ts] (/home/aditya/project/apisrv/node_modules/ts-node/src/index.ts:476:12)\n at Module.load (internal/modules/cjs/loader.js:598:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n at Module.require (internal/modules/cjs/loader.js:636:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at Object. (/home/aditya/project/apisrv/src/controllers/UserController.ts:7:1)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n```\n\nI've been checking multiple times that there are no other models using the same alias name as mentioned ('originMenu')\n\n**PS.**\n\nI'm using Sequelize v5 with typescript decorator\n\n========================================\n\nTop Answer:\nWorked for me.\nI was registering relation two times once in model creation and loaded the module into sequelize and second time while querying for fetch nested data. here is the simple code written in nodejs for better understanding.\n\n```\nlet FavDrivers = sequelize.define('favourite_drivers', {\n id: {\n type: DataTypes.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n \n}, {\n timestamps: true\n});\n\nFavDrivers.belongsTo(User, {\n as: 'driver'\n});\nFavDrivers.belongsTo(User,\n {\n as: 'rider'\n });\nexport default FavDrivers;\n```\n\nadding relation again will send you\n\nSequelizeAssociationError: You have used the alias in two separate\nassociations. Aliased associations must have unique aliases\n\n```\n// FavDrivers.belongsTo(User,\n // {\n // as: 'driver'\n // });\n\n let driver = await FavDrivers.findOne({\n where: {\n driverId: req.body.driverId,\n riderId: req.body.userId,\n },\n include: [\n {\n model: User,\n as: 'driver',\n attributes:['name','mobileNumber','profileImage','loginId','id']\n },\n \n ]\n });\n```\n\n========================================\n\nCode:\n```text\n/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/base.js:106\n      throw new AssociationError(`You have used the alias ${options.as} in two separate associations. ` +\n            ^\nSequelizeAssociationError: You have used the alias originMenu in two separate associations. Aliased associations must have unique aliases.\n    at new Association (/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/base.js:106:13)\n    at new BelongsTo (/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/belongs-to.js:18:5)\n    at Function.<anonymous> (/home/aditya/project/apisrv/node_modules/sequelize/lib/associations/mixin.js:105:25)\n    at Function.Model.(anonymous function) [as belongsTo] (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/model/model/model.js:116:28)\n    at associations.forEach.association (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:54:52)\n    at Array.forEach (<anonymous>)\n    at models.forEach.model (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:48:26)\n    at Array.forEach (<anonymous>)\n    at Sequelize.associateModels (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:44:16)\n    at Sequelize.addModels (/home/aditya/project/apisrv/node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize.js:36:14)\n    at Object.<anonymous> (/home/aditya/project/apisrv/src/repositories/pg/index.ts:44:15)\n    at Module._compile (internal/modules/cjs/loader.js:688:30)\n    at Module.m._compile (/home/aditya/project/apisrv/node_modules/ts-node/src/index.ts:473:23)\n    at Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n    at Object.require.extensions.(anonymous function) [as .ts] (/home/aditya/project/apisrv/node_modules/ts-node/src/index.ts:476:12)\n    at Module.load (internal/modules/cjs/loader.js:598:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n    at Module.require (internal/modules/cjs/loader.js:636:17)\n    at require (internal/modules/cjs/helpers.js:20:18)\n    at Object.<anonymous> (/home/aditya/project/apisrv/src/controllers/UserController.ts:7:1)\n    at Module._compile (internal/modules/cjs/loader.js:688:30)\n```\n\n```text\nlet FavDrivers = sequelize.define('favourite_drivers', {\n    id: {\n        type: DataTypes.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    },\n \n}, {\n    timestamps: true\n});\n\nFavDrivers.belongsTo(User, {\n    as: 'driver'\n});\nFavDrivers.belongsTo(User,\n    {\n        as: 'rider'\n    });\nexport default FavDrivers;\n```\n\n```text\n// FavDrivers.belongsTo(User,\n                //     {\n                //         as: 'driver'\n                //     });\n\n                let driver = await FavDrivers.findOne({\n                    where: {\n                        driverId: req.body.driverId,\n                        riderId: req.body.userId,\n                    },\n                    include: [\n                        {\n                            model: User,\n                            as: 'driver',\n                            attributes:['name','mobileNumber','profileImage','loginId','id']\n                        },\n                       \n                    ]\n                });\n```\n\n========================================\n\nComments:\n- @KyleFarris, the same +1 )\n- Solved . I was adding belongsTo() two times.","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":178,"estimatedTokens":1840}}283{"id":"stack-62556633","source":"stackoverflow","questionId":62556633,"title":"Sequelize 6 import models from file","tags":["node.js","sequelize.js"],"text":"Title: Sequelize 6 import models from file\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI would like to know how can I import the models from file with Sequelize 6 ?\n\nIt works with \"sequelize\": \"^5.22.0\",\n\"sequelize-cli\": \"^5.5.1\", but I have an error with Sequelize 6.\n\nCurrently, I have this :\n\ndatabase/setup/databaseConnection.js\n\n```\n// Imports\nimport { Sequelize } from \"sequelize\"\n\nconst connection = new Sequelize(\n process.env.DATABASE_NAME,\n process.env.DATABASE_USER,\n process.env.DATABASE_PASSWORD,\n {\n host: process.env.DATABASE_URL,\n port: process.env.DATABASE_PORT,\n dialect: \"mysql\",\n logging: false,\n define: {\n // prevent sequelize from pluralizing table names\n freezeTableName: true,\n },\n }\n)\n\n// Test connection\nconsole.info(\"SETUP - Connecting database...\")\n\nconnection\n .authenticate()\n .then(() => {\n console.info(\"INFO - Database connected.\")\n })\n .catch((err) => {\n console.error(\"ERROR - Unable to connect to the database:\", err)\n })\n\nexport { connection as default }\n```\n\ndatabase/models/index.js\n\n```\n// Imports\nimport Sequelize from \"sequelize\"\n\n// App Imports\nimport connection from \"../setup/databaseConnection\"\n\nconst models = {\n Language: connection.import(\"./language\"),\n}\n\nObject.keys(models).forEach((modelName) => {\n if (\"associate\" in models[modelName]) {\n models[modelName].associate(models)\n }\n})\n\nmodels.sequelize = connection\nmodels.Sequelize = Sequelize\n\nexport { models as default }\n```\n\ndatabase/models/language.js\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Language = sequelize.define(\n \"language\",\n {\n /* id : {\n primaryKey: true,\n type : DataTypes.INTEGER\n }, */\n name: {\n type: DataTypes.STRING,\n },\n code: {\n type: DataTypes.STRING,\n },\n is_active: {\n type: DataTypes.BOOLEAN,\n },\n },\n {}\n )\n Language.associate = function (models) {\n // Language has Many Bucket\n models.Language.hasMany(models.Bucket, {\n foreignKey: \"id\",\n })\n }\n return Language\n}\n```\n\nBut I have this error :\n\n```\nformation-api/database/models/index.js:17\n Language: _databaseConnection[\"default\"][\"import\"](\"./language\")\n ^\n\nTypeError: _databaseConnection.default.import is not a function\n at Object. (/Users/jeremiechazelle/Sites/api/database/models/index.js:8:15)\n at Module._compile (internal/modules/cjs/loader.js:1147:30)\n at Module._compile (/Users/jeremiechazelle/Sites/api/node_modules/pirates/lib/index.js:99:24)\n at Module._extensions..js (internal/modules/cjs/loader.js:1167:10)\n at Object.newLoader [as .js] (/Users/jeremiechazelle/Sites/api/node_modules/pirates/lib/index.js:104:7)\n at Module.load (internal/modules/cjs/loader.js:996:32)\n at Function.Module._load (internal/modules/cjs/loader.js:896:14)\n at Module.require (internal/modules/cjs/loader.js:1036:19)\n at require (internal/modules/cjs/helpers.js:72:18)\n at Object. (/Users/jeremiechazelle/Sites/api/resolvers/Queries/User.js:2:1)\n[nodemon] app crashed - waiting for file changes before starting...\n```\n\nI use :\n\"sequelize\": \"^6.1.0\",\n\"sequelize-cli\": \"^6.0.0\"\n\n========================================\n\nTop Answer:\nSequelize ^6.x not longer support sequelize.import. They say that you should use require instead.\n\nI understand that you have to import models manually.\n\nHere is an example using require\n\n./models/index.js\n\n```\nconst dotenv = require('dotenv');\nconst fs = require('fs');\nconst path = require('path');\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst filebasename = path.basename(__filename);\nconst db = {};\n\n// Get env var from .env\ndotenv.config()\nconst { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_FORCE_RESTART } = process.env;\n\nconst config = {\n host: DB_HOST,\n dialect: 'mysql',\n dialectOptions: {\n charset: 'utf8',\n }\n}\n\nconst sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, config);\n\nfs\n .readdirSync(__dirname)\n .filter((file) => {\n const returnFile = (file.indexOf('.') !== 0)\n && (file !== filebasename)\n && (file.slice(-3) === '.js');\n return returnFile;\n })\n .forEach((file) => {\n const model = require(path.join(__dirname, file))(sequelize, DataTypes)\n db[model.name] = model;\n });\n\nObject.keys(db).forEach((modelName) => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nconst sequelizeOptions = { logging: console.log, };\n\n// Removes all tables and recreates them (only available if env is not in production)\nif (DB_FORCE_RESTART === 'true' && process.env.ENV !== 'production') {\n sequelizeOptions.force = true;\n}\n\nsequelize.sync(sequelizeOptions)\n .catch((err) => {\n console.log(err);\n process.exit();\n });\n\nmodule.exports = db;\n```\n\n./models/User.js\n\n```\n'use strict';\n\nimport cryp from 'crypto';\n\nmodule.exports = function (sequelize, DataTypes) {\n const User = sequelize.define('User', {\n email: {\n type: DataTypes.STRING(50),\n allowNull: false,\n unique: true,\n validate: {\n isEmail: { msg: \"Please enter a valid email addresss\" }\n },\n isEmail: true\n },\n password_hash: { type: DataTypes.STRING(80), allowNull: false },\n password: {\n type: DataTypes.VIRTUAL,\n set: function (val) {\n //this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated\n this.setDataValue('password_hash', cryp.createHash(\"md5\").update(val).digest(\"hex\"));\n },\n validate: {\n isLongEnough: function (val) {\n if (val.length .env\n\n```\nDB_HOST=localhost\nDB_USER=wilo087\nDB_PASS=temp\nDB_NAME=database_name\nDB_FORCE_RESTART=true #Remove and create tables\n```\n\nFull example on:\nhttps://github.com/wilo087/pethome_raffle_backend/tree/develop\n\n========================================\n\nCode:\n```text\n// Imports\nimport { Sequelize } from \"sequelize\"\n\nconst connection = new Sequelize(\n    process.env.DATABASE_NAME,\n    process.env.DATABASE_USER,\n    process.env.DATABASE_PASSWORD,\n    {\n        host: process.env.DATABASE_URL,\n        port: process.env.DATABASE_PORT,\n        dialect: \"mysql\",\n        logging: false,\n        define: {\n            // prevent sequelize from pluralizing table names\n            freezeTableName: true,\n        },\n    }\n)\n\n// Test connection\nconsole.info(\"SETUP - Connecting database...\")\n\nconnection\n    .authenticate()\n    .then(() => {\n        console.info(\"INFO - Database connected.\")\n    })\n    .catch((err) => {\n        console.error(\"ERROR - Unable to connect to the database:\", err)\n    })\n\nexport { connection as default }\n```\n\n```text\n// Imports\nimport Sequelize from \"sequelize\"\n\n// App Imports\nimport connection from \"../setup/databaseConnection\"\n\nconst models = {\n    Language: connection.import(\"./language\"),\n}\n\nObject.keys(models).forEach((modelName) => {\n    if (\"associate\" in models[modelName]) {\n        models[modelName].associate(models)\n    }\n})\n\nmodels.sequelize = connection\nmodels.Sequelize = Sequelize\n\nexport { models as default }\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Language = sequelize.define(\n        \"language\",\n        {\n            /* id       : {\n         primaryKey: true,\n         type      : DataTypes.INTEGER\n         }, */\n            name: {\n                type: DataTypes.STRING,\n            },\n            code: {\n                type: DataTypes.STRING,\n            },\n            is_active: {\n                type: DataTypes.BOOLEAN,\n            },\n        },\n        {}\n    )\n    Language.associate = function (models) {\n        // Language has Many Bucket\n        models.Language.hasMany(models.Bucket, {\n            foreignKey: \"id\",\n        })\n    }\n    return Language\n}\n```\n\n```text\nformation-api/database/models/index.js:17\n  Language: _databaseConnection[\"default\"][\"import\"](\"./language\")\n                                                    ^\n\nTypeError: _databaseConnection.default.import is not a function\n    at Object.<anonymous> (/Users/jeremiechazelle/Sites/api/database/models/index.js:8:15)\n    at Module._compile (internal/modules/cjs/loader.js:1147:30)\n    at Module._compile (/Users/jeremiechazelle/Sites/api/node_modules/pirates/lib/index.js:99:24)\n    at Module._extensions..js (internal/modules/cjs/loader.js:1167:10)\n    at Object.newLoader [as .js] (/Users/jeremiechazelle/Sites/api/node_modules/pirates/lib/index.js:104:7)\n    at Module.load (internal/modules/cjs/loader.js:996:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:896:14)\n    at Module.require (internal/modules/cjs/loader.js:1036:19)\n    at require (internal/modules/cjs/helpers.js:72:18)\n    at Object.<anonymous> (/Users/jeremiechazelle/Sites/api/resolvers/Queries/User.js:2:1)\n[nodemon] app crashed - waiting for file changes before starting...\n```\n\n```text\nimport Sequelize from 'sequelize'\n\nimport userModel from './user'\nimport messageModel from './message'\n\nconst sequelize = new Sequelize(process.env.DATABASE, process.env.DATABASE_USER, process.env.DATABASE_PASSWORD, {\n    dialect: 'postgres'\n})\n\nconst models = {\n    User: userModel(sequelize, Sequelize.DataTypes),\n    Message: messageModel(sequelize, Sequelize.DataTypes)\n}\n```\n\n```js\nconst dotenv = require('dotenv');\nconst fs = require('fs');\nconst path = require('path');\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst filebasename = path.basename(__filename);\nconst db = {};\n\n// Get env var from .env\ndotenv.config()\nconst { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_FORCE_RESTART } = process.env;\n\nconst config = {\n  host: DB_HOST,\n  dialect: 'mysql',\n  dialectOptions: {\n    charset: 'utf8',\n  }\n}\n\nconst sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, config);\n\nfs\n  .readdirSync(__dirname)\n  .filter((file) => {\n    const returnFile = (file.indexOf('.') !== 0)\n      && (file !== filebasename)\n      && (file.slice(-3) === '.js');\n    return returnFile;\n  })\n  .forEach((file) => {\n    const model = require(path.join(__dirname, file))(sequelize, DataTypes)\n    db[model.name] = model;\n  });\n\n\nObject.keys(db).forEach((modelName) => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nconst sequelizeOptions = { logging: console.log, };\n\n// Removes all tables and recreates them (only available if env is not in production)\nif (DB_FORCE_RESTART === 'true' && process.env.ENV !== 'production') {\n  sequelizeOptions.force = true;\n}\n\nsequelize.sync(sequelizeOptions)\n  .catch((err) => {\n    console.log(err);\n    process.exit();\n  });\n\nmodule.exports = db;\n```\n\n```js\n'use strict';\n\nimport cryp from 'crypto';\n\nmodule.exports = function (sequelize, DataTypes) {\n  const User = sequelize.define('User', {\n    email: {\n      type: DataTypes.STRING(50),\n      allowNull: false,\n      unique: true,\n      validate: {\n        isEmail: { msg: \"Please enter a valid email addresss\" }\n      },\n      isEmail: true\n    },\n    password_hash: { type: DataTypes.STRING(80), allowNull: false },\n    password: {\n      type: DataTypes.VIRTUAL,\n      set: function (val) {\n        //this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated\n        this.setDataValue('password_hash', cryp.createHash(\"md5\").update(val).digest(\"hex\"));\n      },\n      validate: {\n        isLongEnough: function (val) {\n          if (val.length < 8) {\n            throw new Error(\"Please choose a longer password\");\n          }\n        }\n      }\n    },\n    role: {\n      type: DataTypes.INTEGER,\n      allowNull: false\n    },\n    active: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      defaultValue: 1\n    }\n\n  }, {\n    classMethods: {\n      associate: function (models) {\n        // User.belongsTo(models.Department, { foreignKey: { allowNull: false } });\n        // User.belongsTo(models.Position, { foreignKey: { allowNull: false } });\n        // User.belongsTo(models.Profile, { foreignKey: { allowNull: false } });\n\n        // User.hasMany(models.Report, { foreignKey: { allowNull: false } });\n        // User.hasMany(models.Notification, { foreignKey: { allowNull: false } });\n        // User.hasMany(models.Response, { foreignKey: { allowNull: false } });\n\n      }\n    },\n\n    timestamps: true,\n\n    // don't delete database entries but set the newly added attribute deletedAt\n    // to the current date (when deletion was done). paranoid will only work if\n    // timestamps are enabled\n    paranoid: false,\n\n    // don't use camelcase for automatically added attributes but underscore style\n    // so updatedAt will be updated_at\n    underscored: true\n  });\n  return User;\n};\n```\n\n```sh\nDB_HOST=localhost\nDB_USER=wilo087\nDB_PASS=temp\nDB_NAME=database_name\nDB_FORCE_RESTART=true #Remove and create tables\n```\n\n```text\nconst { Model, DataTypes } = require('sequelize');\nmodule.exports = function(sequelize){\n    class TradingViewAlert extends Model {}\n    return TradingViewAlert.init({\n      action: {\n          type: DataTypes.STRING,\n          allowNull: false\n      },\n      strategy_num_contracts: {\n          type: DataTypes.STRING,\n          allowNull: false\n      },\n      strategy_orderid: {\n          type: DataTypes.STRING,\n          allowNull: false\n      },\n      strategy_price: {\n          type: DataTypes.STRING,\n              allowNull: false\n          },\n      strategy_comment : {\n          type: DataTypes.STRING,\n          allowNull: false \n      },\n      strategy_position_size: {\n          type: DataTypes.STRING,\n          allowNull: false  \n      }\n    }, {\n      sequelize,\n      modelName: 'TradingViewAlert'\n    });\n};\n```\n\n```text\nconst TradingViewAlert = require('../models/trading-view-alert');\nconst TradingViewAlertModel = TradingViewAlert(sequelize);\n```\n\n```text\nTradingViewAlertModel.sync({ alter: true });\n```\n\n```text\nconst autoImport = function(path) {\n  let defineCall = require(path);\n  if (typeof defineCall === 'object' && defineCall.__esModule) {\n    // Babel/ES6 module compatability\n    defineCall = defineCall['default'];\n  }\n  return defineCall(sequelize, Sequelize.DataTypes);\n};\n```\n\n```text\n...\n\nconst models = {\n    Language: connection.import(\"./language\"),\n}\n\n...\n```\n\n```text\n...\n\nconst models = {\n    Language: autoImport(\"./language\"),\n}\n...\n```\n\n========================================\n\nComments:\n- Thank you @wilo087 for your answer, do you have a code example please ?\n- Unfortunately you cannot use \"require\" with the latest Node version with ES modules.\n- You saved my day! God bless you!\n- This is the right answer.\n- The top line needs to be `import { Sequelize } from 'sequelize'` for it to work for me. Maybe they changed this in a newer version?","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":594,"estimatedTokens":3596}}284{"id":"stack-21411848","source":"stackoverflow","questionId":21411848,"title":"Pre-save hook and instance methods in Sequelize?","tags":["node.js","mongoose","sequelize.js"],"text":"Title: Pre-save hook and instance methods in Sequelize?\nTags: node.js, mongoose, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAre there pre-save hooks and instance methods in Sequelize.js?\n\nSpecifically I need to convert this Mongoose code into an equivalent Sequelize code:\n\n### Schema\n\n```\nvar userSchema = new mongoose.Schema({\n username: { type: String, unique: true },\n email: { type: String, unique: true },\n password: String,\n token: String\n});\n```\n\n### Pre-save\n\n```\nuserSchema.pre('save', function(next) {\n var user = this;\n\n var hashContent = user.username + user.password + Date.now() + Math.random();\n user.token = crypto.createHash('sha1').update(hashContent).digest('hex');\n\n if (!user.isModified('password')) return next();\n bcrypt.genSalt(5, function(err, salt) {\n if (err) return next(err);\n bcrypt.hash(user.password, salt, function(err, hash) {\n if (err) return next(err);\n user.password = hash;\n next();\n });\n });\n});\n```\n\n### Instance method\n\n```\nuserSchema.methods.comparePassword = function(candidatePassword, cb) {\n bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {\n if(err) return cb(err);\n cb(null, isMatch);\n });\n};\n```\n\n========================================\n\nTop Answer:\nI faced same issue, but atleast in 2.0 version of sequelize this feature is available, the complete documentation is available at Hooks. \n\nBelow is a sample code that uses a **beforeValidate** hook:\n\n```\n\"use strict\";\nvar md5 = require('blueimp-md5').md5;\n\nmodule.exports = function(sequelize, DataTypes) {\n var Sms = sequelize.define(\"sms\", {\n senderName: DataTypes.STRING,\n smsBody : {\n type : DataTypes.STRING, allowNull:false\n },\n userId : {\n type: DataTypes.INTEGER, allowNull:false\n },\n hash : {\n type:DataTypes.CHAR(32),\n unique:true,\n allowNull:false\n }\n\n });\n\nSms.beforeValidate(function(sms){\n sms.hash = md5(sms.smsBody+sms.userId);\n return sequelize.Promise.resolve(sms)\n});\n\nreturn Sms;\n};\n```\n\nThe requirement here was, create a hash using smsBody and userId, so i created hook i.e. **beforeValidate**, this hook will be executed before any validations are performed by Sequelize on the model. There are many other hooks available and best part is you don't have to write any additional code while you save your data, these hooks will take care of that.\n\nYou should choose wisely between hooks and instanceMethods. But in your case i guess hooks would be a better choice\n\n========================================\n\nCode:\n```text\nvar userSchema = new mongoose.Schema({\n  username: { type: String, unique: true },\n  email: { type: String, unique: true },\n  password: String,\n  token: String\n});\n```\n\n```text\nuserSchema.pre('save', function(next) {\n  var user = this;\n\n  var hashContent = user.username + user.password + Date.now() + Math.random();\n  user.token = crypto.createHash('sha1').update(hashContent).digest('hex');\n\n  if (!user.isModified('password')) return next();\n  bcrypt.genSalt(5, function(err, salt) {\n    if (err) return next(err);\n    bcrypt.hash(user.password, salt, function(err, hash) {\n      if (err) return next(err);\n      user.password = hash;\n      next();\n    });\n  });\n});\n```\n\n```text\nuserSchema.methods.comparePassword = function(candidatePassword, cb) {\n  bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {\n    if(err) return cb(err);\n    cb(null, isMatch);\n  });\n};\n```\n\n```text\nvar User = sequelize.define('User', {\n    username: { type: Sequelize.STRING, unique: true },\n    email: { type: Sequelize.STRING, unique: true },\n    password: Sequelize.STRING,\n    token: Sequelize.STRING\n}, {\n    instanceMethods: {\n        comparePassword : function(candidatePassword, cb) {\n            bcrypt.compare(candidatePassword, this.getDataValue('password'), function(err, isMatch) {\n                if(err) return cb(err);\n                cb(null, isMatch);\n            });\n        },\n        setToken: function(){\n            // bla bla bla\n            // bla bla bla\n        },\n        getFullname: function() {\n            return [this.firstname, this.lastname].join(' ');\n        }\n    }\n})\n```\n\n```text\nUser.build({ firstname: 'foo', lastname: 'bar' }).getFullname(); // 'foo bar'\n```\n\n```text\nUser.build({ ... }).setToken().save();\n```\n\n```text\nUser.find({ ... }).success(function(user) { user.comparePassword('the password to check', function(err, isMatch) { ... } });\n```\n\n```text\n\"use strict\";\nvar md5 = require('blueimp-md5').md5;\n\nmodule.exports = function(sequelize, DataTypes) {\n  var Sms = sequelize.define(\"sms\", {\n    senderName: DataTypes.STRING,\n    smsBody : {\n      type : DataTypes.STRING, allowNull:false\n    },\n    userId : {\n      type: DataTypes.INTEGER, allowNull:false\n    },\n    hash : {\n      type:DataTypes.CHAR(32),\n      unique:true,\n      allowNull:false\n    }\n\n  });\n\nSms.beforeValidate(function(sms){\n  sms.hash = md5(sms.smsBody+sms.userId);\n  return sequelize.Promise.resolve(sms)\n});\n\n\nreturn Sms;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n const User = sequelize.define('users', {    \n   username: { type: String, unique: true },\n   email: { type: String, unique: true },\n      password: String,\n      token: String\n    },\n    {\n    hooks: {\n      beforeCreate: function(user){\n         \n         // do your hashing here to user.password\n      }\n    }\n});\n```\n\n========================================\n\nComments:\n- The \"pre-save\" method in the question sets not only user.token but also user.password. Is setToken (in the sequelize version presented in this answer) meant to replace the \"pre-save\" method presented in the question, and if so, isn't a more appropriate name setTokenAndPass?\n- Also, when I call the instance method on the object returned by build, I get the following error: built_obj.setPass is not a function (where setPass is my instance method). Any tips?\n- already added an edit for hooks which are available now as part of Sequelize @GobiDasu, no idea why you get that errors but won't be able to help without any visible code. Regards\n- Note: md5 is not the way to do password hashing, you should use a hashing alghorithm which isn't broken and is more expensive to hash with to make it more difficult for attackers to crack. A system such as bcrypt or pbkdf2.\n- @leroydev totally agree.. here i just used md5 as an example and if you look carefully, the example that i gave is not storing the password. Its creating a hash from content that is used to maintain uniqueness. So i guess for this scenario its fine. But surely for storing passwords, this approach is horrible that.\n- I know this is not for saving passwords, but the question was about saving passwords, that's why I added the comment :)","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":228,"estimatedTokens":1668}}285{"id":"stack-32404992","source":"stackoverflow","questionId":32404992,"title":"How do i get the primary key of a sequelize model?","tags":["sequelize.js"],"text":"Title: How do i get the primary key of a sequelize model?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nBasically, given an instance or a model, I would like to \na) Know if a primary key exists\nb) know the name of that field(s)\n\n========================================\n\nTop Answer:\nTake a look at Model.primaryKeyAttributes, it is array of string names of primary key attributes:\n\n```\nconsole.dir(Model.primaryKeyAttributes);\n\n[ 'id' ]\n```\n\n========================================\n\nCode:\n```text\nModel.describe().then(function (schema) {\n    return Object.keys(schema).filter(function(field){\n        return schema[field].primaryKey;\n    });\n}).tap(console.log);\n```\n\n```text\nconsole.dir(Model.primaryKeyAttributes);\n\n[ 'id' ]\n```\n\n========================================\n\nComments:\n- I wrote an import script which was importing an existing database and generating Sequelize models while ago, I used `Model.describe()` and parse the result and find the primary keys, indices, foreign keys etc.\n- thanks! I will construct an answer based on your hint.\n- Where is this documented?\n- @Catfish simply found it in Model, can't find documentation anywhere","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":44,"estimatedTokens":290}}286{"id":"stack-36187952","source":"stackoverflow","questionId":36187952,"title":"Sequelize defaultValue not getting set","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize defaultValue not getting set\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHere is my model for a recipe table. I am using mysql as the database, and the sequelize module. If I leave the title, prep_time, or cook_time blank in the form it seems to skip the validation of allowNull and defaultValue and attempts to enter a '' (blank string) into the database. Is there something I am doing wrong? \n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('recipe', {\n title: {\n type: DataTypes.STRING,\n allowNull: false\n },\n description: {\n type: DataTypes.TEXT\n },\n ingredients: {\n type: DataTypes.TEXT\n },\n instructions: {\n type: DataTypes.TEXT\n },\n yield: {\n type: DataTypes.STRING\n },\n prep_time: {\n type: DataTypes.INTEGER,\n allowNull: false,\n defaultValue: '0'\n },\n cook_time: {\n type: DataTypes.INTEGER,\n allowNull: false,\n defaultValue: '0'\n },\n image: {\n type: DataTypes.STRING\n }\n });\n};\n```\n\n========================================\n\nTop Answer:\nI know this question has been years ago. But, this might be helpful for others. In this case, it should use validate notEmpty by Sequelize. Because HTML form by default pass in not null (empty string or '' or \"\" or ``), so there is no need to use validate notNull.\n\nHere, i recommend people to read this:\nhttps://sequelize.org/master/manual/validations-and-constraints.html\n\nSequelize will check orderly:\n\n- custom validation\n\n- built-in validation\n\n- constraint\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    return sequelize.define('recipe', {\n        title: {\n            type: DataTypes.STRING,\n            allowNull: false\n        },\n        description: {\n            type: DataTypes.TEXT\n        },\n        ingredients: {\n            type: DataTypes.TEXT\n        },\n        instructions: {\n            type: DataTypes.TEXT\n        },\n        yield: {\n            type: DataTypes.STRING\n        },\n        prep_time: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            defaultValue: '0'\n        },\n        cook_time: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            defaultValue: '0'\n        },\n        image: {\n            type: DataTypes.STRING\n        }\n    });\n};\n```\n\n```text\ndefaultValue\n```\n\n```text\nallowNull\n```\n\n```text\nsync({force: true)\n```\n\n```text\nAllowNull\n```\n\n```text\ndefaultValue\n```\n\n```text\ntitle\n```\n\n```text\ncreate()\n```\n\n```text\ncreate({title:'',prep_time:''})\n```\n\n```text\ncreate({title:''}\n```\n\n```text\nprep_time\n```\n\n```text\ndefaultValue\n```\n\n```text\ntitle\n```\n\n```text\ncreate(req.body)\n```\n\n```text\ntitle\n```\n\n```text\nprep_time\n```\n\n========================================\n\nComments:\n- That's exactly what is was. Now I just need to pull those keys out of the object before it is submitted. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":162,"estimatedTokens":720}}287{"id":"stack-15213484","source":"stackoverflow","questionId":15213484,"title":"passport.deserializeUser executing a DB (sequelize) command for each HTTP request","tags":["node.js","sequelize.js","passport.js"],"text":"Title: passport.deserializeUser executing a DB (sequelize) command for each HTTP request\nTags: node.js, sequelize.js, passport.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize as an ORM and passport.js (passport-local) for authentication. I noticed that every HTTP request is resulting in a separate database command. I started looking at the deserializeUser() function.\n\nWhen loading a single page, this is what I get:\n\n Executing: SELECT * FROM `Users` WHERE `Users`.`id`=1 LIMIT 1;\n\n \n **Over and over and over!** \n\n \n GET / 200 12ms - 780 \n\n \n Executing: SELECT * FROM `Users` WHERE `Users`.`id`=1 LIMIT 1; \n\n \n Executing: SELECT * FROM `Users` WHERE `Users`.`id`=1 LIMIT 1; \n\n \n **Over and over and over!** \n\n \n GET /js/ui.js 304 4ms \n\n \n **Over and over and over!** \n\n \n GET /stylesheets/main.css 304 6ms\n\n \n Executing: SELECT * FROM `Users` WHERE `Users`.`id`=1 LIMIT 1; \n\n \n **Over and over and over!** \n\n \n GET /images/logo.jpg 304 3ms\n\nHere's how passport.deserializeUser looks:\n\n```\npassport.deserializeUser(function(id, done) {\n User.find(id).success(function(user) {\n console.log('Over and over and over!');\n done(null, user);\n }).error(function(err) {\n done(err, null);\n });\n});\n```\n\nThe page I'm requesting is:\n\n```\nindex: function(req, res) {\n res.render('index', {\n title: \"Welcome to EKIPLE!\",\n currentUser: req.user\n });\n}\n```\n\nIs the deserializeUser supposed to run for every image, html, css file requested? If so, is there a way of reducing the number of requests to the DB?\n\n========================================\n\nCode:\n```text\npassport.deserializeUser(function(id, done) {\n    User.find(id).success(function(user) {\n        console.log('Over and over and over!');\n        done(null, user);\n    }).error(function(err) {\n        done(err, null);\n    });\n});\n```\n\n```text\nindex: function(req, res) {\n    res.render('index', {\n        title: \"Welcome to EKIPLE!\",\n        currentUser: req.user\n    });\n}\n```\n\n```text\nUsers\n```\n\n```text\nUsers\n```\n\n```text\nid\n```\n\n```text\nUsers\n```\n\n```text\nUsers\n```\n\n```text\nid\n```\n\n```text\nUsers\n```\n\n```text\nUsers\n```\n\n```text\nid\n```\n\n```text\nUsers\n```\n\n```text\nUsers\n```\n\n```text\nid\n```\n\n```text\napp.use\n```\n\n```text\nexpress.static\n```\n\n```text\nconnect.static\n```\n\n```text\napp.use\n```\n\n========================================\n\nComments:\n- Great solution, I have a variation of this problem and posted a question in here stackoverflow.com/questions/34277748/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":161,"estimatedTokens":609}}288{"id":"stack-50456128","source":"stackoverflow","questionId":50456128,"title":"unknown column in field list sequelize","tags":["node.js","sequelize.js"],"text":"Title: unknown column in field list sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to perform the following query using Sequelize:\n\n```\ndb.Post.findAll({\n include: [\n {\n model: db.User,\n as: 'Boosters',\n where: {id: {[Op.in]: a_set_of_ids }}\n },\n {\n model: db.Assessment,\n as: 'PostAssessments',\n where: {UserId: {[Op.in]: another_set_of_ids}}\n }\n ],\n attributes: [[db.sequelize.fn('AVG', db.sequelize.col('Assessments.rating')), 'average']],\n where: {\n average: 1\n },\n group: ['id'],\n limit: 20\n })\n```\n\nBut I run to this error: \"ER_BAD_FIELD_ERROR\". Unknown column 'Assessments.rating' in 'field list', although I do have table \"Assessments\" in the database and \"rating\" is a column in that table.\n\nMy Post model looks like this:\n\n```\nconst Post = sequelize.define('Post', {\ntitle: DataTypes.TEXT('long'),\ndescription: DataTypes.TEXT('long'),\nbody: DataTypes.TEXT('long')\n }, {\n timestamps: false\n });\n\n Post.associate = function (models) {\n models.Post.belongsToMany(models.User, {as: 'Boosters', through: 'UserPostBoosts' });\n models.Post.hasMany(models.Assessment, {as: 'PostAssessments'});\n };\n```\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nError is with this one :\n\n```\nmodels.sequelize.col('Assessments.rating'))\n```\n\nChange it to\n\n```\nmodels.sequelize.col('PostAssessments.rating')) // or post_assessments.rating\n```\n\n**Reason :** You are using the alias for include `as: 'PostAssessments',`.\n\n========================================\n\nCode:\n```text\ndb.Post.findAll({\n      include: [\n        {\n          model: db.User,\n          as: 'Boosters',\n          where: {id: {[Op.in]: a_set_of_ids }}\n        },\n        {\n          model: db.Assessment,\n          as: 'PostAssessments',\n          where: {UserId: {[Op.in]: another_set_of_ids}}\n        }\n      ],\n      attributes: [[db.sequelize.fn('AVG', db.sequelize.col('Assessments.rating')), 'average']],\n      where: {\n        average: 1\n      },\n      group: ['id'],\n      limit: 20\n    })\n```\n\n```text\nconst Post = sequelize.define('Post', {\ntitle: DataTypes.TEXT('long'),\ndescription: DataTypes.TEXT('long'),\nbody: DataTypes.TEXT('long')\n  }, {\n  timestamps: false\n    });\n\n  Post.associate = function (models) {\n    models.Post.belongsToMany(models.User, {as: 'Boosters', through: 'UserPostBoosts' });\n    models.Post.hasMany(models.Assessment, {as: 'PostAssessments'});\n  };\n```\n\n```text\ndb.Post.findAll({\n  subQuery: false,\n  include: [\n    {\n      model: db.User,\n      as: 'Boosters',\n      where: {id: {[Op.in]: a_set_of_ids }}\n     }\n    ,{\n      model: db.Assessment,\n      as: 'PostAssessments',\n      where: {UserId: {[Op.in]: another_set_of_ids}}\n    }\n  ],\n  having: db.sequelize.where(db.sequelize.fn('AVG', db.sequelize.col('PostAssessments.rating')), {\n       [Op.eq]: 1,\n     }),\n  limit: 20,\n  offset: 2,\n  group: ['Post.id', 'Boosters.id', 'PostAssessments.id']\n})\n```\n\n```text\nmodels.sequelize.col('Assessments.rating'))\n```\n\n```text\nmodels.sequelize.col('PostAssessments.rating')) // or post_assessments.rating\n```\n\n```text\nas: 'PostAssessments',\n```\n\n========================================\n\nComments:\n- I have tried that one as well but the error persists.\n- @user2511906 , please post the raw query it generates\n- You are awesome!\n- I fought with this issue for a few hours, adjusting my attributes from my associations. This was what was required. Thanks!\n- nice but it was returning first row only, I had to add `separate: true` flag in join to get right result github.com/sequelize/sequelize/issues/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":153,"estimatedTokens":892}}289{"id":"stack-18828218","source":"stackoverflow","questionId":18828218,"title":"Sequelize add association","tags":["sequelize.js"],"text":"Title: Sequelize add association\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an association set up like this: \n\n```\nm.User.hasMany(m.Interests, { joinTableName: 'user_interests', foreignKey: 'user_id' });\nm.Interests.hasMany(m.User, { joinTableName: 'user_interests', foreignKey: 'interest_id' });\n```\n\nSequelize is awesome in that I can just do user.getInterests. But how can I add a new association?\n\n========================================\n\nCode:\n```text\nm.User.hasMany(m.Interests, { joinTableName: 'user_interests', foreignKey: 'user_id' });\nm.Interests.hasMany(m.User, { joinTableName: 'user_interests', foreignKey: 'interest_id' });\n```\n\n```text\nuser.addInterest(interest)\n```\n\n```text\nuser.setInterests([interest])\n```\n\n========================================\n\nComments:\n- That's great. Great answer. Sequelize is awesome :-)\n- What is `interest` in this? An instance of `interest`? Or a query to find it?\n- Can be an instance or a primary key","metadata":{"transformedAt":"2026-08-18T18:33:34.362Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":36,"estimatedTokens":243}}290{"id":"stack-60217417","source":"stackoverflow","questionId":60217417,"title":"Jest tests hang due to open Sequelize connections","tags":["node.js","postgresql","jestjs","sequelize.js","travis-ci"],"text":"Title: Jest tests hang due to open Sequelize connections\nTags: node.js, postgresql, jestjs, sequelize.js, travis-ci\nSource: Stack Overflow\n\nQuestion:\n### The Setup\n\nI have a NodeJS project that uses:\n\n- Jest for testing.\n\n- Sequelize as an ORM.\n\nSequelize is instantiated when loading the models module which gets imported by a few of the files that are being tested with Jest.\n\n### The Problem\n\nJest tests pass but then hang with the message:\n\n Jest did not exit one second after the test run has completed.\n\n \n This usually means that there are asynchronous operations that weren't\n stopped in your tests. Consider running Jest with\n `--detectOpenHandles` to troubleshoot this issue.\n\n***Note:** Adding `--detectOpenHandles` to the test call does not affect the output.*\n\nI do not actually invoke the `sequelize` object from any test paths, however some of the tested files import the `models` module and therefore Sequelize is instantiated.\n\n(I will also note that this only occurs on my TravisCI environment, but I suspect this is a red herring.)\n\n### The Context\n\nBecause Jest is running tests in parallel, the `models` module is loaded multiple times during the entire test process. I confirmed this with debug output saying `SEQUELIZE LOADED` which appears multiple times when I run the tests.\n\n### The Attempts\n\nI did attempt to invoke `sequelize.close()` inside of a `globalTeardown` but this appears to simply open (and then close) a new sequelize connection.\n\nSince none of the tests actually rely on a database connection, I attempted running `sequelize.close()` within the `models` module immediately before export. This fixed the issue (though obviously is not a solution).\n\nI have attempted to configure the test connection pools to aggressively end connections.\n\n```\nconst sequelizeConfig = {\n ...\n pool: {\n idle: 0,\n evict: 0,\n }\n}\n```\n\nThis did nothing.\n\n### The Requirements\n\nI don't want to use a brute force solution such as running `--forceExit` via Jest when I run my tests. This feels like it is ignoring the root issue and might expose me to other kinds of mistakes down the line.\n\nMy tests are spread across dozens of files, which means needing to invoke something in an `afterAllTests` would require a lot of redundancy and would introduce a code smell. \n\n### The Question\n\nHow can I ensure that sequelize connections are closed after tests finish, so they don't cause Jest to hang?\n\n========================================\n\nCode:\n```text\nconst sequelizeConfig = {\n  ...\n  pool: {\n      idle: 0,\n      evict: 0,\n    }\n}\n```\n\n```text\n--detectOpenHandles\n```\n\n```text\n--detectOpenHandles\n```\n\n```text\nsequelize\n```\n\n```text\nmodels\n```\n\n```text\nmodels\n```\n\n```text\nSEQUELIZE LOADED\n```\n\n```text\nsequelize.close()\n```\n\n```text\nglobalTeardown\n```\n\n```text\nsequelize.close()\n```\n\n```text\nmodels\n```\n\n```text\n--forceExit\n```\n\n```text\nafterAllTests\n```\n\n```text\n\"jest\": {\n    ...\n    \"setupFilesAfterEnv\": [\"./src/test/suiteSetup.js\"]\n  }\n```\n\n```text\nimport models from '../server/models'\nafterAll(() => models.sequelize.close())\n\n// Note: in my case sequelize is exposed as an attribute of my models module.\n```\n\n```text\npackage.json\n```\n\n```text\nsuiteSetup.js\n```\n\n```text\n--forceExit\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":152,"estimatedTokens":803}}291{"id":"stack-67051281","source":"stackoverflow","questionId":67051281,"title":"Use Postgres generated columns in Sequelize model","tags":["sql","node.js","postgresql","sequelize.js"],"text":"Title: Use Postgres generated columns in Sequelize model\nTags: sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table where it's beneficial to generate a pre-calculated value in the database engine rather than in my application code. For this, I'm using Postgres' generated column feature. The SQL is like this:\n\n```\nALTER TABLE \"Items\"\nADD \"generatedValue\" DOUBLE PRECISION GENERATED ALWAYS AS (\n LEAST(\"someCol\", \"someOtherCol\")\n) STORED;\n```\n\nThis works well, but I'm using Sequelize with this database. I want to find a way to define this column in my model definition, so that Sequelize will query it, not attempt to update a row's value for that column, and ideally will create the column on sync.\n\n```\nclass Item extends Sequelize.Model {\n static init(sequelize) {\n return super.init({\n someCol: Sequelize.DOUBLE,\n someOtherColl: Sequelize.DOUBLE,\n generatedValue: // How can I do this with Sequelize?\n\nI can specify the column as a DOUBLE, and Sequelize will read it, but the column won't be created correctly on sync. Perhaps there's some post-sync hook I can use? I was considering `afterSync` to drop the column and re-add it with my generated value statement, but I would first need to detect that the column wasn't already converted or I would lose my data. (I run sync [without `force: true`] on every app startup.)\n\nAny thoughts, or alternative ideas would be appreciated.\n\n========================================\n\nCode:\n```text\nALTER TABLE \"Items\"\nADD \"generatedValue\" DOUBLE PRECISION GENERATED ALWAYS AS (\n  LEAST(\"someCol\", \"someOtherCol\")\n) STORED;\n```\n\n```text\nclass Item extends Sequelize.Model {\n  static init(sequelize) {\n    return super.init({\n      someCol: Sequelize.DOUBLE,\n      someOtherColl: Sequelize.DOUBLE,\n      generatedValue: // <<<--  What goes here??\n    });\n  }\n}\n```\n\n```text\nafterSync\n```\n\n```text\nforce: true\n```\n\n```js\nconst Item = sequelize.define('Item', {\n  someCol: { type: DataTypes.DOUBLE },\n  someOtherCol: { type: DataTypes.DOUBLE },\n  generatedValue: {\n    type: 'DOUBLE PRECISION GENERATED ALWAYS AS (LEAST(\"someCol\", \"someOtherCol\")) STORED',\n    set() {\n      throw new Error('generatedValue is read-only')\n    },\n  },\n})\n```\n\n```text\nsync()\n```\n\n```text\ngeneratedValue\n```\n\n========================================\n\nComments:\n- Perhaps this isn't the most possible right now: github.com/sequelize/sequelize/issues/12718\n- This works great, thank you! One -up question... is using a string for a type officially documented somewhere?\n- I could not find any mention in the docs, so it could be behaviour that is subject to change in future versions of sequelize.\n- This unfortunately does not seem to work anymore as of Sequelize v6.32.1\n- @Timaayy, its working in v6.37.3, my requirement was `CHAR(32) GENERATED ALWAYS AS (MD5(some_text)) STORED`. ( didn't notice postgres, im on MySQL )","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":87,"estimatedTokens":720}}292{"id":"stack-50735578","source":"stackoverflow","questionId":50735578,"title":"Add automatic createdAt and updatedAt timestamps in migration","tags":["javascript","sequelize.js"],"text":"Title: Add automatic createdAt and updatedAt timestamps in migration\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm doing a Sequelize migration which adds a new table.\nIn this table I want to add the timestamps createdAt and updatedAt that are automatically updated and my migrations works using literals like this:\n\n```\ncreatedAt: {\n type: Sequelize.DATE,\n defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),\n},\nupdatedAt: {\n type: Sequelize.DATE,\n defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),\n},\n```\n\nI've to only add `timestamps: true` in the options but the timestamps are not automatically updated.\n\nCan I do this without using literals?\n\n========================================\n\nCode:\n```text\ncreatedAt: {\n    type: Sequelize.DATE,\n    defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),\n},\nupdatedAt: {\n    type: Sequelize.DATE,\n    defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),\n},\n```\n\n```text\ntimestamps: true\n```\n\n```text\ndefaultValue\n```\n\n```text\nSequelize.fn('NOW')\n```\n\n========================================\n\nComments:\n- defaultValue: Sequelize.fn('NOW') in migrations works like a charm! It must be added to documentation!\n- For info, this also works in seeders (sequelize v6.x stable)","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":54,"estimatedTokens":326}}293{"id":"stack-52161821","source":"stackoverflow","questionId":52161821,"title":"insert a new record in nodejs using sequelize POST method","tags":["node.js","post","methods","insert","sequelize.js"],"text":"Title: insert a new record in nodejs using sequelize POST method\nTags: node.js, post, methods, insert, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to insert a new data in database using sequelize express, without query. I am trying so hard but I didn't get the output... If my code is wrong, then give me a code for insert a new record in db using sequelize express.\n\n```\nconst Sequelize = require('sequelize');\nvar express = require('express');\nvar app = express();\nvar mysql = require('mysql');\n//var request=require('request')\nconst sequelize = new Sequelize('ganeshdb', 'root', 'welcome123$', {\n host: 'localhost',\n port: 3306,\n dialect: 'mysql'\n});\nvar users = sequelize.define('users', {\n id: {\n primaryKey: true,\n type: Sequelize.INTEGER,\n },\n name: Sequelize.STRING,\n role: Sequelize.STRING,\n email: Sequelize.STRING\n});\napp.post('/test', function (request, response) {\n return users.create({\n name: request.body.name,\n role: request.body.role,\n email: request.body.email\n }).then(function (users) {\n if (users) {\n response.send(users);\n } else {\n response.status(400).send('Error in insert new record');\n }\n });\n});\napp.listen(3000, function () {\n console.log('Express server is listening on port 3000');\n});\n```\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\nvar express = require('express');\nvar app = express();\nvar mysql = require('mysql');\n//var request=require('request')\nconst sequelize = new Sequelize('ganeshdb', 'root', 'welcome123$', {\n    host: 'localhost',\n    port: 3306,\n    dialect: 'mysql'\n});\nvar users = sequelize.define('users', {\n    id: {\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n    },\n    name: Sequelize.STRING,\n    role: Sequelize.STRING,\n    email: Sequelize.STRING\n});\napp.post('/test', function (request, response) {\n    return users.create({\n        name: request.body.name,\n        role: request.body.role,\n        email: request.body.email\n    }).then(function (users) {\n        if (users) {\n            response.send(users);\n        } else {\n            response.status(400).send('Error in insert new record');\n        }\n    });\n});\napp.listen(3000, function () {\n    console.log('Express server is listening on port 3000');\n});\n```\n\n```text\nvar express = require('express')\nvar bodyParser = require('body-parser')\n \nvar app = express()\n \n// parse application/x-www-form-urlencoded\napp.use(bodyParser.urlencoded({ extended: false }))\n \n// parse application/json\napp.use(bodyParser.json())\n \napp.use(function (req, res) {\n  res.setHeader('Content-Type', 'text/plain')\n  res.write('you posted:\\n')\n  res.end(JSON.stringify(req.body, null, 2))\n})\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst express = require('express');\nconst bodyParser = require('body-parser');\n\nconst app = express();\n\napp.use(bodyParser.json({ limit: '100mb' }));\napp.use(bodyParser.urlencoded({ extended: true, limit: '100mb', parameterLimit: 1000000 }));\n\nconst sequelize = new Sequelize('test_01', 'root', 'root', {\n    host: 'localhost',\n    port: 3306,\n    dialect: 'mysql'\n});\n\nconst users = sequelize.define('users', {\n    id: {\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n    },\n    name: Sequelize.STRING,\n    role: Sequelize.STRING,\n    email: Sequelize.STRING\n});\n\napp.post('/test', function (request, response) {\n    return await users.create({\n        id: request.body.id,\n        name: request.body.name,\n        role: request.body.role,\n        email: request.body.email\n    }).then(function (users) {\n        if (users) {\n            response.send(users);\n        } else {\n            response.status(400).send('Error in insert new record');\n        }\n    });\n});\n\napp.listen(3001, function () {\n    console.log('Express server is listening on port 3000');\n});\n```\n\n========================================\n\nComments:\n- Getting any error ?\n- Could you please add a `.catch((err)=>{console.log(err)})` block to the create function and post us error, if it logs\n- can u please give me a full code,actually i am new to nodejs,\n- Did my answer help you?\n- yes sir, can u do me favor.. i want to insert data by seperated files like routes, models, controller like that.. i seen more examples in internet but didnt get proper output.\n- sir, give your mail id, i will my project\n- uladzislau.vavilau@gmail.com\n- i send my project to ur mail, check it","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":162,"estimatedTokens":1095}}294{"id":"stack-40875170","source":"stackoverflow","questionId":40875170,"title":"Sequelize js 'include' and 'raw'","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize js 'include' and 'raw'\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a relation between two entites like (every chest has one user)\n\n```\nentities.Chest.belongsTo(entities.User)\n```\n\ni want to retrieve all chests and their users in one query, so i do \n\n```\nentities.Chest.findAll({include:[{model: entities.User}]})\n```\n\nBut i prefer to manipulate them as plain objects, i do\n\n```\nentities.Chest.findAll({raw:true, include:[{model: entities.User}]})\n```\n\nAnd the result does not include users at all, how can i achieve this?\n\n========================================\n\nTop Answer:\nThis syntax helps for me. You haven't to iterate your records. Just use `nest: true` and `raw: true` in pairs;\n\n```\nentities.Chest.findAll({\n raw:true,\n nest: true,\n include:[entities.User]\n})\n```\n\n========================================\n\nCode:\n```text\nentities.Chest.belongsTo(entities.User)\n```\n\n```text\nentities.Chest.findAll({include:[{model: entities.User}]})\n```\n\n```text\nentities.Chest.findAll({raw:true, include:[{model: entities.User}]})\n```\n\n```text\nentities.Chest.findAll({include:[{model: entities.User}]})\n  .then(function(chestsSeq){\n    var chests = chestsSeq.toJSON(); //same as chestsSeq.get({});\n    //do something with raw chests object\n  });\n```\n\n```text\nentities.Chest.findAll({\n    raw:true,\n    nest: true,\n    include:[entities.User]\n})\n```\n\n```text\nnest: true\n```\n\n```text\nraw: true\n```\n\n========================================\n\nComments:\n- Thanks. 'nest: true' is the required thing when using async and await.\n- This should be the accepted answer!","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":82,"estimatedTokens":402}}295{"id":"stack-53165658","source":"stackoverflow","questionId":53165658,"title":"What findOne returns when there is no match?","tags":["sequelize.js"],"text":"Title: What findOne returns when there is no match?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy `nodejs` app needs to check if `findOne` find any match. \n\n```\nlet o = await Model.findOne({where : {name: 'myname'}});\n if (no match in o ) {\n //do something\n } else {\n //do something else\n };\n```\n\nBut I did not find any document explaining what `findOne` returns when there is no match. I know it does not return `null` or `undefined`. The return is an object and how I know there is no match.\n\n========================================\n\nCode:\n```text\nlet o = await Model.findOne({where : {name: 'myname'}});\n  if (no match in o ) {\n  //do something\n  } else {\n  //do something else\n  };\n```\n\n```text\nnodejs\n```\n\n```text\nfindOne\n```\n\n```text\nfindOne\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n```text\n// search for attributes\nProject.findOne({ where: {title: 'aProject'} }).then(project => {\n  // project will be the first entry of the Projects table with the title 'aProject' || null\n})\n```\n\n```text\nlet o = await Model.findOne({where : {name: 'myname'}});\nif (o) {\n    // Record Found\n} else {\n    // Not Found\n};\n```\n\n========================================\n\nComments:\n- check the last part of the this link docs.mongodb.com/manual/reference/method/db.collection.findO&zwnj;&#8203;ne/&hellip; . This might help you\n- What i found was that `null` was the return without match in debug. This is as expected when there is no match found in the table.\n- In order to use `await`, you have to create a new Promise object for the fineOne. Otherwase `o` will always be `undefine` which is false; await new Promise(() => {Model.fineOne({where: {name: 'myname'}})}).then(result => {o = result});","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":72,"estimatedTokens":426}}296{"id":"stack-50641526","source":"stackoverflow","questionId":50641526,"title":"Async getter/setter in Sequelize as part of a property","tags":["javascript","promise","async-await","sequelize.js"],"text":"Title: Async getter/setter in Sequelize as part of a property\nTags: javascript, promise, async-await, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nCan I define a getter of a property as an asyc function in Sequelize?\n\nIn the getter I should retrieve a value from another table and I've tried this in the model definition:\n\n```\n...\nbio: {\n type: Sequelize.STRING,\n get: async function() {\n let bio = this.getDataValue('bio');\n if (bio) {\n let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))\n if(bestFriend){\n bio += ` Best friend: ${bestFriend.name}.`;\n }\n console.log(bio)\n return bio;\n } else {\n return '';\n }\n }\n},\n...\n```\n\nLogging I can read the correct bio with something like:\n\n`Born yesterday. Love to read Best friend: Markus`\n\nBut the object I retrieve has an empty object in the bio attribute.\n\nI suppose that is because the async function is not supported, am I wrong?\n\nHow can I achieve this without using an async function?\n\n========================================\n\nTop Answer:\nIn Sequelize, you can define *delayed* virtual fields, that you write and read from strategical positions in code, instead of from the model schema. If you store your virtual values alongside with persisted values, then they are automatically managed by collective operations like `model.get()`, `model.toJSON()`, ...\n\n### Setup\n\n```\nmyVirtualField: {\n type: new DataTypes.VIRTUAL(DataTypes.STRING),\n get() {\n return this.getDataValue(\"myVirtualField\")\n },\n set(value) {\n this.setDataValue(\"myVirtualField\", value)\n },\n},\n```\n\n### Usage\n\n```\n// before writing anything into myVirtualField, `item.getDataValues()` has no entry for it\nif (item.myVirtualField === undefined) { // <- true\n\n// set myVirtualField\nitem.myVirtualField = await getHelloWorldAsync() // this resolves to \"Hello, World!\"\n\n// after writing anything into myVirtualField, `item.getDataValues()` has an entry for it\nif (item.myVirtualField === \"Hello, World!\") { // <- true\n```\n\n========================================\n\nCode:\n```text\n...\nbio: {\n    type: Sequelize.STRING,\n    get: async function() {\n        let bio = this.getDataValue('bio');\n        if (bio) {\n            let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))\n            if(bestFriend){\n                bio += ` Best friend: ${bestFriend.name}.`;\n            }\n            console.log(bio)\n            return bio;\n        } else {\n            return '';\n        }\n    }\n},\n...\n```\n\n```text\nBorn yesterday. Love to read Best friend: Markus\n```\n\n```js\nBioModel.prototype.getBio = async function() {\n    let bio = this.getDataValue('bio');\n    if (bio) {\n        let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))\n        if(bestFriend){\n            bio += ` Best friend: ${bestFriend.name}.`;\n        }\n        return bio;\n    } else {\n        return '';\n    }\n}\n```\n\n```text\nvirtual getter\n```\n\n```text\nasync\n```\n\n```text\nmyVirtualField: {\n  type: new DataTypes.VIRTUAL(DataTypes.STRING),\n  get() {\n    return this.getDataValue(\"myVirtualField\")\n  },\n  set(value) {\n    this.setDataValue(\"myVirtualField\", value)\n  },\n},\n```\n\n```text\n// before writing anything into myVirtualField, `item.getDataValues()` has no entry for it\nif (item.myVirtualField === undefined) { // <- true\n\n// set myVirtualField\nitem.myVirtualField = await getHelloWorldAsync() // this resolves to \"Hello, World!\"\n\n// after writing anything into myVirtualField, `item.getDataValues()` has an entry for it\nif (item.myVirtualField === \"Hello, World!\") { // <- true\n```\n\n```text\nmodel.get()\n```\n\n```text\nmodel.toJSON()\n```\n\n========================================\n\nComments:\n- The documentation link provided does not mention anything about async setters / getters.\n- Are you sure about this? When I copy your definition of myVirtualField into one of my models, my IDE draws red squigglies under the \"myVirtualField\" names in the getter and setter and says I can't use them, and the property virtual field itself gives this TypeScript error: TS2353: Object literal may only specify known properties, and myVirtualField does not exist in type.","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":159,"estimatedTokens":1033}}297{"id":"stack-61254851","source":"stackoverflow","questionId":61254851,"title":"heroku Postgres - sequelize : no pg_hba.conf entry for host","tags":["node.js","postgresql","heroku","sequelize.js"],"text":"Title: heroku Postgres - sequelize : no pg_hba.conf entry for host\nTags: node.js, postgresql, heroku, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to run migrations on my Nodejs application hosted on Heroku using the Heroku free Postgres database.\n\nI am using Sequelize as my ORM.This is my configuration for the production connection.\n\n```\nconst dotenv = require('dotenv');\n\ndotenv.config();\n\nmodule.exports = {\n production: {\n use_env_variable: 'DATABASE_URL',\n dialect: process.env.DIALECT,\n protocol: process.env.DIALECT,\n }\n}\n```\n\nWhen I use the above configuration, I get the following error: `no pg_hba.conf entry for host \"000.000.000.0\", user \"yyyyyyyyyyyyyy\", database \"xxxxxxxxxxxxx\", SSL off`\n\nHowever when I add the options below to the config, I get a self-signed certificate error.\n\n```\ndialectOptions: {\nssl: true\n}\n```\n\nPlease, how do I resolve this?\n\n========================================\n\nTop Answer:\nAs explained in this related answer, setting `rejectUnauthorized: false` is a bad idea because it allows you to create non-encrypted connections to your database and can, thus, expose you to MITM attacks (man-in-the-middle attacks).\n\nA better solution is to give your Postgres client the CA that you want it to use. In my case it was a CA used by AWS RDS for the North Virginia region (us-east-1). I downloaded the CA from this AWS page, placed it in the same directory as the file I wanted to use to connect to the DB and then modified my config to:\n\n```\n{\n ...\n dialectOptions: {\n ssl: {\n require: true,\n ca: fs.readFileSync(`${__dirname}/us-east-1-bundle.pem`),\n },\n },\n}\n```\n\n========================================\n\nCode:\n```text\nconst dotenv = require('dotenv');\n\ndotenv.config();\n\nmodule.exports = {\n  production: {\n    use_env_variable: 'DATABASE_URL',\n    dialect: process.env.DIALECT,\n    protocol: process.env.DIALECT,\n  }\n}\n```\n\n```text\ndialectOptions: {\nssl: true\n}\n```\n\n```text\nno pg_hba.conf entry for host \"000.000.000.0\", user \"yyyyyyyyyyyyyy\", database \"xxxxxxxxxxxxx\", SSL off\n```\n\n```text\ndialectOptions: {\n    ssl: {\n        rejectUnauthorized: false\n    }\n}\n```\n\n```text\n{\n  ...\n  dialectOptions: {\n    ssl: {\n      require: true,\n      ca: fs.readFileSync(`${__dirname}/us-east-1-bundle.pem`),\n    },\n  },\n}\n```\n\n```text\nrejectUnauthorized: false\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":104,"estimatedTokens":578}}298{"id":"stack-42470383","source":"stackoverflow","questionId":42470383,"title":"Sequelize query with count in inner join","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize query with count in inner join\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to convert this query to sequelize query object what is the right wayto do it?\n\n```\nSELECT families.id, count('answers.familyId') FROM families LEFT JOIN \nanswers on families.id = answers.familyId WHERE answers.isActive=1 AND\nanswers.answer=1 GROUP BY families.id HAVING COUNT('answers.familyId')>=6\n```\n\n========================================\n\nTop Answer:\n**You need to use `get()` on the `attribute:` aliased `count` column**\n\nThere are two important gotchas when reading the aggregates out:\n\nthe `count` only shows up on results if you alias it with `attributes` as shown by Piotr at https://stackoverflow.com/a/42472696/895245 and as shown at How do I select a column using an alias `attributes` aliasing has the unexpected effect of requiring you to use `.get()`.\n\nas mentioned at: How does group by works in sequelize? the `count` comes out as a string in PostgreSQL due to bigint shenanigans, and you need `parseInt` it\n\nHere's a minimal runnable example where we have posts and users who can like posts, and we want to count how:\n\n- how many likes each user has\n\n- ignoring likes to post2\n\n- considering only users that have 0 or 1 likes in total\n\nThe following small improvements are made over Piotr's code:\n\n- you likely don't want `attributes: ['*'` because that selects all columns, and therefore generally includes columns that are neither aggregates nor grouped by, leading to indeterminate behavior in some DBMSs and errors in others. You should just specify the GROUP by column instead, in our case the column is `name`.\n\n- using the slightly cleaner `Op.lte` rather than the literal `'\nDue to `required: false`, this first version does a `LEFT OUTER JOIN` + `COUNT(column)`, see also: https://dba.stackexchange.com/questions/174694/how-to-get-a-group-where-the-count-is-zero\n\nsqlite.js\n\n```\nconst assert = require('assert');\nconst { DataTypes, Op, Sequelize } = require('sequelize');\nconst sequelize = new Sequelize('tmp', undefined, undefined, Object.assign({\n dialect: 'sqlite',\n storage: 'tmp.sqlite'\n}));\n;(async () => {\nconst User = sequelize.define('User', {\n name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n body: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(Post, {through: 'UserLikesPost'});\nPost.belongsToMany(User, {through: 'UserLikesPost'});\nawait sequelize.sync({force: true});\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\nconst post0 = await Post.create({body: 'post0'})\nconst post1 = await Post.create({body: 'post1'})\nconst post2 = await Post.create({body: 'post2'})\n// Set likes for each user.\nawait user0.addPosts([post0, post1])\nawait user1.addPosts([post0, post2])\n\nlet rows = await User.findAll({\n attributes: [\n 'name',\n [sequelize.fn('COUNT', sequelize.col('Posts.id')), 'count'],\n ],\n include: [\n {\n model: Post,\n attributes: [],\n required: false,\n through: {attributes: []},\n where: { id: { [Op.ne]: post2.id }},\n },\n ],\n group: ['User.name'],\n order: [[sequelize.col('count'), 'DESC']],\n having: sequelize.where(sequelize.fn('COUNT', sequelize.col('Posts.id')), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].get('count'), 10), 1)\nassert.strictEqual(rows[1].name, 'user2')\nassert.strictEqual(parseInt(rows[1].get('count'), 10), 0)\nassert.strictEqual(rows.length, 2)\n})().finally(() => { return sequelize.close() });\n```\n\nwith:\n\npackage.json\n\n```\n{\n \"name\": \"tmp\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"dependencies\": {\n \"pg\": \"8.5.1\",\n \"pg-hstore\": \"2.3.3\",\n \"sequelize\": \"6.5.1\",\n \"sqlite3\": \"5.0.2\"\n }\n}\n```\n\nand Node v14.17.0.\n\nIf we wanted the `INNER JOIN` version excluding 0 counts, we could just remove the `required: false`, which makes it be the default `true`. We can also use do a slightly simpler `COUNT(*)` since there will be no NULLs now:\n\n```\nlet rows = await User.findAll({\n attributes: [\n 'name',\n [sequelize.fn('COUNT', '*'), 'count'],\n ],\n include: [\n {\n model: Post,\n attributes: [],\n through: {attributes: []},\n where: { id: { [Op.ne]: post2.id }},\n },\n ],\n group: ['User.name'],\n order: [[sequelize.col('count'), 'DESC']],\n having: sequelize.where(sequelize.fn('COUNT', '*'), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].get('count'), 10), 1)\nassert.strictEqual(rows.length, 1)\n```\n\n**PostgreSQL support has been broken for several years due to `column X must appear in the GROUP BY clause or be used in an aggregate function`**\n\nThe above code should work for PostgreSQL too, but as mentioned at:\n\n- https://github.com/sequelize/sequelize/issues/3256\n\n- https://github.com/sequelize/sequelize/issues/5481#issuecomment-964387232\n\nthere's a bug and it doesn't. The fact that such glaring bugs have persisted for several years make me doubt if I should really be using this ORM.\n\nThe workaround is to use both:\n\n```\nraw: true,\n includeIgnoreAttributes: false,\n```\n\nFull working example with the workaround:\n\n```\n#!/usr/bin/env node\nconst assert = require('assert');\nconst { DataTypes, Op, Sequelize } = require('sequelize');\nconst sequelize = new Sequelize('tmp', undefined, undefined, Object.assign({\n dialect: 'postgres',\n host: '/var/run/postgresql',\n}));\n;(async () => {\nconst User = sequelize.define('User', {\n name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n body: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(Post, {through: 'UserLikesPost'});\nPost.belongsToMany(User, {through: 'UserLikesPost'});\nawait sequelize.sync({force: true});\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\nconst post0 = await Post.create({body: 'post0'})\nconst post1 = await Post.create({body: 'post1'})\nconst post2 = await Post.create({body: 'post2'})\n// Set likes for each user.\nawait user0.addPosts([post0, post1])\nawait user1.addPosts([post0, post2])\n\nlet rows = await User.findAll({\n attributes: [\n 'name',\n [sequelize.fn('COUNT', '*'), 'count'],\n ],\n raw: true,\n includeIgnoreAttributes: false,\n include: [\n {\n model: Post,\n where: { id: { [Op.ne]: post2.id }},\n },\n ],\n group: ['User.name'],\n order: [[sequelize.col('count'), 'DESC']],\n having: sequelize.where(sequelize.fn('COUNT', '*'), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].count, 10), 1)\nassert.strictEqual(rows.length, 1)\n})().finally(() => { return sequelize.close() });\n```\n\ntested on PostgreSQL 13.4, Ubuntu 21.10.\n\n**Related**\n\nCounting associated entries with Sequelize\n\n========================================\n\nCode:\n```text\nSELECT families.id, count('answers.familyId') FROM families LEFT JOIN \nanswers on families.id = answers.familyId WHERE answers.isActive=1 AND\nanswers.answer=1 GROUP BY families.id HAVING COUNT('answers.familyId')>=6\n```\n\n```js\nFamily.findAll({\n    attributes: ['*', sequelize.fn('COUNT', sequelize.col('Answers.familyId'))],\n    include: [\n        {\n            model: Answer,\n            attributes: [],\n            where: {\n                isActive: 1,\n                answer: 1\n            }\n        }\n    ],\n    group: '\"Family.id\"',\n    having: sequelize.where(sequelize.fn('COUNT', sequelize.col('Answers.familyId')), '>=', 6)\n}).then((families) => {\n    // result\n});\n```\n\n```text\nFamily\n```\n\n```text\nfamilies\n```\n\n```text\nAnswer\n```\n\n```text\nanswers\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize.fn()\n```\n\n```text\nsequelize.where()\n```\n\n```text\nsequelize.col()\n```\n\n```text\nconst assert = require('assert');\nconst { DataTypes, Op, Sequelize } = require('sequelize');\nconst sequelize = new Sequelize('tmp', undefined, undefined, Object.assign({\n  dialect: 'sqlite',\n  storage: 'tmp.sqlite'\n}));\n;(async () => {\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(Post, {through: 'UserLikesPost'});\nPost.belongsToMany(User, {through: 'UserLikesPost'});\nawait sequelize.sync({force: true});\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\nconst post0 = await Post.create({body: 'post0'})\nconst post1 = await Post.create({body: 'post1'})\nconst post2 = await Post.create({body: 'post2'})\n// Set likes for each user.\nawait user0.addPosts([post0, post1])\nawait user1.addPosts([post0, post2])\n\nlet rows = await User.findAll({\n  attributes: [\n    'name',\n    [sequelize.fn('COUNT', sequelize.col('Posts.id')), 'count'],\n  ],\n  include: [\n    {\n      model: Post,\n      attributes: [],\n      required: false,\n      through: {attributes: []},\n      where: { id: { [Op.ne]: post2.id }},\n    },\n  ],\n  group: ['User.name'],\n  order: [[sequelize.col('count'), 'DESC']],\n  having: sequelize.where(sequelize.fn('COUNT', sequelize.col('Posts.id')), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].get('count'), 10), 1)\nassert.strictEqual(rows[1].name, 'user2')\nassert.strictEqual(parseInt(rows[1].get('count'), 10), 0)\nassert.strictEqual(rows.length, 2)\n})().finally(() => { return sequelize.close() });\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.5.1\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\nlet rows = await User.findAll({\n  attributes: [\n    'name',\n    [sequelize.fn('COUNT', '*'), 'count'],\n  ],\n  include: [\n    {\n      model: Post,\n      attributes: [],\n      through: {attributes: []},\n      where: { id: { [Op.ne]: post2.id }},\n    },\n  ],\n  group: ['User.name'],\n  order: [[sequelize.col('count'), 'DESC']],\n  having: sequelize.where(sequelize.fn('COUNT', '*'), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].get('count'), 10), 1)\nassert.strictEqual(rows.length, 1)\n```\n\n```text\nraw: true,\n  includeIgnoreAttributes: false,\n```\n\n```text\n#!/usr/bin/env node\nconst assert = require('assert');\nconst { DataTypes, Op, Sequelize } = require('sequelize');\nconst sequelize = new Sequelize('tmp', undefined, undefined, Object.assign({\n  dialect: 'postgres',\n  host: '/var/run/postgresql',\n}));\n;(async () => {\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n}, {});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n}, {});\nUser.belongsToMany(Post, {through: 'UserLikesPost'});\nPost.belongsToMany(User, {through: 'UserLikesPost'});\nawait sequelize.sync({force: true});\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\nconst post0 = await Post.create({body: 'post0'})\nconst post1 = await Post.create({body: 'post1'})\nconst post2 = await Post.create({body: 'post2'})\n// Set likes for each user.\nawait user0.addPosts([post0, post1])\nawait user1.addPosts([post0, post2])\n\nlet rows = await User.findAll({\n  attributes: [\n    'name',\n    [sequelize.fn('COUNT', '*'), 'count'],\n  ],\n  raw: true,\n  includeIgnoreAttributes: false,\n  include: [\n    {\n      model: Post,\n      where: { id: { [Op.ne]: post2.id }},\n    },\n  ],\n  group: ['User.name'],\n  order: [[sequelize.col('count'), 'DESC']],\n  having: sequelize.where(sequelize.fn('COUNT', '*'), Op.lte, 1)\n})\nassert.strictEqual(rows[0].name, 'user1')\nassert.strictEqual(parseInt(rows[0].count, 10), 1)\nassert.strictEqual(rows.length, 1)\n})().finally(() => { return sequelize.close() });\n```\n\n```text\nget()\n```\n\n```text\nattribute:\n```\n\n```text\ncount\n```\n\n```text\ncount\n```\n\n```text\nattributes\n```\n\n```text\nattributes\n```\n\n```text\n.get()\n```\n\n```text\ncount\n```\n\n```text\nparseInt\n```\n\n```text\nattributes: ['*'\n```\n\n```text\nname\n```\n\n```text\nOp.lte\n```\n\n```text\n'<='\n```\n\n```text\nrequired: false\n```\n\n```text\nLEFT OUTER JOIN\n```\n\n```text\nCOUNT(column)\n```\n\n```text\nINNER JOIN\n```\n\n```text\nrequired: false\n```\n\n```text\ntrue\n```\n\n```text\nCOUNT(*)\n```\n\n```text\ncolumn X must appear in the GROUP BY clause or be used in an aggregate function\n```\n\n========================================\n\nComments:\n- Had a similar problem and using the `includeIgnoreAttributes` + `raw` helped me! Thank you so much fella!","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":510,"estimatedTokens":3111}}299{"id":"stack-29499051","source":"stackoverflow","questionId":29499051,"title":"A Sequelize column that cannot be updated","tags":["mysql","node.js","rest","sequelize.js"],"text":"Title: A Sequelize column that cannot be updated\nTags: mysql, node.js, rest, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to create a column on a MySQL table using Sequelize that can be initialized when creating a new row, but never updated?\n\nFor example, a REST service allows a user to update his profile. He can change any field except his `id`. I can strip the `id` from the request on the API route, but that's a little redundant because there are a number of different models that behave similarly. Ideally, I'd like to be able to define a constraint in Sequelize that prevents the `id` column from being set to anything other than `DEFAULT`.\n\nCurrently, I'm using a `setterMethod` for the `id` to manually throw a `ValidationError`, but this seems hackish, so I was wondering if there's a cleaner way of doing this. Even worse is that this implementation still allows the `id` to be set when creating a new record, but I don't know a way around this as when Sequelize generates the query it calls `setterMethods.id` to set the value to `DEFAULT`.\n\n```\nreturn sequelize.define('Foo',\n {\n title: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n validate: {\n notEmpty: true\n }\n }\n },\n {\n setterMethods: {\n id: function (value) {\n if (!this.isNewRecord) {\n throw new sequelize.ValidationError(null, [\n new sequelize.ValidationErrorItem('readonly', 'id may not be set', 'id', value)\n ]);\n }\n }\n }\n }\n);\n```\n\n========================================\n\nCode:\n```text\nreturn sequelize.define('Foo',\n    {\n        title: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            unique: true,\n            validate: {\n                notEmpty: true\n            }\n        }\n    },\n    {\n        setterMethods: {\n            id: function (value) {\n                if (!this.isNewRecord) {\n                    throw new sequelize.ValidationError(null, [\n                        new sequelize.ValidationErrorItem('readonly', 'id may not be set', 'id', value)\n                    ]);\n                }\n            }\n        }\n    }\n);\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nDEFAULT\n```\n\n```text\nsetterMethod\n```\n\n```text\nid\n```\n\n```text\nValidationError\n```\n\n```text\nid\n```\n\n```text\nsetterMethods.id\n```\n\n```text\nDEFAULT\n```\n\n```text\n{\n  title: {\n    type: DataTypes.STRING,\n    allowNull: false,\n    unique   : true,\n    noUpdate : true\n  }\n}\n```\n\n```text\ntitle\n```\n\n========================================\n\nComments:\n- Just wondering the same. github.com/sequelize/sequelize/issues/4603","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":125,"estimatedTokens":639}}300{"id":"stack-59928730","source":"stackoverflow","questionId":59928730,"title":"Sequelize js how to get average (aggregate) of associated model","tags":["node.js","orm","sequelize.js","associations","aggregate-functions"],"text":"Title: Sequelize js how to get average (aggregate) of associated model\nTags: node.js, orm, sequelize.js, associations, aggregate-functions\nSource: Stack Overflow\n\nQuestion:\nI am trying to get average rating of an associated Model \"Rating\" of Model \"User\" using sequelize.\n\n```\nsequelize.sync({logging: false}).then(()=>{\n return Model.Rating.findAll({\n attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]\n })\n}).then(res => {\n res = res.map(r => r.get())\n console.log(res);\n})\n```\n\nI get correct response when trying directly from \"Rating\" Model:\n\n```\n[ { rating: '3.5000000000000000' } ]\n```\n\nHowever, when trying to do the same through the association of \"User\", I get separate values instead of getting average.\n\n```\nsequelize.sync({logging: false}).then(()=>{\n return Model.User.findOne({\n where: {id: 7},\n include : [{\n model: Model.Rating, as: 'seller_rating',\n attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]\n }],\n attributes: {\n exclude: ['password']\n },\n group: ['seller_rating.id', 'user.id'],\n })\n}).then(res => {\n res = res.get()\n res.seller_rating = res.seller_rating.map(r => r.get())\n console.log(res)\n})\n```\n\nI had to add \"seller_rating.id\" and \"user.id\" in group as sequelize was throwing error otherwise.\n\n```\n{\n id: 7,\n email: 'example@gmail.com',\n createdAt: 2020-01-20T09:07:47.101Z,\n updatedAt: 2020-01-21T08:58:52.036Z,\n seller_rating: [\n { rating: '4.0000000000000000' },\n { rating: '3.0000000000000000' }\n ]\n}\n```\n\nFollowing are the models for User and Rating\n**User:**\n\n```\nlet User = sequelize.define('user', {\n email: {type: Sequelize.STRING, unique: true, allowNull: false},\n password : {type: Sequelize.STRING, },\n})\n```\n\n**Rating:**\n\n```\nlet Rating = sequelize.define('rating', {\n seller_id: {\n type: Sequelize.INTEGER,\n references: {model: User, key: 'id'},\n unique: 'rateObject'\n },\n buyer_id: {\n type: Sequelize.INTEGER,\n references: {model: User, key: 'id'},\n unique: 'rateObject'\n },\n stars: {\n type: Sequelize.INTEGER,\n validate: {\n min: 1,\n max: 5\n },\n allowNull: false\n }\n})\n\nRating.belongsTo(User,{ onDelete: 'cascade', foreignKey: 'seller_id'})\nRating.belongsTo(User,{ onDelete: 'cascade', foreignKey: 'buyer_id'})\nUser.hasMany(Rating, { foreignKey: 'seller_id', as: 'seller_rating'})\nUser.hasMany(Rating, { foreignKey: 'buyer_id', as: 'buyer_rating'})\n```\n\n========================================\n\nTop Answer:\nThis solution should work for you:\n\n```\nModel.User.findOne({\n where: { id: 7 },\n attributes: [\n [Sequelize.fn('AVG', Sequelize.col('seller_rating.stars')), 'avgRating'],\n ],\n include: [\n {\n model: Model.Rating,\n as: 'seller_rating',\n attributes: [],\n },\n ],\n raw: true,\n group: ['User.id'],\n}).then((res) => console.log(res));\n```\n\n========================================\n\nCode:\n```text\nsequelize.sync({logging: false}).then(()=>{\n  return Model.Rating.findAll({\n    attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]\n  })\n}).then(res => {\n  res = res.map(r => r.get())\n  console.log(res);\n})\n```\n\n```text\n[ { rating: '3.5000000000000000' } ]\n```\n\n```text\nsequelize.sync({logging: false}).then(()=>{\n  return Model.User.findOne({\n    where: {id: 7},\n    include : [{\n      model: Model.Rating, as: 'seller_rating',\n      attributes: [[Sequelize.fn('avg', Sequelize.col('stars')),'rating']]\n    }],\n    attributes: {\n      exclude: ['password']\n    },\n    group: ['seller_rating.id', 'user.id'],\n  })\n}).then(res => {\n  res = res.get()\n  res.seller_rating = res.seller_rating.map(r => r.get())\n  console.log(res)\n})\n```\n\n```text\n{\n  id: 7,\n  email: 'example@gmail.com',\n  createdAt: 2020-01-20T09:07:47.101Z,\n  updatedAt: 2020-01-21T08:58:52.036Z,\n  seller_rating: [\n    { rating: '4.0000000000000000' },\n    { rating: '3.0000000000000000' }\n  ]\n}\n```\n\n```text\nlet User = sequelize.define('user', {\n    email: {type: Sequelize.STRING, unique: true, allowNull: false},\n    password : {type: Sequelize.STRING, },\n})\n```\n\n```text\nlet Rating = sequelize.define('rating', {\n    seller_id: {\n        type: Sequelize.INTEGER,\n        references: {model: User, key: 'id'},\n        unique: 'rateObject'\n    },\n    buyer_id: {\n        type: Sequelize.INTEGER,\n        references: {model: User, key: 'id'},\n        unique: 'rateObject'\n    },\n    stars: {\n        type: Sequelize.INTEGER,\n        validate: {\n            min: 1,\n            max: 5\n        },\n        allowNull: false\n    }\n})\n\nRating.belongsTo(User,{ onDelete: 'cascade', foreignKey: 'seller_id'})\nRating.belongsTo(User,{ onDelete: 'cascade', foreignKey: 'buyer_id'})\nUser.hasMany(Rating, { foreignKey: 'seller_id', as: 'seller_rating'})\nUser.hasMany(Rating, { foreignKey: 'buyer_id', as: 'buyer_rating'})\n```\n\n```text\nconst product = await Product.findOne({\n  where: {id: 1},\n  include: [\n    {\n      model: Rating, //including ratings array\n      as: 'ratings',\n      //no attributes, so nothing actually attaches to Product object\n      attributes: [],\n    },\n  ],\n  attributes: {\n    include: [ // this adds AVG attribute to others instead of rewriting whole body\n      [sequelize.fn('AVG', sequelize.col('ratings.rating')), 'avgRating'],\n    ],\n  },\n  group: ['Product.id'],\n});\n```\n\n```text\n{\n  \"id\": 1,\n  \"name\": \"product\",\n  \"price\": 50,\n  \"createdAt\": \"2022-04-21T11:32:56.666Z\",\n  \"updatedAt\": \"2022-04-21T11:32:56.666Z\",\n  \"categoryId\": 1,\n  \"avgRating\": \"2.7500000000000000\"\n}\n```\n\n```text\nModel.User.findOne({\n  where: { id: 7 },\n  attributes: [\n    [Sequelize.fn('AVG', Sequelize.col('seller_rating.stars')), 'avgRating'],\n  ],\n  include: [\n    {\n      model: Model.Rating,\n      as: 'seller_rating',\n      attributes: [],\n    },\n  ],\n  raw: true,\n  group: ['User.id'],\n}).then((res) => console.log(res));\n```\n\n========================================\n\nComments:\n- Is there anyway to do this with aggregate?","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":264,"estimatedTokens":1447}}301{"id":"stack-64648688","source":"stackoverflow","questionId":64648688,"title":"How to mock Sequelize with Jest?","tags":["typescript","unit-testing","jestjs","mocking","sequelize.js"],"text":"Title: How to mock Sequelize with Jest?\nTags: typescript, unit-testing, jestjs, mocking, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to write unit tests for code which makes calls to Sequelize to create a database.\n\nI cannot for the life of me figure out how to mock out calls to Sequelize such that I can assert they have created the database tables correctly.\n\nMy code which hits Sequelize is as follows:\n\n```\nimport { Sequelize, DataTypes } from \"sequelize\";\n\nexport setup_db = async (db_path: string) => {\n //Get read/write connection to database\n const sequelizeContext = new Sequelize({\n dialect: \"sqlite\",\n storage: db_path,\n });\n\n //Check if connection is secure, throw error if not\n try {\n await sequelizeContext.authenticate();\n } catch (err) {\n throw err;\n }\n\n //Define first table\n const Table1 = sequelizeContext.define(\n \"table1\",\n {\n fieldName_1: {\n type: DataTypes.STRING\n }\n },\n { tableName: \"table1\" }\n );\n\n //Define second table\n const Table2 = sequelizeContext.define(\n \"table2\", \n {\n fieldName_1: {\n type: DataTypes.STRING\n },\n {tablename: \"table2\"}\n });\n\n //Define relationship between tables... each Gamertag hasMany wzMatches\n Table1.hasMany(Table2);\n\n await Table1.sync();\n await Table2.sync();\n };\n```\n\nIdeally, I would like to assert that `define` was called properly, `hasMany` was called properly, and `sync` was called for each database.\n\nMy test code currently is as follows, although it throws an error about\n\nCannot spy the authenticate property because it is not a function; undefined given instead.\n\n```\nimport { setup_db } from \"../../core/dataManager\";\nconst Sequelize = require(\"sequelize\").Sequelize;\n\ndescribe(\"DataManager.setup_db\", () => {\n it(\"should call sequelize to correctly set up databases\", async () => {\n //Arrange\n const authenticateSpy = jest.spyOn(Sequelize, \"authenticate\");\n\n //Act\n await setup_db(\"path/to/db.db\");\n\n //Assert\n expect(authenticateSpy).toHaveBeenCalledTimes(1);\n });\n});\n```\n\nI'm not sure if `spyOn` is the right method to call, or whether I can/how I can use `jest.mock` to mock out and inspect calls to `Sequelize`.\n\n========================================\n\nCode:\n```js\nimport { Sequelize, DataTypes } from \"sequelize\";\n\nexport setup_db = async (db_path: string) => {\n    //Get read/write connection to database\n    const sequelizeContext = new Sequelize({\n      dialect: \"sqlite\",\n      storage: db_path,\n    });\n\n    //Check if connection is secure, throw error if not\n    try {\n      await sequelizeContext.authenticate();\n    } catch (err) {\n      throw err;\n    }\n\n    //Define first table\n    const Table1 = sequelizeContext.define(\n      \"table1\",\n      {\n        fieldName_1: {\n          type: DataTypes.STRING\n        }\n      },\n      { tableName: \"table1\" }\n    );\n\n    //Define second table\n    const Table2 = sequelizeContext.define(\n      \"table2\", \n      {\n        fieldName_1: {\n          type: DataTypes.STRING\n        },\n      {tablename: \"table2\"}\n    });\n\n    //Define relationship between tables... each Gamertag hasMany wzMatches\n    Table1.hasMany(Table2);\n\n    await Table1.sync();\n    await Table2.sync();\n  };\n```\n\n```js\nimport { setup_db } from \"../../core/dataManager\";\nconst Sequelize = require(\"sequelize\").Sequelize;\n\ndescribe(\"DataManager.setup_db\", () => {\n  it(\"should call sequelize to correctly set up databases\", async () => {\n    //Arrange\n    const authenticateSpy = jest.spyOn(Sequelize, \"authenticate\");\n\n    //Act\n    await setup_db(\"path/to/db.db\");\n\n    //Assert\n    expect(authenticateSpy).toHaveBeenCalledTimes(1);\n  });\n});\n```\n\n```text\ndefine\n```\n\n```text\nhasMany\n```\n\n```text\nsync\n```\n\n```text\nspyOn\n```\n\n```text\njest.mock\n```\n\n```text\nSequelize\n```\n\n```js\nimport { Sequelize, DataTypes } from 'sequelize';\n\nexport const setup_db = async (db_path: string) => {\n  const sequelizeContext = new Sequelize({\n    dialect: 'sqlite',\n    storage: db_path,\n  });\n\n  try {\n    await sequelizeContext.authenticate();\n  } catch (err) {\n    throw err;\n  }\n\n  const Table1 = sequelizeContext.define(\n    'table1',\n    {\n      fieldName_1: {\n        type: DataTypes.STRING,\n      },\n    },\n    { tableName: 'table1' },\n  );\n\n  const Table2 = sequelizeContext.define(\n    'table2',\n    {\n      fieldName_1: {\n        type: DataTypes.STRING,\n      },\n    },\n    { tableName: 'table2' },\n  );\n\n  (Table1 as any).hasMany(Table2);\n\n  await Table1.sync();\n  await Table2.sync();\n};\n```\n\n```js\nimport { setup_db } from './';\nimport { Sequelize, DataTypes } from 'sequelize';\nimport { mocked } from 'ts-jest/utils';\n\njest.mock('sequelize', () => {\n  const mSequelize = {\n    authenticate: jest.fn(),\n    define: jest.fn(),\n  };\n  const actualSequelize = jest.requireActual('sequelize');\n  return { Sequelize: jest.fn(() => mSequelize), DataTypes: actualSequelize.DataTypes };\n});\n\nconst mSequelizeContext = new Sequelize();\n\ndescribe('64648688', () => {\n  afterAll(() => {\n    jest.resetAllMocks();\n  });\n  it('should setup db correctly', async () => {\n    const mTable1 = { hasMany: jest.fn(), sync: jest.fn() };\n    const mTable2 = { sync: jest.fn() };\n    mocked(mSequelizeContext.define).mockImplementation((modelName): any => {\n      switch (modelName) {\n        case 'table1':\n          return mTable1;\n        case 'table2':\n          return mTable2;\n      }\n    });\n    await setup_db(':memory:');\n    expect(Sequelize).toBeCalledWith({ dialect: 'sqlite', storage: ':memory:' });\n    expect(mSequelizeContext.authenticate).toBeCalled();\n    expect(mSequelizeContext.define).toBeCalledWith(\n      'table1',\n      {\n        fieldName_1: {\n          type: DataTypes.STRING,\n        },\n      },\n      { tableName: 'table1' },\n    );\n    expect(mSequelizeContext.define).toBeCalledWith(\n      'table2',\n      {\n        fieldName_1: {\n          type: DataTypes.STRING,\n        },\n      },\n      { tableName: 'table2' },\n    );\n    expect(mTable1.hasMany).toBeCalledWith(mTable2);\n    expect(mTable1.sync).toBeCalledTimes(1);\n    expect(mTable2.sync).toBeCalledTimes(1);\n  });\n});\n```\n\n```text\nPASS  src/stackoverflow/64648688/index.test.ts (16.442s)\n  64648688\n    ✓ should setup db correctly (11ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |    91.67 |      100 |      100 |    90.91 |                   |\n index.ts |    91.67 |      100 |      100 |    90.91 |                12 |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        20.184s\n```\n\n```text\nsequelize\n```\n\n```text\nindex.ts\n```\n\n```text\nindex.test.ts\n```\n\n========================================\n\nComments:\n- I do find that in the example you provided, if I have another test case, I am not able to have two different behaviors. See my question here: stackoverflow.com/questions/76039291/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":308,"estimatedTokens":1750}}302{"id":"stack-43122077","source":"stackoverflow","questionId":43122077,"title":"Left excluding join in sequelize","tags":["sequelize.js"],"text":"Title: Left excluding join in sequelize\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two tables, where one table has the ID of the other. 1:1 relation.\nSo something like\n\n```\nEventFeedback\n somePrimaryKey\n userEventID\nUserEvent\n userEventID\n```\n\nSequalize has the relation defined with \n\n```\nmodels.UserEvent.hasOne(models.EventFeedback, { foreignKey: 'userEventID' });\n```\n\nI need all entries in `UserEvent` that do not have an entry in `EventFeedback`, which is an exclusionary join.\nStealing images from this article because they have nice individual images: https://i.sstatic.net/pNyOw.png\n\nThey even give example code!\n\n```\nSELECT \nFROM Table_A A\nLEFT JOIN Table_B B\nON A.Key = B.Key\nWHERE B.Key IS NULL\n```\n\nHow do I do this in sequelize?\nDo I just need to do a left join and process it manually?\n\n========================================\n\nTop Answer:\nBy default SEQUALIZE always use INNER JOIN. \nIt's very easy to make it LEFT JOIN.\nJust add the...\n\n```\nrequired: false\n```\n\nalong with the code.\n the sample query code.\n\n```\nUserModel.findAll({\n attributes: {\n exclude: ['role_id', 'username', 'password', 'otp', 'active']\n },\n where: {\n active: 1,\n role_id: 2\n },\n include: [{\n model: StateModel,\n attributes: ['id', 'short_name'],\n as: 'state_details',\n where: {\n active: 1\n },\n required: false\n }]\n }).then(List => {\n console.log(List);\n }).catch(err => {\n console.log(err); \n });\n```\n\n========================================\n\nCode:\n```text\nEventFeedback\n    somePrimaryKey\n    userEventID\nUserEvent\n    userEventID\n```\n\n```text\nmodels.UserEvent.hasOne(models.EventFeedback, { foreignKey: 'userEventID' });\n```\n\n```text\nSELECT <select_list> \nFROM Table_A A\nLEFT JOIN Table_B B\nON A.Key = B.Key\nWHERE B.Key IS NULL\n```\n\n```text\nUserEvent\n```\n\n```text\nEventFeedback\n```\n\n```js\nUserEvent.findAll({\n    include: [{\n        model: EventFeedback,\n        required: false, // do not generate INNER JOIN\n        attributes: [] // do not return any columns of the EventFeedback table\n    }],\n    where: sequelize.where(\n        sequelize.col('EventFeedback.userEventID'),\n        'IS',\n        null\n    )\n}).then(userEvents => {\n    // user events...\n});\n```\n\n```text\nEventFeedback\n```\n\n```text\nUserEvent\n```\n\n```text\nwhere\n```\n\n```text\nEventFeedback\n```\n\n```text\nLEFT JOIN\n```\n\n```text\nINNER JOIN\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize.where()\n```\n\n```text\nsequelize.col()\n```\n\n```text\nrequired: false\n```\n\n```text\nUserModel.findAll({\n        attributes: {\n            exclude: ['role_id', 'username', 'password', 'otp', 'active']\n        },\n        where: {\n            active: 1,\n            role_id: 2\n        },\n        include: [{\n            model: StateModel,\n            attributes: ['id', 'short_name'],\n            as: 'state_details',\n            where: {\n                active: 1\n            },\n            required: false\n        }]\n    }).then(List => {\n        console.log(List);\n    }).catch(err => {\n        console.log(err);            \n });\n```\n\n```text\nUserEvent.findAll({\n    include: [\n      {\n        model: EventFeedback,\n        as: 'feedback',\n        on: { user_event_id: null },\n      },\n    ]\n  });\n```\n\n========================================\n\nComments:\n- adding `required:false` isn't enough.","metadata":{"transformedAt":"2026-08-18T18:33:34.363Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":206,"estimatedTokens":813}}303{"id":"stack-38069797","source":"stackoverflow","questionId":38069797,"title":"Easy way to handle nested transactions","tags":["node.js","sequelize.js"],"text":"Title: Easy way to handle nested transactions\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSuppose there is an \"addUser\" function, inside we need to insert a record to \"Account\" table and \"User\" table, so the two steps have to be within a transaction too, so we will write the following code: \n\n```\nfunction addUser (userName, password) {\n sequelize.transaction(function () {\n return AccountModel.create(...)\n .then(UserModel.create(...)) \n })\n}\n```\n\nHowever, in another \"addTeam\" function, inside we need to insert a record to \"Team\" table and create a admin user using the above function. The function also need to be wrapped inside a transaction. \n\nSo the problem comes, the \"addUser\" function sometimes need to begin a new transaction, and sometimes need to use the transaction passed in. The most obvious ways is below: \n\n```\nfunction addUser (userName, password, transaction) {\n let func = function (t) {\n return AccountModel.create(..., t)\n .then(()=>UserModel.create(..., t)));\n if (transaction) func(t);\n else sequelize.transaction(x=>func(t));\n}\n\nfunction addTeam() {\n sequelize.transaction(x=> {\n TeamModel.create(..., x)\n .then(y=>addUser(x));\n });\n}\n```\n\nObviously, it is awful. How to deal with it easily, which let transaction totally transparent to the caller like below: \n\n```\n@Transaction\nasync function addUser(userName, password) {\n await AccountModel.create(...);\n await UserModel.create(...);\n}\n\n@Transaction\nasync function addTeam(...) {\n await TeamModel.create(...);\n await addUser(...);\n}\n```\n\n========================================\n\nTop Answer:\n`sequelize.transaction` accepts an options object - If `options.transaction` is set, this will create a savepoint in the transaction (provided that the SQL dialects supports it), otherwise it will create a new transaction\n\nhttp://docs.sequelizejs.com/en/latest/api/sequelize/#transactionoptions-promise\n\nSo you should be able to do simply\n\n```\nsequelize.transaction({ transaction }, x=>func(t));\n```\n\n========================================\n\nCode:\n```text\nfunction addUser (userName, password) {\n    sequelize.transaction(function () {\n        return AccountModel.create(...)\n        .then(UserModel.create(...))    \n    })\n}\n```\n\n```text\nfunction addUser (userName, password, transaction) {\n       let func = function (t) {\n           return  AccountModel.create(..., t)\n           .then(()=>UserModel.create(..., t)));\n       if (transaction) func(t);\n       else sequelize.transaction(x=>func(t));\n}\n\nfunction addTeam() {\n     sequelize.transaction(x=> {\n         TeamModel.create(..., x)\n         .then(y=>addUser(x));\n     });\n}\n```\n\n```text\n@Transaction\nasync function addUser(userName, password) {\n    await AccountModel.create(...);\n    await UserModel.create(...);\n}\n\n@Transaction\nasync function addTeam(...) {\n    await TeamModel.create(...);\n    await addUser(...);\n}\n```\n\n```text\nlet namespace = Sequelize.cls = cls.createNamespace('myschool');\nexport const db = new Sequelize(config.db.url);\n\nexport const trans = option => operation => async function () {\n    let t = namespace.get('transaction');\n    let hasTrans = !!t;\n    t = t  || await db.transaction();\n    try {\n        let result = await operation.apply(null, arguments);\n        if (!hasTrans) await t.commit();\n        return result;\n    }\n    catch (e) {\n        if (!hasTrans) await t.rollback();\n        throw e;\n    }\n};\n```\n\n```text\nexport const createSchool = trans()( async (name, accountProps) => {\n    let school = await SchoolModel.create({name});\n    let teacher = await createTeacher({...accountProps, schoolId: school.get('id')});\n    return {school, teacher};\n});\n```\n\n```text\nsequelize.transaction({ transaction }, x=>func(t));\n```\n\n```text\nsequelize.transaction\n```\n\n```text\noptions.transaction\n```\n\n```js\nconst cls = require('continuation-local-storage');\nconst Sequelize = require('sequelize');\nconst NAMESPACE = 'your-namespace';\n\n// Use CLS for Sequelize\nSequelize.cls = cls.createNamespace(NAMESPACE);\nconst sequelize = new Sequelize(...);\n\n/* * * * * * * * * * * * * * * * * * * * *\n * THE MAGIC: Create a transaction wrapper\n * * * * * * * * * * * * * * * * * * * * */\n\nfunction transaction(task) {\n  return cls.getNamespace(NAMESPACE).get('transaction') ? task() : sequelize.transaction(task);\n};\n\n/* * * * * * * * * * * * * * * * * * * * *\n * Your code below\n * * * * * * * * * * * * * * * * * * * * */\n\nfunction addUser(userName, password) {\n  return transaction(function() {\n    return AccountModel\n      .create(...)\n      .then(() => UserModel.create(...));\n  });\n}\n\nfunction addTeam() {\n  return transaction(function() {\n    return TeamModel\n      .create(...)\n      .then(() => addUser(...));\n  });\n}\n```\n\n```text\ntry{\n      // create a transaction\n      let transaction = await sequelize.transaction();\n      // \"parent\" insertion, id is auto increment, so we will need the id of inserted data\n      let record = await Parent_Record.create({ \n        data_1: req.params.data1,\n        data_2: req.params.data2,\n        ....\n        }, {transaction});\n        //the array contains data depending upon the id of inserted parent transaction \n        for ( x  in dataForChildTable) {\n          result = await Child_Record.create({\n          id: record.id, //same transaction so we can use record.id of parent\n          .....\n          other_data: dataForChildTable[x].otherData}, {transaction});\n      }\n      //commit the transaction\n      await transaction.commit();\n    } catch (err) {\n      console.log(err.message);\n    }\n```\n\n```text\nimport { Transactional, Tx } from 'zb-sequelize';\n\n@Transactional\nfunction addUser(user, password, @Tx transaction) {\n  // no need to create, commit or rollback a transaction.\n}\n```\n\n```text\nimport { Sequelize } from 'sequelize';\nimport { initSequelizeResolver } from 'zb-sequelize';\n\n// you already have this somewhere.\nconst sequelize = new Sequelize(options);\n\n// you need to add this:\ninitSequelizeResolver((args) => sequelize);\n```\n\n```text\nsequelize\n```\n\n========================================\n\nComments:\n- I actually want the transaction to be transparent to the caller, but your solution still need the caller kown it.\n- This does not appear to be a `sequelize.transaction` option. Current (5.x) options are `type`, `isolationLevel`, `deferrable`, `logging`, and `autoCallback`. The option `transaction` is not specified. A PR is needed for sequelize, as this is an undocumented option: github.com/sequelize/sequelize/issues/10840\n- There is a discussion in v5.x to remove cls: github.com/sequelize/sequelize/issues/10819\n- There is a discussion in v5.x to remove cls: github.com/sequelize/sequelize/issues/10819\n- @coler-j The `cls-hooked` is now considered a valid option, and the cls support is no longer considered to be dropped.\n- @Vladius Actually, cls will be set as default in v7 sequelize.org/docs/v7/querying/transactions/#disabling-cls\n- How is this a nested transaction. I only see 1 transaction...\n- @Glen you are right, i may misinterpreted the question a bit. I modified the answer so it is more clear which issue it addresses. Thank you for pointing it out.","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":246,"estimatedTokens":1780}}304{"id":"stack-33091197","source":"stackoverflow","questionId":33091197,"title":"Sequelize - Cannot read property 'define' of undefined","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize - Cannot read property 'define' of undefined\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to insert a record into MYSQL table using sequelize.\n\nInstalled sequelize and mysql.\n\n```\nnpm install --save sequelize\n\nnpm install --save mysql\n```\n\ndefined it in app.js\n\n```\nvar Sequelize = require('sequelize');\n```\n\ndb.js\n\n```\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('randomdb', 'root', 'root', {\n host: 'localhost',\n dialect: 'mysql',\n port : 8889,\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n }\n});\n\nexports.sequelize = sequelize;\nmodule.exports = Sequelize;\n```\n\nroutes/index.js\n\n```\nvar express = require('express');\nvar router = express.Router();\nvar sequelize = require('../db').sequelize;\n\n/* GET home page. */\nrouter.get('/', function (req, res, next) {\n res.render('index', {title: 'Express'});\n});\n\nrouter.get('/adduser', function (req, res) {\n var User = sequelize.define('users', {\n first_name: Sequelize.STRING\n });\n\n sequelize.sync().then(function () {\n return User.create({\n first_name: 'janedoe'\n });\n }).then(function (jane) {\n console.log(jane.get({\n plain: true\n }))\n });\n});\n\nmodule.exports = router;\n```\n\nHere's the error.\n\n Cannot read property 'define' of undefined\n\n \n TypeError: Cannot read property 'define' of undefined\n\nWhat's missing?\n\n**EDIT 2**\n\ndb.js\n\n```\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('randomdb', 'root', 'root', {\n host: 'localhost',\n dialect: 'mysql',\n port: 8889,\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n },\n define: {\n timestamps: false\n }\n});\n\nvar db = {};\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nmodels/user.js\n\n```\nvar db = require('../db'),\n sequelize = db.sequelize,\n Sequelize = db.Sequelize;\n\nvar User = sequelize.define('random', {\n first_name: Sequelize.STRING\n});\n\nmodule.exports = User;\n```\n\nroutes/index.js\n\n```\nvar express = require('express');\nvar router = express.Router();\nvar db = require('../db'),\n sequelize = db.sequelize,\n Sequelize = db.Sequelize;\n\nvar User = require('../models/user');\n\nrouter.get('/adduseryes', function (req, res) {\n sequelize.sync().then(function () {\n return User.create({\n first_name: 'janedoe'\n });\n }).then(function (jane) {\n res.send(\"YES\");\n });\n});\n\nmodule.exports = router;\n```\n\n========================================\n\nCode:\n```text\nnpm install --save sequelize\n\nnpm install --save mysql\n```\n\n```text\nvar Sequelize = require('sequelize');\n```\n\n```text\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('randomdb', 'root', 'root', {\n    host: 'localhost',\n    dialect: 'mysql',\n    port : 8889,\n\n    pool: {\n        max: 5,\n        min: 0,\n        idle: 10000\n    }\n});\n\nexports.sequelize = sequelize;\nmodule.exports = Sequelize;\n```\n\n```text\nvar express = require('express');\nvar router = express.Router();\nvar sequelize = require('../db').sequelize;\n\n/* GET home page. */\nrouter.get('/', function (req, res, next) {\n    res.render('index', {title: 'Express'});\n});\n\nrouter.get('/adduser', function (req, res) {\n    var User = sequelize.define('users', {\n        first_name: Sequelize.STRING\n    });\n\n    sequelize.sync().then(function () {\n        return User.create({\n            first_name: 'janedoe'\n        });\n    }).then(function (jane) {\n        console.log(jane.get({\n            plain: true\n        }))\n    });\n});\n\nmodule.exports = router;\n```\n\n```text\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('randomdb', 'root', 'root', {\n    host: 'localhost',\n    dialect: 'mysql',\n    port: 8889,\n\n    pool: {\n        max: 5,\n        min: 0,\n        idle: 10000\n    },\n    define: {\n        timestamps: false\n    }\n});\n\nvar db = {};\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nvar db = require('../db'),\n    sequelize = db.sequelize,\n    Sequelize = db.Sequelize;\n\nvar User = sequelize.define('random', {\n    first_name: Sequelize.STRING\n});\n\nmodule.exports = User;\n```\n\n```text\nvar express = require('express');\nvar router = express.Router();\nvar db = require('../db'),\n    sequelize = db.sequelize,\n    Sequelize = db.Sequelize;\n\nvar User = require('../models/user');\n\nrouter.get('/adduseryes', function (req, res) {\n    sequelize.sync().then(function () {\n        return User.create({\n            first_name: 'janedoe'\n        });\n    }).then(function (jane) {\n        res.send(\"YES\");\n    });\n});\n\nmodule.exports = router;\n```\n\n```text\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize(...);\n\nvar db = {};\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nvar db = require('../db'),\n  sequelize = db.sequelize,\n  Sequelize = db.Sequelize;\n```\n\n```text\nexports\n```\n\n```text\nmodule.exports\n```\n\n```text\nexports\n```\n\n========================================\n\nComments:\n- Try alter for tiny: `first_name: Sequelize.STRING` to `first_name: sequelize.STRING`\n- It works, thank you. Could you please check EDIT2? I made a few changes, right now it works but I wonder something. In `user.js`, I put `module.exports = User;` , then used this in `index.js`as `var User = require('..&#47;models&#47;user');` Is my `User` variable in the `index.js` looks for other one? Is that how it works?\n- I don't completely understand your question, but if you are confused about what each variable is, you could always just print them out with `console.log`. Also, you may want to examine your new code because the callback of creating the user might not get called correctly.\n- Okay, let's put it that way. We \"throw\" db in the db.js using module.exports and \"catch\" in the routes/index.js as db with require, is that right? Hope it's clear now :) Thank you again.\n- The naming of the variables is arbitrary and you could name it whatever when you import it with `require`. You could say `var abcd = require('..&#47;db'),` `sequelize = abcd.sequelize,` `Sequelize = abcd.Sequelize`.\n- i faced the same issue, probably there could be the typo error. example Users.create({foo: 1}). check users is correct.","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":311,"estimatedTokens":1520}}305{"id":"stack-44751996","source":"stackoverflow","questionId":44751996,"title":"Sequelize v4 | Instance Methods not working","tags":["node.js","sequelize.js"],"text":"Title: Sequelize v4 | Instance Methods not working\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've been trying to update my code to accommodate the newest upgrades to Sequelize. I'm using \n\nSequelize: 4.2.0\n\nNode: 7.10.0\n\nNPM: 5.0.3\n\n**The Problem**\n\nI can't seem to set the User model properly. I've implemented some instance methods that don't seem to be working. The class must not be instantiated properly. \n\n**user.js**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n var User = sequelize.define('user', {\n attributes ....\n }, { \n hooks: { \n afterCreate(user, options) {\n user.testFunction();\n }\n }\n });\n\n // Instance methods\n User.prototype.testFunction = () => {\n this.firstName = \"John\";\n }\n\n // Class methods\n User.anotherTestFunction = () => {\n User.findOne().then(() => doSomething());\n }\n\n return User;\n}\n```\n\n**index.js**\n\n```\nvar sequelize;\nsequelize = new Sequelize(config.DATABASE_URL);\n\ndb.User = sequelize.import(__dirname + '/user.js');\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n**usersController.js**\n\n```\nvar db = require('../path/to/db');\n\nfunction create_post_function = (req, res) => {\n var body = getBody();\n db.User.create(body).then(user => respondSuccess());\n}\n```\n\nNow, everything in this example works perfectly EXCEPT the instance method!!!\n\nI'm continually getting `TypeError: Cannot set property 'firstName' of undefined`\n\nFor some reason, it's not applying the instance method to the sequelize Model. Very strange, but I'm probably doing something noticeably wrong and not seeing it.\n\nReally appreciate any help!\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  var User = sequelize.define('user', {\n    attributes ....\n  }, { \n    hooks: { \n      afterCreate(user, options) {\n        user.testFunction();\n      }\n    }\n  });\n\n  // Instance methods\n  User.prototype.testFunction = () => {\n    this.firstName = \"John\";\n  }\n\n  // Class methods\n  User.anotherTestFunction = () => {\n    User.findOne().then(() => doSomething());\n  }\n\n  return User;\n}\n```\n\n```text\nvar sequelize;\nsequelize = new Sequelize(config.DATABASE_URL);\n\ndb.User = sequelize.import(__dirname + '/user.js');\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nvar db = require('../path/to/db');\n\nfunction create_post_function = (req, res) => {\n  var body = getBody();\n  db.User.create(body).then(user => respondSuccess());\n}\n```\n\n```text\nTypeError: Cannot set property 'firstName' of undefined\n```\n\n```text\n// Instance methods\nUser.prototype.testFunction = function testFunction() {\n  this.firstName = \"John\";\n}\n\n// Class methods\nUser.anotherTestFunction = function anotherTestFunction() {\n  User.findOne().then(() => doSomething());\n}\n```\n\n```text\nthis\n```\n\n========================================\n\nComments:\n- I've never felt so lucky to find an answer. I had no idea you couldn't use `this` with arrow functions. I would have wasted so much time looking in the wrong direction.\n- Actually you can use 'this' in the arrow functions, but context will be set from parent env.","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":153,"estimatedTokens":783}}306{"id":"stack-60092875","source":"stackoverflow","questionId":60092875,"title":"Where to define sequelize associations","tags":["node.js","sequelize.js"],"text":"Title: Where to define sequelize associations\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize in my Node js app. All of the models are defined in separate files named, for instance, `user.js`, `message.js` and so on. I also have the `index.js` file that's auto-generated, here's a snippet of it, you'll probably recognize it:\n\n```\nif (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n .readdirSync(__dirname)\n .filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n .forEach(file => {\n const model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n```\n\nSo I'm looking at the associations manual of sequelize here.\nThe thing I can't figure out is where this would go in my case, since I'm using the auto-generated `index.js` file which gathers all the `models`. In their example, as you can see on the link, they've got something like:\n\n```\nconst A = sequelize.define('A', /* ... */);\nconst B = sequelize.define('B', /* ... */);\n\nA.hasOne(B); // A HasOne B\nA.belongsTo(B); // A BelongsTo B\nA.hasMany(B); // A HasMany B\nA.belongsToMany(B, { through: 'C' });\n```\n\nHow would I do the same thing when my models are spread across multiple files? I've tried something like this (for instance, in the message model):\n\n```\nreturn sequelize.define('message', {\n message_id: {\n type: DataTypes.BIGINT,\n allowNull: false,\n autoIncrement:true,\n primaryKey: true\n },\n user_id: {\n type: DataTypes.BIGINT,\n allowNull: true\n }\n // and other stuff..\n }, {\n tableName: 'message'\n }).hasOne(require('./user'));\n};\n```\n\nwhich gives an error: ***message.hasOne called with something that's not a subclass of Sequelize.Model***\n\nAny ideas?\n\nThanks.\n\n========================================\n\nTop Answer:\nHere is another option. After a lot of try and fail\n\nHope helps other people\n\n```\n// there must be the default express generated models/index.js\n\n// user.js\nconst { Model } = require('sequelize')\nmodule.exports = (sequelize, DataTypes) => {\n class User extends Model {\n static associate(models) {\n User.hasMany(models.Restaurant, {\n as: 'restaurants',\n foreignKey: { name: 'user_id', type: DataTypes.UUID },\n })\n }\n }\n User.init({\n id: {\n type: DataTypes.UUID,\n primaryKey: true,\n allowNull: false,\n },\n // ...\n }, {\n sequelize,\n modelName: 'User',\n tableName: 'users',\n paranoid: true,\n })\n return User\n}\n\nrestaurant.js\nconst {\n Model,\n} = require('sequelize')\n\nmodule.exports = (sequelize, DataTypes) => {\n class Restaurant extends Model {\n static associate(models) {\n Restaurant.belongsTo(models.User, {\n foreignKey: { name: 'user_id', type: DataTypes.UUID },\n as: 'user',\n })\n }\n }\n Restaurant.init({\n id: {\n type: DataTypes.UUID,\n primaryKey: true,\n allowNull: false,\n },\n user_id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n field: 'user_id',\n },\n // ...\n }, {\n sequelize,\n modelName: 'Restaurant',\n tableName: 'restaurants',\n paranoid: true,\n })\n return Restaurant\n}\n\n// in the consumer app.js\nconst { User, Restaurant } = require('../../models/index')\n//...\nconst user = await User.findOne({ where: { id }, include: { model: Restaurant, as: 'restaurants' } })\nconst response = {\n first_name: user.first_name,\n last_name: user.last_name,\n email: user.email,\n restaurants: user.restaurants,\n}\nreturn response\n```\n\n========================================\n\nCode:\n```text\nif (config.use_env_variable) {\n  sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n  sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n  .readdirSync(__dirname)\n  .filter(file => {\n    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n  })\n  .forEach(file => {\n    const model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(modelName => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n```\n\n```text\nconst A = sequelize.define('A', /* ... */);\nconst B = sequelize.define('B', /* ... */);\n\nA.hasOne(B); // A HasOne B\nA.belongsTo(B); // A BelongsTo B\nA.hasMany(B); // A HasMany B\nA.belongsToMany(B, { through: 'C' });\n```\n\n```text\nreturn sequelize.define('message', {\n    message_id: {\n      type: DataTypes.BIGINT,\n      allowNull: false,\n      autoIncrement:true,\n      primaryKey: true\n    },\n    user_id: {\n      type: DataTypes.BIGINT,\n      allowNull: true\n    }\n    // and other stuff..\n  }, {\n    tableName: 'message'\n  }).hasOne(require('./user'));\n};\n```\n\n```text\nuser.js\n```\n\n```text\nmessage.js\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\nmodels\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const MyEntity = sequelize.define(\n    'MyEntity',\n    {\n      name: DataTypes.STRING\n    },\n    {}\n  );\n  MyEntity.associate = function(models) {\n    // associations can be defined here\n    MyEntity.hasMany(models.OtherEntity, {\n      foreignKey: 'myEntityId',\n      as: 'myEntities'\n    });\n  };\n  return MyEntity;\n};\n```\n\n```js\n// there must be the default express generated models/index.js\n\n// user.js\nconst { Model } = require('sequelize')\nmodule.exports = (sequelize, DataTypes) => {\n  class User extends Model {\n    static associate(models) {\n      User.hasMany(models.Restaurant, {\n        as: 'restaurants',\n        foreignKey: { name: 'user_id', type: DataTypes.UUID },\n      })\n    }\n  }\n  User.init({\n    id: {\n      type: DataTypes.UUID,\n      primaryKey: true,\n      allowNull: false,\n    },\n    // ...\n  }, {\n    sequelize,\n    modelName: 'User',\n    tableName: 'users',\n    paranoid: true,\n  })\n  return User\n}\n\nrestaurant.js\nconst {\n  Model,\n} = require('sequelize')\n\nmodule.exports = (sequelize, DataTypes) => {\n  class Restaurant extends Model {\n    static associate(models) {\n      Restaurant.belongsTo(models.User, {\n        foreignKey: { name: 'user_id', type: DataTypes.UUID },\n        as: 'user',\n      })\n    }\n  }\n  Restaurant.init({\n    id: {\n      type: DataTypes.UUID,\n      primaryKey: true,\n      allowNull: false,\n    },\n    user_id: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      field: 'user_id',\n    },\n    // ...\n  }, {\n    sequelize,\n    modelName: 'Restaurant',\n    tableName: 'restaurants',\n    paranoid: true,\n  })\n  return Restaurant\n}\n\n\n// in the consumer app.js\nconst { User, Restaurant } = require('../../models/index')\n//...\nconst user = await User.findOne({ where: { id }, include: { model: Restaurant, as: 'restaurants' } })\nconst response = {\n  first_name: user.first_name,\n  last_name: user.last_name,\n  email: user.email,\n  restaurants: user.restaurants,\n}\nreturn response\n```\n\n========================================\n\nComments:\n- I have exactly the same issue","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":341,"estimatedTokens":1777}}307{"id":"stack-58086800","source":"stackoverflow","questionId":58086800,"title":"NodeJS Sequelize: Association with alias [alias] does not exist on [model]","tags":["node.js","postgresql","express","sequelize.js","associations"],"text":"Title: NodeJS Sequelize: Association with alias [alias] does not exist on [model]\nTags: node.js, postgresql, express, sequelize.js, associations\nSource: Stack Overflow\n\nQuestion:\ni'm using NodeJS & Sequelize for a school project and i'm struggling on making associations w/ sequelize work. I tried a couple of things before but nothing that made my day.\n\nBasically the thing is that a user can have several playlists (hasMany).\nAnd a playlist belongs to a user (belongsTo).\n\nMy error is:\n**Association with alias \"playlist\" does not exist on users**\n\nHere are my models:\n\n```\n/* USER MODEL */\nconst Sequelize = require('sequelize');\nconst { db } = require('../utils/db');\n\nconst User = db.define('users', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER,\n },\n userID: {\n type: Sequelize.INTEGER,\n allowNull: false,\n field: 'user_id',\n },\n firstName: {\n type: Sequelize.STRING,\n field: 'first_name',\n allowNull: false,\n },\n}, {\n underscored: true,\n tableName: 'users',\n freezeTableName: true, // Model tableName will be the same as the model name\n});\n\nmodule.exports = {\n User,\n};\n```\n\n```\n/* PLAYLIST MODEL */\n\nconst sequelize = require('sequelize');\nconst { db } = require('../utils/db');\n\nconst Playlist = db.define('playlist', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: sequelize.INTEGER,\n },\n name: {\n type: sequelize.STRING,\n field: 'name',\n allowNull: false,\n },\n coverUrl: {\n type: sequelize.STRING,\n field: 'cover_url',\n allowNull: true,\n },\n ownerId: {\n type: sequelize.INTEGER,\n allowNull: false,\n references: {\n model: 'users',\n key: 'user_id',\n },\n },\n}, {\n underscored: true,\n tableName: 'playlist',\n freezeTableName: true,\n});\n\nmodule.exports = {\n Playlist,\n};\n```\n\nHere is how i load my models:\n\n```\nconst { Credentials } = require('./credentials');\nconst { User } = require('./users');\nconst { Playlist } = require('./playlist');\n\nfunction loadModels() {\n User.associate = (models) => {\n User.hasMany(models.Playlist, { as: 'playlist' });\n };\n\n Playlist.associate = (models) => {\n Playlist.belongsTo(models.User, { foreignKey: 'owner_id', as: 'owner' });\n };\n\n Credentials.sync({ force: false });\n User.sync({ force: false });\n Playlist.sync({ force: false });\n}\n\nmodule.exports = {\n loadModels,\n};\n```\n\nAnd finally here is my query where i get this error:\n\n```\nconst express = require('express');\nconst { auth } = require('../../middlewares/auth');\nconst { Playlist } = require('../../models/playlist');\nconst { User } = require('../../models/users');\n\nconst router = express.Router();\n\nrouter.get('/playlist', [], auth, (req, res) => {\n User.findOne({\n where: { userID: req.user.user_id }, include: 'playlist',\n }).then((r) => {\n console.log(r);\n });\n});\n\nmodule.exports = router;\n```\n\nI'm trying to get all the playlist that belongs to a user.\n\nI removed all the useless code (jwt check etc..)\nSo when i'm doing a get request on /playlist I get:\n**Unhandled rejection Error: Association with alias \"playlist\" does not exist on users**.\n\nI understand the error but don't understand why i get this.\nWhat did I miss, any ideas ?\n\nThanks,\n\n========================================\n\nCode:\n```text\n/* USER MODEL */\nconst Sequelize = require('sequelize');\nconst { db } = require('../utils/db');\n\nconst User = db.define('users', {\n  id: {\n    allowNull: false,\n    autoIncrement: true,\n    primaryKey: true,\n    type: Sequelize.INTEGER,\n  },\n  userID: {\n    type: Sequelize.INTEGER,\n    allowNull: false,\n    field: 'user_id',\n  },\n  firstName: {\n    type: Sequelize.STRING,\n    field: 'first_name',\n    allowNull: false,\n  },\n}, {\n  underscored: true,\n  tableName: 'users',\n  freezeTableName: true, // Model tableName will be the same as the model name\n});\n\nmodule.exports = {\n  User,\n};\n```\n\n```text\n/* PLAYLIST MODEL */\n\nconst sequelize = require('sequelize');\nconst { db } = require('../utils/db');\n\nconst Playlist = db.define('playlist', {\n  id: {\n    allowNull: false,\n    autoIncrement: true,\n    primaryKey: true,\n    type: sequelize.INTEGER,\n  },\n  name: {\n    type: sequelize.STRING,\n    field: 'name',\n    allowNull: false,\n  },\n  coverUrl: {\n    type: sequelize.STRING,\n    field: 'cover_url',\n    allowNull: true,\n  },\n  ownerId: {\n    type: sequelize.INTEGER,\n    allowNull: false,\n    references: {\n      model: 'users',\n      key: 'user_id',\n    },\n  },\n}, {\n  underscored: true,\n  tableName: 'playlist',\n  freezeTableName: true,\n});\n\nmodule.exports = {\n  Playlist,\n};\n```\n\n```text\nconst { Credentials } = require('./credentials');\nconst { User } = require('./users');\nconst { Playlist } = require('./playlist');\n\nfunction loadModels() {\n  User.associate = (models) => {\n    User.hasMany(models.Playlist, { as: 'playlist' });\n  };\n\n  Playlist.associate = (models) => {\n    Playlist.belongsTo(models.User, { foreignKey: 'owner_id', as: 'owner' });\n  };\n\n  Credentials.sync({ force: false });\n  User.sync({ force: false });\n  Playlist.sync({ force: false });\n}\n\nmodule.exports = {\n  loadModels,\n};\n```\n\n```text\nconst express = require('express');\nconst { auth } = require('../../middlewares/auth');\nconst { Playlist } = require('../../models/playlist');\nconst { User } = require('../../models/users');\n\nconst router = express.Router();\n\nrouter.get('/playlist', [], auth, (req, res) => {\n  User.findOne({\n    where: { userID: req.user.user_id }, include: 'playlist',\n  }).then((r) => {\n    console.log(r);\n  });\n});\n\nmodule.exports = router;\n```\n\n========================================\n\nComments:\n- Hi friend. How did you realize that? I saw your answer and it worked for me, I have a model called Payments (plural), and it showed me the same error as you, when I saw your answer I tried placing Payment (singular) and it worked, but I don't understand why. check my database and the table is called Payments (plural), does it have something to do with associations or what? I really don't understand anything, would you be so kind as to explain me?\n- @JulianProg Hi mate, I realized it by reading the doc and trying things. Hard to tell what the problem is for you without seeing your models and migrations file. But basically be aware that when you have a hasMany association, you need to pluralize the model associated. For example, if I take the same code as I wrote up there, I have two models: User and Playlist. My User model has a hasMany association with Playlist model. But because I used hasMany, I had to pluralize Playlist so I had to write this: User.hasMany(models.Playlists, { foreignKey: 'user_id' }); // models.Playlists (pluralized)\n- If I had made a hasOne association instead of a hasMany association I would had to write model.Playlist instead of model.Playlists. Hope it will help","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":275,"estimatedTokens":1677}}308{"id":"stack-54639183","source":"stackoverflow","questionId":54639183,"title":"Sequelize cannot sync to MySQL in a docker container from Node/express app (ECONNREFUSED)","tags":["mysql","node.js","docker","docker-compose","sequelize.js"],"text":"Title: Sequelize cannot sync to MySQL in a docker container from Node/express app (ECONNREFUSED)\nTags: mysql, node.js, docker, docker-compose, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize, MySQL and docker together for the first time and cannot get sequelize to connect to the db.\n\nI have tested the presence of the DB with DBeaver and I can connect. I can also see the MySQL container respond in the terminal when I connect via DBeaver. However, when attempting to connect with code I get an ECONNREFUSED error.\n\nI have checked my code with the sequelize docs and double checked port settings but cannot seem to see where I am going wrong.\n\n### After the correct answer was provided below I noticed that I had a bug. I missed the following from the 'mysql' container in the docker-compose.yml file.\n\n```\nnetworks:\n - app-tier\n```\n\n### To avoid requiring other users to read the comments in the answer to discover this, I have added this to the docker-compose.yml file so that the question and answer now align more clearly\n\ndocker-compose.yml file:\n\n```\nversion: '3'\n\nnetworks:\n app-tier:\n driver: bridge\nservices:\n server:\n image: bitnami/node\n networks:\n - app-tier\n command: \"sh -c 'npm install && npm run dev'\"\n volumes:\n - ./server:/app\n ports:\n - 5000:5000\n depends_on:\n - mysql\n mysql:\n image: 'bitnami/mysql:latest'\n environment:\n - MYSQL_USER=root\n - MYSQL_PASSWORD=password\n - MYSQL_ROOT_PASSWORD=password\n - MYSQL_DATABASE=school\n networks:\n - app-tier\n ports:\n - '3306:3306'\n volumes:\n - ./db:/bitnami/mysql/data\n```\n\nSequelize connection:\n\n```\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('school', 'root', 'password', {\ndialect: 'mysql'\n});\n\nmodule.exports = sequelize;\n```\n\nAttempt to sync from app.js:\n\n```\nsequelize.sync()\n .then(result => console.log(result))\n .catch(err => console.log('EEEERRRROOOOOOR',err));\n```\n\nTerminal output:\n\n```\nserver_1 | { SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306\nserver_1 | at Utils.Promise.tap.then.catch.err (/app/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:139:19)\nserver_1 | at tryCatcher (/app/node_modules/bluebird/js/release/util.js:16:23)\nserver_1 | at Promise._settlePromiseFromHandler (/app/node_modules/bluebird/js/release/promise.js:512:31)\nserver_1 | at Promise._settlePromise (/app/node_modules/bluebird/js/release/promise.js:569:18)\nserver_1 | at Promise._settlePromise0 (/app/node_modules/bluebird/js/release/promise.js:614:10)\nserver_1 | at Promise._settlePromises (/app/node_modules/bluebird/js/release/promise.js:689:18)\nserver_1 | at Async._drainQueue (/app/node_modules/bluebird/js/release/async.js:133:16)\nserver_1 | at Async._drainQueues (/app/node_modules/bluebird/js/release/async.js:143:10)\nserver_1 | at Immediate.Async.drainQueues (/app/node_modules/bluebird/js/release/async.js:17:14)\nserver_1 | at runCallback (timers.js:810:20)\nserver_1 | at tryOnImmediate (timers.js:768:5)\nserver_1 | at processImmediate [as _immediateCallback] (timers.js:745:5)\nserver_1 | name: 'SequelizeConnectionRefusedError',\nserver_1 | parent:\nserver_1 | { Error: connect ECONNREFUSED 127.0.0.1:3306\nserver_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)\nserver_1 | errno: 'ECONNREFUSED',\nserver_1 | code: 'ECONNREFUSED',\nserver_1 | syscall: 'connect',\nserver_1 | address: '127.0.0.1',\nserver_1 | port: 3306,\nserver_1 | fatal: true },\nserver_1 | original:\nserver_1 | { Error: connect ECONNREFUSED 127.0.0.1:3306\nserver_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)\nserver_1 | errno: 'ECONNREFUSED',\nserver_1 | code: 'ECONNREFUSED',\nserver_1 | syscall: 'connect',\nserver_1 | address: '127.0.0.1',\nserver_1 | port: 3306,\nserver_1 | fatal: true } }\n```\n\n========================================\n\nTop Answer:\n**Work In Progress**\nI'm fighting against similar issue, this is my steps for static addressing:\n\n```\nnetworks:\n internal_UJJigBWx:\n driver: bridge\n ipam:\n config:\n - subnet: 172.16.238.0/24\n driver: default\nservices:\n express:\n build:\n context: .\n depends_on:\n - sql\n environment:\n DB_DATABASE: sequebase\n DB_DIALECT: mysql\n DB_HOST: 172.16.238.2\n DB_PASSWORD: sequeword\n DB_USERNAME: sequeuser\n networks:\n internal_UJJigBWx:\n ipv4_address: 172.16.238.3\n ports:\n - 80:3000/tcp\n sql:\n environment:\n MYSQL_DATABASE: sequebase\n MYSQL_PASSWORD: sequeword\n MYSQL_RANDOM_ROOT_PASSWORD: \"yes\"\n MYSQL_USER: sequeuser\n image: bitnami/mysql:latest\n networks:\n internal_UJJigBWx:\n ipv4_address: 172.16.238.2\nversion: '3.0'\n```\n\nThe main difference is the static addressing with ipam .\nYou can use `docker-compose config` to check and see env expansions.\n\nI'm using gulp tasks into the build stage to call sequelize sync. It's working well locally but I'm not sure if is a good approach to docker compose\n\nThe build image process use args rather than `environment`.\nand that phase looks like to happen before the database spinup. I'm don't know how to wait the sql to sync the sequelize...\n\n========================================\n\nCode:\n```text\nnetworks:\n    - app-tier\n```\n\n```text\nversion: '3'\n\nnetworks:\n    app-tier:\n        driver: bridge\nservices:\n    server:\n        image: bitnami/node\n        networks:\n        - app-tier\n        command: \"sh -c 'npm install && npm run dev'\"\n        volumes:\n        - ./server:/app\n        ports:\n        - 5000:5000\n        depends_on:\n        - mysql\n    mysql:\n        image: 'bitnami/mysql:latest'\n        environment:\n        - MYSQL_USER=root\n        - MYSQL_PASSWORD=password\n        - MYSQL_ROOT_PASSWORD=password\n        - MYSQL_DATABASE=school\n        networks:\n            - app-tier\n        ports:\n        - '3306:3306'\n        volumes:\n        - ./db:/bitnami/mysql/data\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('school', 'root', 'password', {\ndialect: 'mysql'\n});\n\nmodule.exports = sequelize;\n```\n\n```text\nsequelize.sync()\n    .then(result => console.log(result))\n    .catch(err => console.log('EEEERRRROOOOOOR',err));\n```\n\n```text\nserver_1    |  { SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306\nserver_1    |     at Utils.Promise.tap.then.catch.err (/app/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:139:19)\nserver_1    |     at tryCatcher (/app/node_modules/bluebird/js/release/util.js:16:23)\nserver_1    |     at Promise._settlePromiseFromHandler (/app/node_modules/bluebird/js/release/promise.js:512:31)\nserver_1    |     at Promise._settlePromise (/app/node_modules/bluebird/js/release/promise.js:569:18)\nserver_1    |     at Promise._settlePromise0 (/app/node_modules/bluebird/js/release/promise.js:614:10)\nserver_1    |     at Promise._settlePromises (/app/node_modules/bluebird/js/release/promise.js:689:18)\nserver_1    |     at Async._drainQueue (/app/node_modules/bluebird/js/release/async.js:133:16)\nserver_1    |     at Async._drainQueues (/app/node_modules/bluebird/js/release/async.js:143:10)\nserver_1    |     at Immediate.Async.drainQueues (/app/node_modules/bluebird/js/release/async.js:17:14)\nserver_1    |     at runCallback (timers.js:810:20)\nserver_1    |     at tryOnImmediate (timers.js:768:5)\nserver_1    |     at processImmediate [as _immediateCallback] (timers.js:745:5)\nserver_1    |   name: 'SequelizeConnectionRefusedError',\nserver_1    |   parent:\nserver_1    |    { Error: connect ECONNREFUSED 127.0.0.1:3306\nserver_1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)\nserver_1    |      errno: 'ECONNREFUSED',\nserver_1    |      code: 'ECONNREFUSED',\nserver_1    |      syscall: 'connect',\nserver_1    |      address: '127.0.0.1',\nserver_1    |      port: 3306,\nserver_1    |      fatal: true },\nserver_1    |   original:\nserver_1    |    { Error: connect ECONNREFUSED 127.0.0.1:3306\nserver_1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)\nserver_1    |      errno: 'ECONNREFUSED',\nserver_1    |      code: 'ECONNREFUSED',\nserver_1    |      syscall: 'connect',\nserver_1    |      address: '127.0.0.1',\nserver_1    |      port: 3306,\nserver_1    |      fatal: true } }\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('school', 'root', 'password', {\nhost: 'mysql',\ndialect: 'mysql'\n});\n\nmodule.exports = sequelize;\n```\n\n```text\nnetworks:\n  internal_UJJigBWx:\n    driver: bridge\n    ipam:\n      config:\n      - subnet: 172.16.238.0/24\n      driver: default\nservices:\n  express:\n    build:\n      context: .\n    depends_on:\n    - sql\n    environment:\n      DB_DATABASE: sequebase\n      DB_DIALECT: mysql\n      DB_HOST: 172.16.238.2\n      DB_PASSWORD: sequeword\n      DB_USERNAME: sequeuser\n    networks:\n      internal_UJJigBWx:\n        ipv4_address: 172.16.238.3\n    ports:\n    - 80:3000/tcp\n  sql:\n    environment:\n      MYSQL_DATABASE: sequebase\n      MYSQL_PASSWORD: sequeword\n      MYSQL_RANDOM_ROOT_PASSWORD: \"yes\"\n      MYSQL_USER: sequeuser\n    image: bitnami/mysql:latest\n    networks:\n      internal_UJJigBWx:\n        ipv4_address: 172.16.238.2\nversion: '3.0'\n```\n\n```text\ndocker-compose config\n```\n\n```text\nenvironment\n```\n\n========================================\n\nComments:\n- Thanks for this. Error now changed from ECONNREFUSED to ETIMEDOUT. I thought docker mapped host to localhost no?\n- It maps to your machine localhost if you expose port, but inside containers it got it own addresses. So now you get `ETIMEDOUT` because mysql is not ready to recieve connection. `depend_on` is waiting when container will start, not when finish setup. So you need to add in your app check when mysql is ready\n- OK, so of course you are right. Having rechecked my docker-file I missed networks: - app-tier I forgot to add it to the named network hence it did not work on the first fix. Thanks for your help!\n- Oh, I saw your `app-tier` declared in first service and I assumed that is also declared in `mysql` service to network. Good that you resolved that!","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":320,"estimatedTokens":2478}}309{"id":"stack-34135555","source":"stackoverflow","questionId":34135555,"title":"Recursive include Sequelize?","tags":["javascript","mysql","orm","sequelize.js"],"text":"Title: Recursive include Sequelize?\nTags: javascript, mysql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have category that can have child categories\n\nAnd when I'm doing findAll I want to include all of those nested, but I don't know the depth. \n\n```\nvar includeCondition = { \n include: [\n { \n model: models.categories,\n as:'subcategory', nested: true \n }]\n };\n\nmodels.categories.findAll(includeCondition)\n .then(function (categories) {\n resolve(categories);\n })\n .catch(function (err) {\n reject(err);\n })\n});\n```\n\nThe result brings me only one level nested include.\n\n```\n[ \n { \n dataValues:{ \n\n },\n subcategory:{ \n model:{ \n dataValues:{ \n\n }\n // no subcategory here \n }\n }\n }\n]\n```\n\nCan I somehow make sequalize include those nested subcategories ?\n\n========================================\n\nTop Answer:\nThis is ihoryam's answer adapted to ES6, using `async/await`, arrow functions `() =>` and Sequelize ORM to fetch the data, and not using Lodash.\n\n```\nconst getSubCategoriesRecursive = async (category) => {\n let subCategories = await models.category.findAll({\n where: {\n parentId: category.id\n },\n raw : true\n });\n\n if (subCategories.length > 0) {\n const promises = [];\n subCategories.forEach(category => {\n promises.push(getSubCategoriesRecursive(category));\n });\n category['subCategories'] = await Promise.all(promises);\n }\n else category['subCategories'] = []; \n return category;\n};\n```\n\nAsync functions returning promises, you do not need to precise `return new promise(...)`\n\n========================================\n\nCode:\n```text\nvar includeCondition = { \n                         include: [\n                            { \n                               model: models.categories,\n                               as:'subcategory', nested: true \n                            }]\n                       };\n\nmodels.categories.findAll(includeCondition)\n        .then(function (categories) {\n            resolve(categories);\n        })\n        .catch(function (err) {\n            reject(err);\n        })\n});\n```\n\n```text\n[  \n   {  \n      dataValues:{  \n\n      },\n      subcategory:{  \n         model:{  \n            dataValues:{  \n\n            }\n            // no subcategory here            \n         }\n      }\n   }\n]\n```\n\n```text\nvar expandSubcategories = function (category) {\n    return new promise(function (resolve, reject) {\n        category.getSubcategories().then(function (subcategories) {\n            //if has subcategories expand recursively inner subcategories\n            if (subcategories && subcategories.length > 0) {\n                var expandPromises = [];\n                _.each(subcategories, function (subcategory) {\n                    expandPromises.push(expandSubcategories(subcategory));\n                });\n\n                promise.all(expandPromises).then(function (expandedCategories) {\n                    category.subcategories = [];\n\n                    _.each(expandedCategories, function (expandedCategory) {\n                        category.subcategories.push(expandedCategory);\n                    }, this);\n\n\n                    //return self with expanded inner\n                    resolve(category);\n                });\n\n            } else {\n                //if has no subcategories return self\n                resolve(category);\n            }\n        });\n    });\n};\n```\n\n```text\nconst  Sequelize = require('sequelize');\nrequire('sequelize-hierarchy')(Sequelize);\nconst sequelize = new Sequelize(\"stackoverflow\", null, null, {\n  dialect: \"sqlite\",\n  storage: \"database.db\"\n});\nsequelize.sync().then(() => {console.log(\"Database ready\");});\nmodule.exports = sequelize;\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Skill = sequelize.define(\"skill\", {\n    name:           DataTypes.STRING,\n  });\n  Skill.isHierarchy();\n  return Skill;\n};\n```\n\n```text\nSkill.findAll().then(skills => {\n  res.send(skills); // Return a list\n});\nSkill.findAll({ hierarchy: true }).then(skills => {\n  res.send(skills); // Return a tree\n});\n```\n\n```text\ninclude: [{ all: true, nested: true }]\n```\n\n```text\nA.findAll(where:{// add conditions}, { include: [{ all: true, nested: true }]});\n```\n\n```js\nconst getSubCategoriesRecursive = async (category) => {\n  let subCategories = await models.category.findAll({\n      where: {\n          parentId: category.id\n      },\n      raw : true\n  });\n\n  if (subCategories.length > 0) {\n      const promises = [];\n      subCategories.forEach(category => {\n          promises.push(getSubCategoriesRecursive(category));\n      });\n      category['subCategories'] = await Promise.all(promises);\n  }\n  else category['subCategories'] = []; \n  return category;\n};\n```\n\n```text\nasync/await\n```\n\n```text\n() =>\n```\n\n```text\nreturn new promise(...)\n```\n\n```text\nconst getChildrenRecursive = async (menu) => {\n  const childrenMenus = await models.Menu.findAll(\n    { where: { parentId: menu.id }, raw: true },\n  );\n  const children = await Promise.all(childrenMenus.map(async (child) => {\n    const childObj = {\n      ...child,\n      children: await getChildrenRecursive(child),\n    };\n    return childObj;\n  }));\n  return children;\n};\n```\n\n```text\nasync getChildrenRecursively(user, document) {\n    const children = []; //here will be our final result\n    const unprocessed = []; //the list children, that we need to search through\n    unprocessed.push(document); //adding root element to the list\n    while(unprocessed.length > 0) {\n        const found = await this.getDocumentsByParentId(user, unprocessed[0].parentId); //function to get first level nested\n        children.push(...found); //adding results to final result\n        unprocessed.push(...found); //adding results to continue search\n        unprocessed.shift(); //removing the element we just searched\n    }\n    return children;\n}\n```\n\n========================================\n\nComments:\n- Related: github.com/sequelize/sequelize/issues/4890\n- He is not asking for a solution for different models but for nesting the same model.\n- If you're just updating the code, make an edit to the answer. If you're attributing a new answer to yourself, add something new.\n- Sharing code / answer generated with chat GPT is not allow : meta.stackoverflow.com/questions/421831/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":259,"estimatedTokens":1552}}310{"id":"stack-32965014","source":"stackoverflow","questionId":32965014,"title":"MySQL Query 10 Tables (Sequelize or Raw Query)","tags":["mysql","sql","json","node.js","sequelize.js"],"text":"Title: MySQL Query 10 Tables (Sequelize or Raw Query)\nTags: mysql, sql, json, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn order to return the following JSON example, we need to query 10 tables, while looking up values in between.\nMy knowledge of SQL is limited, so we are here asking for help.\n\n### JSON:\n\n```\n{\n project: 1,\n name: \"BluePrint1\",\n description: \"BluePrint 1 Description\",\n listWorkPackages: [\n {\n id: 1,\n name: \"WorkPackage 1 Name\",\n description: \"WorkPackage 1 Description\",\n type: \"WorkPackage Type\",\n department: \"WorkPackage Department\",\n status: \"Workpackage work status\"\n },\n {\n id: 2,\n name: \"WorkPackage 2 Name\",\n description: \"WorkPackage 2 Description\",\n type: \"WorkPackage Type\",\n department: \"WorkPackage Department\",\n status: \"Workpackage work status\"\n }\n ],\n assignments: [\n {\n id: 3,\n name: \"WorkPackage 3 Name\",\n description: \"WorkPackage 3 Description\",\n type: \"WorkPackage Type\",\n department: \"WorkPackage Department\",\n status: \"Workpackage work status\"\n }\n ]\n}\n```\n\n### Database:\n\nThe database looks like this (*open in new tab for more details)* :\n\nhttps://i.sstatic.net/lPe6U.png\n\n### Logic:\n\nWith the WorkerID, we want All the **WorkPackages** that:\n\n- Have the same **Type** as the **Worker**;\n\n- And belong to the same **Department**;\n\n- And also the ones by direct **Assignment** (*via table WA_Assignments*)\n\nSo we can sent the information present on the JSON, we need to look into these 10 tables:\n\n- WK_Worker\n\n- WT_WorkerType\n\n- TY_Type\n\n- WP_WorkPackage\n\n- WE_WorkPackageExecution\n\n- WS_WorkStatus\n\n- BL_Blueprint\n\n- PR_Project\n\n- DP_Department\n\n- WA_WorkAssignments\n\n### My Problem:\n\nMy knowledge of SQL is limited to JOIN's:\n\n```\nSELECT *\nFROM BL_Blueprint \nJOIN PR_Project ON BL_idBlueprint = PR_idBlueprint\nJOIN WP_WorkPackage ON BL_idBlueprint = WP_idBlueprint\nJOIN WE_WorkPackageExecution ON WE_idWorkPackage = WP_idWorkPackage\nJOIN DP_Department ON WE_idDepartment = DP_idDepartment\n```\n\nAnd we need to only search work packages that have the same **Type** as the **Worker**, but we don't know the types before hand, only after looking into the table *WT_WorkerType*.\n\nI read about subQuery where you can SELECT in the WHERE field, but couldn't get my head around it, and get a working query.\n\n### Problems:\n\nIn the end, my problems are:\n\n- The SQL query;\n\nI am using Sequelize, if it can help, but from the docs I think a Raw Query would be easier.\n\nThank you all for your help and support.\n\n### SOLUTION\n\nAll the love goes to @MihaiOvidiuDrăgoi (in the comments) that helped me arrive at the solution\n\nThe **First** *SELECT* gets the Assignments and the **Second** the logic describe above. The labels help to identify which is which, and we order to ease the creation of the JSON.\n\n```\nSELECT *\nFROM\n ((SELECT \n BL_Name,\n BL_Description,\n WP_Name,\n WP_Description,\n PR_idProject,\n WE_idWorkPackageExecution,\n WE_idWorkStatus,\n TY_TypeName,\n TY_Description,\n WS_WorkStatus,\n DP_Name,\n DP_Description,\n 'second_select'\n FROM\n WK_Worker, WP_WorkPackage\n INNER JOIN BL_Blueprint ON BL_idBlueprint = WP_idBlueprint\n INNER JOIN PR_Project ON PR_idBlueprint = BL_idBlueprint\n INNER JOIN WE_WorkPackageExecution ON WE_idWorkPackage = WP_idWorkPackage\n AND WE_idProject = PR_idProject\n INNER JOIN WS_WorkStatus ON WS_idWorkStatus = WE_idWorkStatus\n INNER JOIN DP_Department ON DP_idDepartment = WE_idDepartment\n INNER JOIN WA_WorkAssignments ON WA_idWorkPackageExecution = WE_idWorkPackageExecution\n INNER JOIN TY_Type ON TY_idType = WP_idType\n WHERE\n WA_idWorker = 1 AND WK_idWorker = 1) UNION ALL (SELECT \n BL_Name,\n BL_Description,\n WP_Name,\n WP_Description,\n PR_idProject,\n WE_idWorkPackageExecution,\n WE_idWorkStatus,\n TY_TypeName,\n TY_Description,\n WS_WorkStatus,\n DP_Name,\n DP_Description,\n 'first_select'\n FROM\n WK_Worker, WP_WorkPackage\n JOIN BL_Blueprint ON BL_idBlueprint = WP_idBlueprint\n JOIN PR_Project ON PR_idBlueprint = BL_idBlueprint\n JOIN WE_WorkPackageExecution ON WE_idWorkPackage = WP_idWorkPackage\n AND WE_idProject = PR_idProject\n JOIN WS_WorkStatus ON WS_idWorkStatus = WE_idWorkStatus\n JOIN DP_Department ON DP_idDepartment = WE_idDepartment\n JOIN TY_Type ON TY_idType = WP_idType\n WHERE\n WK_idWorker = 1\n AND DP_idDepartment IN \n (SELECT \n WK_idDepartment\n FROM\n WK_Worker\n WHERE\n WK_idWorker = 1)\n AND WP_idType IN \n (SELECT \n TY_idType\n FROM\n TY_Type\n JOIN WT_WorkerType ON TY_idType = WT_idType\n WHERE\n WT_idWorker = 1)\n )\n) AS T1\nORDER BY T1.PR_idProject\n```\n\n========================================\n\nTop Answer:\nIf you wanted to try to do a subquery with sequelize, you could use a literal in part of your query:\n\n```\nUser.findAll({\n attributes: [\n [sequelize.literal('SELECT ...'), 'subq'],\n ]\n}).then(function(users) {\n\n});\n```\n\n========================================\n\nCode:\n```text\n{\n  project: 1,\n  name: \"BluePrint1\",\n  description: \"BluePrint 1 Description\",\n  listWorkPackages: [\n    {\n      id: 1,\n      name: \"WorkPackage 1 Name\",\n      description: \"WorkPackage 1 Description\",\n      type: \"WorkPackage Type\",\n      department: \"WorkPackage Department\",\n      status: \"Workpackage work status\"\n    },\n    {\n      id: 2,\n      name: \"WorkPackage 2 Name\",\n      description: \"WorkPackage 2 Description\",\n      type: \"WorkPackage Type\",\n      department: \"WorkPackage Department\",\n      status: \"Workpackage work status\"\n    }\n  ],\n  assignments: [\n    {\n      id: 3,\n      name: \"WorkPackage 3 Name\",\n      description: \"WorkPackage 3 Description\",\n      type: \"WorkPackage Type\",\n      department: \"WorkPackage Department\",\n      status: \"Workpackage work status\"\n    }\n  ]\n}\n```\n\n```text\nSELECT *\nFROM BL_Blueprint \nJOIN PR_Project ON BL_idBlueprint = PR_idBlueprint\nJOIN WP_WorkPackage ON BL_idBlueprint = WP_idBlueprint\nJOIN WE_WorkPackageExecution ON WE_idWorkPackage = WP_idWorkPackage\nJOIN DP_Department ON WE_idDepartment = DP_idDepartment\n```\n\n```text\nSELECT *\nFROM\n    ((SELECT \n        BL_Name,\n            BL_Description,\n            WP_Name,\n            WP_Description,\n            PR_idProject,\n            WE_idWorkPackageExecution,\n            WE_idWorkStatus,\n            TY_TypeName,\n            TY_Description,\n            WS_WorkStatus,\n            DP_Name,\n            DP_Description,\n            'second_select'\n    FROM\n        WK_Worker, WP_WorkPackage\n    INNER JOIN BL_Blueprint ON BL_idBlueprint = WP_idBlueprint\n    INNER JOIN PR_Project ON PR_idBlueprint = BL_idBlueprint\n    INNER JOIN WE_WorkPackageExecution ON WE_idWorkPackage = WP_idWorkPackage\n        AND WE_idProject = PR_idProject\n    INNER JOIN WS_WorkStatus ON WS_idWorkStatus = WE_idWorkStatus\n    INNER JOIN DP_Department ON DP_idDepartment = WE_idDepartment\n    INNER JOIN WA_WorkAssignments ON WA_idWorkPackageExecution = WE_idWorkPackageExecution\n    INNER JOIN TY_Type ON TY_idType = WP_idType\n    WHERE\n        WA_idWorker = 1 AND WK_idWorker = 1) UNION ALL (SELECT \n        BL_Name,\n            BL_Description,\n            WP_Name,\n            WP_Description,\n            PR_idProject,\n            WE_idWorkPackageExecution,\n            WE_idWorkStatus,\n            TY_TypeName,\n            TY_Description,\n            WS_WorkStatus,\n            DP_Name,\n            DP_Description,\n            'first_select'\n    FROM\n        WK_Worker, WP_WorkPackage\n    JOIN BL_Blueprint ON BL_idBlueprint = WP_idBlueprint\n    JOIN PR_Project ON PR_idBlueprint = BL_idBlueprint\n    JOIN WE_WorkPackageExecution ON WE_idWorkPackage = WP_idWorkPackage\n        AND WE_idProject = PR_idProject\n    JOIN WS_WorkStatus ON WS_idWorkStatus = WE_idWorkStatus\n    JOIN DP_Department ON DP_idDepartment = WE_idDepartment\n    JOIN TY_Type ON TY_idType = WP_idType\n    WHERE\n        WK_idWorker = 1\n            AND DP_idDepartment IN \n            (SELECT \n                WK_idDepartment\n            FROM\n                WK_Worker\n            WHERE\n                WK_idWorker = 1)\n            AND WP_idType IN \n            (SELECT \n                TY_idType\n            FROM\n                TY_Type\n            JOIN WT_WorkerType ON TY_idType = WT_idType\n            WHERE\n                WT_idWorker = 1)\n    )\n) AS T1\nORDER BY T1.PR_idProject\n```\n\n```text\nSELECT * from\n(\nSELECT 1 \nUNION ALL \nSELECT 2 \n) a\nORDER by ...\n```\n\n```text\nUser.findAll({\n  attributes: [\n    [sequelize.literal('SELECT ...'), 'subq'],\n  ]\n}).then(function(users) {\n\n});\n```\n\n========================================\n\nComments:\n- Could you post that not-working WHERE? It'd probably help in understanding the logic you are trying to implement.\n- @MihaiOvidiuDrăgoi Of course. From the web I arrived at that. Now I am trying to see if I can get the information from the other tables. I have to be careful with the JOIN's. Am I on a good track?\n- Try only joining the tables that you need data from (or that link those tables). We'll work on the WHERE after that :)\n- @MihaiOvidiuDrăgoi Sorry, I already have 2 where. I think all the JOIN's are there, should the Assignments be on the Where or as a JOIN?\n- Can you post the results from the current query vs. the expected results?\n- @MihaiOvidiuDrăgoi, posted the output. I get the correct 2 records, but I want to receive 3 in total, that last one is from the Assignments.\n- Let us continue this discussion in chat.\n- I wrote a lot in chat :) are you still around?\n- I end up using your response for another case I had. Thanks for the help.","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":358,"estimatedTokens":2336}}311{"id":"stack-45051927","source":"stackoverflow","questionId":45051927,"title":"SequelizeConnectionError: Client does not support authentication protocol requested by server; consider upgrading MariaDB client","tags":["mysql","node.js","database","mariadb","sequelize.js"],"text":"Title: SequelizeConnectionError: Client does not support authentication protocol requested by server; consider upgrading MariaDB client\nTags: mysql, node.js, database, mariadb, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize version 4.3.0 on nodejs(v6.11.0) application having Mariadb (mysql Ver 15.1 Distrib 10.0.29-MariaDB, for debian-linux-gnu (i686) using readline 5.2\n) on Ubuntu 16.04.\nwhen application starts and calls function:\n `Sequelize.sync();`\nThen sequelize connection manager throws following error: \n\n Unhandled rejection SequelizeConnectionError: Client does not support authentication protocol requested by server; consider upgrading MariaDB client\n\n```\nat Utils.Promise.tap.then.catch.err (/home/dariksoft/cars/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:146:17)\nat tryCatcher (/home/dariksoft/cars/node_modules/bluebird/js/release/util.js:16:23)\nat Promise._settlePromiseFromHandler (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:512:31)\nat Promise._settlePromise (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:569:18)\nat Promise._settlePromise0 (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:614:10)\nat Promise._settlePromises (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:689:18)\nat Async._drainQueue (/home/dariksoft/cars/node_modules/bluebird/js/release/async.js:133:16)\nat Async._drainQueues (/home/dariksoft/cars/node_modules/bluebird/js/release/async.js:143:10)\nat Immediate.Async.drainQueues (/home/dariksoft/cars/node_modules/bluebird/js/release/async.js:17:14)\nat runCallback (timers.js:672:20)\nat tryOnImmediate (timers.js:645:5)\nat processImmediate [as _immediateCallback] (timers.js:617:5)\n```\n\nI updated mariadb-server and mariadb-client but the problem already exists!\n\nAnyone can help me to solve this problem ?\n\n========================================\n\nTop Answer:\nIn case you are using higher versions of mysql, you don't need to use password function. Instead you can write it as below\n\n```\nuse mysql;\n\nupdate user set authentication_string='new_root_password', plugin='mysql_native_password' where user='root';\n\nflush privileges;\n```\n\n========================================\n\nCode:\n```text\nat Utils.Promise.tap.then.catch.err (/home/dariksoft/cars/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:146:17)\nat tryCatcher (/home/dariksoft/cars/node_modules/bluebird/js/release/util.js:16:23)\nat Promise._settlePromiseFromHandler (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:512:31)\nat Promise._settlePromise (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:569:18)\nat Promise._settlePromise0 (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:614:10)\nat Promise._settlePromises (/home/dariksoft/cars/node_modules/bluebird/js/release/promise.js:689:18)\nat Async._drainQueue (/home/dariksoft/cars/node_modules/bluebird/js/release/async.js:133:16)\nat Async._drainQueues (/home/dariksoft/cars/node_modules/bluebird/js/release/async.js:143:10)\nat Immediate.Async.drainQueues (/home/dariksoft/cars/node_modules/bluebird/js/release/async.js:17:14)\nat runCallback (timers.js:672:20)\nat tryOnImmediate (timers.js:645:5)\nat processImmediate [as _immediateCallback] (timers.js:617:5)\n```\n\n```text\nSequelize.sync();\n```\n\n```text\nuse mysql;\n```\n\n```text\nupdate user set authentication_string=password(''),plugin='mysql_native_password' where user='root';\n```\n\n```text\nuse mysql;\nupdate user set authentication_string=password('new_root_password'), plugin='mysql_native_password' where user='root';\nflush privileges;\n```\n\n```text\nuse mysql;\n\nupdate user set authentication_string='new_root_password', plugin='mysql_native_password' where user='root';\n\nflush privileges;\n```\n\n========================================\n\nComments:\n- MySQL 8.0.11 with sql_mode=TRADITIONAL did not like the syntax. The following worked without having to go to the system database, `alter user 'USER'@'localhost' identified with mysql_native_password by 'PASSWORD'`.","metadata":{"transformedAt":"2026-08-18T18:33:34.364Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":93,"estimatedTokens":1013}}312{"id":"stack-36074800","source":"stackoverflow","questionId":36074800,"title":"id: null when creating a new item in sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: id: null when creating a new item in sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen I try to create a new Conversation item Sequelize will return an object with `id: null` eventhough there is an valid id in the database. How can I get Sequelize to return the last inserted id to the newly created item?\n\n```\nConversation.create({\n type: 'private',\n createdBy: 1,\n}).then(conversation => {\n reply(conversation);\n});\n```\n\nWill return\n\n```\n{\n \"type\": \"conversations\",\n \"id\": null,\n \"createdBy\": 1,\n \"created_at\": \"2016-03-18T01:47:48.000Z\"\n}\n```\n\nMy code:\n\n```\nconst Conversation = model.define('Conversation', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n },\n type: {\n type: Sequelize.ENUM,\n values: ['private', 'group'],\n validate: {\n isIn: ['private', 'group'],\n },\n },\n createdBy: {\n type: Sequelize.INTEGER,\n field: 'created_by',\n },\n}, {\n tableName: 'conversations',\n timestamps: true,\n createdAt: 'created_at',\n updatedAt: false,\n getterMethods: {\n type: () => 'conversations',\n },\n});\n\nconst User = model.define('User', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n },\n firstName: {\n type: Sequelize.STRING,\n field: 'first_name',\n allowNull: false,\n },\n lastName: {\n type: Sequelize.STRING,\n field: 'last_name',\n allowNull: true,\n },\n email: {\n type: Sequelize.STRING,\n allowNull: false,\n },\n profileImg: {\n type: Sequelize.STRING,\n field: 'profile_img',\n allowNull: false,\n },\n password: Sequelize.STRING,\n}, {\n tableName: 'users',\n timestamps: true,\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n getterMethods: {\n type: () => 'users',\n },\n});\n\nConversation.belongsToMany(User, {\n foreignKey: 'conversation_id',\n otherKey: 'user_id',\n through: 'conversation_user',\n timestamps: false,\n});\n\nUser.belongsToMany(Conversation, {\n as: 'conversations',\n foreignKey: 'user_id',\n otherKey: 'conversation_id',\n through: 'conversation_user',\n timestamps: false,\n});\n```\n\n========================================\n\nTop Answer:\nYo need to put `autoIncrement: true` in `id` field:\n\n```\nid: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n }\n```\n\nPersonally I would advice to skip the `id` column as `sequalize` does it automatically for you and works nicely.\n\nhope it helps :)\n\n========================================\n\nCode:\n```js\nConversation.create({\n  type: 'private',\n  createdBy: 1,\n}).then(conversation => {\n  reply(conversation);\n});\n```\n\n```js\n{\n  \"type\": \"conversations\",\n  \"id\": null,\n  \"createdBy\": 1,\n  \"created_at\": \"2016-03-18T01:47:48.000Z\"\n}\n```\n\n```js\nconst Conversation = model.define('Conversation', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n  },\n  type: {\n    type: Sequelize.ENUM,\n    values: ['private', 'group'],\n    validate: {\n      isIn: ['private', 'group'],\n    },\n  },\n  createdBy: {\n    type: Sequelize.INTEGER,\n    field: 'created_by',\n  },\n}, {\n  tableName: 'conversations',\n  timestamps: true,\n  createdAt: 'created_at',\n  updatedAt: false,\n  getterMethods: {\n    type: () => 'conversations',\n  },\n});\n\nconst User = model.define('User', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n  },\n  firstName: {\n    type: Sequelize.STRING,\n    field: 'first_name',\n    allowNull: false,\n  },\n  lastName: {\n    type: Sequelize.STRING,\n    field: 'last_name',\n    allowNull: true,\n  },\n  email: {\n    type: Sequelize.STRING,\n    allowNull: false,\n  },\n  profileImg: {\n    type: Sequelize.STRING,\n    field: 'profile_img',\n    allowNull: false,\n  },\n  password: Sequelize.STRING,\n}, {\n  tableName: 'users',\n  timestamps: true,\n  createdAt: 'created_at',\n  updatedAt: 'updated_at',\n  getterMethods: {\n    type: () => 'users',\n  },\n});\n\nConversation.belongsToMany(User, {\n  foreignKey: 'conversation_id',\n  otherKey: 'user_id',\n  through: 'conversation_user',\n  timestamps: false,\n});\n\nUser.belongsToMany(Conversation, {\n  as: 'conversations',\n  foreignKey: 'user_id',\n  otherKey: 'conversation_id',\n  through: 'conversation_user',\n  timestamps: false,\n});\n```\n\n```text\nid: null\n```\n\n```text\nid: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true,\n  }\n```\n\n```text\nautoIncrement: true\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nsequalize\n```\n\n```js\nconsole.info(instance.id); // null\nconsole.info(instance.get('id')); // 25 => Real ID\nconsole.info(instance.getDataValue('id')); // 25 => Real ID\n```\n\n```js\nclass FooModel extends Model {\n  // ...\n\n  /**\n   * @inheritdoc\n   */\n  public async save(options?: SaveOptions<TModelAttributes>): Promise<this> {\n    await super.save(options);\n    this.loadBaseData();\n    return this;\n  }\n\n  /**\n   * @inheritdoc\n   */\n  public async reload(options?: FindOptions<TModelAttributes>): Promise<this> {\n    await super.reload(options);\n    this.loadBaseData();\n    return this;\n  }\n\n  private loadBaseData() {\n    this.id = this.getDataValue('id');\n    this.createdAt = this.getDataValue('createdAt');\n    this.updatedAt = this.getDataValue('updatedAt');\n  }\n}\n```\n\n```text\nid\n```\n\n```text\nnull\n```\n\n```text\ninstance.id\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nid\n```\n\n```text\ninstance.id // null\n```\n\n```text\ninstance.save()\ninstance.id // someNumber\n```\n\n```text\nautoIncrement: true\n```\n\n```text\nautoIncrement: true\n```\n\n========================================\n\nComments:\n- which version of sequelize are you using? and type conversations? really is returning you that? 1 more thing, try adding a .catch(function(err) { console.log(err); }) in your promise code.\n- I'm using `\"mysql\": \"2.10.2\", \"sequelize\": \"3.19.3\"`. The catch doesn't console.log anything\n- When I add the `autoIncrement: true` or remove the id column from the model I get a `SequelizeUniqueConstraintError: Validation error` saying `PRIMARY must be unique`\n- after making changes make sure you use sync(force:true) and restart server\n- I synced and restarted but it didn't make a difference\n- Maybe you have the counter for the autoincrement set to a value that already exists in the db. Try to change it.","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":337,"estimatedTokens":1501}}313{"id":"stack-50597131","source":"stackoverflow","questionId":50597131,"title":"Query by Date Range for a column field in Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Query by Date Range for a column field in Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to query a database with Sequelize to get items that were created between a certain date range. I used the `$between` operator but I don't seem to be getting anything.\n\n`{ where: {\"createdAt\":{\"$between\":[\"2018-03-31T21:00:00.000Z\",\"2018-05-30T05:23:59.007Z\"]}} }`\n\nCan anyone help with how I can achieve this?\n\n========================================\n\nTop Answer:\n`$between` syntax seems to be right. There are no issues with the way you used. I tried to replicate with the following query\n\n```\nmodel.findAll({\n where: {\n created_at: { \n \"$between\": [\"2018-03-31T21:00:00.000Z\",\"2018-05-30T05:23:59.007Z\"]\n }\n }\n })\n```\n\nThe only change is, I use `created_at` instead of `createdAt`. Make sure that your column name is right. If it is not, it should have thrown `SequelizeDatabaseError`. Look for it. \n\nIf everything else is right, then you might not be having data in that date range :)\n\n========================================\n\nCode:\n```text\n$between\n```\n\n```text\n{ where: {\"createdAt\":{\"$between\":[\"2018-03-31T21:00:00.000Z\",\"2018-05-30T05:23:59.007Z\"]}} }\n```\n\n```text\nconst Op = Sequelize.Op;\n```\n\n```text\nwhere: {\n  createdAt: {\n    [Op.between]: [\"2018-07-08T14:06:48.000Z\", \"2019-10-08T22:33:54.000Z\"]\n  }\n}\n```\n\n```text\n[Op.between]\n```\n\n```text\nmodel.findAll({\n    where: {\n      created_at: { \n        \"$between\": [\"2018-03-31T21:00:00.000Z\",\"2018-05-30T05:23:59.007Z\"]\n      }\n    }\n  })\n```\n\n```text\n$between\n```\n\n```text\ncreated_at\n```\n\n```text\ncreatedAt\n```\n\n```text\nSequelizeDatabaseError\n```\n\n========================================\n\nComments:\n- Thanks. It's funny it's not working on my end. I've tried a larger date range and I keep getting an empty value. I'll go through my code again.\n- Ideally you should also be using the symbol based operators like [Op.between]: docs.sequelizejs.com/manual/tutorial/querying.html#operators (it's better from a security perspective)\n- ahhh I looking for something like select * FROM table where \"2021-04-13\" BETWEEN start_date_column and end_date_column any idea?","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":89,"estimatedTokens":540}}314{"id":"stack-52260934","source":"stackoverflow","questionId":52260934,"title":"how to measure query execution time in seqilize?","tags":["mysql","orm","sequelize.js"],"text":"Title: how to measure query execution time in seqilize?\nTags: mysql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I calculate the execution time of a query Seqilize ORM?\n\n- There is a build in function that measures it?\nHow can I manage the\nrunning queries(PROCESS LIST)? \n\n- How do I know how many connections running?\n\n========================================\n\nTop Answer:\nIf you'd like to log execution time for all queries run by sequelize you might want to configure this globally:\n\n```\nconst sequelize = new Sequelize({\n benchmark: true, // logger.info(`${sql} - [Execution time: ${timingMs}ms]`),\n \n});\n```\n\nThe link from comments to benchmark configuration is outdated. Here are the new ones for query level and global\n\n========================================\n\nCode:\n```js\nconst game = await Game.findAll({\n    benchmark: true,\n    logging: console.log,\n    <...>\n}\n```\n\n```text\nlogging\n```\n\n```text\nbenchmark\n```\n\n```text\nconst sequelize = new Sequelize({\n  benchmark: true,  // <-- this one enables tracking execution time\n  logging: (sql: string, timingMs?: number) => logger.info(`${sql} - [Execution time: ${timingMs}ms]`),\n  <...>\n});\n```\n\n========================================\n\nComments:\n- Here it is in the documentation... \"options.benchmark\" docs.sequelizejs.com/class/lib/&hellip;\n- Tested as of sequelize 6.14.0 the custom `logging` option is not strictly necessary, `logging: console.log` already shows the `Elapsed time: 0ms` at the end by default. Good to know that it can also be used on custom logs though.","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":59,"estimatedTokens":388}}315{"id":"stack-45459721","source":"stackoverflow","questionId":45459721,"title":"sequelize multiple foreign key includes only one column","tags":["mysql","node.js","sequelize.js"],"text":"Title: sequelize multiple foreign key includes only one column\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni have made two foreign keys from user table.\n\n```\ndb.Subscription.belongsTo(db.User, {foreignKey: 'creatorId'});\ndb.Subscription.belongsTo(db.User, {foreignKey: 'subscriberId'});\n```\n\nduring search query i get `subscriberId` column included instead of `creatorId` \n\n```\nSubscription.findAll({\n where: {\n subscriberId: req.decoded._id\n },\n include: [\n {\n model: User, \n foreignKey: 'creatorId', \n attributes: ['name', 'role', 'uid', 'imageUrl']\n }\n ]\n})\n```\n\ncan someone please find out what i am doing wrong here.\n\n========================================\n\nCode:\n```text\ndb.Subscription.belongsTo(db.User, {foreignKey: 'creatorId'});\ndb.Subscription.belongsTo(db.User, {foreignKey: 'subscriberId'});\n```\n\n```text\nSubscription.findAll({\n    where: {\n      subscriberId: req.decoded._id\n    },\n    include: [\n      {\n          model: User, \n          foreignKey: 'creatorId', \n          attributes: ['name', 'role', 'uid', 'imageUrl']\n      }\n    ]\n})\n```\n\n```text\nsubscriberId\n```\n\n```text\ncreatorId\n```\n\n```text\ndb.Subscription.belongsTo(db.User, {\n  as: 'creator',\n  foreignKey: 'creatorId'\n});\n\ndb.Subscription.belongsTo(db.User, {\n  as: 'subscriber',\n  foreignKey: 'subscriberId'\n});\n```\n\n```text\nSubscription.findAll({\n  include: {\n    model: User,\n    as: 'creator',\n    attributes: ['name', 'role', 'uid', 'imageUrl']\n  },\n  where: {\n    subscriberId: req.decoded._identer\n  }\n});\n```\n\n```text\n.creator\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":90,"estimatedTokens":387}}316{"id":"stack-37813467","source":"stackoverflow","questionId":37813467,"title":"Sequelize.js insert a model with one-to-many relationship","tags":["javascript","sql","node.js","orm","sequelize.js"],"text":"Title: Sequelize.js insert a model with one-to-many relationship\nTags: javascript, sql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two sequelize models with one-to-many relationship. Let's call them Owner and Property.\n\nAssume they are defined using the sails-hook-sequelize as such (simplified).\n\n```\n//Owner.js\nmodule.exports = {\noptions: {\n tableName: 'owner'\n},\nattributes: {\n id: {\n type: Sequelize.BIGINT,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING(255)\n },\n associations: function () {\n Owner.hasMany(Property, {\n foreignKey: {\n name: 'owner_id'\n }\n });\n }\n}\n\n//Property.js\nmodule.exports = {\noptions: {\n tableName: 'property'\n},\nattributes: {\n id: {\n type: Sequelize.BIGINT,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING(255)\n }\n}\n```\n\nNow assume I want to insert an Owner record in my database and insert a few property records to associate with the owner. How do I do this? \n\nI'm looking for something like\n\n```\nOwner.create({name:'nice owner',\n property: [{name:'nice property'},\n {name:'ugly property'}]});\n```\n\nSurprisingly I can't find this in the Sequelize documentation.\n\n========================================\n\nCode:\n```text\n//Owner.js\nmodule.exports = {\noptions: {\n  tableName: 'owner'\n},\nattributes: {\n  id: {\n    type: Sequelize.BIGINT,\n    allowNull: false,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: {\n    type: Sequelize.STRING(255)\n  },\n  associations: function () {\n     Owner.hasMany(Property, {\n     foreignKey: {\n       name: 'owner_id'\n     }\n   });\n }\n}\n\n//Property.js\nmodule.exports = {\noptions: {\n  tableName: 'property'\n},\nattributes: {\n  id: {\n    type: Sequelize.BIGINT,\n    allowNull: false,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: {\n    type: Sequelize.STRING(255)\n  }\n}\n```\n\n```text\nOwner.create({name:'nice owner',\n              property: [{name:'nice property'},\n                         {name:'ugly property'}]});\n```\n\n```text\nOwner.create({name:'nice owner'}).then(function(owner){ \n    owner.setProperties([{name:'nice property'}, {name:'ugly property'}]).then(/*...*/);\n});\n```\n\n```text\nsequelize.transaction(function(t) {\n    return Owner.create({name:'nice owner'}, {transaction: t}).then(function(owner){ \n        return owner.setProperties([{name:'nice property'}, {name:'ugly property'}], {transaction : t});\n    });\n});\n```\n\n```text\nOwner.create({\n   name: 'nice owner',\n   property: [\n      { name: 'nice property'},\n      { name: 'ugly property'}\n   ]\n},{\n   include: [ Property]\n});\n```\n\n========================================\n\nComments:\n- I struggled some hours because the syntax was slighty different in the latest release, for anyone that can't make this work I recommend you to check out the integration tests to see how to use the create method in the most recent version github.com/sequelize/sequelize/blob/master/test/integration/&zwnj;&#8203;&hellip;\n- I would recommend to also use a transaction for your third `create` example because otherwise if the INSERT of the properties fails you are stuck with the half-finished owner.","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":147,"estimatedTokens":790}}317{"id":"stack-48407329","source":"stackoverflow","questionId":48407329,"title":"Unable to create views in mysql using sequelize ORM","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: Unable to create views in mysql using sequelize ORM\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nCurrently, I am building a web app with nodejs + mysql and sequelize as ORM. I want to create some views like we do in mysql, but I can't find any option in **Sequelize** to create views.\n\nIs there any ORM where it's possible to create views? Or is it possible to do it with sequelize?\n\n========================================\n\nCode:\n```text\nconst view_name = 'my_view';\nconst query = '<SQL QUERY THAT RETURNS YOUR VIEW>';\nmodule.exports = {\n  up: function (database, Sequelize) {\n    return database.query(`CREATE VIEW ${view_name} AS ${query}`);\n  },\n  down: function (database, Sequelize) {\n    return database.query(`DROP VIEW ${view_name}`);\n  }\n}\n```\n\n```text\nconst view_name = 'my_view';\nconst original_query = '<SQL QUERY THAT RETURNS YOUR VIEW>';\nconst new_query = '<SQL QUERY THAT RETURNS YOUR UPDATED VIEW>';\nmodule.exports = {\n  up: function (database, Sequelize) {\n    return database.query(`CREATE OR REPLACE VIEW ${view_name} AS ${new_query}`);\n  },\n  down: function (database, Sequelize) {\n    return database.query(`CREATE OR REPLACE VIEW ${view_name} AS ${original_query}`);\n  }\n}\n```\n\n```text\nfind\n```\n\n```text\nupdate\n```\n\n```text\ndelete\n```\n\n```text\ncreate\n```\n\n========================================\n\nComments:\n- There is a beautiful way of handling views on Sequelize in this answer: stackoverflow.com/a/42795937/2730233\n- Great answer! For anyone else that generates their migrations with sequelize-cli, you'll notice the `database` parameter in the up/down functions shows up as a `queryInterface` - you can't just use `queryInterface.query` as it's not valid - to get the object to run a raw query on, you need: `queryInterface.sequelize.query`.\n- ERROR: database.query is not a function \"sequelize\": \"^6.6.5\",","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":61,"estimatedTokens":468}}318{"id":"stack-35838701","source":"stackoverflow","questionId":35838701,"title":"Sequelize datatype TEXT not working with mySQL","tags":["mysql","node.js","sequelize.js","sqldatatypes"],"text":"Title: Sequelize datatype TEXT not working with mySQL\nTags: mysql, node.js, sequelize.js, sqldatatypes\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize ORM with mySQL database.\n\nI have a model with attribute type ***TEXT*** as :\n\n```\ndescription: {\n type: Sequelize.TEXT,\n unique: true\n },\n```\n\nWhen I am trying to create table for the corresponding model, its giving an error message as :\n\nUnhandled rejection SequelizeDatabaseError:\nER_BLOB_KEY_WITHOUT_LENGTH: BLOB/TEXT column 'description' used in key\nspecification without a key length\n\nThis worked fine when used with postgreSQL.\nPossible reason for this error which i could think of can be that mySQL doesn't support TEXT datatype and therefore, i have to specify it as LONGTEXT.\n\nIf I am thinking correct or is there some other reason for the same, if someone can help.\n\n========================================\n\nTop Answer:\nesmrkbr is correct, mySQL does not accept UNIQUE KEY on a TEXT field, you need to use VARCHAR instead (see: make text column as unique key). That being said, depending on the Database being used, you may need to explicitly specify a size for a TEXT (or BLOB) type. The documentation (http://docs.sequelizejs.com/en/latest/api/datatypes/) is pretty terse on this point and other than a link to the code, currently only has the following information:\n\n An (un)limited length text column. Available lengths: tiny, medium,\n long\n\nYou can pass the size as a string argument to the type. For example, to have it defined as `LONGTEXT` you will need:\n\n```\ndescription: {\n type: Sequelize.TEXT('long')\n },\n```\n\nThe code in lib/data-types.js has the following mapping to SQL for TEXT (there is a similar one for BLOB also):\n\n```\nTEXT.prototype.toSql = function() {\n switch (this._length.toLowerCase()) {\n case 'tiny':\n return 'TINYTEXT';\n case 'medium':\n return 'MEDIUMTEXT';\n case 'long':\n return 'LONGTEXT';\n default:\n return this.key;\n }\n};\n```\n\n========================================\n\nCode:\n```text\ndescription: {\n            type: Sequelize.TEXT,\n            unique: true\n        },\n```\n\n```text\nunique: true\n```\n\n```text\nTEXT\n```\n\n```text\nunique: true\n```\n\n```text\ndescription: {\n            type: Sequelize.TEXT('long')\n        },\n```\n\n```text\nTEXT.prototype.toSql = function() {\n  switch (this._length.toLowerCase()) {\n  case 'tiny':\n    return 'TINYTEXT';\n  case 'medium':\n    return 'MEDIUMTEXT';\n  case 'long':\n    return 'LONGTEXT';\n  default:\n    return this.key;\n  }\n};\n```\n\n```text\nLONGTEXT\n```\n\n```text\nvar filters = sequelize.define('filters', {\n description: { \n  type: DataTypes.STRING, \n  validate: { notEmpty: true }\n }\n}\n```\n\n========================================\n\nComments:\n- thanks @GeekyDeaks but still the same error is coming.\n- Hi @PrernaJain, with logging enabled what SQL does it output for the CREATE TABLE?\n- thanks for the well explanatory answer. and yea i did not understand what you are asking, can you just explain it a bit more. @GeekyDeaks\n- Hi @PrernaJain, by default Sequelize should output all SQL generated to console.log() so you can check it's doing the right thing. But if nothing is output, take a look at the following Q/A for some hints on how to get it to work: stackoverflow.com/questions/21427501/&hellip;.\n- Ah - well spotted! I forgot mySQL does not support TEXT UNIQUE - stackoverflow.com/questions/14033378/&hellip;\n- Yeah. Thanks esmrkbr , it worked. and @GeekyDeaks , why have you removed your answer, that was also helpful.\n- Ok - I'll put it back in if you think it helps! :)\n- doesn't DataTypes.STRING translate to varchar?","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":127,"estimatedTokens":892}}319{"id":"stack-17253052","source":"stackoverflow","questionId":17253052,"title":"Cannot get Sequelize validation working","tags":["node.js","sequelize.js"],"text":"Title: Cannot get Sequelize validation working\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement validation in my Sequelize models. The model is defined as follows\n\n```\nvar model = sequelize.define('Model', {\n from: {\n type: DataTypes.STRING,\n allowNull: false,\n validate: {\n isEmail: true\n }\n }\n}\n```\n\nThen I'm trying to build an instance and validate it:\n\n```\nvar m = Model.build({ from: 'obviously not a email' });\nvar err = m.validate();\n```\n\nBut if I do `console.log(err)`, I get `{ fct: [Function] }` only. Defining a custom validator that throws an exception results in an unhandled exception.\n\nHow should I use `validate()` properly?\n\n========================================\n\nTop Answer:\nAn alternative approach for validating in Sequelize, use a hook instead of a model validation. I'm using the 'beforeValidate' hook and adding custom validation (using validator module) with Promises that are rejected when validation fails.\n\n```\nvar validator = require('validator');\n\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define(\"User\", {\n email: {\n type:DataTypes.STRING\n },\n password: {\n type:DataTypes.STRING\n }\n });\n //validate here\n User.hook('beforeValidate', function(user, options) {\n if(validator.isEmail(user.email)){\n return sequelize.Promise.resolve(user);\n }else{\n return sequelize.Promise.reject('Validation Error: invalid email');\n }\n });\n return User;\n};\n```\n\n========================================\n\nCode:\n```text\nvar model = sequelize.define('Model', {\n  from: {\n    type:               DataTypes.STRING,\n    allowNull:          false,\n    validate: {\n      isEmail: true\n    }\n  }\n}\n```\n\n```text\nvar m = Model.build({ from: 'obviously not a email' });\nvar err = m.validate();\n```\n\n```text\nconsole.log(err)\n```\n\n```text\n{ fct: [Function] }\n```\n\n```text\nvalidate()\n```\n\n```text\nvar Sequelize = require(\"sequelize\")\n  , sequelize = new Sequelize(\"sequelize_test\", \"root\")\n\nvar Model = sequelize.define('Model', {\n  from: {\n    type:      Sequelize.STRING,\n    allowNull: false,\n    validate:  {\n      isEmail: true\n    }\n  }\n})\n\nModel.sync().success(function() {\n  Model.build({ from: \"foo@bar\" }).validate().success(function(errors) {\n    console.log(errors)\n  })\n})\n```\n\n```text\n{ from: [ 'Invalid email' ] }\n```\n\n```text\nModel.sync().success(function() {\n  Model\n    .create({ from: \"foo@bar\" })\n    .success(function() {\n      console.log('ok')\n    })\n    .error(function(errors) {\n      console.log(errors)\n    })\n})\n```\n\n```text\nv2.0.0\n```\n\n```text\nvalidate\n```\n\n```text\nvar validator = require('validator');\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define(\"User\", {\n    email: {\n      type:DataTypes.STRING\n    },\n    password: {\n      type:DataTypes.STRING\n    }\n  });\n  //validate here\n  User.hook('beforeValidate', function(user, options) {\n    if(validator.isEmail(user.email)){\n      return sequelize.Promise.resolve(user);\n    }else{\n      return sequelize.Promise.reject('Validation Error: invalid email');\n    }\n });\n return User;\n};\n```\n\n```text\nvar model = sequelize.define('Model', {\n  from: {\n    type:               DataTypes.STRING,\n    allowNull:          false,\n    validate: {\n      isEmail: true\n    }\n  }\n}\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar Model = require('your_model_folderpath').model;\n\nModel.create({from: 'not email'}).then(function(model) {\n                    // if validation passes you will get saved model\n            }).catch(Sequelize.ValidationError, function(err) {\n                    // responds with validation errors\n            }).catch(function(err) {\n                    // every other error\n            });\n```\n\n========================================\n\nComments:\n- @sdepold First I've tried 2.0.0-alpha2. I've managed to understand that it uses promises instead of direct return value, just this is not described in the documentation yet. Now I've rolled back to 1.6.0 where value is returned directly. I'll try to work it out with promises later\n- Interested in a 2.0.0-solution?\n- @sdepold it would be nice, thanks\n- will provide one later the day\n- They really need to update the documentation to indicate that validation is no longer synchronous. The result of validate() is definitely some sort of promise object, but the documentation leaves this out completely. :(\n- True. Will try to do this later the day.\n- I think it's important to note explicitly that when `validate()` fails, it still calls `success()`, but with a list of errors. Easy to assume `error()` would be called on a failed validation.\n- The docs are in need of a major update. I keep getting the promise notices since bluebird/promise has changed where they are expecting .then .catch etc. not what is shown above. This is very confusing for most who are trying to use sequelize. I'm unable to get the validation to work. It continues to insert a string that should be a isURL however missing the http protocols.\n- I just tried with the isInt: true validator and it got into the catch so it's the isUrl that is failing. Removed the .com at the end and the url validator doesn't care about the protocol in the beginning yet the docs mention \"// checks for url format (foo.com)\". I'll submit an issue on github.","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":198,"estimatedTokens":1318}}320{"id":"stack-31867889","source":"stackoverflow","questionId":31867889,"title":"SequelizeJS Soft Deleting","tags":["sql","database","node.js","sequelize.js"],"text":"Title: SequelizeJS Soft Deleting\nTags: sql, database, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI can't figure out how the soft deleting works with SequelizeJS and I cannot find any documentation online.\n\nI've already setup at a `deletedAt` column as\n\n```\ndeletedAt: {\n type: Sequelize.DATE\n}\n```\n\nbut I don't know how to now setup the system so that `MyModel.destroy(query)` soft deletes it instead. Currently, it plainly removes the entry completely.\n\n========================================\n\nTop Answer:\nFirst Add `deletedAt` column **both** the **model & migrations** file like -\n\n```\ndeletedAt: {\n type: Sequelize.DATE,\n allowNull: false\n}\n```\n\nThen set the `timestamps` & `paranoid` to **true**. I think it will be work..\n\n========================================\n\nCode:\n```text\ndeletedAt: {\n    type: Sequelize.DATE\n}\n```\n\n```text\ndeletedAt\n```\n\n```text\nMyModel.destroy(query)\n```\n\n```text\noptions.timestamps\n```\n\n```text\noptions.paranoid\n```\n\n```text\ndeletedAt\n```\n\n```text\ndeletedAt: {\n    type: Sequelize.DATE,\n    allowNull: false\n}\n```\n\n```text\ndeletedAt\n```\n\n```text\ntimestamps\n```\n\n```text\nparanoid\n```\n\n========================================\n\nComments:\n- can someone explain it,, i'm still searching and not found anything,, `timestamps: true,paranoid: true`, still only deleted item..\n- my fault, my error is i'm wrong to define `deletedAt` as `deleted_at`.. ok, it's solved,, btw, could we customize it ? source : docs.sequelizejs.com/manual/instances.html\n- we can customize it, you create deletedAt column in table, by migrations first, and if you have chosen any different custom name for that column, than you should also specify that custom name in options.deletedAt: 'deleted_at', near the options.paranoid:true . sequelize.org/docs/v6/core-concepts/paranoid","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":85,"estimatedTokens":450}}321{"id":"stack-34255792","source":"stackoverflow","questionId":34255792,"title":"Sequelize - How to search multiple columns?","tags":["javascript","sql","node.js","sequelize.js"],"text":"Title: Sequelize - How to search multiple columns?\nTags: javascript, sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a database of articles with several columns and would like to be able to search both `title` and `description`.\n\nCurrently, I have:\n\n```\nArticle.findAll({\n where: {\n title: { like: '%' + searchQuery + '%' }\n }\n});\n```\n\nHow can I also search the description as well?\n\nI've read through the sequelize documentation, even in the `Complex filtering / OR / NOT queries` section, but the examples only seem to explain searching in one column.\n\n========================================\n\nTop Answer:\n**Sequelize >= 4.12**\n\n```\nArticle.findAll({\n where = {\n [Op.or]: [\n { name: { [Op.like]: `%${req.query.query_string}%` } },\n { description: { [Op.like]: `%${req.query.query_string}%` } }\n ]\n}\n});\n```\n\njust fyi: mysql doesn't supports iLike ;)\n\n========================================\n\nCode:\n```text\nArticle.findAll({\n  where: {\n    title: { like: '%' + searchQuery + '%' }\n  }\n});\n```\n\n```text\ntitle\n```\n\n```text\ndescription\n```\n\n```text\nComplex filtering / OR / NOT queries\n```\n\n```text\nconst Op = Sequelize.Op;\nArticle.findAll({\n  where: {\n    title: { [Op.like]: '%' + searchQuery + '%' },\n    description: { [Op.like]: '%' + searchQuery2 + '%' }\n  }\n});\n```\n\n```text\nArticle.findAll({\n  where: {\n    title: { like: '%' + searchQuery + '%' },\n    description: { like: '%' + searchQuery2 + '%' }\n  }\n});\n```\n\n```text\nconst Op = Sequelize.Op;\nArticle.findAll({\n  where: {\n    [Op.or]: [\n     title: { [Op.like]: '%' + searchQuery + '%' },\n     description: { [Op.like]: '%' + searchQuery2 + '%' }\n    ]\n  }\n});\n```\n\n```text\nArticle.findAll({\n  where: {\n    $or: [\n     title: { like: '%' + searchQuery + '%' },\n     description: { like: '%' + searchQuery2 + '%' }\n    ]\n  }\n});\n```\n\n```text\ntitle\n```\n\n```text\nsearchQuery\n```\n\n```text\ndescription\n```\n\n```text\nsearchQuery2\n```\n\n```text\nProject.findOne({\n  where: {\n    name: 'a project',\n    $or: [\n      { id: [1,2,3] },\n      { id: { $gt: 10 } }\n    ]\n  }\n})\n\nProject.findOne({\n  where: {\n    name: 'a project',\n    id: {\n      $or: [\n        [1,2,3],\n        { $gt: 10 }\n      ]\n    }\n  }\n})\n```\n\n```text\nSELECT *\nFROM `Projects`\nWHERE (\n  `Projects`.`name` = 'a project'\n   AND (`Projects`.`id` IN (1,2,3) OR `Projects`.`id` > 10)\n)\nLIMIT 1;\n```\n\n```text\nProject.findAll({\n  where: {\n    id: {\n      $and: {a: 5}           // AND (a = 5)\n      $or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)\n  ... etc\n```\n\n```text\n$and\n```\n\n```text\n$or\n```\n\n```text\nArticle.findAll({\n where = {\n  [Op.or]: [\n    { name: { [Op.like]: `%${req.query.query_string}%` } },\n    { description: { [Op.like]: `%${req.query.query_string}%` } }\n  ]\n}\n});\n```\n\n```text\nwhere: {\n  [op.or]: [\n    {\n      model: {\n        [op.like]: `%${ req.query.search }%`\n      }\n    },\n    {\n      description: {\n        [op.like]: `%${ req.query.search }%`\n      }\n    }\n  ]\n}\n```\n\n```text\nasync findFilterAndCountAll(pg: { limit : number, offset : number, sort:string, order: string, pfilter : any}) {\n        var filters = Array();\n        for (const key in this.repo.rawAttributes ) {\n            console.log(key);\n            filters.push(sequelize.where(\n                sequelize.cast(sequelize.col(key), 'varchar'),\n                {[Op.iLike]: `%tes%`}\n              ))\n        }\n        return await this.repo.findAndCountAll({\n            limit : pg.limit,\n            offset : pg.offset,\n            order: [\n                [pg.order, pg.sort]\n            ],\n            where : {\n                [Op.or]: filters\n            }\n        }); \n    }\n```\n\n========================================\n\nComments:\n- Thanks for your response but correct me if I'm mistaken, but does this still not only search one column? (in this example `Projects.id`)\n- I think these joiners can be used within the `where` between fields. See the `$not example` near these ones for use with two different columns.\n- Unfortunately, this does not work in sequelize 6. Sequelize docs: stackoverflow.com/questions/34255792/&hellip; mention very few available options for findOne. Options mentioned in this answer are supported in findAll method, but not findOne.\n- The syntax for logical operations is modified in the latest version of sequelize, please check docs.sequelizejs.com/manual/tutorial/querying.html\n- @SohamLawar thanks for the heads up, I've added it to the answer as preferred way for Sequelize 4.12 and up.\n- Good job,@leroydev\n- This is still forcing that the record include both a title and description. What if one of my params is not included?\n- Is there a possibility to search by all columns inside table without explicitly saying which column to search in? @leroydev\n- @BartusZak Please create a new question for that question. :)","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":234,"estimatedTokens":1194}}322{"id":"stack-46444745","source":"stackoverflow","questionId":46444745,"title":"Typescript async/await not working","tags":["node.js","typescript","asynchronous","async-await","sequelize.js"],"text":"Title: Typescript async/await not working\nTags: node.js, typescript, asynchronous, async-await, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've a problem about async/await on typescript with target es2017. Below is my code :\n\nmy route.ts :\n\n```\nmethod: 'POST',\n config: { \n auth: {\n strategy: 'token', \n }\n },\n path: '/users',\n handler: (request, reply) {\n\n let { username, password } = request.payload;\n\n const getOperation = User\n .findAll({\n where: {\n username: username\n }\n })\n .then(([User]) => {\n if(!User) {\n reply({\n error: true,\n errMessage: 'The specified user was not found'\n });\n return;\n }\n\n let comparedPassword = compareHashPassword(User.password, password);\n console.log(comparedPassword);\n\n if(comparedPassword) {\n const token = jwt.sign({\n username,\n scope: User.id\n\n }, 'iJiYpmaVwXMp8PpzPkWqc9ShQ5UhyEfy', {\n algorithm: 'HS256',\n expiresIn: '1h'\n });\n\n reply({\n token,\n scope: User.id\n });\n } else {\n reply('incorrect password');\n }\n } )\n .catch(error => { reply('server-side error') });\n\n};\n```\n\nmy helper.ts :\n\n```\nexport async function compareHashPassword(pw:string, originalPw:string) {\n console.log(pw);\n console.log(originalPw);\n let compared = bcrypt.compare(originalPw, pw, function(err, isMatch) {\n if(err) {\n return console.error(err);\n }\n console.log(isMatch);\n return isMatch;\n });\n\n return await compared;\n}\n```\n\nthis auth route supposed to return JWT token when user login. but the problem here is even when I enter the valid password to sign-in the function compareHashPassword always return undefined.\n\nFor example when i call the api with json string \n\n```\n{\n \"username\": \"x\",\n \"password\": \"helloword\"\n}\n```\n\nWhen i track using console.log(), the log is : \n\n```\n$2a$10$Y9wkjblablabla -> hashed password stored in db\nhelloword \nPromise {\n ,\n domain: \n Domain {\n domain: null,\n _events: { error: [Function: bound ] },\n _eventsCount: 1,\n _maxListeners: undefined,\n members: [] } }\ntrue\n```\n\nmaybe this is just my lack of understanding about using async/await with typescript. for note my env is :\n\n```\nnode : v8.6.0\ntypescript : v2.5.2\nts-node : v3.3.0\nmy tsconfig.json //\n{\n \"compilerOptions\": {\n \"outDir\": \"dist\",\n \"target\": \"es2017\",\n \"module\": \"commonjs\",\n \"removeComments\": true,\n \"types\": [\n \"node\"\n ],\n \"allowJs\": true,\n \"moduleResolution\": \"classic\"\n },\n \"exclude\": [\n \"node_modules\"\n ]\n}\n```\n\n========================================\n\nTop Answer:\nSince you're targeting ES2017, let's clean up your code, starting with the simpler `helper.ts`:\n\n```\nimport { promisify } from 'util' // you'll thank me later\n\nconst compare = promisify(bcrypt.compare)\n\nexport async function compareHashPassword(pw:string, originalPw:string) {\n console.log(pw);\n console.log(originalPw);\n return compare(originalPw, pw);\n}\n```\n\nNow for the `route.ts`:\n\n```\nhandler: async (request, reply) => {\n let { username, password } = request.payload;\n\n try {\n const [user] = await User.findAll({\n where: {\n username: username\n }\n })\n\n if(!user) {\n reply({\n error: true,\n errMessage: 'The specified user was not found'\n });\n\n return;\n }\n\n let match = await compareHashPassword(user.password, password);\n\n console.log(match);\n\n if (match) {\n const token = jwt.sign({\n username,\n scope: User.id\n }, 'iJiYpmaVwXMp8PpzPkWqc9ShQ5UhyEfy', {\n algorithm: 'HS256',\n expiresIn: '1h'\n });\n\n reply({\n token,\n scope: user.id\n });\n } else {\n reply('incorrect password');\n }\n } catch (error) {\n reply('server-side error')\n }\n}\n```\n\nHopefully I've matched what you're attempting to accomplish, based on the code you've provided. If there's an issue somewhere with this updated code, please let me know in the comments.\n\n========================================\n\nCode:\n```text\nmethod: 'POST',\n        config: {            \n            auth: {\n                strategy: 'token',        \n            }\n        },\n        path: '/users',\n        handler: (request, reply) {\n\n    let { username, password } = request.payload;\n\n    const getOperation = User\n    .findAll({\n        where: {\n            username: username\n        }\n    })\n    .then(([User]) => {\n        if(!User) {\n            reply({\n                error: true,\n                errMessage: 'The specified user was not found'\n            });\n            return;\n        }\n\n        let comparedPassword = compareHashPassword(User.password, password);\n        console.log(comparedPassword);\n\n        if(comparedPassword) {\n            const token = jwt.sign({\n                username,\n                scope: User.id\n\n            }, 'iJiYpmaVwXMp8PpzPkWqc9ShQ5UhyEfy', {\n                algorithm: 'HS256',\n                expiresIn: '1h'\n            });\n\n            reply({\n                token,\n                scope: User.id\n            });\n        } else {\n            reply('incorrect password');\n        }\n    } )\n    .catch(error => { reply('server-side error') });\n\n};\n```\n\n```text\nexport async function compareHashPassword(pw:string, originalPw:string) {\n    console.log(pw);\n    console.log(originalPw);\n    let compared = bcrypt.compare(originalPw, pw, function(err, isMatch) {\n        if(err) {\n                return console.error(err);\n        }\n        console.log(isMatch);\n        return isMatch;\n        });\n\n    return await compared;\n}\n```\n\n```text\n{\n  \"username\": \"x\",\n  \"password\": \"helloword\"\n}\n```\n\n```text\n$2a$10$Y9wkjblablabla -> hashed password stored in db\nhelloword \nPromise {\n  <pending>,\n  domain: \n   Domain {\n     domain: null,\n     _events: { error: [Function: bound ] },\n     _eventsCount: 1,\n     _maxListeners: undefined,\n     members: [] } }\ntrue\n```\n\n```text\nnode : v8.6.0\ntypescript : v2.5.2\nts-node : v3.3.0\nmy tsconfig.json //\n{\n    \"compilerOptions\": {\n        \"outDir\": \"dist\",\n        \"target\": \"es2017\",\n        \"module\": \"commonjs\",\n        \"removeComments\": true,\n        \"types\": [\n            \"node\"\n        ],\n        \"allowJs\": true,\n        \"moduleResolution\": \"classic\"\n    },\n    \"exclude\": [\n        \"node_modules\"\n    ]\n}\n```\n\n```text\nconst someFunc = async function() {\n    return new Promise((resolve, reject) => { \n        setTimeout(resolve, 100, true);\n    });\n};\n\n(async () => {\n     const result = await someFunc(); // true\n})();\n```\n\n```text\nexport async function compareHashPassword(pw:string, originalPw:string) {\n    return new Promise((resolve, reject) => {\n        bcrypt.compare(originalPw, pw, function(err, isMatch) {\n            if(err) {\n                reject(err);\n            }\n            console.log(isMatch);\n            resolve(isMatch);\n        });\n    });\n}\n\n// and call it this way\n(async () => {\n     const compared = await compareHashPassword(pw, originPw);\n})()\n```\n\n```text\nPromise\n```\n\n```text\nasync\n```\n\n```text\ncompareHashPassword\n```\n\n```text\nutil.promisify\n```\n\n```text\nnode 8.xx\n```\n\n```text\nbluebird\n```\n\n```text\nimport { promisify } from 'util' // you'll thank me later\n\nconst compare = promisify(bcrypt.compare)\n\nexport async function compareHashPassword(pw:string, originalPw:string) {\n    console.log(pw);\n    console.log(originalPw);\n    return compare(originalPw, pw);\n}\n```\n\n```text\nhandler: async (request, reply) => {\n  let { username, password } = request.payload;\n\n  try {\n    const [user] = await User.findAll({\n      where: {\n        username: username\n      }\n    })\n\n    if(!user) {\n      reply({\n        error: true,\n        errMessage: 'The specified user was not found'\n      });\n\n      return;\n    }\n\n    let match = await compareHashPassword(user.password, password);\n\n    console.log(match);\n\n    if (match) {\n      const token = jwt.sign({\n        username,\n        scope: User.id\n      }, 'iJiYpmaVwXMp8PpzPkWqc9ShQ5UhyEfy', {\n        algorithm: 'HS256',\n        expiresIn: '1h'\n      });\n\n      reply({\n        token,\n        scope: user.id\n      });\n    } else {\n      reply('incorrect password');\n    }\n  } catch (error) {\n    reply('server-side error')\n  }\n}\n```\n\n```text\nhelper.ts\n```\n\n```text\nroute.ts\n```\n\n========================================\n\nComments:\n- *As for now, you can only call await inside an async function* As per the specification, that will **always** be the case, just saying.\n- I find that sad, although I didn't check the implementation itself in v8. Thanks for the tip, I will update my answer\n- By the way, in your first example, the `Promise.resolve(...)` is redundant. All you have to do is `return true` and the `async` function will implicitly coerce it into a resolved promise.\n- I dind't know that, so explicitely return a Promise only needs to be done when having a callback style async call ?\n- Yes, or in node.js you have the option of using `util.promisify()` to convert callback-style functions into promise-style functions. See my answer for usage.\n- Now your `new Promise()` is no longer redundant, but I personally prefer writing it like this `setTimeout(resolve, 100, true);` Just food for thought~\n- wow, that's really helpful utility from node. Thanks for all your answer. Both of your solution worked and help me understand how async works. cheers.","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":448,"estimatedTokens":2244}}323{"id":"stack-51789824","source":"stackoverflow","questionId":51789824,"title":"How to set collation for a specific Column in a Sequelize model?","tags":["node.js","orm","sequelize.js"],"text":"Title: How to set collation for a specific Column in a Sequelize model?\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow to set collation for a specific Column in a Sequelize model?\n\nI tried this:\n\n```\nname: {\n type: Sequelize.STRING,\n allowNull: false,\n collate: 'utf8_general_ci'\n},\n```\n\nApparently it doesn't work. Any other ideia?\n\n========================================\n\nTop Answer:\nWhat It worked for me\n\n\r\n\r\n\n```\nawait queryInterface.sequelize.query(`\n ALTER TABLE files\n MODIFY COLUMN original_name VARCHAR(255)\n CHARACTER SET utf8mb4\n COLLATE utf8mb4_general_ci NOT NULL;\n`);\n```\n\n========================================\n\nCode:\n```text\nname: {\n  type: Sequelize.STRING,\n  allowNull: false,\n  collate: 'utf8_general_ci'\n},\n```\n\n```text\nsequlize.define('table', {\n\n}, {\n    charset: 'utf8',\n    collate: 'utf8_general_ci'\n})\n```\n\n```text\nsequelize.define('table', {\n    column: Sequelize.STRING + ' CHARSET utf8 COLLATE utf8_general_ci'\n})\n```\n\n```text\nlet sequelize = new Sequelize('database', {\n    dialectOptions: {\n        charset: 'utf8',\n        collate: 'utf8_general_ci',\n    }\n});\n```\n\n```js\nawait queryInterface.sequelize.query(`\n    ALTER TABLE files\n    MODIFY COLUMN original_name VARCHAR(255)\n    CHARACTER SET utf8mb4\n    COLLATE utf8mb4_general_ci NOT NULL;\n`);\n```\n\n========================================\n\nComments:\n- do you want to map the column named \"name\", in this case?\n- yes, or for any other.\n- sorry @Tiago B&#233;rtolo I thought your problem was in the construction of the model. Had not read the word \"collate\"\n- No problem mate. Thanks for trying.\n- Try this `Sequelize.STRING + ' CHARSET utf8 COLLATE utf8_general_ci'` in your type\n- Didn't work! Nice attempt though! :D\n- hum... this works for me\n- What your sequelize version? Your different charset is only for this column or all database?\n- Ok... Let's try, at some point, we can get it right. Set the define in sequelize... whith the column level sample. Outside your model","metadata":{"transformedAt":"2026-08-18T18:33:34.365Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":92,"estimatedTokens":498}}324{"id":"stack-55775328","source":"stackoverflow","questionId":55775328,"title":"No Sequelize instance passed","tags":["node.js","sequelize.js"],"text":"Title: No Sequelize instance passed\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to outsource my models for the `dbInit` function from my dbController because I have several models which makes the dbController to big.\n\nSo I am calling `initDb` from my `db_controller.js` which looks like this (I use that docu http://docs.sequelizejs.com/manual/getting-started.html )\n\n```\nconst userModel = require('../model/user')\nconst subjectModel = require('../model/subject')\nconst Sequelize = require('sequelize')\nconst seq = new Sequelize({\n dialect: 'sqlite',\n storage: './user.db'\n})\n\nasync function initDb () {\n await userModel.user.initUser()\n await subjectModel.subject.initSubject()\n userModel.user.userClass.hasMany(subjectModel.subject.subjectClass)\n}\n```\n\nThe **user** in the `user.js` looks like this:\n\n```\nconst Sequelize = require('sequelize')\nconst seq = new Sequelize({\n dialect: 'sqlite',\n storage: './user.db'\n})\n\nclass User extends Sequelize.Model {\n}\n\nexports.user = {\n initUser: initUser,\n userClass: User\n}\n\nasync function initUser () {\n return new Promise(resolve => {\n User.init(\n // attributes\n {\n firstName: {\n type: Sequelize.STRING,\n allowNull: false\n },\n lastName: {\n type: Sequelize.STRING,\n allowNull: false\n },\n email: {\n type: Sequelize.STRING,\n allowNull: false\n }\n },\n // options\n {\n seq,\n modelName: 'user'\n }\n )\n resolve()\n })\n}\n```\n\nand pretty much the same for the `subject.js`\n\n```\nconst Sequelize = require('sequelize')\nconst sequelize = new Sequelize({\n dialect: 'sqlite',\n storage: './user.db'\n})\n\nclass Subject extends Sequelize.Model {\n}\n\nexports.subject = {\n initSubject: initSubject,\n subjectClass: Subject\n}\n\nasync function initSubject () {\n return new Promise(resolve => {\n Subject.init(\n // attributes\n {\n name: {\n type: Sequelize.STRING,\n allowNull: false\n }\n },\n // options\n {\n seq: sequelize,\n modelName: 'subject'\n }\n )\n resolve()\n })\n}\n```\n\nSo when I try to execute this via `node db_controller.js`\n\nI receive this **error** (shortened)\n\n```\n(node:12444) UnhandledPromiseRejectionWarning: Error: No Sequelize instance passed\n at Function.init (D:\\Git\\ppb\\node_modules\\sequelize\\lib\\model.js:915:13)\n at resolve (D:\\Git\\ppb\\src\\model\\user.js:26:10)\n at new Promise ()\n at Object.initUser (D:\\Git\\ppb\\src\\model\\user.js:25:10)\n at initDb (D:\\Git\\ppb\\src\\controller\\db_controller.js:18:24)\n at Object. (D:\\Git\\ppb\\src\\controller\\db_controller.js:45:1)\n at Module._compile (module.js:652:30)\n at Object.Module._extensions..js (module.js:663:10)\n```\n\nThank you very much for any advice in advance!\n\n========================================\n\nTop Answer:\n```\nimport database from 'path/some*.ts';\n```\n\nthis is my init database file when used in express app.ts; also in this database file I export the sequelize instance;\n\n```\nimport User from '../some/model/define/file';\n```\n\nafter database to import Sequelize can auto sync define to schema ,the models like this:\n\n```\nClass User extends Model {...} \nUser.define(...);\nUser.has or many();\n```\n\nthis can solve the problem: sequelize instance error.\n\npoint: behind your sequelize reference order!!!!\n\n========================================\n\nCode:\n```text\nconst userModel = require('../model/user')\nconst subjectModel = require('../model/subject')\nconst Sequelize = require('sequelize')\nconst seq = new Sequelize({\n  dialect: 'sqlite',\n  storage: './user.db'\n})\n\nasync function initDb () {\n  await userModel.user.initUser()\n  await subjectModel.subject.initSubject()\n  userModel.user.userClass.hasMany(subjectModel.subject.subjectClass)\n}\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst seq = new Sequelize({\n  dialect: 'sqlite',\n  storage: './user.db'\n})\n\nclass User extends Sequelize.Model {\n}\n\nexports.user = {\n  initUser: initUser,\n  userClass: User\n}\n\nasync function initUser () {\n  return new Promise(resolve => {\n    User.init(\n      // attributes\n      {\n        firstName: {\n          type: Sequelize.STRING,\n          allowNull: false\n        },\n        lastName: {\n          type: Sequelize.STRING,\n          allowNull: false\n        },\n        email: {\n          type: Sequelize.STRING,\n          allowNull: false\n        }\n      },\n      // options\n      {\n        seq,\n        modelName: 'user'\n      }\n    )\n    resolve()\n  })\n}\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: './user.db'\n})\n\nclass Subject extends Sequelize.Model {\n}\n\nexports.subject = {\n  initSubject: initSubject,\n  subjectClass: Subject\n}\n\nasync function initSubject () {\n  return new Promise(resolve => {\n    Subject.init(\n      // attributes\n      {\n        name: {\n          type: Sequelize.STRING,\n          allowNull: false\n        }\n      },\n      // options\n      {\n        seq: sequelize,\n        modelName: 'subject'\n      }\n    )\n    resolve()\n  })\n}\n```\n\n```text\n(node:12444) UnhandledPromiseRejectionWarning: Error: No Sequelize instance passed\n    at Function.init (D:\\Git\\ppb\\node_modules\\sequelize\\lib\\model.js:915:13)\n    at resolve (D:\\Git\\ppb\\src\\model\\user.js:26:10)\n    at new Promise (<anonymous>)\n    at Object.initUser (D:\\Git\\ppb\\src\\model\\user.js:25:10)\n    at initDb (D:\\Git\\ppb\\src\\controller\\db_controller.js:18:24)\n    at Object.<anonymous> (D:\\Git\\ppb\\src\\controller\\db_controller.js:45:1)\n    at Module._compile (module.js:652:30)\n    at Object.Module._extensions..js (module.js:663:10)\n```\n\n```text\ndbInit\n```\n\n```text\ninitDb\n```\n\n```text\ndb_controller.js\n```\n\n```text\nuser.js\n```\n\n```text\nsubject.js\n```\n\n```text\nnode db_controller.js\n```\n\n```text\n{\n  seq: sequelize,\n  modelName: 'subject'\n}\n```\n\n```text\n{\n  sequelize: sequelize,\n  modelName: 'subject'\n}\n```\n\n```text\nseq\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize\n```\n\n```text\nseq\n```\n\n```text\nimport database from 'path/some*.ts';\n```\n\n```text\nimport User from '../some/model/define/file';\n```\n\n```text\nClass User extends Model {...} \nUser.define(...);\nUser.has or many();\n```\n\n========================================\n\nComments:\n- Oh! I renamed it and obviously something messed up then. Thank you :) Btw the solution is just: sequelize, modelName: 'subject\n- `const seq = sequelize;` if it is just for clarity maybe?","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":336,"estimatedTokens":1548}}325{"id":"stack-48475999","source":"stackoverflow","questionId":48475999,"title":"async / await proper error handling","tags":["javascript","node.js","error-handling","async-await","sequelize.js"],"text":"Title: async / await proper error handling\nTags: javascript, node.js, error-handling, async-await, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAssume we have an action that runs on user login (express, node). \nThis is the code that works, written using a lot of callbacks:\n\n```\ncheckIfEmailAndPasswordAreSet(email, password, (error, response) => {\n if (error) return errorResponse(403, 'validation error', error)\n findUserByEmail(email, (error, user) => {\n if (error) return errorResponse(500, 'db error', error)\n if (!user) return errorResponse(403, 'user not found')\n checkUserPassword(user, password, (error, result) => {\n if (error) return errorResponse(500, 'bcrypt error', error)\n if (!result) return errorResponse(403, 'incorrect password')\n updateUserLastLoggedIn(user, (error, response) => {\n if (error) return errorResponse(500, 'db error', error) \n generateSessionToken(user, (error, token) => {\n if (error) return errorResponse(500, 'jwt error', error)\n return successResponse(user, token)\n })\n })\n })\n })\n})\n```\n\nI want to rewrite this code using async/await and avoid callback hell. How to do that? \n\nThe first attempt could look like that: \n\n```\ntry {\n await checkIfEmailAndPasswordAreSet(email, password)\n const user = await findUserByEmail(email)\n if (!user) throw new Error('user not found')\n const result = await checkUserPassword(user, password)\n if (!result) throw new Error('incorrect password')\n await updateUserLastLoggedIn(user)\n const token = await generateSessionToken(user)\n return successResponse(user, token)\n} catch (e) {\n // How to handle the error here?\n}\n```\n\nI want to keep the proper error handling, that is if the error was thrown in `checkUserPassword` method, I want the response to contain info about this. What should I write in the catch method? \n\nFor example, I could wrap every instruction into it's own try / catch block like that:\n\n```\ntry {\n\n let user, result\n\n try {\n await checkIfEmailAndPasswordAreSet(email, password)\n } catch (error) {\n throw new Error('This error was thrown in checkIfEmailAndPasswordAreSet')\n }\n\n try {\n user = await findUserByEmail(email)\n } catch (error) {\n throw new Error('This error was thrown in findUserByEmail')\n }\n\n if (!user) throw new Error('user not found')\n\n ...\n} catch (error) {\n return errorResponse(error)\n}\n```\n\nBut this code.. probably that's not a callback hell, but I would call it try/catch hell. It takes at least 2 times more rows that the original old fashioned code with callbacks. How to rewrite it to be shorter and take an advantage of async/await?\n\n========================================\n\nCode:\n```text\ncheckIfEmailAndPasswordAreSet(email, password, (error, response) => {\n  if (error) return errorResponse(403, 'validation error', error)\n  findUserByEmail(email, (error, user) => {\n    if (error) return errorResponse(500, 'db error', error)\n    if (!user) return errorResponse(403, 'user not found')\n    checkUserPassword(user, password, (error, result) => {\n      if (error) return errorResponse(500, 'bcrypt error', error)\n      if (!result) return errorResponse(403, 'incorrect password')\n      updateUserLastLoggedIn(user, (error, response) => {\n        if (error) return errorResponse(500, 'db error', error)      \n        generateSessionToken(user, (error, token) => {\n          if (error) return errorResponse(500, 'jwt error', error)\n          return successResponse(user, token)\n        })\n      })\n    })\n  })\n})\n```\n\n```text\ntry {\n  await checkIfEmailAndPasswordAreSet(email, password)\n  const user = await findUserByEmail(email)\n  if (!user) throw new Error('user not found')\n  const result = await checkUserPassword(user, password)\n  if (!result) throw new Error('incorrect password')\n  await updateUserLastLoggedIn(user)\n  const token = await generateSessionToken(user)\n  return successResponse(user, token)\n} catch (e) {\n  // How to handle the error here?\n}\n```\n\n```text\ntry {\n\n  let user, result\n\n  try {\n    await checkIfEmailAndPasswordAreSet(email, password)\n  } catch (error) {\n    throw new Error('This error was thrown in checkIfEmailAndPasswordAreSet')\n  }\n\n  try {\n    user = await findUserByEmail(email)\n  } catch (error) {\n    throw new Error('This error was thrown in findUserByEmail')\n  }\n\n  if (!user) throw new Error('user not found')\n\n  ...\n} catch (error) {\n  return errorResponse(error)\n}\n```\n\n```text\ncheckUserPassword\n```\n\n```text\nfunction error(code, msg) {\n    return e => {\n        e.status = code;\n        e.details = msg;\n        throw e;\n    };\n}\nfunction ifEmpty(fn) {\n    return o => o || fn(new Error(\"empty\"));\n}\n```\n\n```text\ntry {\n    await checkIfEmailAndPasswordAreSet(email, password)\n        .catch(error(403, 'validation error'));\n    const user = await findUserByEmail(email)\n        .then(ifEmpty(error(403, 'user not found')), error(500, 'db error', error));\n    await checkUserPassword(user, password)\n        .then(ifEmpty(error(403, 'incorrect password')), error(500, 'bcrypt error'));\n    await updateUserLastLoggedIn(user)\n        .catch(error(500, 'db error'));\n    const token = generateSessionToken(user)\n        .catch(error(500, 'jwt error'));\n    return successResponse(user, token);\n} catch(err) {\n    errorResponse(err.status, err.details, err);\n}\n```\n\n```text\ntry\n```\n\n```text\ncatch\n```\n\n========================================\n\nComments:\n- You can add specific error types , like `throw new UserNotFoundError` instead of `new Error('user not found')` and then do some `instanceof` branching in the catch block.\n- `it takes at least 2 more rows` ... cool. But its definetly more readable.\n- Thanks for the idea. I used your approach and the code looks prettier now, imho. Will mark as answer in several days if no other response.\n- Yeah, prettiness is in the eye of the beholder :-) You might also write different helper functions that operate on promises and could be called like `await rejectEmpty(wrapRejection(checkPassword(…), 500, 'bcrypt'), 403, 'password')`. Any abstraction that makes the code DRY will do :-)","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":193,"estimatedTokens":1499}}326{"id":"stack-36969162","source":"stackoverflow","questionId":36969162,"title":"How to `include` two separate references of same model using Sequelize ORM?","tags":["sequelize.js"],"text":"Title: How to `include` two separate references of same model using Sequelize ORM?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a website using the MEAN stack but replacing MongoDB with PostGRES and, as a result, using Sequelize ORM.\n\nI have two models -- `User` and `AudioConfig`. A `User` can have many `AudioConfig` and an `AudioConfig` belongs to a `User` by the `createdBy` and `updatedBy`.\n\nHere's how my association looks like using Sequelize\n\n```\nmodels.User.hasMany(models.AudioConfig, {\n foreignKey: {\n name: 'createdBy',\n allowNull: false\n }\n});\nmodels.User.hasMany(models.AudioConfig, {\n foreignKey: {\n name: 'updatedBy'\n }\n});\nmodels.AudioConfig.belongsTo(models.User, {\n foreignKey: {\n name: 'createdBy',\n as: 'createdBy',\n allowNull: false\n }\n});\nmodels.AudioConfig.belongsTo(models.User, {\n foreignKey: {\n name: 'updatedBy',\n as: 'updatedBy'\n }\n});\n```\n\nIn my `findAll` query for `AudioConfig`, I have tried several variations from what I've found online but none appear to work as I expect:\n\n```\nvar Db = require('../../models');\nvar entityModel = Db.AudioConfig;\n\nexports.index = function (req, res) {\n entityModel.findAll({\n include: {all:true}\n })\n .then(function (entities) {\n return res.status(200).json(entities);\n })\n .catch(function (err) {\n return handleError(res, err);\n })\n};\n\n// And I've tried this...\nexports.index = function (req, res) {\n entityModel.findAll({\n include: [\n {model: Db.User, as: 'createdBy'},\n {model: Db.User, as: 'updatedBy'}\n ]\n })\n .then(function (entities) {\n return res.status(200).json(entities);\n })\n .catch(function (err) {\n return handleError(res, err);\n })\n};\n\n// And this too...\nexports.index = function (req, res) {\n entityModel.findAll({\n include: [\n {\n model: Db.User\n }\n ]\n })\n .then(function (entities) {\n return res.status(200).json(entities);\n })\n .catch(function (err) {\n return handleError(res, err);\n })\n};\n```\n\nNow, in my database, I have a single record of `AudioConfig` that has two different `User` references -- one for `createdBy` and another for `updatedBy`. But when I do a query for `AudioConfig`, I only get the `User` record back for the `updatedBy` field.\n\n```\n[\n {\n \"id\": \"e3011e31-b907-47ad-99f3-61016283a523\",\n \"sampleRate\": 16000,\n \"format\": \"WAV\",\n \"channel\": 2,\n \"bitRate\": 16,\n \"createdAt\": \"2016-05-01T16:30:11.847Z\",\n \"updatedAt\": \"2016-05-01T16:30:11.847Z\",\n \"createdBy\": \"1375263f-a3f0-4eef-800f-99b28fdce9d8\",\n \"updatedBy\": \"5bb8cac0-b916-4000-81fe-9b1f8f597847\",\n \"User\": {\n \"id\": \"5bb8cac0-b916-4000-81fe-9b1f8f597847\",\n \"email\": \"johnd@email.com\",\n \"firstName\": \"John\",\n \"lastName\": \"Doe\",\n \"resetPasswordToken\": null,\n \"resetPasswordTokenExpiresOn\": null,\n \"createdAt\": \"2016-05-01T16:30:11.816Z\",\n \"updatedAt\": \"2016-05-01T16:30:11.816Z\",\n \"roleId\": \"10ae3879-9f9f-4370-aa47-3677c492afd8\"\n }\n }\n]\n```\n\nHow do I get it so that `createdBy` value of UUID is replaced with the `User` object associated with it? And same for the `updatedBy` field?\n\nI'm somewhat expecting the same behavior as with MongoDB and Mongoose's `populate`\n\n========================================\n\nCode:\n```text\nmodels.User.hasMany(models.AudioConfig, {\n  foreignKey: {\n    name: 'createdBy',\n    allowNull: false\n  }\n});\nmodels.User.hasMany(models.AudioConfig, {\n  foreignKey: {\n    name: 'updatedBy'\n  }\n});\nmodels.AudioConfig.belongsTo(models.User, {\n  foreignKey: {\n    name: 'createdBy',\n    as: 'createdBy',\n    allowNull: false\n  }\n});\nmodels.AudioConfig.belongsTo(models.User, {\n  foreignKey: {\n    name: 'updatedBy',\n    as: 'updatedBy'\n  }\n});\n```\n\n```text\nvar Db = require('../../models');\nvar entityModel = Db.AudioConfig;\n\nexports.index = function (req, res) {\n  entityModel.findAll({\n      include: {all:true}\n    })\n    .then(function (entities) {\n      return res.status(200).json(entities);\n    })\n    .catch(function (err) {\n      return handleError(res, err);\n    })\n};\n\n// And I've tried this...\nexports.index = function (req, res) {\n  entityModel.findAll({\n      include: [\n        {model: Db.User, as: 'createdBy'},\n        {model: Db.User, as: 'updatedBy'}\n      ]\n    })\n    .then(function (entities) {\n      return res.status(200).json(entities);\n    })\n    .catch(function (err) {\n      return handleError(res, err);\n    })\n};\n\n// And this too...\nexports.index = function (req, res) {\n  entityModel.findAll({\n      include: [\n        {\n          model: Db.User\n        }\n      ]\n    })\n    .then(function (entities) {\n      return res.status(200).json(entities);\n    })\n    .catch(function (err) {\n      return handleError(res, err);\n    })\n};\n```\n\n```text\n[\n  {\n    \"id\": \"e3011e31-b907-47ad-99f3-61016283a523\",\n    \"sampleRate\": 16000,\n    \"format\": \"WAV\",\n    \"channel\": 2,\n    \"bitRate\": 16,\n    \"createdAt\": \"2016-05-01T16:30:11.847Z\",\n    \"updatedAt\": \"2016-05-01T16:30:11.847Z\",\n    \"createdBy\": \"1375263f-a3f0-4eef-800f-99b28fdce9d8\",\n    \"updatedBy\": \"5bb8cac0-b916-4000-81fe-9b1f8f597847\",\n    \"User\": {\n      \"id\": \"5bb8cac0-b916-4000-81fe-9b1f8f597847\",\n      \"email\": \"johnd@email.com\",\n      \"firstName\": \"John\",\n      \"lastName\": \"Doe\",\n      \"resetPasswordToken\": null,\n      \"resetPasswordTokenExpiresOn\": null,\n      \"createdAt\": \"2016-05-01T16:30:11.816Z\",\n      \"updatedAt\": \"2016-05-01T16:30:11.816Z\",\n      \"roleId\": \"10ae3879-9f9f-4370-aa47-3677c492afd8\"\n    }\n  }\n]\n```\n\n```text\nUser\n```\n\n```text\nAudioConfig\n```\n\n```text\nUser\n```\n\n```text\nAudioConfig\n```\n\n```text\nAudioConfig\n```\n\n```text\nUser\n```\n\n```text\ncreatedBy\n```\n\n```text\nupdatedBy\n```\n\n```text\nfindAll\n```\n\n```text\nAudioConfig\n```\n\n```text\nAudioConfig\n```\n\n```text\nUser\n```\n\n```text\ncreatedBy\n```\n\n```text\nupdatedBy\n```\n\n```text\nAudioConfig\n```\n\n```text\nUser\n```\n\n```text\nupdatedBy\n```\n\n```text\ncreatedBy\n```\n\n```text\nUser\n```\n\n```text\nupdatedBy\n```\n\n```text\npopulate\n```\n\n```js\nmodels.User.hasMany(models.AudioConfig, {\n  as: 'createdByUser',\n  foreignKey: {\n    name: 'createdBy',\n    allowNull: false\n  }\n});\nmodels.User.hasMany(models.AudioConfig, {\n  as: 'updatedByUser',\n  foreignKey: {\n    name: 'updatedBy'\n  }\n});\nmodels.AudioConfig.belongsTo(models.User, {\n  as: 'createdByUser',\n  foreignKey: {\n    name: 'createdBy',\n    allowNull: false\n  }\n});\nmodels.AudioConfig.belongsTo(models.User, {\n  as: 'updatedByUser'\n  foreignKey: {\n    name: 'updatedBy'\n  }\n});\n```\n\n========================================\n\nComments:\n- Have you tried defining the 'as' property in the foreign key object on both ends of the relationship? I see you only have it on the belongsTo but not hasMany. In their documentation it is set on both ends.\n- @GrimurD, I tried what you suggested but I got the same result back.\n- Try changing the names in the 'as' so the names dont conflict with the fields on the models. For example createdByUser and updatedByUser\n- Thank you so much! Your solution, along with using `include: {all:true}` in my `findAll` query, did the trick.\n- instead of using `include: {all:true}` in `findAll` you can use `include: {model: models.User, as: 'createdByUser'}`, etc. Be sure to use `as:` in all associations to the same model in your Sequelize model declaration.\n- Isn't this still strange though that you can't decide which associated models to include, it is either one or all?","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":352,"estimatedTokens":1799}}327{"id":"stack-36466395","source":"stackoverflow","questionId":36466395,"title":"Sequelize optional where clause parameters?","tags":["sequelize.js"],"text":"Title: Sequelize optional where clause parameters?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThis is one thing that really annoys me! I have to write 2 different functions for almost the same query!\n\nSay I've got an API that returns `posts` that are associated to a particular `typeId` and `cityId`. To get `ALL` posts that are associated to `typeId 1 OR 2, OR 3` ***and*** `cityId 1` I would parse the following to my sequelize `findAll` query:\n\n```\n$or: [{typeId: 1}, {typeId: 2}, {typeId: 3}]\ncityId: 1\n```\n\nBut say I want to get all post where `cityId = 1 andOr typeId = 1,2,3,4,5,6,7,8,9,10,etc...` I cannot do something like:\n\n```\nvar types = [{typeId: 1}, {typeId: 2}, {typeId: 3}]\nPost.findAll({\n where: {\n if (types != []) $or: types,\n cityId: 1\n }\n```\n\nSo instead I have to make a new query that won't include the `$or: types` where clause...Because if I parse an empty `types` array I get a weird `sql` output:\n\n```\nWHERE 0 = 1 AND `post`.`cityId` = '1'\n```\n\nNotice how it's outputting 0 = 1?! No idea why\n\n========================================\n\nTop Answer:\nYou can do this:\n\n```\nPost.findAll({\n where: {\n cityId: 1,\n ...(types && types.length && {\n types\n })\n }\n```\n\n`types` attr will only be evaluated in the expression if the array has elements.\n\n========================================\n\nCode:\n```text\n$or: [{typeId: 1}, {typeId: 2}, {typeId: 3}]\ncityId: 1\n```\n\n```text\nvar types = [{typeId: 1}, {typeId: 2}, {typeId: 3}]\nPost.findAll({\n     where: {\n          if (types != []) $or: types,\n          cityId: 1\n      }\n```\n\n```text\nWHERE 0 = 1 AND `post`.`cityId` = '1'\n```\n\n```text\nposts\n```\n\n```text\ntypeId\n```\n\n```text\ncityId\n```\n\n```text\nALL\n```\n\n```text\ntypeId 1 OR 2, OR 3\n```\n\n```text\ncityId 1\n```\n\n```text\nfindAll\n```\n\n```text\ncityId = 1 andOr typeId = 1,2,3,4,5,6,7,8,9,10,etc...\n```\n\n```text\n$or: types\n```\n\n```text\ntypes\n```\n\n```text\nsql\n```\n\n```js\n// Get typeIds from whatever source you have\n\n// Here's an example\nvar typeIds = [1, 2, 3];\n\n// Or you could try this to build a query without typeIds\n// var typeIds = [];\n\nvar whereCondition = {};\n\nif (typeIds.length > 0) {\n    whereCondition['$or'] = typeIds.map(function(id) {\n        return {\n            typeId: id\n        };\n    })\n};\n\nwhereCondition['cityId'] = 1;\n\nconsole.log(whereCondition);\n\nPost.findAll(whereCondition).then(function(posts) {\n    // The rest of your logic\n});\n```\n\n```text\nUser.findOne({\nwhere: {\n  [Op.or]: [\n    { email: `${req.body.email || \"\"}` },\n    { username: `${req.body.username || \"\"}` },\n  ],\n},\n```\n\n```text\nPost.findAll({\n     where: {\n          cityId: 1,\n          ...(types && types.length && {\n              types\n          })\n      }\n```\n\n```text\ntypes\n```\n\n```text\nlet name = req.body.name ? { name: req.body.name } : undefined;\nlet gender = req.body.gender ? { gender: req.body.gender } : undefined;\nlet phoneNumber = req.body.phoneNumber ? { phoneNumber: req.body.phoneNumber } : undefined;\n\nlet users = await User.findAll({\n   where: {\n      [Op.and]: [\n         name,\n         gender,\n         phoneNumber\n      ]\n   }\n})\n```\n\n========================================\n\nComments:\n- This is the perfect solution. Can't believe I didn't think of it earlier!\n- the perfect solution is using a where property key with as value undefined, which doesn't work (this is a bug in sequelize)\n- my blog if you want to read extra few sentence : blog","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":189,"estimatedTokens":845}}328{"id":"stack-41556888","source":"stackoverflow","questionId":41556888,"title":"Sequelize in Node/Express - 'no such table: main.User` error","tags":["node.js","express","sqlite","sequelize.js","sequelize-cli"],"text":"Title: Sequelize in Node/Express - 'no such table: main.User` error\nTags: node.js, express, sqlite, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a simple Node/Express app with Sequelize, but when I try to create a new record in my relational database, I am getting the error `Unhandled rejection SequelizeDatabaseError: SQLITE_ERROR: no such table: main.User`. Basically, I create a user in the `Users` table and then try to create a related address in the `Addresses` table - the user is successfully created but it fails with this error when creating the address... where is it getting the `main` prefix from in the table name? (full error readout below)...\n\nFirst off, here's a rundown of my program...\n\nMy Sequelize version is `Sequelize [Node: 6.8.1, CLI: 2.4.0, ORM: 3.29.0]`, and I used the Sequelize CLI command `sequelize init` to set up this portion of my project.\n\nI am using SQLite3 for local development, and in `config/config.json` I have the development db defined as\n\n```\n\"development\": {\n \"storage\": \"dev.sqlite\",\n \"dialect\": \"sqlite\"\n}\n```\n\nMy user migration:\n\n```\n'use strict';\n module.exports = {\n up: function(queryInterface, Sequelize) {\n return queryInterface.createTable('Users', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n first_name: {\n type: Sequelize.STRING\n },\n last_name: {\n type: Sequelize.STRING\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: function(queryInterface, Sequelize) {\n return queryInterface.dropTable('Users');\n }\n };\n```\n\nand the address migration (abbreviated):\n\n```\nmodule.exports = {\n up: function(queryInterface, Sequelize) {\n return queryInterface.createTable('Addresses', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n address_line_one: {\n type: Sequelize.STRING\n },\n UserId: {\n type: Sequelize.INTEGER,\n allowNull: false,\n references: {\n model: \"User\",\n key: \"id\"\n }\n }\n })\n }\n```\n\nThe user model:\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define('User', {\n first_name: DataTypes.STRING,\n last_name: DataTypes.STRING\n }, {\n classMethods: {\n associate: function(models) {\n models.User.hasOne(models.Address);\n }\n }\n });\nreturn User;\n};\n```\n\nand the address model:\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var Address = sequelize.define('Address', {\n address_line_one: DataTypes.STRING,\n UserId: DataTypes.INTEGER\n }, {\n classMethods: {\n associate: function(models) {\n models.Address.hasOne(models.Geometry);\n models.Address.belongsTo(models.User, {\n onDelete: \"CASCADE\",\n foreignKey: {\n allowNull: false\n }\n });\n }\n }\n });\n return Address;\n };\n```\n\nfinally, my route `index.js`:\n\n```\nrouter.post('/createUser', function(req, res){\n var firstName = req.body.first_name;\n var lastName = req.body.last_name;\n var addressLineOne = req.body.address_line_one;\n\n models.User.create({\n 'first_name': newUser.firstName,\n 'last_name': newUser.lastName\n }).then(function(user){ \n return user.createAddress({\n 'address_line_one': newUser.addressLineOne\n })\n})\n```\n\nSo when I try to post to `/createUser`, the User will successfully be created and the console will say that a new Address has been created (`INSERT INTO 'Addresses'...`), but the address is NOT created and the following error is logged:\n\n`Unhandled rejection SequelizeDatabaseError: SQLITE_ERROR: no such table: main.User\n at Query.formatError (/Users/darrenklein/Desktop/Darren/NYCDA/WDI/projects/world_table/wt_test_app_1/node_modules/sequelize/lib/dialects/sqlite/query.js:348:14)\n at afterExecute (/Users/darrenklein/Desktop/Darren/NYCDA/WDI/projects/world_table/wt_test_app_1/node_modules/sequelize/lib/dialects/sqlite/query.js:112:29)\n at Statement.errBack (/Users/darrenklein/Desktop/Darren/NYCDA/WDI/projects/world_table/wt_test_app_1/node_modules/sqlite3/lib/sqlite3.js:16:21)`\n\nI've done this sort of thing with Sequelize once before a few months ago and it was successful, I cannot for the life of me figure out what I'm missing here. Why is the app looking for `main.User`, and how can I get it to look for the correct table? Thank you!\n\n========================================\n\nTop Answer:\nThe same thing happens to me.\n\nIn my development and production database, I use MySQL; it seems to be that for MySQL you can use `references.model` and `references.id` the name of the model and the field in the model.\n\nLocally I started to use SQLite for testing, and that doesn't work. It requires for you to indicate the table name and field exactly as it is in the referenced table.\n\n========================================\n\nCode:\n```text\n\"development\": {\n    \"storage\": \"dev.sqlite\",\n    \"dialect\": \"sqlite\"\n}\n```\n\n```text\n'use strict';\n    module.exports = {\n        up: function(queryInterface, Sequelize) {\n            return queryInterface.createTable('Users', {\n                id: {\n                    allowNull: false,\n                    autoIncrement: true,\n                    primaryKey: true,\n                    type: Sequelize.INTEGER\n                },\n                first_name: {\n                    type: Sequelize.STRING\n                },\n                last_name: {\n                    type: Sequelize.STRING\n                },\n                createdAt: {\n                    allowNull: false,\n                    type: Sequelize.DATE\n                },\n                updatedAt: {\n                    allowNull: false,\n                    type: Sequelize.DATE\n                }\n            });\n        },\n        down: function(queryInterface, Sequelize) {\n            return queryInterface.dropTable('Users');\n        }\n    };\n```\n\n```text\nmodule.exports = {\n    up: function(queryInterface, Sequelize) {\n        return queryInterface.createTable('Addresses', {\n            id: {\n                allowNull: false,\n                autoIncrement: true,\n                primaryKey: true,\n                type: Sequelize.INTEGER\n            },\n            address_line_one: {\n                type: Sequelize.STRING\n            },\n            UserId: {\n                type: Sequelize.INTEGER,\n                allowNull: false,\n                references: {\n                    model: \"User\",\n                    key: \"id\"\n                }\n            }\n        })\n    }\n```\n\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n    var User = sequelize.define('User', {\n        first_name: DataTypes.STRING,\n        last_name: DataTypes.STRING\n    }, {\n   classMethods: {\n       associate: function(models) {\n           models.User.hasOne(models.Address);\n       }\n    }\n });\nreturn User;\n};\n```\n\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n    var Address = sequelize.define('Address', {\n        address_line_one: DataTypes.STRING,\n        UserId: DataTypes.INTEGER\n    }, {\n        classMethods: {\n            associate: function(models) {\n                models.Address.hasOne(models.Geometry);\n                models.Address.belongsTo(models.User, {\n                    onDelete: \"CASCADE\",\n                    foreignKey: {\n                        allowNull: false\n                    }\n                });\n            }\n          }\n      });\n return Address;\n };\n```\n\n```text\nrouter.post('/createUser', function(req, res){\n    var firstName = req.body.first_name;\n    var lastName = req.body.last_name;\n    var addressLineOne = req.body.address_line_one;\n\n    models.User.create({\n        'first_name': newUser.firstName,\n        'last_name': newUser.lastName\n    }).then(function(user){         \n        return user.createAddress({\n            'address_line_one': newUser.addressLineOne\n    })\n})\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: SQLITE_ERROR: no such table: main.User\n```\n\n```text\nUsers\n```\n\n```text\nAddresses\n```\n\n```text\nmain\n```\n\n```text\nSequelize [Node: 6.8.1, CLI: 2.4.0, ORM: 3.29.0]\n```\n\n```text\nsequelize init\n```\n\n```text\nconfig/config.json\n```\n\n```text\nindex.js\n```\n\n```text\n/createUser\n```\n\n```text\nINSERT INTO 'Addresses'...\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: SQLITE_ERROR: no such table: main.User\n    at Query.formatError (/Users/darrenklein/Desktop/Darren/NYCDA/WDI/projects/world_table/wt_test_app_1/node_modules/sequelize/lib/dialects/sqlite/query.js:348:14)\n    at afterExecute (/Users/darrenklein/Desktop/Darren/NYCDA/WDI/projects/world_table/wt_test_app_1/node_modules/sequelize/lib/dialects/sqlite/query.js:112:29)\n    at Statement.errBack (/Users/darrenklein/Desktop/Darren/NYCDA/WDI/projects/world_table/wt_test_app_1/node_modules/sqlite3/lib/sqlite3.js:16:21)\n```\n\n```text\nmain.User\n```\n\n```text\nreferences: {\n    model: \"Users\",\n    key: \"id\"\n}\n```\n\n```text\nreferences.model\n```\n\n```text\nreferences.model\n```\n\n```text\nreferences.id\n```\n\n```text\ninAppNotificationId: {\n        allowNull: false,\n        type: DataTypes.UUID,\n        references: {\n          model: 'InAppNotifications',\n          key: 'id',\n        },\n        onUpdate: 'CASCADE',\n        onDelete: 'CASCADE',\n      }\n```\n\n```text\ninAppNotificationId: {\n        allowNull: false,\n        type: DataTypes.UUID,\n        references: {\n          model: 'in_app_notifications',\n          key: 'id',\n        },\n        onUpdate: 'CASCADE',\n        onDelete: 'CASCADE',\n      }\n```\n\n```text\nUsers\n```\n\n========================================\n\nComments:\n- if you dont want to worry about pluralization, you can add the option: 'freezeTableName: true' to your table\n- @R.Gulbrandsen That is awesome!","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":391,"estimatedTokens":2409}}329{"id":"stack-28737194","source":"stackoverflow","questionId":28737194,"title":"How to use of AND and OR operator in same query in sequelize?","tags":["mysql","node.js","sequelize.js"],"text":"Title: How to use of AND and OR operator in same query in sequelize?\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI execute the below query but i gives error. I want the result of my SQL query which i posted at end.\n\n```\nuserServiceAppointmentModel.findAll({\n where: {\n technician_id: resultsFromAuthentication.technician_id,\n is_confirmed_by_user: 1,\n $or: {\n service_start_time: {\n gte: curLocalDate\n },\n service_running_status: 1\n }\n },\n attributes: attributes\n }).complete(function (err, appointmentResponse) {\n if (err) {\n console.log(err);\n }\n\nSELECT\n `id`, `technician_id`, `user_id`, `service_id`, `service_name`,\n `service_location_string`, `service_location_latitude`,\n `service_location_longitude`, `service_start_time`, `service_end_time`,\n `notes`, `total_cost`, `service_cost`, `is_confirmed_by_user`,\n `is_confirmed_by_technician`, `service_running_status`,\n `service_start_time_by_technician`,`service_complete_time_by_technician`\nFROM `user_service_appointment` AS `user_service_appointment`\nWHERE `user_service_appointment`.`technician_id`=154\nAND `user_service_appointment`.`is_confirmed_by_user`=1\nAND (`user_service_appointment`.`service_start_time` >='2015-02-26 01:07'\n OR `user_service_appointment`.`service_running_status`=1)\n```\n\n========================================\n\nTop Answer:\n**in new version try like this**\n\n```\nmodel.update(\n req.body,\n {\n\n where: { task_id: req.params.task_id,\n $and: {id: 11}\n $gt: {end_date: myDate}\n } }\n )\n .then(function () {\n res.status(200).json({\"message\":\"done\"})\n }\n )\n .catch(function (err) {\n\n })\n```\n\nFor more detail see the Documentation\n\nHere i want to mention some of them\n\n```\n$and: {a: 5} // AND (a = 5)\n$or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)\n$gt: 6, // > 6\n$gte: 6, // >= 6\n$lt: 10, // [1, 2] (PG array contains operator)\n$contained: [1, 2] // <@ [1, 2] (PG array contained by operator)\n$any: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only)\n```\n\n========================================\n\nCode:\n```text\nuserServiceAppointmentModel.findAll({\n        where: {\n            technician_id: resultsFromAuthentication.technician_id,\n            is_confirmed_by_user: 1,\n            $or: {\n                service_start_time: {\n                    gte: curLocalDate\n                },\n                service_running_status: 1\n            }\n    },\n        attributes: attributes\n    }).complete(function (err, appointmentResponse) {\n        if (err) {\n            console.log(err);\n        }\n\n\nSELECT\n    `id`, `technician_id`, `user_id`, `service_id`, `service_name`,\n    `service_location_string`, `service_location_latitude`,\n    `service_location_longitude`, `service_start_time`, `service_end_time`,\n    `notes`, `total_cost`, `service_cost`, `is_confirmed_by_user`,\n    `is_confirmed_by_technician`, `service_running_status`,\n    `service_start_time_by_technician`,`service_complete_time_by_technician`\nFROM `user_service_appointment` AS `user_service_appointment`\nWHERE `user_service_appointment`.`technician_id`=154\nAND `user_service_appointment`.`is_confirmed_by_user`=1\nAND (`user_service_appointment`.`service_start_time` >='2015-02-26 01:07'\n    OR `user_service_appointment`.`service_running_status`=1)\n```\n\n```text\n..\n where: {where: Sequelize.and(\n    {technician_id: resultsFromAuthentication.technician_id},\n    {is_confirmed_by_user: 1},\n    Sequelize.or({\n            service_start_time: {\n                gte: curLocalDate\n            }},\n        {service_running_status: 1}\n    )\n)\n..\n```\n\n```text\nuserServiceAppointmentModel.findAll({where: Sequelize.and(\n            {technician_id: resultsFromAuthentication.technician_id},\n            {is_confirmed_by_user: 1},\n            Sequelize.or({\n                    service_start_time: {\n                        gte: curLocalDate\n                    }},\n                {service_running_status: 1}\n            )\n\n    )\n}).complete(function (err, appointmentResponse) {\n```\n\n```text\nmodel.update(\n                req.body,\n                {\n\n                    where: { task_id: req.params.task_id,\n                        $and: {id: 11}\n                        $gt: {end_date: myDate}\n                    } }\n            )\n                .then(function () {\n                res.status(200).json({\"message\":\"done\"})\n                }\n    )\n    .catch(function (err) {\n\n        })\n```\n\n```text\n$and: {a: 5}           // AND (a = 5)\n$or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)\n$gt: 6,                // > 6\n$gte: 6,               // >= 6\n$lt: 10,               // < 10\n$lte: 10,              // <= 10\n$ne: 20,               // != 20\n$eq: 3,                // = 3\n$not: true,            // IS NOT TRUE\n$between: [6, 10],     // BETWEEN 6 AND 10\n$notBetween: [11, 15], // NOT BETWEEN 11 AND 15\n$in: [1, 2],           // IN [1, 2]\n$notIn: [1, 2],        // NOT IN [1, 2]\n$like: '%hat',         // LIKE '%hat'\n$notLike: '%hat'       // NOT LIKE '%hat'\n$iLike: '%hat'         // ILIKE '%hat' (case insensitive) (PG only)\n$notILike: '%hat'      // NOT ILIKE '%hat'  (PG only)\n$like: { $any: ['cat', 'hat']}       // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike\n$overlap: [1, 2]       // && [1, 2] (PG array overlap operator)\n$contains: [1, 2]      // @> [1, 2] (PG array contains operator)\n$contained: [1, 2]     // <@ [1, 2] (PG array contained by operator)\n$any: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)\n```\n\n========================================\n\nComments:\n- Post the error, please\n- { [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`gte` = '2015-02-26 01:07' AND `user_service_appointment`.`$or` 1' at line 1] [app-4 (out)] code: 'ER_PARSE_ERROR', [app-4 (out)] errno: 1064, [app-4 (out)] sqlState: '42000', [app-4 (out)] index: 0, [app-4 (out)]\n- WHERE `user_service_appointment`.`technician_id`=154 AND `user_service_appointment`.`is_confirmed_by_user`=1 AND `user_service_appointment`.`$or` `gte` = \\'2015-02-26 01:07\\' AND `user_service_appointment`.`$or` 1;' }, I think the problem in Where condition synatx\n- Check representation of datetime field.\n- Joe all are working fine. The problem is i am unable to find the code to implement and or operator both in same query. If you see above the Where condition is not correct the $or operator is not correct. It should be (`user_service_appointment`.`service_start_time` >='2015-02-26 01:07' OR `user_service_appointment`.`service_running_status`=1)\n- I think the exact error here indicates the problem. On line 7, you have `gte` and it should be `$gte`. If you look at the error exactly, it always begins where the problem occurred, `gte = ...` It was taking `gte` as a string instead of the `>=` operator.\n- Sorry didn't really tested. I edited the answer, but you probably need a Sequelize.and first.\n- Yes i did but the issue is still there.\n- Thanks a lot i resolved the syntax mistake. Really appreciate your work.\n- @Gurpinder you could have mentioned what syntax mistake it was that you were making\n- for or inside and? for eg: AND (a = 5 OR a=6) how to write?","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":201,"estimatedTokens":1780}}330{"id":"stack-59639791","source":"stackoverflow","questionId":59639791,"title":"Sequelize - How to list/view all columns of existing model","tags":["javascript","mysql","sequelize.js"],"text":"Title: Sequelize - How to list/view all columns of existing model\nTags: javascript, mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI know a simple answer could be query table with all attributes returned.\n\nHowever, since the models are defined in code, I want to know is it possible to get the result without querying database? \nOr, if query is necessary, which query is the optimised one?\n\nBtw, I am using **Sequelize V5** and **Mysql 5.7**.\n\n========================================\n\nTop Answer:\nYou can also use this as an answer:\n\n```\nfor( let key of Object.keys(models.Modelname.attributes)) {\n columns.push({\n name:key,\n type:models.Modelname.attributes[key].type.key\n });\n}\n```\n\n========================================\n\nCode:\n```text\nfor( let key in Model.rawAttributes ){\n    console.log('Field Name: ', key); // this is name of the field\n    console.log('Field Type: ', Model.rawAttributes[key].type.key); // Sequelize type of field\n}\n```\n\n```text\nrawAttributes\n```\n\n```text\nrawAttributes\n```\n\n```text\nrawAttributes\n```\n\n```text\ninit/define\n```\n\n```text\ntype\n```\n\n```text\nallowNull\n```\n\n```text\ndefaultValue\n```\n\n```text\nunique\n```\n\n```text\nrawAttributes\n```\n\n```text\nModel\n```\n\n```text\nModel.hasOne()\n```\n\n```text\nModel.belongsTo()\n```\n\n```text\nModel.associate()\n```\n\n```text\nModel.attributes===Model.rawAttributes\n```\n\n```text\nModel.getAttributes()\n```\n\n```text\nfor( let key of Object.keys(models.Modelname.attributes))   {\n      columns.push({\n          name:key,\n          type:models.Modelname.attributes[key].type.key\n      });\n}\n```\n\n========================================\n\nComments:\n- Thanks. Is the \"rawAttributes\" explained in official documents? It will hard to figure it out without documentation.\n- yeap, the documentation of sequelize isn&#180;t that good but checking how are the files are generated you can figureout, and with some research\n- This would be an expensive operation, re-calculating `Object.keys` in each iteration of the loop.","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":111,"estimatedTokens":494}}331{"id":"stack-54756410","source":"stackoverflow","questionId":54756410,"title":"Sequelize CLI : cannot read property 'replace' of undefined when migrating DB","tags":["node.js","foreign-keys","sequelize.js","associations","sequelize-cli"],"text":"Title: Sequelize CLI : cannot read property 'replace' of undefined when migrating DB\nTags: node.js, foreign-keys, sequelize.js, associations, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am trying to migrate DB using `db:migrate` function, however I am getting the error printed:\n\n ERROR: Cannot read property 'replace' of undefined\n\nI have referred to other solutions for this error on GitHub but none resolve the issue. I am using sequelize-cli to perform migration.\n\nhere is my model:\n\n```\n'use strict';\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Containers', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n name: {\n type: Sequelize.STRING\n },\n userId: {\n type: Sequelize.INTEGER,\n references: \"Users\",\n refereceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\",\n },\n type: {\n type: Sequelize.STRING\n },\n detail: {\n type: Sequelize.INTEGER\n },\n checkin: {\n type: Sequelize.DATE\n },\n checkout: {\n type: Sequelize.DATE\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Containers');\n }\n};\n```\n\nI have tried to execute other models by deleting this and nothing seems to work. Please help me here!\n\n**UPDATE**\n\nI have figured out that this is caused due to relations that I am trying to add, so I moved all the relations for all the posts in one separate migration:\n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return [\n queryInterface.addColumn(\"Containers\", \"userId\", {\n type: Sequelize.INTEGER,\n references: \"Users\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n\n queryInterface.addColumn(\"Containers\", \"parentContainer\", {\n type: Sequelize.INTEGER,\n references: \"Containers\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n\n queryInterface.addColumn(\"Entities\", \"containerId\", {\n type: Sequelize.INTEGER,\n references: \"Containers\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\",\n }),\n\n queryInterface.addColumn(\"Posts\", \"userId\", {\n type: Sequelize.INTEGER,\n references: \"Users\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n\n queryInterface.addColumn(\"Posts\", \"containerId\", {\n type: Sequelize.INTEGER,\n references: \"Containers\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\",\n nullable: true\n }),\n\n queryInterface.addColumn(\"Votes\", \"userId\", {\n type: Sequelize.INTEGER,\n references: \"Users\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n\n queryInterface.addColumn(\"Votes\", \"postId\", {\n type: Sequelize.INTEGER,\n references: \"Posts\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n\n queryInterface.addColumn(\"Comments\", \"userId\", {\n type: Sequelize.INTEGER,\n references: \"Users\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n\n queryInterface.addColumn(\"Comments\", \"postId\", {\n type: Sequelize.INTEGER,\n references: \"Posts\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n\n queryInterface.addColumn(\"Comments\", \"commentId\", {\n type: Sequelize.INTEGER,\n references: \"Comments\",\n referenceKey: \"id\",\n onUpdate: \"cascade\",\n onDelete: \"cascade\"\n }),\n ]\n },\n\n down: (queryInterface, Sequelize) => {\n\n }\n};\n```\n\nNow, all the tables are created BUT, the error persists for this migration.\n\n========================================\n\nTop Answer:\nFor me it was coming from my environment variables not being loaded while doing `npx sequelize-cli db:create`. When I managed to load it (with dot-env loading in my config.js file + dot-env cli to be sure) it worked fine.\n\nIf you use an IDE, you can climb to the definition that is being undefined. Or just check the slack trace.\n\nTo me, it was that line :\n\n```\nat getCreateDatabaseQuery (D:\\Code\\restaurant_project\\website_engine\\back_end\\node_modules\\sequelize-cli\\lib\\commands\\database.js:82:64)\n```\n\nLeading to that line in the script (ctrl+click on the slack trace to go to the file)\n\n```\nreturn 'CREATE DATABASE IF NOT EXISTS ' + queryGenerator.quoteIdentifier(config.database)\n```\n\n`config.database` wasn't defineds, hence the error.\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('Containers', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      name: {\n        type: Sequelize.STRING\n      },\n      userId: {\n          type: Sequelize.INTEGER,\n          references: \"Users\",\n          refereceKey: \"id\",\n          onUpdate: \"cascade\",\n          onDelete: \"cascade\",\n      },\n      type: {\n        type: Sequelize.STRING\n      },\n      detail: {\n        type: Sequelize.INTEGER\n      },\n      checkin: {\n        type: Sequelize.DATE\n      },\n      checkout: {\n        type: Sequelize.DATE\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable('Containers');\n  }\n};\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return [\n        queryInterface.addColumn(\"Containers\", \"userId\", {\n            type: Sequelize.INTEGER,\n            references: \"Users\",\n            referenceKey: \"id\",\n            onUpdate: \"cascade\",\n            onDelete: \"cascade\"\n        }),\n\n        queryInterface.addColumn(\"Containers\", \"parentContainer\", {\n            type: Sequelize.INTEGER,\n            references: \"Containers\",\n            referenceKey: \"id\",\n            onUpdate: \"cascade\",\n            onDelete: \"cascade\"\n        }),\n\n        queryInterface.addColumn(\"Entities\", \"containerId\", {\n              type: Sequelize.INTEGER,\n              references: \"Containers\",\n              referenceKey: \"id\",\n              onUpdate: \"cascade\",\n              onDelete: \"cascade\",\n        }),\n\n        queryInterface.addColumn(\"Posts\", \"userId\", {\n                type: Sequelize.INTEGER,\n                references: \"Users\",\n                referenceKey: \"id\",\n                onUpdate: \"cascade\",\n                onDelete: \"cascade\"\n        }),\n\n        queryInterface.addColumn(\"Posts\", \"containerId\", {\n              type: Sequelize.INTEGER,\n              references: \"Containers\",\n              referenceKey: \"id\",\n              onUpdate: \"cascade\",\n              onDelete: \"cascade\",\n              nullable: true\n        }),\n\n        queryInterface.addColumn(\"Votes\", \"userId\", {\n                type: Sequelize.INTEGER,\n                references: \"Users\",\n                referenceKey: \"id\",\n                onUpdate: \"cascade\",\n                onDelete: \"cascade\"\n        }),\n\n        queryInterface.addColumn(\"Votes\", \"postId\", {\n                type: Sequelize.INTEGER,\n                references: \"Posts\",\n                referenceKey: \"id\",\n                onUpdate: \"cascade\",\n                onDelete: \"cascade\"\n        }),\n\n        queryInterface.addColumn(\"Comments\", \"userId\", {\n                type: Sequelize.INTEGER,\n                references: \"Users\",\n                referenceKey: \"id\",\n                onUpdate: \"cascade\",\n                onDelete: \"cascade\"\n        }),\n\n        queryInterface.addColumn(\"Comments\", \"postId\", {\n                type: Sequelize.INTEGER,\n                references: \"Posts\",\n                referenceKey: \"id\",\n                onUpdate: \"cascade\",\n                onDelete: \"cascade\"\n        }),\n\n        queryInterface.addColumn(\"Comments\", \"commentId\", {\n                type: Sequelize.INTEGER,\n                references: \"Comments\",\n                referenceKey: \"id\",\n                onUpdate: \"cascade\",\n                onDelete: \"cascade\"\n        }),\n    ]\n  },\n\n  down: (queryInterface, Sequelize) => {\n\n  }\n};\n```\n\n```text\ndb:migrate\n```\n\n```text\n...\n\nreferences: TABLE_NAME,\nreferenceKey: COLUMN_NAME\n\n...\n```\n\n```text\n...\n\nreferences: {\n model: TABLE_NAME,\n key: COLUMN_NAME\n\n...\n```\n\n```text\nat getCreateDatabaseQuery (D:\\Code\\restaurant_project\\website_engine\\back_end\\node_modules\\sequelize-cli\\lib\\commands\\database.js:82:64)\n```\n\n```text\nreturn 'CREATE DATABASE IF NOT EXISTS ' + queryGenerator.quoteIdentifier(config.database)\n```\n\n```text\nnpx sequelize-cli db:create\n```\n\n```text\nconfig.database\n```\n\n```bash\nnode --env-file=.env ./node_modules/sequelize-cli/lib/sequelize db:create\n```\n\n```json\n\"scripts\": {\n  \"db:create\": \"node --env-file=.env ./node_modules/sequelize-cli/lib/sequelize db:create\",\n  \"db:migrate\": \"node --env-file=.env ./node_modules/sequelize-cli/lib/sequelize db:migrate\",\n  \"db:seed\": \"node --env-file=.env ./node_modules/sequelize-cli/lib/sequelize db:seed:all\"\n}\n```\n\n```bash\nnpm run db:create\nnpm run db:migrate\nnpm run db:seed\n```\n\n```text\nCannot read properties of undefined (reading 'replace')\n```\n\n```text\nsequelize-cli db:create\n```\n\n```text\n.env\n```\n\n```text\nnpx sequelize-cli ...\n```\n\n```text\nprocess.env.DB_NAME\n```\n\n```text\nundefined\n```\n\n```text\ngetCreateDatabaseQuery()\n```\n\n```text\ndotenv\n```\n\n```text\nnpx\n```\n\n```text\npackage.json\n```\n\n```text\n.env\n```\n\n```text\nDB_NAME\n```\n\n```text\nDB_USER\n```\n\n```text\nreplace\n```\n\n========================================\n\nComments:\n- And do not confuse `references.model` with `references.table` from `queryInterface.addConstraint`. table option doesn't work with `queryInterface.createTable` and `queryInterface.addColumn` in Sequelize 6","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":450,"estimatedTokens":2419}}332{"id":"stack-49659475","source":"stackoverflow","questionId":49659475,"title":"How to use MySQL JSON datatype with Sequelize","tags":["sequelize.js","mysql-5.7"],"text":"Title: How to use MySQL JSON datatype with Sequelize\nTags: sequelize.js, mysql-5.7\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use MySQL 5.7 with Sequelize, and I want to use the JSON datatype for the `attributes` field on my `users` table to keep track of user attributes such as home_phone, mobile_phone, work_phone, address and several other attributes/settings that every user may or may not have.\n\nI've been able to locate the documentation for performing selects here: http://docs.sequelizejs.com/manual/tutorial/querying.html#json.\n\nI'm struggling to find documentation on how I would perform create, update and delete.\n\nI guess I could always just do a raw query, but is there a sequelize way to do this?\n\n**Update 1**\n\nI'm specifically looking for how to perform a query like this in sequelize:\n\n```\nupdate Users \nset user_attributes = JSON_SET(user_attributes, \"$.phone\", \"5554443333\") \nwhere id=7;\n```\n\n========================================\n\nCode:\n```text\nupdate Users \nset user_attributes = JSON_SET(user_attributes, \"$.phone\", \"5554443333\") \nwhere id=7;\n```\n\n```text\nattributes\n```\n\n```text\nusers\n```\n\n```text\nUser.update({\n  user_attributes: Sequelize.fn(\"JSON_SET\", Sequelize.col('user_attributes'), \"$.phone\", \"5554443333\")\n}, {\n  where: {id: 7}\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":319}}333{"id":"stack-38638619","source":"stackoverflow","questionId":38638619,"title":"MySql - Sequalize - Cannot add foreign key constraint","tags":["mysql","sql","database","sequelize.js"],"text":"Title: MySql - Sequalize - Cannot add foreign key constraint\nTags: mysql, sql, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to using Nodejs sequelize to create database. The commands being invoked are\n\n```\nCREATE TABLE IF NOT EXISTS `wheel` (`id` INTEGER NOT NULL auto_increment , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `shopId` VARCHAR(255), PRIMARY KEY (`id`), \nFOREIGN KEY (`shopId`) REFERENCES `shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\n\nCREATE TABLE IF NOT EXISTS `segments` (`segmentID` VARCHAR(255) NOT NULL , `heading` VARCHAR(255) NOT NULL, `subHeading` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `wheelId` INTEGER, PRIMARY KEY (`segmentID`),\n FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\n\nCREATE TABLE IF NOT EXISTS `shop` (`id` VARCHAR(255) NOT NULL , `accessToken` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\n```\n\nBut I get this error \n\n Unhandled rejection SequelizeDatabaseError: ER_CANNOT_ADD_FOREIGN:\n Cannot add foreign key constraint\n\nWhen I try to see the last foreign key error , it says \n\n```\n------------------------\nLATEST FOREIGN KEY ERROR\n------------------------\n2016-07-28 19:23:21 0x700000d95000 Error in foreign key constraint of table exitpopup/segments:\nFOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB:\nCannot resolve table name close to:\n (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB\n```\n\nStrangely, When I put the sql statements in sql console , it works and there isn't any error.\nWhat am I doing wrong ?\n\n========================================\n\nTop Answer:\nIf you need to turn off this check, because you're importing a bunch of tables from a dump from another DB, you want to run:\n\n```\nset FOREIGN_KEY_CHECKS=0\n```\n\nAs if it was a SQL statement. So for me in Sequelize I ran:\n\n```\nlet promise = sequelize.query(\"set FOREIGN_KEY_CHECKS=0\");\n```\n\n========================================\n\nCode:\n```text\nCREATE TABLE IF NOT EXISTS `wheel` (`id` INTEGER NOT NULL auto_increment , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `shopId` VARCHAR(255), PRIMARY KEY (`id`), \nFOREIGN KEY (`shopId`) REFERENCES `shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\n\nCREATE TABLE IF NOT EXISTS `segments` (`segmentID` VARCHAR(255) NOT NULL , `heading` VARCHAR(255) NOT NULL, `subHeading` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `wheelId` INTEGER, PRIMARY KEY (`segmentID`),\n FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\n\nCREATE TABLE IF NOT EXISTS `shop` (`id` VARCHAR(255) NOT NULL , `accessToken` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\n```\n\n```text\n------------------------\nLATEST FOREIGN KEY ERROR\n------------------------\n2016-07-28 19:23:21 0x700000d95000 Error in foreign key constraint of table exitpopup/segments:\nFOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB:\nCannot resolve table name close to:\n (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB\n```\n\n```text\nCREATE TABLE IF NOT EXISTS `shop` \n (`id` VARCHAR(255) NOT NULL , `accessToken` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, \n PRIMARY KEY (`id`)) ENGINE=InnoDB;\n\n\nCREATE TABLE IF NOT EXISTS `wheel` \n(`id` INTEGER NOT NULL auto_increment , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `shopId` VARCHAR(255), \n PRIMARY KEY (`id`), \n FOREIGN KEY (`shopId`) REFERENCES `shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\n\nCREATE TABLE IF NOT EXISTS `segments` \n(`segmentID` VARCHAR(255) NOT NULL , `heading` VARCHAR(255) NOT NULL, `subHeading` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `wheelId` INTEGER, \n PRIMARY KEY (`segmentID`),\n FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\n```\n\n```text\nwheel\n```\n\n```text\nshop\n```\n\n```text\nset FOREIGN_KEY_CHECKS=0\n```\n\n```text\nlet promise = sequelize.query(\"set FOREIGN_KEY_CHECKS=0\");\n```\n\n```text\nreturn sequelize.define('Manager', {\n    id: {\n      type: DataTypes.INTEGER(11), // The data type defined here and \n      references: {\n        model: 'User',\n        key: 'id'\n      }\n    }\n  }\n)\n\nreturn sequelize.define('User', {\n    id: {\n      type: DataTypes.INTEGER(11),  // This data type should be the same\n    }\n  }\n)\n```\n\n```text\nreturn sequelize.define('User', {\n        id: {\n          primaryKey: true  \n        },\n        mail: {\n            type: DataTypes.STRING(45),\n            allowNull: false,\n            primaryKey: true   // You should change this to 'unique:true'. you cant have two primary keys in one table. \n        }\n    }\n)\n```\n\n```text\nclass Team extends Model {\n  static associate({ Player }) {\n  this.hasMany(Player, { foreignKey: 'playerId', onDelete: 'CASCADE' });\n  }\n}\n\nclass Player extends Model {\n  static associate({ Team }) {\n  this.belongsTo(Team, {foreignKey: 'playerId', onDelete: 'CASCADE', targetKey: 'id',\n  });\n }\n}\n```\n\n```text\nonDelete: 'CASCADE'\n```\n\n========================================\n\nComments:\n- This should be fixed by Sequlize because I am using database sync.\n- where did u add this?\n- @MendonAshwini Just before creating the tables.","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":167,"estimatedTokens":1399}}334{"id":"stack-41258500","source":"stackoverflow","questionId":41258500,"title":"How to create mysql database with sequelize (nodejs)","tags":["mysql","database","sequelize.js","database-create"],"text":"Title: How to create mysql database with sequelize (nodejs)\nTags: mysql, database, sequelize.js, database-create\nSource: Stack Overflow\n\nQuestion:\nI am trying to automate the process of creating db and tables as much as possible. Is it possible to create database via sequelize? Can I make a connection string that connects just to server, not to db directly?\n\n========================================\n\nTop Answer:\nHere are main steps to populate mySql tables with sequelize and sequelize-fixtures modules:\n\nstep 1: creating model\n\n```\nmodule.exports = function(sequelize, Sequelize) {\n// Sequelize user model is initialized earlier as User\nconst User = sequelize.define('user', {\n id : { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },\n firstname : { type: Sequelize.STRING },\n lastname : { type: Sequelize.STRING },\n email : { type: Sequelize.STRING, validate: {isEmail:true} },\n password : { type: Sequelize.STRING }, \n});\n\n// User.drop();\nreturn User;\n}\n```\n\nStep 2: creating a config file to store database configs\n\n```\n{\n \"development\": {\n\n \"username\": \"root\",\n \"password\": null,\n \"database\": \"hotsausemedia\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"mysql\"\n },\n \"test\": { \n \"username\": \"\",\n \"password\": null,\n \"database\": \"hotsausemedia\",\n \"host\": \"\",\n \"dialect\": \"mysql\"\n },\n \"production\": {\n \"username\": \"\",\n \"password\": null,\n \"database\": \"hotsausemedia\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"mysql\"\n }\n}\n```\n\nstep 3: creating sequelize-fixture to populate tables. here is an example of a json file to use for populating data\n\n```\n[\n {\n \"model\": \"product\",\n \"keys\": [\"id\"],\n \"data\": {\n \"id\": 1,\n \"name\": \"Product #1\",\n \"src\": \"./assets/img/products/01.jpg\",\n \"price\": 9.99,\n \"desc\": \"Product description...\"\n }\n },\n {\n \"model\": \"product\",\n \"keys\": [\"id\"],\n \"data\": {\n \"id\": 2,\n \"name\": \"Product #2\",\n \"src\": \"./assets/img/products/02.jpg\",\n \"price\": 19.99,\n \"desc\": \"Product description...\"\n }\n },\n ...\n\n]\n```\n\nstep 4: connecting to database and populating tables\n\n```\nmodels.sequelize.sync().then(() => {\n console.log('You are connected to the database successfully.');\n sequelize_fixtures.loadFile('./fixtures/*.json', models).then(() =>{\n console.log(\"database is updated!\");\n });\n }).catch((err) => {\n console.log(err,\"Some problems with database connection!!!\");\n});\n```\n\n========================================\n\nCode:\n```text\n//create the sequelize instance, omitting the database-name arg\nconst sequelize = new Sequelize(\"\", \"<db_user>\", \"<db_password>\", {\n  dialect: \"<dialect>\"\n});\n\nreturn sequelize.query(\"CREATE DATABASE `<database_name>`;\").then(data \n=> {\n  // code to run after successful creation.\n});\n```\n\n```text\nmodule.exports = function(sequelize, Sequelize) {\n// Sequelize user model is initialized earlier as User\nconst User = sequelize.define('user', {\n    id          :       { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },\n    firstname   :       { type: Sequelize.STRING },\n    lastname    :       { type: Sequelize.STRING },\n    email       :       { type: Sequelize.STRING, validate: {isEmail:true} },\n    password    :       { type: Sequelize.STRING }, \n});\n\n// User.drop();\nreturn User;\n}\n```\n\n```text\n{\n  \"development\": {\n\n    \"username\": \"root\",\n    \"password\": null,\n    \"database\": \"hotsausemedia\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\"\n  },\n  \"test\": { \n    \"username\": \"\",\n    \"password\": null,\n    \"database\": \"hotsausemedia\",\n    \"host\": \"\",\n    \"dialect\": \"mysql\"\n  },\n  \"production\": {\n    \"username\": \"\",\n    \"password\": null,\n    \"database\": \"hotsausemedia\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\"\n  }\n}\n```\n\n```text\n[\n    {\n        \"model\": \"product\",\n        \"keys\": [\"id\"],\n        \"data\": {\n            \"id\": 1,\n            \"name\": \"Product #1\",\n            \"src\": \"./assets/img/products/01.jpg\",\n            \"price\": 9.99,\n            \"desc\": \"Product description...\"\n        }\n    },\n    {\n        \"model\": \"product\",\n        \"keys\": [\"id\"],\n        \"data\": {\n            \"id\": 2,\n            \"name\": \"Product #2\",\n            \"src\": \"./assets/img/products/02.jpg\",\n            \"price\": 19.99,\n            \"desc\": \"Product description...\"\n        }\n    },\n    ...\n\n]\n```\n\n```text\nmodels.sequelize.sync().then(() => {\n    console.log('You are connected to the database successfully.');\n    sequelize_fixtures.loadFile('./fixtures/*.json', models).then(() =>{\n        console.log(\"database is updated!\");\n   });\n   }).catch((err) => {\n       console.log(err,\"Some problems with database connection!!!\");\n});\n```\n\n```js\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    // logic for transforming into the new state\n  },\n  down: (queryInterface, Sequelize) => {\n    // logic for reverting the changes\n  }\n```\n\n```text\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(__dirname + '/../config/config.json')[env];\n\nconst { host, port, username, password } = config;\n\n# create sequelize instance without providing db name in config\nsequelize = new Sequelize('', username, password, config);\n\nsequelize.beforeConnect(async (config) => {\n     const connection = await mysql.createConnection({ host: host, port: port, user: username, password: password });\n     await connection.query(`CREATE DATABASE IF NOT EXISTS \\`${process.env.DB_NAME}\\`;`);\n     config.database = process.env.DB_NAME;\n});\n```\n\n```text\n{\n  \"development\": {\n    \"username\": \"root\",\n    \"password\": \"init@123\",\n    \"host\": \"mysqldb\",\n    \"dialect\": \"mysql\"\n  },\n  \"test\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\"\n  },\n  \"production\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\",\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":249,"estimatedTokens":1425}}335{"id":"stack-61163520","source":"stackoverflow","questionId":61163520,"title":"[NodeJs][Sequelize] ReferenceError: Cannot access 'ModelName' before initialization","tags":["javascript","node.js","ecmascript-6","sequelize.js"],"text":"Title: [NodeJs][Sequelize] ReferenceError: Cannot access 'ModelName' before initialization\nTags: javascript, node.js, ecmascript-6, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nCurrently I realize an API using *Node Js 13* and the ORM *Sequelize v5* and all this in *ES6* (via \"type\": \"module\" in package.json).\n\nIn this project there is a problem when I try to use associations.\n\nI have three models which are associated: author.js, authorbook.js and book.js .\n\n**author.js:**\n\n```\nimport Sequelize from 'sequelize';\nimport AuthorBook from './authorbook.js';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\nconst sequelize = new Sequelize(\n process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{\n host: process.env.DB_HOST,\n dialect: 'mysql'\n }\n);\n\nexport default class Author extends Sequelize.Model {}\nAuthor.init({\n firstName: {\n firstName: false,\n type: Sequelize.STRING(100)\n },\n lastName: {\n allowNull: false,\n type: Sequelize.STRING(100)\n }\n}, { sequelize });\n\nAuthor.hasMany(AuthorBook, {\n onUpdate: 'CASCADE'\n});\n```\n\n**book.js**:\n\n```\nimport Sequelize from 'sequelize';\nimport AuthorBook from './authorbook.js';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\nconst sequelize = new Sequelize(\n process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{\n host: process.env.DB_HOST,\n dialect: 'mysql'\n }\n);\n\nexport default class Book extends Sequelize.Model {}\nBook.init({\n title: {\n firstName: false,\n type: Sequelize.STRING(100)\n }\n}, { sequelize });\n\nBook.hasMany(AuthorBook, {\n onUpdate: 'CASCADE'\n});\n```\n\n**authorbook.js**:\n\n```\nimport Sequelize from 'sequelize';\nimport Author from './author.js';\nimport Book from './book.js';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\nconst sequelize = new Sequelize(\n process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{\n host: process.env.DB_HOST,\n dialect: 'mysql'\n }\n);\n\nexport default class AuthorBook extends Sequelize.Model {}\nAuthorBook.init({\n authorId: {\n type: Number,\n allowNull: false\n },\n bookId: {\n type: Number,\n allowNull: false\n },\n}, { sequelize });\n\nAuthorBook.belongsTo(Author, { foreignKey: 'authorId'});\nAuthorBook.belongsTo(Book, { foreignKey: 'bookId'});\n```\n\nHere is the error I get when I run the cmd `node src/server.js`:\n\n```\n(node:23142) ExperimentalWarning: The ESM module loader is experimental.\nfile:///Users/alexandre/Documents/project/server/src/db/models/.js:18\nAuthor.hasMany(AuthorBook, {\n ^\n\nReferenceError: Cannot access 'AuthorBook' before initialization\n at file:///Users/alexandre/Documents/project/server/src/db/models/author.js:38:22\n at ModuleJob.run (internal/modules/esm/module_job.js:110:37)\n at async Loader.import (internal/modules/esm/loader.js:176:24)\n```\n\nSomeone can help me ?\n\n========================================\n\nCode:\n```text\nimport Sequelize from 'sequelize';\nimport AuthorBook from './authorbook.js';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\nconst sequelize = new Sequelize(\n  process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{\n    host: process.env.DB_HOST,\n    dialect: 'mysql'\n  }\n);\n\nexport default class Author extends Sequelize.Model {}\nAuthor.init({\n  firstName: {\n    firstName: false,\n    type: Sequelize.STRING(100)\n  },\n  lastName: {\n    allowNull: false,\n    type: Sequelize.STRING(100)\n  }\n}, { sequelize });\n\nAuthor.hasMany(AuthorBook, {\n  onUpdate: 'CASCADE'\n});\n```\n\n```text\nimport Sequelize from 'sequelize';\nimport AuthorBook from './authorbook.js';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\nconst sequelize = new Sequelize(\n  process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{\n    host: process.env.DB_HOST,\n    dialect: 'mysql'\n  }\n);\n\nexport default class Book extends Sequelize.Model {}\nBook.init({\n  title: {\n    firstName: false,\n    type: Sequelize.STRING(100)\n  }\n}, { sequelize });\n\nBook.hasMany(AuthorBook, {\n  onUpdate: 'CASCADE'\n});\n```\n\n```text\nimport Sequelize from 'sequelize';\nimport Author from './author.js';\nimport Book from './book.js';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\nconst sequelize = new Sequelize(\n  process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{\n    host: process.env.DB_HOST,\n    dialect: 'mysql'\n  }\n);\n\nexport default class AuthorBook extends Sequelize.Model {}\nAuthorBook.init({\n  authorId: {\n    type: Number,\n    allowNull: false\n  },\n  bookId: {\n    type: Number,\n    allowNull: false\n  },\n}, { sequelize });\n\nAuthorBook.belongsTo(Author, { foreignKey: 'authorId'});\nAuthorBook.belongsTo(Book, { foreignKey: 'bookId'});\n```\n\n```text\n(node:23142) ExperimentalWarning: The ESM module loader is experimental.\nfile:///Users/alexandre/Documents/project/server/src/db/models/.js:18\nAuthor.hasMany(AuthorBook, {\n               ^\n\nReferenceError: Cannot access 'AuthorBook' before initialization\n    at file:///Users/alexandre/Documents/project/server/src/db/models/author.js:38:22\n    at ModuleJob.run (internal/modules/esm/module_job.js:110:37)\n    at async Loader.import (internal/modules/esm/loader.js:176:24)\n```\n\n```text\nnode src/server.js\n```\n\n```js\nimport Sequelize from 'sequelize';\nimport { sequelize } from '../../../db';\n\nexport default class Book extends Sequelize.Model {}\nBook.init(\n  {\n    title: {\n      allowNull: false,\n      type: Sequelize.STRING(100),\n    },\n  },\n  { sequelize, modelName: 'books' },\n);\n```\n\n```js\nimport Sequelize from 'sequelize';\nimport { sequelize } from '../../../db';\n\nexport default class Author extends Sequelize.Model {}\nAuthor.init(\n  {\n    firstName: {\n      allowNull: false,\n      type: Sequelize.STRING(100),\n    },\n    lastName: {\n      allowNull: false,\n      type: Sequelize.STRING(100),\n    },\n  },\n  { sequelize, modelName: 'authors' },\n);\n```\n\n```js\nimport Sequelize from 'sequelize';\nimport { sequelize } from '../../../db';\n\nexport default class AuthorBook extends Sequelize.Model {}\nAuthorBook.init(\n  {\n    authorId: {\n      type: Sequelize.INTEGER,\n      allowNull: false,\n    },\n    bookId: {\n      type: Sequelize.INTEGER,\n      allowNull: false,\n    },\n  },\n  { sequelize, modelName: 'authorbooks' },\n);\n```\n\n```js\nimport Author from './author';\nimport Book from './book';\nimport AuthorBook from './authorbook';\n\nAuthor.hasMany(AuthorBook, {\n  onUpdate: 'CASCADE',\n});\nBook.hasMany(AuthorBook, {\n  onUpdate: 'CASCADE',\n});\nAuthorBook.belongsTo(Author, { foreignKey: 'authorId' });\nAuthorBook.belongsTo(Book, { foreignKey: 'bookId' });\n\nexport { Author, Book, AuthorBook };\n```\n\n```js\nimport { Author, AuthorBook, Book } from './models';\nimport { sequelize } from '../../db';\nimport faker from 'faker';\n\n(async function test() {\n  try {\n    await sequelize.sync({ force: true });\n    // seed\n    const author = await Author.create({\n      firstName: faker.name.firstName(),\n      lastName: faker.name.lastName(),\n    });\n    const book = await Book.create({\n      title: faker.lorem.words(3),\n    });\n    await AuthorBook.create({ authorId: author.id, bookId: book.id });\n  } catch (error) {\n    console.log(error);\n  } finally {\n    await sequelize.close();\n  }\n})();\n```\n\n```sh\nExecuting (default): DROP TABLE IF EXISTS \"authorbooks\" CASCADE;\nExecuting (default): DROP TABLE IF EXISTS \"books\" CASCADE;\nExecuting (default): DROP TABLE IF EXISTS \"authors\" CASCADE;\nExecuting (default): DROP TABLE IF EXISTS \"authors\" CASCADE;\nExecuting (default): CREATE TABLE IF NOT EXISTS \"authors\" (\"id\"   SERIAL , \"firstName\" VARCHAR(100) NOT NULL, \"lastName\" VARCHAR(100) NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authors' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): DROP TABLE IF EXISTS \"books\" CASCADE;\nExecuting (default): CREATE TABLE IF NOT EXISTS \"books\" (\"id\"   SERIAL , \"title\" VARCHAR(100) NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'books' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): DROP TABLE IF EXISTS \"authorbooks\" CASCADE;\nExecuting (default): CREATE TABLE IF NOT EXISTS \"authorbooks\" (\"id\"   SERIAL , \"authorId\" INTEGER NOT NULL REFERENCES \"authors\" (\"id\") ON DELETE CASCADE ON UPDATE CASCADE, \"bookId\" INTEGER NOT NULL REFERENCES \"books\" (\"id\") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authorbooks' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): INSERT INTO \"authors\" (\"id\",\"firstName\",\"lastName\") VALUES (DEFAULT,$1,$2) RETURNING *;\nExecuting (default): INSERT INTO \"books\" (\"id\",\"title\") VALUES (DEFAULT,$1) RETURNING *;\nExecuting (default): INSERT INTO \"authorbooks\" (\"id\",\"authorId\",\"bookId\") VALUES (DEFAULT,$1,$2) RETURNING *;\n```\n\n```sh\nnode-sequelize-examples=# select * from \"authors\";\n id | firstName | lastName\n----+-----------+----------\n  1 | Laron     | Deckow\n(1 row)\n\nnode-sequelize-examples=# select * from \"books\";\n id |          title\n----+-------------------------\n  1 | facilis molestias sequi\n(1 row)\n\nnode-sequelize-examples=# select * from \"authorbooks\";\n id | authorId | bookId\n----+----------+--------\n  1 |        1 |      1\n(1 row)\n```\n\n```text\nindex.ts\n```\n\n```text\n./models/book.ts\n```\n\n```text\n./models/author.ts\n```\n\n```text\n./models/authorbook.ts\n```\n\n```text\n./models/index.ts\n```\n\n```text\nindex.ts\n```\n\n```text\n\"sequelize\": \"^5.21.3\"\n```\n\n```text\npostgres:9.6\n```\n\n========================================\n\nComments:\n- move all association definitions in associations.js and import all your models in it. I guess you have a circular reference.\n- The error is because of cyclic dependency, `authorBook.js` imports `author.js` and `book`.js and both of these again import `authBook.js`\n- Hello, first thank you for your quick answer. Can you show me how to do this ?\n- Isn't it a bad way of solving this by adding all associations in a single file, it could lead to difficulties in managing the code for large projects","metadata":{"transformedAt":"2026-08-18T18:33:34.366Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":405,"estimatedTokens":2778}}336{"id":"stack-34361593","source":"stackoverflow","questionId":34361593,"title":"Can't connect to SQL Azure Database with sequelize, but SQL Server on localhost works fine","tags":["sql-server","node.js","azure","azure-sql-database","sequelize.js"],"text":"Title: Can't connect to SQL Azure Database with sequelize, but SQL Server on localhost works fine\nTags: sql-server, node.js, azure, azure-sql-database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have deployed a few sites to Heroku with MongoDB, but this is the first time I've made a site with SQL and tried to deploy to Azure, so I'm probably missing something obvious. \n\nI have been developing a website on my dev machine using Node.js, a SQL Server Database, and Sequelize as the ORM. Everything works fine, but when I tried to deploy to Azure with a connection string I can't connect with the SQL Azure database. I can use SQL Server Management Studio to connect with the empty database on Azure, so I'm sure my connection info is correct.\n\nWhen I tried to deploy to Azure, I tried with the connection string that Azure provides:\n\n\r\n\r\n\n```\nvar Sql = require('sequelize');\r\nvar sql = new Sql('Driver={SQL Server Native Client 11.0};Server=tcp:server.database.windows.net,1433;Database=databasename;Uid=UserName@server;Pwd={password};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;');\n```\n\n\r\n\r\n\r\n\nWhen I try to connect with this string, the error I get is:\n\n\r\n\r\n\n```\nC:\\Users\\username\\Documents\\GitHub\\event-site\\node_modules\\sequelize\\lib\\sequelize.js:110\r\n options.dialect = urlParts.protocol.replace(/:$/, '');\r\n ^\r\n\r\nTypeError: Cannot read property 'replace' of null\r\n at new Sequelize (C:\\Users\\v-mibowe\\Documents\\GitHub\\event-site\\node_modules\\sequelize\\lib\\sequelize.js:110:40)\r\n at Object. (C:\\Users\\v-mibowe\\Documents\\GitHub\\event-site\\routes\\db-routes.js:68:11)\r\n at Module._compile (module.js:435:26)\r\n at Object.Module._extensions..js (module.js:442:10)\r\n at Module.load (module.js:356:32)\r\n at Function.Module._load (module.js:311:12)\r\n at Module.require (module.js:366:17)\r\n at require (module.js:385:17)\r\n at Object. (C:\\Users\\v-mibowe\\Documents\\GitHub\\event-site\\server.js:16:1)\r\n at Module._compile (module.js:435:26)\r\n at Object.Module._extensions..js (module.js:442:10)\r\n at Module.load (module.js:356:32)\r\n at Function.Module._load (module.js:311:12)\r\n at Function.Module.runMain (module.js:467:10)\r\n at startup (node.js:136:18)\r\n at node.js:963:3\n```\n\n\r\n\r\n\r\n\n`db-routes.js:68:11` is the connection string to the db.\n\nWhen I try to configure my connection with the following, the server no longer crashes or gives an error, but none of the content that should be created by the code in the schema is created. That code looks like this:\n\n\r\n\r\n\n```\nvar Sql = require('sequelize');\r\nvar sql = new Sql('dbname', 'UserName@server', 'password', {\r\n host: 'server.database.windows.net',\r\n dialect: 'mssql',\r\n driver: 'tedious',\r\n options: {\r\n encrypt: true,\r\n database: 'dbname'\r\n },\r\n port: 1433,\r\n pool: {\r\n max: 5,\r\n min: 0,\r\n idle: 10000\r\n }\r\n});\n```\n\n\r\n\r\n\r\n\nMy original connection to my localhost (which works fine) looks like this:\n\n\r\n\r\n\n```\nvar Sql = require('sequelize');\r\nvar sql = new Sql('dbname', 'username', 'password', {\r\n host: 'localhost',\r\n dialect: 'mssql',\r\n\r\n pool: {\r\n max: 5,\r\n min: 0,\r\n idle: 10000\r\n }\r\n})\n```\n\n\r\n\r\n\r\n\nThanks in advance for all the help!\n\n========================================\n\nTop Answer:\nYou need to Enable the SQL Azure Firewall to add Azure Services to it. in not your App will not be able to communicate with SQL Azure,\n\n========================================\n\nCode:\n```js\nvar Sql = require('sequelize');\nvar sql = new Sql('Driver={SQL Server Native Client 11.0};Server=tcp:server.database.windows.net,1433;Database=databasename;Uid=UserName@server;Pwd={password};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;');\n```\n\n```js\nC:\\Users\\username\\Documents\\GitHub\\event-site\\node_modules\\sequelize\\lib\\sequelize.js:110\n    options.dialect = urlParts.protocol.replace(/:$/, '');\n                                       ^\n\nTypeError: Cannot read property 'replace' of null\n    at new Sequelize (C:\\Users\\v-mibowe\\Documents\\GitHub\\event-site\\node_modules\\sequelize\\lib\\sequelize.js:110:40)\n    at Object.<anonymous> (C:\\Users\\v-mibowe\\Documents\\GitHub\\event-site\\routes\\db-routes.js:68:11)\n    at Module._compile (module.js:435:26)\n    at Object.Module._extensions..js (module.js:442:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:311:12)\n    at Module.require (module.js:366:17)\n    at require (module.js:385:17)\n    at Object.<anonymous> (C:\\Users\\v-mibowe\\Documents\\GitHub\\event-site\\server.js:16:1)\n    at Module._compile (module.js:435:26)\n    at Object.Module._extensions..js (module.js:442:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:311:12)\n    at Function.Module.runMain (module.js:467:10)\n    at startup (node.js:136:18)\n    at node.js:963:3\n```\n\n```js\nvar Sql = require('sequelize');\nvar sql = new Sql('dbname', 'UserName@server', 'password', {\n  host: 'server.database.windows.net',\n  dialect: 'mssql',\n  driver: 'tedious',\n  options: {\n    encrypt: true,\n    database: 'dbname'\n  },\n  port: 1433,\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  }\n});\n```\n\n```js\nvar Sql = require('sequelize');\nvar sql = new Sql('dbname', 'username', 'password', {\n  host: 'localhost',\n  dialect: 'mssql',\n\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  }\n})\n```\n\n```text\ndb-routes.js:68:11\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('dbname', 'username', 'passwd', {\n  host: 'hostname',\n  dialect: 'mssql',\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  },\n  dialectOptions: {\n    encrypt: true\n  }\n});\n```\n\n```text\nencrypt: true\n```\n\n========================================\n\nComments:\n- If I understood correctly, your application is running on Heroku and your database in Azure, right? Did you check firewall?\n- @BrunoFaria Thanks for getting back to me. Nothing is on Heroku, the entire App is running on Azure. I only mentioned Heroku , because I haven't deployed on Azure before and I may be trying to do things in a \"Heroku\" kind of way when it should be done differently in Azure.\n- Is SQL Azure firewall checked for Azure Services? Otherwise, you have to manually add the frontend ip.\n- Hi, I have a very similar situation to yours and the solution for me was to add \"@hostname\" after the username, like so: `const { Sequelize } = require ('sequelize'); const db = new Sequelize(\"myDBName\", \"myDBName@mysqlinstance.mysql.database.azure.com\", \"myPassword\", { host: 'mySqlinstance.mysql.database.azure.com', dialect: 'mysql', });` hope it will help\n- Thanks for the help Gary Liu - MSFT, I think I'm almost there. With the answer you gave, I'm able to connect to the online azure database with my connection string, but when I deploy to azure I still get the error: \"The page cannot be displayed because an internal server error has occurred.\"\n- Usually, the code error or deployment error will raise the 500 error. If your application will run well without `sequelize`, it may be a code issue, you can check whether the node.js modules dependencies have been uploaded with your app, you can sign in KUDU console cmdlet of your site,which url should be `https:&#47;&#47;.scm.azurewebsites.net&#47;DebugConsole`. and about Node.js modules with Azure applications, you can refer to azure.microsoft.com/en-us/documentation/articles/&hellip;\n- additionally, you can enable diagnostic logs of your site, refer to azure.microsoft.com/en-us/documentation/articles/&hellip; for more. And you can download the **system file** tier logs via KUDU api `https:&#47;&#47;.scm.azurewebsites.net&#47;api&#47;dump`\n- Thanks so much for your help Gary Liu - MSFT . It was an separate problem from connecting to the DB, but your links to the logs let me figure out the problem. My node modules were causing file names that exceeded 260 characters. In order to fix the problem I used a module from npm called flatten-packages which flattens out the deeply nested folders in node_modules and once I ran that I was able to push to Azure successfully!\n- Happy to hear that, congratulations.","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":217,"estimatedTokens":1997}}337{"id":"stack-32292037","source":"stackoverflow","questionId":32292037,"title":"Create timestamps in a Sequelize migration","tags":["sequelize.js"],"text":"Title: Create timestamps in a Sequelize migration\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using SequelizeJS for my ORM. \n\nI have a \"Video\" model. This model uses the \"Videos\" table. \n\nHow can I create a migration that includes timestamps? Do I need to define my own timestamp columns, or is there a shortcut?\n\nIn **/migrations/123412341234-create-videos-table.js**\n\n```\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n queryInterface.createTable(\n 'Videos',\n {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n title: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: true\n },\n author: {\n type: Sequelize.STRING,\n allowNull: false\n },\n videoUrl: {\n type: Sequelize.STRING,\n },\n coverUrl: {\n type: Sequelize.STRING,\n }\n }\n );\n },\n\n down: function (queryInterface, Sequelize) {\n queryInterface.dropTable('Videos');\n }\n};\n```\n\nIn **/models/video.js**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('Video', {\n title: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true\n },\n author: {\n type: DataTypes.STRING,\n allowNull: false\n },\n videoUrl: {\n type: DataTypes.STRING,\n },\n coverUrl: {\n type: DataTypes.STRING,\n }\n });\n}\n```\n\nIn **/models/index.js** (this is the default created by running `$ sequelize init`)\n\n```\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(module.filename);\nvar env = process.env.NODE_ENV || 'development';\nvar config = require(__dirname + '/../config/config.json')[env];\nvar db = {};\n\nif (config.use_env_variable) {\n var sequelize = new Sequelize(process.env[config.use_env_variable]);\n} else {\n var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf('.') !== 0) && (file !== basename);\n })\n .forEach(function(file) {\n if (file.slice(-3) !== '.js') return;\n var model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function(modelName) {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n========================================\n\nTop Answer:\nTLDR: sequelize 6, umzug, typescript, no hooks needed.\n\nI prefer using Umzug with Sequelize. Umzug actually powers the sequelize-cli, but is more flexible and provides typescript support.\n\nMy migration file looks is provided below. You can see I manually define the `createdAt` field:\n\n```\n// src/db/migrations/10_visited_users.ts\nimport {DataTypes} from 'sequelize';\nimport {Migration, MigrationParams} from '../../types/db.migrations';\n\nexport const up: Migration = async ({context: queryInterface}: MigrationParams) => {\n await queryInterface.createTable('VisitedUsers', {\n id: {\n type: DataTypes.INTEGER,\n autoIncrement: true,\n primaryKey: true,\n allowNull: false,\n },\n\n project: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n\n server: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n\n uid: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n\n level: {\n type: DataTypes.INTEGER,\n },\n\n name: {\n type: DataTypes.STRING,\n },\n\n country: {\n type: DataTypes.STRING,\n },\n\n createdAt: {\n type: DataTypes.DATE,\n allowNull: false,\n },\n });\n\n await queryInterface.addIndex('VisitedUsers', ['id'], {unique: true});\n\n await queryInterface.addIndex('VisitedUsers', ['createdAt'], {using: 'BTREE'});\n};\n\nexport const down: Migration = async ({context: queryInterface}: MigrationParams) => {\n await queryInterface.dropTable('VisitedUsers');\n};\n\nmodule.exports = {up, down};\n```\n\nMy model file listed below. Please notice how I manage `createdAt` and disable `updatedAt` since I dont need it (otherwise you will face an error on queries because by default sequelize expect both `createdAt` and `updatedAd` to be present):\n\n```\n// src/db/models/VisitedUsers.model.ts\nimport {DataTypes, Sequelize} from 'sequelize';\nimport {ModelDefined} from 'sequelize/types/model';\nimport {VisitedUserRecord} from '../../types/db';\n\nconst VisitedUsersModel = (sequelize: Sequelize): ModelDefined => {\n return sequelize.define('VisitedUsers', {\n id: {\n type: DataTypes.INTEGER,\n autoIncrement: true,\n primaryKey: true,\n allowNull: false,\n },\n\n project: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n\n server: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n\n uid: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n\n level: {\n type: DataTypes.INTEGER,\n },\n\n name: {\n type: DataTypes.STRING,\n },\n\n country: {\n type: DataTypes.STRING,\n },\n\n createdAt: {\n type: DataTypes.DATE,\n allowNull: false,\n comment: 'Дата создания записи',\n },\n }, {\n updatedAt: false,\n });\n};\n\nexport default VisitedUsersModel;\n```\n\nAttaching the types I used in migration files because I have struggled to make it work:\n\n```\n// src/types/db.migrations.d.ts\nimport {QueryInterface} from 'sequelize';\nimport {Umzug} from 'umzug';\n\ntype Migration = typeof Umzug.prototype._types.migration;\ntype MigrationParams = {context: QueryInterface};\n\nexport {Migration, MigrationParams};\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    queryInterface.createTable(\n      'Videos',\n      {\n        id: {\n          type: Sequelize.INTEGER,\n          primaryKey: true,\n          autoIncrement: true\n        },\n        title: {\n          type: Sequelize.STRING,\n          allowNull: false,\n          unique: true\n        },\n        author: {\n          type: Sequelize.STRING,\n          allowNull: false\n        },\n        videoUrl: {\n          type: Sequelize.STRING,\n        },\n        coverUrl: {\n          type: Sequelize.STRING,\n        }\n      }\n    );\n  },\n\n  down: function (queryInterface, Sequelize) {\n    queryInterface.dropTable('Videos');\n  }\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('Video', {\n    title: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true\n    },\n    author: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    videoUrl: {\n      type: DataTypes.STRING,\n    },\n    coverUrl: {\n      type: DataTypes.STRING,\n    }\n  });\n}\n```\n\n```text\n'use strict';\n\nvar fs        = require('fs');\nvar path      = require('path');\nvar Sequelize = require('sequelize');\nvar basename  = path.basename(module.filename);\nvar env       = process.env.NODE_ENV || 'development';\nvar config    = require(__dirname + '/../config/config.json')[env];\nvar db        = {};\n\nif (config.use_env_variable) {\n  var sequelize = new Sequelize(process.env[config.use_env_variable]);\n} else {\n  var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf('.') !== 0) && (file !== basename);\n  })\n  .forEach(function(file) {\n    if (file.slice(-3) !== '.js') return;\n    var model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(function(modelName) {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n$ sequelize init\n```\n\n```text\nmodule.exports = function (sequelize, DataTypes) {\n\n    var Person = sequelize.define('Person', {\n        id: {\n            type: DataTypes.INTEGER,\n            primary: true,\n            autoincrement: true\n        },\n        name: DataTypes.STRING,\n        updatedAt: DataTypes.DATE,\n        createdAt: DataTypes.DATE\n    }, {\n        hooks: {\n           beforeCreate: function (person, options, fn) {\n               person.createdAt = new Date();\n               person.updatedAt = new Date();\n               fn(null, person);\n           },\n           beforeUpdate: function (person, options, fn) {\n               person.updatedAt = new Date();\n               fn(null, person);\n           }\n       }\n    });\n\n    return Person;\n}\n```\n\n```js\n// src/db/migrations/10_visited_users.ts\nimport {DataTypes} from 'sequelize';\nimport {Migration, MigrationParams} from '../../types/db.migrations';\n\nexport const up: Migration = async ({context: queryInterface}: MigrationParams) => {\n  await queryInterface.createTable('VisitedUsers', {\n    id: {\n      type: DataTypes.INTEGER,\n      autoIncrement: true,\n      primaryKey: true,\n      allowNull: false,\n    },\n\n    project: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n\n    server: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n\n    uid: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n\n    level: {\n      type: DataTypes.INTEGER,\n    },\n\n    name: {\n      type: DataTypes.STRING,\n    },\n\n    country: {\n      type: DataTypes.STRING,\n    },\n\n    createdAt: {\n      type: DataTypes.DATE,\n      allowNull: false,\n    },\n  });\n\n  await queryInterface.addIndex('VisitedUsers', ['id'], {unique: true});\n\n  await queryInterface.addIndex('VisitedUsers', ['createdAt'], {using: 'BTREE'});\n};\n\nexport const down: Migration = async ({context: queryInterface}: MigrationParams) => {\n  await queryInterface.dropTable('VisitedUsers');\n};\n\nmodule.exports = {up, down};\n```\n\n```js\n// src/db/models/VisitedUsers.model.ts\nimport {DataTypes, Sequelize} from 'sequelize';\nimport {ModelDefined} from 'sequelize/types/model';\nimport {VisitedUserRecord} from '../../types/db';\n\nconst VisitedUsersModel = (sequelize: Sequelize): ModelDefined<\n  VisitedUserRecord,\n  VisitedUserRecord\n> => {\n  return sequelize.define('VisitedUsers', {\n    id: {\n      type: DataTypes.INTEGER,\n      autoIncrement: true,\n      primaryKey: true,\n      allowNull: false,\n    },\n\n    project: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n\n    server: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n\n    uid: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n\n    level: {\n      type: DataTypes.INTEGER,\n    },\n\n    name: {\n      type: DataTypes.STRING,\n    },\n\n    country: {\n      type: DataTypes.STRING,\n    },\n\n    createdAt: {\n      type: DataTypes.DATE,\n      allowNull: false,\n      comment: 'Дата создания записи',\n    },\n  }, {\n    updatedAt: false,\n  });\n};\n\nexport default VisitedUsersModel;\n```\n\n```js\n// src/types/db.migrations.d.ts\nimport {QueryInterface} from 'sequelize';\nimport {Umzug} from 'umzug';\n\ntype Migration = typeof Umzug.prototype._types.migration;\ntype MigrationParams = {context: QueryInterface};\n\nexport {Migration, MigrationParams};\n```\n\n```text\ncreatedAt\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAd\n```\n\n========================================\n\nComments:\n- You don't need to add hooks at all, sequelize manages that logic for you (in case you haven't added `timestamps: false` in your model definition options)\n- That is true unless you used a migration to create the table (In Seqeulize 2, I am not sure after that).\n- Using `4.28.0` works for me: I have model definition + table migration (don't use `sequelize.sync()`) and it manages timestamps without hooks\n- Cool, I didn't know that they had added that.","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":547,"estimatedTokens":2814}}338{"id":"stack-32965833","source":"stackoverflow","questionId":32965833,"title":"Sequelizejs: how to use transactions along with raw queries","tags":["sequelize.js"],"text":"Title: Sequelizejs: how to use transactions along with raw queries\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize orm. I cannot find in their documentation how to use transactions when using raw queries. All I see there is for model defined query methods. But for raw queries, there is no specification on where to put the transaction object to use for that specific query.\n\n========================================\n\nTop Answer:\nThe link above does not help me, but have figure out the solution:\n(If you rollback in the catch block, the transaction will be reverted.)\n\n```\nsequelize.transaction(async transaction => {\n try {\n await sequelize.query(\n `\n UPDATE Balances\n SET amount = @amount := amount - ${10}\n WHERE userId=${1}`,\n {\n type: Sequelize.QueryTypes.UPDATE,\n transaction,\n raw: true\n },\n )\n\n await sequelize.query(\n `\n UPDATE Balances\n SET amount = @amount := amount - ${10}\n WHERE userId=${2}`,\n {\n type: Sequelize.QueryTypes.UPDATE,\n transaction,\n raw: true\n },\n )\n\n } catch (error) {\n transaction.rollback();\n throw `TRANSACTION_ERROR`;\n }\n })\n```\n\n========================================\n\nCode:\n```js\nconst t = await sequelize.transaction();\n\nsequelize.query('SELECT * FROM table;', { transaction: t })\n```\n\n```js\nsequelize.transaction(async transaction => {\n    try {\n      await sequelize.query(\n        `\n        UPDATE Balances\n        SET amount = @amount := amount - ${10}\n        WHERE userId=${1}`,\n        {\n          type: Sequelize.QueryTypes.UPDATE,\n          transaction,\n          raw: true\n        },\n      )\n\n      await sequelize.query(\n        `\n        UPDATE Balances\n        SET amount = @amount := amount - ${10}\n        WHERE userId=${2}`,\n        {\n          type: Sequelize.QueryTypes.UPDATE,\n          transaction,\n          raw: true\n        },\n      )\n\n    } catch (error) {\n      transaction.rollback();\n      throw `TRANSACTION_ERROR`;\n    }\n  })\n```\n\n```js\nconst t = await sequelize.transaction();\n\ntry{\n  await sequelize.query('SELECT * FROM table;', { transaction: t })\n  await t.commit();\n}\ncatch (e) {\n await t.rollback();\n}\n```\n\n```js\nlet t = db.transaction();\nawait db.sequelize.query(query, {\n    type: QueryTypes.INSERT,\n    // Use transaction in the object just after query \n    transaction: t,\n    replacements: {},\n});\n```\n\n========================================\n\nComments:\n- They've restructured the docs. Details now at sequelize.org/master/class/lib/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":612}}339{"id":"stack-50414899","source":"stackoverflow","questionId":50414899,"title":"Node.js Sequelize UUID primary key + Postgres","tags":["node.js","postgresql","orm","sequelize.js","graphql"],"text":"Title: Node.js Sequelize UUID primary key + Postgres\nTags: node.js, postgresql, orm, sequelize.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI try to create database model by using sequelize but I'm facing a problem with model's primary key.\n\n### Setting\n\nI'm using Postgres (v10) in docker container and sequalize (Node.js v10.1.0\n) for models and GraphQL (0.13.2) + GraphQL-Sequalize (8.1.0) for request processing.\n\n### Problem\n\nAfter creating models by sequelize-cli I've **manually tried to replace id column with uuid**. Here's my model migration that I'm using.\n\n```\n'use strict';\nconst DataTypes = require('sequelize').DataTypes;\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Currencies', {\n uuid: {\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: DataTypes.UUIDV4,\n allowNull: false\n },\n name: {\n type: Sequelize.STRING\n },\n ticker: {\n type: Sequelize.STRING\n },\n alt_tickers: {\n type: Sequelize.ARRAY(Sequelize.STRING)\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Currencies');\n }\n};\n```\n\nModel:\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const Currency = sequelize.define('Currency', {\n uuid: DataTypes.UUID,\n name: DataTypes.STRING,\n ticker: DataTypes.STRING,\n alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n }, {});\n Currency.associate = function(models) {\n // associations can be defined here\n };\n return Currency;\n};\n```\n\nDue to some problem sequalize executes next expression:\n\nExecuting (default): SELECT \"id\", \"uuid\", \"name\", \"ticker\", \"alt_tickers\", \"createdAt\", \"updatedAt\" FROM \"Currencies\" AS \"Currency\" ORDER BY \"Currency\".\"id\" ASC;\n\nThat leads to \"column 'id' doesn't exist\" error.\n\nAlternatively, I've tried to fix it by renaming *uuid* column to *id* at migration:\n\n```\n... \n id: {\n allowNull: false,\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4()\n },\n ...\n```\n\nAnd at the model:\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const Currency = sequelize.define('Currency', {\n id: DataTypes.INTEGER,\n name: DataTypes.STRING,\n ticker: DataTypes.STRING,\n alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n }, {});\n Currency.associate = function(models) {\n // associations can be defined here\n };\n return Currency;\n};\n```\n\nbut the result was the following error at the start of the program:\n\nError: A column called 'id' was added to the attributes of 'Currencies' but not marked with 'primaryKey: true'\n\n### Questions\n\n- So, is there a way to force sequelize to use UUID as the tables primary key without defining id column?\n\n- Is there a way to create columns without id columns?\n\n- What possibly caused this errors and how should fix it?\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nThis is just about the only resource I've found online that explains what it takes to set up a UUID column that the *database* provides defaults for, without relying on the third-party `uuid` npm package: https://krmannix.com/2017/05/23/postgres-autogenerated-uuids-with-sequelize/\n\nShort version:\n\n- You'll need to install the \"uuid-ossp\" postgres extension, using a sqlz migration\n\n- When defining the table, use this `defaultValue`: `Sequelize.literal( 'uuid_generate_v4()' )`\n\n========================================\n\nCode:\n```text\n'use strict';\nconst DataTypes = require('sequelize').DataTypes;\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('Currencies', {\n      uuid: {\n        primaryKey: true,\n        type: Sequelize.UUID,\n        defaultValue: DataTypes.UUIDV4,\n        allowNull: false\n      },\n      name: {\n        type: Sequelize.STRING\n      },\n      ticker: {\n        type: Sequelize.STRING\n      },\n      alt_tickers: {\n        type: Sequelize.ARRAY(Sequelize.STRING)\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable('Currencies');\n  }\n};\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n    const Currency = sequelize.define('Currency', {\n        uuid: DataTypes.UUID,\n        name: DataTypes.STRING,\n        ticker: DataTypes.STRING,\n        alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n    }, {});\n    Currency.associate = function(models) {\n        // associations can be defined here\n    };\n    return Currency;\n};\n```\n\n```text\n...      \n  id: {\n      allowNull: false,\n      primaryKey: true,\n      type: Sequelize.UUID,\n      defaultValue: Sequelize.UUIDV4()\n  },\n  ...\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n    const Currency = sequelize.define('Currency', {\n        id: DataTypes.INTEGER,\n        name: DataTypes.STRING,\n        ticker: DataTypes.STRING,\n        alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n    }, {});\n    Currency.associate = function(models) {\n        // associations can be defined here\n    };\n    return Currency;\n};\n```\n\n```text\nconst User = sequelize.define('user', {\n  uuid: {\n    type: Sequelize.UUID,\n    defaultValue: Sequelize.UUIDV1,\n    primaryKey: true\n  },\n  username: Sequelize.STRING,\n});\n\nsequelize.sync({ force: true })\n  .then(() => User.create({\n    username: 'test123'\n  }).then((user) => {\n    console.log(user);\n  }));\n```\n\n```text\nmodel\n```\n\n```text\nid\n```\n\n```text\nuuid\n```\n\n```text\nid\n```\n\n```text\nuuid\n```\n\n```text\nuuid\n```\n\n```text\nuuid\n```\n\n```text\ndefaultValue\n```\n\n```text\nSequelize.literal( 'uuid_generate_v4()' )\n```\n\n========================================\n\nComments:\n- Actually, the model has been changed in the first place. I've also tried to rollback to Integer \"id\", but the primary key was not set in the database.\n- Sure. Take a look.\n- The model still shows `id` field? it should be `uuid`. You should also make it primary key `primaryKey: true`\n- I've provided two cases. First is the table with *uuid* as UUID data type and second with *id* as UUID data type, so two models are provided, one after another. If I understood you correct you want me to add a primary key to migration but that is already done.\n- Model and DB declaration of primary key should happen independently and recommended. So if you are solving `Error: A column called 'id' was added to the attributes of 'Currencies', you should make it primary key in the model as well as in the db as the query is generated by the Sequelize\n- Ok, now I get it. Thanks a lot.","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":281,"estimatedTokens":1667}}340{"id":"stack-53373072","source":"stackoverflow","questionId":53373072,"title":"How to delete a migration using sequalize-cli","tags":["sequelize.js","sequelize-cli"],"text":"Title: How to delete a migration using sequalize-cli\nTags: sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI manually deleted a migration file name `20171125081136-create-task.js`.\n\nAfter deleting the migration file, I ran this command \n\n```\ndb:migrate:undo:all\n```\n\nWhile running this command I'm getting an error in the terminal:\n`ERROR: Unable to find migration: 20171125081136-create-task.js`.\n\nDue to this error I'm stuck and not able to undo other migration files that exists.\n\n========================================\n\nTop Answer:\nI was getting the same issue an this is how I solved it:\n\nSequelize stores the migration history within a separate table, ex \"SequelizeMeta\". If you delete a migration file and no longer want to use it after, you can remove the migration rows corresponding to your migration file from the SequelizeMeta table.\n\nHope that helps!\n\n========================================\n\nCode:\n```text\ndb:migrate:undo:all\n```\n\n```text\n20171125081136-create-task.js\n```\n\n```text\nERROR: Unable to find migration: 20171125081136-create-task.js\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n    return Promise.resolve()\n  },\n\n  down: function(queryInterface) {\n    return Promise.resolve()\n  }\n};\n```\n\n```text\n20171125081136-create-task.js\n```\n\n```text\ndown\n```\n\n```text\nnode_modules/.bin/sequelize db:migrate:undo\n```\n\n```text\nselect * from SequelizeMeta\n```\n\n```text\ndelete from table_name [where clause]\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nSELECT ALL FROM \"SequelizeMeta\"\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nname\n```\n\n```text\nDELETE FROM \"SequelizeMeta\" WHERE name='migration'\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":95,"estimatedTokens":417}}341{"id":"stack-51865038","source":"stackoverflow","questionId":51865038,"title":"Sequelize - To define foreign key, should I use references or belongsTo? or both?","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize - To define foreign key, should I use references or belongsTo? or both?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAs far as I know, in sequelize, there are two ways to define foreign key.\n\nFirst, use `references` like:\n\n```\nsequelize.define('foo', {\n bar_id: {\n type: 'blahblah',\n references: {\n model: Bar,\n key: 'id'\n }\n }\n});\n```\n\nand second, use `belongsTo` method:\n\n```\nFoo.belongsTo(Bar, { foreignKey: 'bar_id', targetKey: 'id' });\n```\n\nThen when I define foreign key in a model, should I use one of them? or both?\n\n- If I should use both, what is the difference between them?\n\n- Or if `belongsTo` is enough for defining foreign key, can I remove the `bar_id` definition in `sequelize.define('foo', {...})`?\n\n========================================\n\nCode:\n```text\nsequelize.define('foo', {\n    bar_id: {\n        type: 'blahblah',\n        references: {\n           model: Bar,\n           key: 'id'\n        }\n    }\n});\n```\n\n```text\nFoo.belongsTo(Bar, { foreignKey: 'bar_id', targetKey: 'id' });\n```\n\n```text\nreferences\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsTo\n```\n\n```text\nbar_id\n```\n\n```text\nsequelize.define('foo', {...})\n```\n\n========================================\n\nComments:\n- You mean, I can use one of them and if I use a method like `belongsTo`, I don't have to define a property like `bar_id` for foreign key?\n- Yes, if you use BelongsTo, etc, Sequelize will create the foreign key fields and indexes for you and the fields will be in the model.\n- ... again please review the document link I posted - their documentation is pretty good and it details various options that allow you to control things as you need or prefer.","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":78,"estimatedTokens":422}}342{"id":"stack-52809572","source":"stackoverflow","questionId":52809572,"title":"Sequelize: how to use `scope` inside `include`?","tags":["javascript","mysql","sequelize.js"],"text":"Title: Sequelize: how to use `scope` inside `include`?\nTags: javascript, mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to ask if it's possible to use the scope of the associate model inside `include` option?\n\nIn my case, there are two models, `User` and `Code`:\n\n```\nconst ACTIVE_FIELDS = ['fullname', 'idCard']\nconst User = sequelize.define('User', {\n uid: DataTypes.STRING,\n fullname: DataTypes.TEXT,\n idCard: DataTypes.STRING,\n province: DataTypes.STRING,\n}, {\n scopes: {\n activated: {\n where: ACTIVE_FIELDS.reduce((condition, field) => {\n condition[field] = {[sequelize.Op.ne]: null}\n return condition\n }, {}),\n },\n inProvinces: (provinces) => ({\n where: {\n province: {\n [sequelize.Op.in]: provinces,\n },\n },\n }),\n },\n})\n\nconst Code = sequelize.define('Code', {\n id: {\n type: DataTypes.STRING,\n primaryKey: true,\n },\n uid: DataTypes.STRING,\n}, {});\n```\n\n`Code` belongs to `User` through `uid`\n\n```\nCode.belongsTo(User, {\n foreignKey: 'uid',\n targetKey: 'uid',\n as: 'user',\n})\n```\n\nI want to select a random `Code` of users who are activated and in particular provinces. Is there any way to reuse `activated` and `inProvinces` scope so it may look like:\n\n```\nconst randomCode = (provinces) =>\n Code.findOne({\n include: [{\n model: User,\n as: 'user',\n scopes: ['activated', {method: ['inProvinces', provinces]}],\n attributes: [],\n required: true,\n }],\n order: sequelize.random(),\n })\n```\n\n========================================\n\nCode:\n```text\nconst ACTIVE_FIELDS = ['fullname', 'idCard']\nconst User = sequelize.define('User', {\n  uid: DataTypes.STRING,\n  fullname: DataTypes.TEXT,\n  idCard: DataTypes.STRING,\n  province: DataTypes.STRING,\n}, {\n  scopes: {\n    activated: {\n      where: ACTIVE_FIELDS.reduce((condition, field) => {\n        condition[field] = {[sequelize.Op.ne]: null}\n        return condition\n      }, {}),\n    },\n    inProvinces: (provinces) => ({\n      where: {\n        province: {\n          [sequelize.Op.in]: provinces,\n        },\n      },\n    }),\n  },\n})\n\nconst Code = sequelize.define('Code', {\n  id: {\n    type: DataTypes.STRING,\n    primaryKey: true,\n  },\n  uid: DataTypes.STRING,\n}, {});\n```\n\n```text\nCode.belongsTo(User, {\n  foreignKey: 'uid',\n  targetKey: 'uid',\n  as: 'user',\n})\n```\n\n```text\nconst randomCode = (provinces) =>\n  Code.findOne({\n    include: [{\n      model: User,\n      as: 'user',\n      scopes: ['activated', {method: ['inProvinces', provinces]}],\n      attributes: [],\n      required: true,\n    }],\n    order: sequelize.random(),\n  })\n```\n\n```text\ninclude\n```\n\n```text\nUser\n```\n\n```text\nCode\n```\n\n```text\nCode\n```\n\n```text\nUser\n```\n\n```text\nuid\n```\n\n```text\nCode\n```\n\n```text\nactivated\n```\n\n```text\ninProvinces\n```\n\n```text\nCode.findOne({\n  include: [{\n    model: User.unscoped() \n  }],\n})\n```\n\n```text\nCode.findOne({\n  include: [{\n    model: User.scope('activated', {method: ['inProvinces', provinces]}) \n  }],\n})\n```\n\n========================================\n\nComments:\n- I don't really get it. Could you elaborate please?","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":184,"estimatedTokens":747}}343{"id":"stack-36396878","source":"stackoverflow","questionId":36396878,"title":"Query junction table without getting both associations in Sequelize","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: Query junction table without getting both associations in Sequelize\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nConsider the following models:\n\n```\nvar User = sequelize.define('User', {\n _id:{\n type: Datatypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: Datatypes.STRING,\n email:{\n type: Datatypes.STRING,\n unique: {\n msg: 'Email Taken'\n },\n validate: {\n isEmail: true\n }\n }\n});\n\nvar Location= sequelize.define('Location', {\n _id:{\n type: Datatypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: Datatypes.STRING,\n address: type: Datatypes.STRING\n});\n\nLocation.belongsToMany(User, {through: 'UserLocation'});\nUser.belongsToMany(Location, {through: 'UserLocation'});\n```\n\nIs there a way to query the `UserLocation` table for a specific `UserId` and get the corresponding `Locations`. Something like:\n\n`SELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8`\n\nFrom what I can find you can do something similar to:\n\n```\nLocation.findAll({\n include: [{\n model: User,\n where: {\n _id: req.user._id\n }\n }]\n}).then( loc => {\n console.log(loc);\n});\n```\n\nHowever, this returns the `Locations`, `UserLocation` junctions, and `User` which it is joining the `User` table when I do not need any user information and I just need the `Locations` for that user. What I have done is working, however, the query against the junction table is prefered instead of the lookup on the `User` table.\n\nI hope this is clear. Thanks in advance.\n\n**Edit**\n\nI actually ended up implementing this in a different way. However, I am still going to leave this as a question because this should be possible.\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {\n  _id:{\n    type: Datatypes.INTEGER,\n    allowNull: false,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: Datatypes.STRING,\n  email:{\n    type: Datatypes.STRING,\n    unique: {\n      msg: 'Email Taken'\n    },\n    validate: {\n      isEmail: true\n    }\n  }\n});\n\nvar Location= sequelize.define('Location', {\n  _id:{\n    type: Datatypes.INTEGER,\n    allowNull: false,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: Datatypes.STRING,\n  address: type: Datatypes.STRING\n});\n\nLocation.belongsToMany(User, {through: 'UserLocation'});\nUser.belongsToMany(Location, {through: 'UserLocation'});\n```\n\n```text\nLocation.findAll({\n  include: [{\n    model: User,\n    where: {\n      _id: req.user._id\n    }\n  }]\n}).then( loc => {\n  console.log(loc);\n});\n```\n\n```text\nUserLocation\n```\n\n```text\nUserId\n```\n\n```text\nLocations\n```\n\n```text\nSELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8\n```\n\n```text\nLocations\n```\n\n```text\nUserLocation\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nLocations\n```\n\n```text\nUser\n```\n\n```text\nvar UserLocation = sequelize.define('UserLocation', {\n  //you can define additional junction props here\n});\n\nUser.belongsToMany(Location, {through: 'UserLocation', foreignKey: 'user_id'});\nLocation.belongsToMany(User, {through: 'UserLocation', foreignKey: 'location_id'});\n```\n\n========================================\n\nComments:\n- Could you provide the way you would use the `UserLocation` table to produce exactly the query the OP is asking about? Thanks.\n- I couldn't try it now because i haven't live sequelize project here. But I am pretty sure that you can use junction table as any other table without harm to relations definition. In worst case you can daclare foreign key columns on UserLocation explicitly, but I guess they are defined on class by sequelized. (Similar to id column, declared automatically, but if you redeclare it explicitly nothihng happens) And after that you should be able use UserLocation as basic foreign key and construct query in same way.\n- This still doesn't let you join one of the association entities with the junction table without the other association entity.","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":175,"estimatedTokens":1006}}344{"id":"stack-55715724","source":"stackoverflow","questionId":55715724,"title":"How to log queries with bounded paramenters in Sequelize?","tags":["sequelize.js"],"text":"Title: How to log queries with bounded paramenters in Sequelize?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize (version 5.3.5) to connect to a postgre database and have configured the logging to use `console.log`, but whenever a query with bounded parameters appears, I am unable to see which parameters are being bound.\n\nThe configuration is very standard.\n\n```\nimport Sequelize from 'sequelize';\nlet db = new Sequelize (\n \"database\", \"username\", \"password\",\n {\n dialect: 'postgres',\n logging: console.log\n }\n);\n```\n\nTaking for example this log of an INSERT operation (inside a transaction):\n\n```\nExecuting (a7ed97b4-66a2-43a2-b4c5-eaa067e7ec28): INSERT INTO \"Entities\" (\"id\",\"type\",\"createdAt\",\"updatedAt\") VALUES ($1,$2,$3,$4) RETURNING *;\n```\n\nIs there a way to make sequelize show me what values are being mapped to `$1` .. `$6`?\n\n========================================\n\nTop Answer:\n**`logQueryParameters: true`**\n\nWe now have this option which does it, usage:\n\n```\nsequelize = new Sequelize({\n dialect: 'sqlite',\n storage: 'tmp.sqlite',\n logQueryParameters: true,\n })\n```\n\nIt outputs something like:\n\n```\nExecuting (default): INSERT INTO `IntegerNames` \n(`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); \n{\"$1\":2,\"$2\":\"two\",\"$3\":\"2022-02-02 10:37:21.618 +00:00\",\"$4\":\"2022-02-02 10:37:21.618 +00:00\"}\n```\n\nFull example:\n\nmain.js\n\n```\n#!/usr/bin/env node\nconst assert = require('assert')\nconst path = require('path')\nconst { DataTypes, Sequelize } = require('sequelize')\nlet sequelize\nif (process.argv[2] === 'p') {\n sequelize = new Sequelize('tmp', undefined, undefined, {\n dialect: 'postgres',\n host: '/var/run/postgresql',\n logQueryParameters: true,\n })\n} else {\n sequelize = new Sequelize({\n dialect: 'sqlite',\n storage: 'tmp.sqlite',\n logQueryParameters: true,\n })\n}\n;(async () => {\nconst IntegerNames = sequelize.define('IntegerNames', {\n value: { type: DataTypes.INTEGER },\n name: { type: DataTypes.STRING },\n});\nawait IntegerNames.sync({ force: true })\nasync function reset() {\n await sequelize.truncate({ cascade: true })\n await IntegerNames.create({ value: 2, name: 'two' })\n await IntegerNames.create({ value: 3, name: 'three' })\n await IntegerNames.create({ value: 5, name: 'five' })\n}\nawait reset()\nlet rows\nrows = await IntegerNames.findAll()\nassert.strictEqual(rows[0].id, 1)\nassert.strictEqual(rows[0].name, 'two')\nassert.strictEqual(rows[0].value, 2)\nassert.strictEqual(rows[1].id, 2)\nassert.strictEqual(rows[1].name, 'three')\nassert.strictEqual(rows[1].value, 3)\nassert.strictEqual(rows[2].id, 3)\nassert.strictEqual(rows[2].name, 'five')\nassert.strictEqual(rows[2].value, 5)\nassert.strictEqual(rows.length, 3)\n})().finally(() => { return sequelize.close() })\n```\n\npackage.json\n\n```\n{\n \"name\": \"tmp\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"dependencies\": {\n \"pg\": \"8.5.1\",\n \"pg-hstore\": \"2.3.3\",\n \"sequelize\": \"6.14.0\",\n \"sqlite3\": \"5.0.2\"\n }\n}\n```\n\noutput:\n\n```\nExecuting (default): DROP TABLE IF EXISTS `IntegerNames`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `IntegerNames` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `value` INTEGER, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`IntegerNames`)\nExecuting (default): DELETE FROM `IntegerNames`\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); {\"$1\":2,\"$2\":\"two\",\"$3\":\"2022-02-02 10:38:54.369 +00:00\",\"$4\":\"2022-02-02 10:38:54.369 +00:00\"}\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); {\"$1\":3,\"$2\":\"three\",\"$3\":\"2022-02-02 10:38:54.379 +00:00\",\"$4\":\"2022-02-02 10:38:54.379 +00:00\"}\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); {\"$1\":5,\"$2\":\"five\",\"$3\":\"2022-02-02 10:38:54.385 +00:00\",\"$4\":\"2022-02-02 10:38:54.385 +00:00\"}\nExecuting (default): SELECT `id`, `value`, `name`, `createdAt`, `updatedAt` FROM `IntegerNames` AS `IntegerNames`;\n```\n\nTested PostgreSQL 13.5.\n\nI couldn't use it when I wanted to indent my queries though: How to indent/pretty print logged queries in sequelize? so I just used the `queryObject.bind` mentioned by Rafael in that case.\n\n========================================\n\nCode:\n```text\nimport Sequelize from 'sequelize';\nlet db = new Sequelize (\n    \"database\", \"username\", \"password\",\n    {\n        dialect: 'postgres',\n        logging: console.log\n    }\n);\n```\n\n```text\nExecuting (a7ed97b4-66a2-43a2-b4c5-eaa067e7ec28): INSERT INTO \"Entities\" (\"id\",\"type\",\"createdAt\",\"updatedAt\") VALUES ($1,$2,$3,$4) RETURNING *;\n```\n\n```text\nconsole.log\n```\n\n```text\n$1\n```\n\n```text\n$6\n```\n\n```text\nimport Sequelize from 'sequelize';\nlet db = new Sequelize (\n    \"database\", \"username\", \"password\",\n    {\n        dialect: 'postgres',\n        logging: customLogger\n    }\n);\n\n\nfunction customLogger ( queryString, queryObject ) {\n    console.log( queryString )      // outputs a string\n    console.log( queryObject.bind ) // outputs an array\n}\n```\n\n```text\n5.19.0\n```\n\n```text\nsequelize = new Sequelize({\n    dialect: 'sqlite',\n    storage: 'tmp.sqlite',\n    logQueryParameters: true,\n  })\n```\n\n```text\nExecuting (default): INSERT INTO `IntegerNames` \n(`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); \n{\"$1\":2,\"$2\":\"two\",\"$3\":\"2022-02-02 10:37:21.618 +00:00\",\"$4\":\"2022-02-02 10:37:21.618 +00:00\"}\n```\n\n```text\n#!/usr/bin/env node\nconst assert = require('assert')\nconst path = require('path')\nconst { DataTypes, Sequelize } = require('sequelize')\nlet sequelize\nif (process.argv[2] === 'p') {\n  sequelize = new Sequelize('tmp', undefined, undefined, {\n    dialect: 'postgres',\n    host: '/var/run/postgresql',\n    logQueryParameters: true,\n  })\n} else {\n  sequelize = new Sequelize({\n    dialect: 'sqlite',\n    storage: 'tmp.sqlite',\n    logQueryParameters: true,\n  })\n}\n;(async () => {\nconst IntegerNames = sequelize.define('IntegerNames', {\n  value: { type: DataTypes.INTEGER },\n  name: { type: DataTypes.STRING },\n});\nawait IntegerNames.sync({ force: true })\nasync function reset() {\n  await sequelize.truncate({ cascade: true })\n  await IntegerNames.create({ value: 2, name: 'two' })\n  await IntegerNames.create({ value: 3, name: 'three' })\n  await IntegerNames.create({ value: 5, name: 'five' })\n}\nawait reset()\nlet rows\nrows = await IntegerNames.findAll()\nassert.strictEqual(rows[0].id, 1)\nassert.strictEqual(rows[0].name, 'two')\nassert.strictEqual(rows[0].value, 2)\nassert.strictEqual(rows[1].id, 2)\nassert.strictEqual(rows[1].name, 'three')\nassert.strictEqual(rows[1].value, 3)\nassert.strictEqual(rows[2].id, 3)\nassert.strictEqual(rows[2].name, 'five')\nassert.strictEqual(rows[2].value, 5)\nassert.strictEqual(rows.length, 3)\n})().finally(() => { return sequelize.close() })\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.14.0\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS `IntegerNames`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `IntegerNames` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `value` INTEGER, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`IntegerNames`)\nExecuting (default): DELETE FROM `IntegerNames`\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); {\"$1\":2,\"$2\":\"two\",\"$3\":\"2022-02-02 10:38:54.369 +00:00\",\"$4\":\"2022-02-02 10:38:54.369 +00:00\"}\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); {\"$1\":3,\"$2\":\"three\",\"$3\":\"2022-02-02 10:38:54.379 +00:00\",\"$4\":\"2022-02-02 10:38:54.379 +00:00\"}\nExecuting (default): INSERT INTO `IntegerNames` (`id`,`value`,`name`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4); {\"$1\":5,\"$2\":\"five\",\"$3\":\"2022-02-02 10:38:54.385 +00:00\",\"$4\":\"2022-02-02 10:38:54.385 +00:00\"}\nExecuting (default): SELECT `id`, `value`, `name`, `createdAt`, `updatedAt` FROM `IntegerNames` AS `IntegerNames`;\n```\n\n```text\nlogQueryParameters: true\n```\n\n```text\nqueryObject.bind\n```\n\n========================================\n\nComments:\n- basically in your code i have tested it prints the complete object of the model that are involved in query by the Variable `queryObject.bind`. Instead if somebody just want to see the bind variable just need to add `logQueryParameters: true` below the logging line in sequelize object creation as defined in the first answer of this thread.","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":284,"estimatedTokens":2167}}345{"id":"stack-28174502","source":"stackoverflow","questionId":28174502,"title":"Sequelize limit include association","tags":["javascript","mysql","sequelize.js"],"text":"Title: Sequelize limit include association\nTags: javascript, mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem with Sequelize when limiting results and including associated models.\n\nThe following produces the correct result, limited by 10 and sorted correctly.\n\n```\nVisit.findAll({\n limit: 10,\n order: 'updatedAt DESC',\n}).success(function(visits) {\n res.jsonp(visits);\n}).failure(function(err) {\n res.jsonp(err);\n})\n```\n\nSQL\n\n```\nSELECT * FROM `Visits` ORDER BY updatedAt DESC LIMIT 10;\n```\n\nHowever when I add an association it suddently limits on the subquery instead and thus the ordering never happens because of a limited result set.\n\n```\nVisit.findAll({\n limit: 10,\n order: 'updatedAt DESC',\n include: [\n { model: Account, required: true }\n ]\n}).success(function(visits) {\n res.jsonp(visits);\n}).failure(function(err) {\n res.jsonp(err);\n})\n```\n\nSQL\n\n```\nSELECT \n `Visits`.* \nFROM \n (SELECT \n `Visits`.*, `Account`.`id` AS `Account.id`, `Account`.`email` AS `Account.email`, `Account`.`password` AS `Account.password`, `Account`.`role` AS `Account.role`, `Account`.`active` AS `Account.active`, `Account`.`createdAt` AS `Account.createdAt`, `Account`.`updatedAt` AS `Account.updatedAt`, `Account`.`practice_id` AS `Account.practice_id` \n FROM \n `Visits` INNER JOIN `Accounts` AS `Account` ON `Account`.`id` = `visits`.`account_id` LIMIT 10) AS `visits` \nORDER BY updatedAt DESC;\n```\n\nWhat I'm was expecting was having the limit on the top query as so:\n\n```\nSELECT \n ...\nFROM \n (SELECT ...) AS `Visits`\nORDER BY `Visits`.updatedAt DESC LIMIT 10\nLIMIT 10;\n```\n\n========================================\n\nTop Answer:\n- order field key model `order: ['FieldOrder', 'DESC']`\n\nex:\n\n```\ndb.ModelA.findAll({\n include: [{\n model: db.ModelB\n }],\n order: ['CreatedDateModelA', 'DESC']\n})\n.then(function(response){\n}, function(err){\n})\n```\n\norder field include model \n`order: [ModelInclude,'FieldOrder', 'DESC']`\n\nex: \n\n```\ndb.ModelA.findAll({\n include: [{\n model: db.ModelB\n }],\n order: [db.ModelB,'CreatedDateModelA', 'DESC']\n})\n.then(function(response){\n\n}, function(err){\n\n})\n```\n\n========================================\n\nCode:\n```text\nVisit.findAll({\n  limit: 10,\n  order: 'updatedAt DESC',\n}).success(function(visits) {\n  res.jsonp(visits);\n}).failure(function(err) {\n  res.jsonp(err);\n})\n```\n\n```text\nSELECT * FROM `Visits` ORDER BY updatedAt DESC LIMIT 10;\n```\n\n```text\nVisit.findAll({\n  limit: 10,\n  order: 'updatedAt DESC',\n  include: [\n    { model: Account, required: true }\n  ]\n}).success(function(visits) {\n  res.jsonp(visits);\n}).failure(function(err) {\n  res.jsonp(err);\n})\n```\n\n```text\nSELECT \n  `Visits`.* \nFROM \n  (SELECT \n    `Visits`.*, `Account`.`id` AS `Account.id`, `Account`.`email` AS `Account.email`, `Account`.`password` AS `Account.password`, `Account`.`role` AS `Account.role`, `Account`.`active` AS `Account.active`, `Account`.`createdAt` AS `Account.createdAt`, `Account`.`updatedAt` AS `Account.updatedAt`, `Account`.`practice_id` AS `Account.practice_id` \n  FROM \n    `Visits` INNER JOIN `Accounts` AS `Account` ON `Account`.`id` = `visits`.`account_id` LIMIT 10) AS `visits` \nORDER BY updatedAt DESC;\n```\n\n```text\nSELECT \n  ...\nFROM \n  (SELECT ...) AS `Visits`\nORDER BY `Visits`.updatedAt DESC LIMIT 10\nLIMIT 10;\n```\n\n```text\norder: ['updatedAt', 'DESC']\n```\n\n```js\n'use strict';\n\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize(\n    'test', // database\n    'test', // username\n    'test', // password\n    {\n        host: 'localhost',\n        dialect: 'postgres'\n    }\n);\n\nvar Customer = sequelize.define('Customer', {\n    firstName: {type: Sequelize.STRING},\n    lastName: {type: Sequelize.STRING}\n});\n\nvar Order = sequelize.define('Order', {\n    amount: {type: Sequelize.FLOAT}\n});\n\nvar firstCustomer;\n\nCustomer.hasMany(Order, {constraints: true});\nOrder.belongsTo(Customer, {constraints: true});\n\nsequelize.sync({force: true})\n    .then(function () {\n        return Customer.create({firstName: 'Test', lastName: 'Testerson'});\n    })\n    .then(function (author1) {\n        firstCustomer = author1;\n        return Order.create({CustomerId: firstCustomer.id, amount: 10});\n    })\n    .then(function () {\n        return Order.create({CustomerId: firstCustomer.id, amount: 20})\n    })\n    .then(function () {\n        return Order.findAll({\n            limit: 10,\n            include: [Customer],\n            order: [\n                ['updatedAt', 'DESC']\n            ]\n        });\n    })\n    .then(function displayResults(results) {\n        results.forEach(function (c) {\n            console.dir(c.toJSON());\n        });\n    })\n    .then(function () {\n        process.exit(0);\n    });\n```\n\n```sql\nSELECT \"Order\".\"id\", \"Order\".\"amount\", \"Order\".\"createdAt\", \"Order\".\"updatedAt\", \"Order\".\"CustomerId\", \"Customer\".\"id\" AS \"Customer.id\", \"Customer\".\"firstName\" AS \"Customer.firstName\", \"Customer\".\"lastName\" AS \"Customer.lastName\", \"Customer\".\"createdAt\" AS \"Customer.createdAt\", \"Customer\".\"updatedAt\" AS \"Customer.updatedAt\" FROM \"Orders\" AS \"Order\" LEFT OUTER JOIN \"Customers\" AS \"Customer\" ON \"Order\".\"CustomerId\" = \"Customer\".\"id\" ORDER BY \"Order\".\"updatedAt\" DESC LIMIT 10;\n```\n\n```text\nusername DESC\n```\n\n```text\ndb.ModelA.findAll({\n    include: [{\n        model: db.ModelB\n    }],\n    order: ['CreatedDateModelA', 'DESC']\n})\n.then(function(response){\n}, function(err){\n})\n```\n\n```text\ndb.ModelA.findAll({\n    include: [{\n        model: db.ModelB\n    }],\n    order: [db.ModelB,'CreatedDateModelA', 'DESC']\n})\n.then(function(response){\n\n}, function(err){\n\n})\n```\n\n```text\norder: ['FieldOrder', 'DESC']\n```\n\n```text\norder: [ModelInclude,'FieldOrder', 'DESC']\n```\n\n========================================\n\nComments:\n- I have the same problem as above and if I try the above solution it adds an order by clause both in the subquery and outside of it. Outside of the subquery fails with an error ofcourse 'unknown column ... in order clause'.\n- Not sure why this is the accepted answer, even though there was indeed a problem with the 'order'. To avoid the subquery and keep LIMIT at the end, you either need to call findAll({ subQuery: false, ...}), or findAll({include: { duplicating: false, ...}). See also stackoverflow.com/questions/26021965/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":265,"estimatedTokens":1556}}346{"id":"stack-26581715","source":"stackoverflow","questionId":26581715,"title":"Sequelize update does not work anymore: \"Missing where attribute in the options parameter passed to update\"","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize update does not work anymore: \"Missing where attribute in the options parameter passed to update\"\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe official API documentation suggests using `Model.update` like this:\n\n```\nvar gid = ...;\nvar uid = ...;\n\nvar values = { gid: gid };\nvar where = { uid: uid };\nmyModel.update(values, where)\n.then(function() {\n // update callback\n});\n```\n\nBut this gives me: \"Missing where attribute in the options parameter passed to update\".\nThe docs also mention that this usage is deprecated. Seeing this error makes me think, they already changed it. What am I doing wrong?\n\n========================================\n\nCode:\n```text\nvar gid = ...;\nvar uid = ...;\n\nvar values = { gid: gid };\nvar where = { uid: uid };\nmyModel.update(values, where)\n.then(function() {\n    // update callback\n});\n```\n\n```text\nModel.update\n```\n\n```text\nvar gid = ...;\nvar uid = ...;\n\nvar values = { \n  gid\n};\nvar selector = { \n  where: {\n    uid\n  }\n};\nawait myModel.update(values, selector);\n// done!\n```\n\n```text\nwhere\n```\n\n```text\nModel.update\n```\n\n```text\nwhere\n```\n\n```text\noptions.where\n```\n\n========================================\n\nComments:\n- Your link is not linking to the docs\n- Thanks @J.Kirk. - Fixed it! It was the right link at some point (a long long time ago) :/\n- This belongs in their migration guide.\n- I wonder why such an important information is not in the doc.. Maybe I shouldn't be using sequelize?\n- @SoichiHayashi Actually, it has been added to the docs for a while. I updated my answer with the link :)","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":397}}347{"id":"stack-48376479","source":"stackoverflow","questionId":48376479,"title":"Executing Multiple Sequelize JS model query methods with Promises - Node","tags":["node.js","express","sequelize.js","mean-stack","sequelize-cli"],"text":"Title: Executing Multiple Sequelize JS model query methods with Promises - Node\nTags: node.js, express, sequelize.js, mean-stack, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am having a problem retrieving data from database using sequelize js. I am new to NODEJS. I don't know if Promise and Promise.all are built in functions \nSo i install and require npm promise in my code too.\nBelow is my code.\n\n```\nvar Promise = require('promise');\n\nvar user_profile = new Promise(function(resolve, reject) {\n db.user_profile.findOne({\n where: {\n profile_id: new_profile_id\n }\n }).then(user => {\n console.log('Summary Result User found.');\n resolve(user);\n });\n});\n\nvar all_reports = new Promise(function(resolve, reject) {\n db.report.all().then(reports => {\n console.log('Summary Result Reports found.');\n resolve(reports);\n });\n});\n\nvar report_details = new Promise(function(resolve, reject) {\n db.report_detail.findAll({\n where: {\n profile_id: new_profile_id\n }\n }).then(report_details => {\n console.log('Summary Result Report Details found');\n resolve(report_details);\n });\n});\n\nvar all_promises = Promise.all([user_profile, all_reports, report_details]).then(function(data) {\n console.log('**********COMPLETE RESULT****************');\n console.log(data);\n}).catch(err => {\n console.log('**********ERROR RESULT****************');\n console.log(err);\n});\n```\n\nI want to get the data of all three queries. When i run them individually I get the data but when i run them in Promise.all I only get user_profile data and other two remain **undefined**\nI have also tried nested these queries with .then but result is still same I only get one query data other two remain **undefined**\n\n**with then chainging**\n\n```\nvar results = [];\nvar new_profile_id = req.params.profile_id;\nconsole.log(new_profile_id);\ndb.user_profile.findOne({\n where: {\n profile_id: new_profile_id\n }\n}).then(user => {\n console.log('Summary Result User found.');\n results.push(user.dataValues);\n return user;\n}).then(user => {\n db.report.all().then(reports => {\n console.log('Summary Result Reports found.');\n results.push(reports.dataValues);\n return reports\n });\n}).then(reports => {\n db.report_detail.findAll({\n where: {\n profile_id: new_profile_id\n }\n }).then(report_details => {\n console.log('Summary Result Report Details found');\n results.push(report_details.dataValues);\n console.log('**********COMPLETE RESULT****************');\n console.log(results);\n console.log('**********COMPLETE RESULT****************');\n return report_details;\n });\n});\n```\n\ncan someone please help me in this concept what i am doing wrong.\nThanks\n\n========================================\n\nCode:\n```text\nvar Promise = require('promise');\n\nvar user_profile = new Promise(function(resolve, reject) {\n    db.user_profile.findOne({\n        where: {\n            profile_id: new_profile_id\n        }\n    }).then(user => {\n        console.log('Summary Result User found.');\n        resolve(user);\n    });\n});\n\nvar all_reports = new Promise(function(resolve, reject) {\n    db.report.all().then(reports => {\n        console.log('Summary Result Reports found.');\n        resolve(reports);\n    });\n});\n\nvar report_details = new Promise(function(resolve, reject) {\n    db.report_detail.findAll({\n        where: {\n            profile_id: new_profile_id\n        }\n    }).then(report_details => {\n        console.log('Summary Result Report Details found');\n        resolve(report_details);\n    });\n});\n\nvar all_promises = Promise.all([user_profile, all_reports, report_details]).then(function(data) {\n    console.log('**********COMPLETE RESULT****************');\n    console.log(data);\n}).catch(err => {\n    console.log('**********ERROR RESULT****************');\n    console.log(err);\n});\n```\n\n```text\nvar results = [];\nvar new_profile_id = req.params.profile_id;\nconsole.log(new_profile_id);\ndb.user_profile.findOne({\n    where: {\n        profile_id: new_profile_id\n    }\n}).then(user => {\n    console.log('Summary Result User found.');\n    results.push(user.dataValues);\n    return user;\n}).then(user => {\n    db.report.all().then(reports => {\n        console.log('Summary Result Reports found.');\n        results.push(reports.dataValues);\n        return reports\n    });\n}).then(reports => {\n    db.report_detail.findAll({\n        where: {\n            profile_id: new_profile_id\n        }\n    }).then(report_details => {\n        console.log('Summary Result Report Details found');\n        results.push(report_details.dataValues);\n        console.log('**********COMPLETE RESULT****************');\n        console.log(results);\n        console.log('**********COMPLETE RESULT****************');\n        return report_details;\n    });\n});\n```\n\n```text\nconst user_profile = db.user_profile.findOne({\n    where: {\n        profile_id: new_profile_id\n    }\n});\n\nconst all_reports = db.report.all();\n\nconst report_details = db.report_detail.findAll({\n    where: {\n        profile_id: new_profile_id\n    }\n});\n\nPromise\n    .all([user_profile, all_reports, report_details])\n    .then(responses => {\n        console.log('**********COMPLETE RESULTS****************');\n        console.log(responses[0]); // user profile\n        console.log(responses[1]); // all reports\n        console.log(responses[2]); // report details\n    })\n    .catch(err => {\n        console.log('**********ERROR RESULT****************');\n        console.log(err);\n    });\n```\n\n```text\nPromise\n```\n\n```text\nSequelize\n```\n\n```text\npromise\n```\n\n```text\nPromise\n```\n\n```text\ncatch\n```\n\n```text\nPromise.all()\n```\n\n```text\nresolve\n```\n\n```text\nPromise.all()\n```\n\n========================================\n\nComments:\n- @Eye Can you help me?. I have a doubt in using sequelize in node js. I couldn't build the large logic with sequelize. Can you send your mail, I'll send my code. my email: sakkeer@brigita.co\n- Really nice way to get the responses. I just used in on my projects and works well, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":236,"estimatedTokens":1473}}348{"id":"stack-32212945","source":"stackoverflow","questionId":32212945,"title":"Sequelize - findOne().success() is undefined","tags":["javascript","node.js","passport.js","sequelize.js"],"text":"Title: Sequelize - findOne().success() is undefined\nTags: javascript, node.js, passport.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am following the passport.js doc in order to create a LocalStrategy using Sequelize as ORM for my postgres database. However, during authentification, doing `User.findOne(...).success(function(user){...]});` in my login.js module returns `undefined`. What am I doing wrong?\n\nuser.js:\n\n```\nvar pg = require('pg');\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('database', 'username', 'password', {\n host: 'localhost',\n port: 5432,\n dialect: 'postgres'\n});\n\nvar User = sequelize.define('users', {\n username: Sequelize.STRING,\n password: Sequelize.STRING\n\n});\n\nUser.sync();\n\nmodule.exports = User;\n```\n\nmy login.js (router)\n\n```\nvar express = require('express');\nvar router = express.Router();\nvar passport = require('passport');\nvar LocalStrategy = require('passport-local').Strategy;\n\npassport.serializeUser(function(user, done){\n done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done){\n console.log(id)\n User.findById(id, function(err, user){\n done(err, user);\n });\n});\n\npassport.use(new LocalStrategy(\n function(username, password, done){\n var User = require('../models/user');\n User.find({where:{username: username, password: password}}).success(function(user){\n if(!user) {\n return done(null, false, {message: 'Nom d\\'usager incorrect.' });\n }\n if (!user.validPassword(password)) {\n return done(null, false, { message: 'Mot de passe incorrect.' });\n }\n return done(null, user);\n });\n }\n));\n\nrouter.post('/login', passport.authenticate('local', { successRedirect: '/decoupage',\n failureRedirect: '/login',\n failureFlash: true })\n);\n\nmodule.exports = router;\n```\n\n========================================\n\nCode:\n```text\nvar pg = require('pg');\nvar Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize('database', 'username', 'password', {\n    host: 'localhost',\n    port: 5432,\n    dialect: 'postgres'\n});\n\nvar User = sequelize.define('users', {\n    username: Sequelize.STRING,\n    password: Sequelize.STRING\n\n});\n\nUser.sync();\n\nmodule.exports = User;\n```\n\n```text\nvar express = require('express');\nvar router = express.Router();\nvar passport = require('passport');\nvar LocalStrategy = require('passport-local').Strategy;\n\n\npassport.serializeUser(function(user, done){\n    done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done){\n    console.log(id)\n    User.findById(id, function(err, user){\n        done(err, user);\n    });\n});\n\npassport.use(new LocalStrategy(\n    function(username, password, done){\n        var User = require('../models/user');\n        User.find({where:{username: username, password: password}}).success(function(user){\n            if(!user) {\n                return done(null, false, {message: 'Nom d\\'usager incorrect.' });\n            }\n            if (!user.validPassword(password)) {\n                return done(null, false, { message: 'Mot de passe incorrect.' });\n            }\n            return done(null, user);\n        });\n    }\n));\n\nrouter.post('/login', passport.authenticate('local', { successRedirect: '/decoupage',\n                                                       failureRedirect: '/login',\n                                                       failureFlash: true })\n);\n\n\nmodule.exports = router;\n```\n\n```text\nUser.findOne(...).success(function(user){...]});\n```\n\n```text\nundefined\n```\n\n```text\nUser.find(options).then(\n  function(user) { ... },\n  function(err) { ... }\n);\n```\n\n```text\nbluebird\n```\n\n```text\n.success()\n```\n\n```text\n.then()\n```\n\n========================================\n\nComments:\n- You should accept the @robertklep answer wich is correct.\n- @abhishek, Current versions of `sequelize` use the stock version of `bluebird`. To catch errors use `.catch` or `.error`. Documentation can be found here.","metadata":{"transformedAt":"2026-08-18T18:33:34.367Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":170,"estimatedTokens":966}}349{"id":"stack-61762127","source":"stackoverflow","questionId":61762127,"title":"Sequelize - Adding a limit to a query with an include, fails to properly limit retrievals","tags":["mysql","node.js","sequelize.js","serverless-framework"],"text":"Title: Sequelize - Adding a limit to a query with an include, fails to properly limit retrievals\nTags: mysql, node.js, sequelize.js, serverless-framework\nSource: Stack Overflow\n\nQuestion:\n### Issue Description\n\nAdding a limit to a Sequelize Query with a SubQuery fails to limit retrievals. Multiple online resources referencing this error and no solutions. Is this a Sequelize error or user error?\n\n### What are you doing?\n\n```\nThreadFolderUser.findAll({\norder: [\n ['updated_at', 'DESC']\n],\nwhere: {\n user_id,\n folder_id,\n deleted,\n archived,\n},\ndistinct: true,\noffset,\nlimit: 10,\ninclude: [\n {\n model: Thread,\n include: [\n { model: Email, include: [Attachment] },\n ]\n }\n],\n```\n\n})\n\n### Associations\n\n```\n// ThreadFolderUser (assoc table) - Thread / Folder / User (tables)\nUser.hasMany(ThreadFolderUser, { foreignKey: 'user_id' })\nThreadFolderUser.belongsTo(User, { foreignKey: 'user_id' })\nFolder.hasMany(ThreadFolderUser, { foreignKey: 'folder_id' })\nThreadFolderUser.belongsTo(Folder, { foreignKey: 'folder_id' })\nThread.hasMany(ThreadFolderUser, { foreignKey: 'thread_id' })\nThreadFolderUser.belongsTo(Thread, { foreignKey: 'thread_id' })\n\n// Thread - Emails\nThread.hasMany(Email, { foreignKey: 'thread_id' })\nEmail.belongsTo(Thread, { foreignKey: 'thread_id' })\n\n// Email - Attachments\nEmail.hasMany(Attachment, { foreignKey: 'email_id' })\nAttachment.belongsTo(Email, { foreignKey: 'email_id' })\n```\n\n### What do you expect to happen?\n\nI expected 10 records (based on the limit currently set to 10) retrieved from the AssociationTable, since I have at least 15 records in the database that match this query. \n\n### What is actually happening?\n\nReturns 6 in my case, instead of 10 (with the limit set to 10). Instead of pulling the first 10 matches.\n\n### Additional context\n\nIf I remove the **limit**, it works as intended (even with the includes).\n\nIf I remove the **include**, it works as intended (even with the limit). \n\n**If I copy/paste the SQL Query generated by Sequelize and insert it directly into Workbench, it retrieves the proper amount of rows.**\n\nIt seems the issue is the **limit** combined with the **include** cause the query to retrieve only the records that match within the first 10 searched in the DB.\n\nOther references to the same issue without a proper solution presented:\n\nhttps://github.com/sequelize/sequelize/issues/7344\n\nhttps://github.com/sequelize/sequelize/issues/7585\n\nSequelize limit include association\n\n### Environment\n\n- Sequelize version: v5.21.3\n\n- Node.js version: v12.13.1\n\n- Operating System: AWS Lambda Function\n\n- TypeScript version: 3.7.2\n\nI'm well aware that this exact same issue has been brought up in multiple other threads and platforms -- as I have linked a few of them above -- however none of them have a direct answer, and 1 of them marked an irrelevant point as the answer which did not solve the intended issue. I'm hoping we can get an answer to this, or a realistic workaround beyond hard coding the SQL Query (last resort). \n\nIt would be unthinkable for Sequelize not to be able to handle a limit with an include in the same query, so there must be something missing / user error on my side. I've searched multiple times and certainly started with Sequelize documentation, of which does not reference this issue or a similar example, or any problems that may arise with combining a limit and include. \n\nMany thanks for any contributions made to help solve this issue. Hopefully some @Sequelize Engineer is out there able to help answer this :)\n\n========================================\n\nTop Answer:\nAdding foreign key in the `attribute` array should do the trick.\n\n```\ninclude: [\n {\n model: ModelName,\n attributes: [...otherAttributes, foreignKey]\n } \n]\n```\n\nWorks fine in my case.\n\n========================================\n\nCode:\n```text\nThreadFolderUser.findAll({\norder: [\n  ['updated_at', 'DESC']\n],\nwhere: {\n  user_id,\n  folder_id,\n  deleted,\n  archived,\n},\ndistinct: true,\noffset,\nlimit: 10,\ninclude: [\n  {\n    model: Thread,\n    include: [\n      { model: Email, include: [Attachment] },\n    ]\n  }\n],\n```\n\n```text\n// ThreadFolderUser (assoc table) - Thread / Folder / User (tables)\nUser.hasMany(ThreadFolderUser, { foreignKey: 'user_id' })\nThreadFolderUser.belongsTo(User, { foreignKey: 'user_id' })\nFolder.hasMany(ThreadFolderUser, { foreignKey: 'folder_id' })\nThreadFolderUser.belongsTo(Folder, { foreignKey: 'folder_id' })\nThread.hasMany(ThreadFolderUser, { foreignKey: 'thread_id' })\nThreadFolderUser.belongsTo(Thread, { foreignKey: 'thread_id' })\n\n// Thread - Emails\nThread.hasMany(Email, { foreignKey: 'thread_id' })\nEmail.belongsTo(Thread, { foreignKey: 'thread_id' })\n\n// Email - Attachments\nEmail.hasMany(Attachment, { foreignKey: 'email_id' })\nAttachment.belongsTo(Email, { foreignKey: 'email_id' })\n```\n\n```text\ninclude: [\n      { \n       model: Email, \n       separate: true,\n       include: [{\n         model: Attachment,\n         separate: true\n       }] },\n    ]\n```\n\n```text\ninclude: [\n  {\n    model: ModelName,\n    attributes: [...otherAttributes, foreignKey]\n   } \n]\n```\n\n```text\nattribute\n```\n\n========================================\n\nComments:\n- Show association definitions\n- @Anatoly - thanks, added them.\n- where is an association for AssociationModel?\n- @Anatoly updated - I was trying to use generic names to keep it simple and forgot when adding associations it would need updating.\n- This is an amazing answer, and I have yet to see anything remotely close to a logical answer such as this. Thank you for providing the solution and most importantly explaining why it works this way. I am dealing with a large database, over 10 million email records (individual records in 1 table) from an old DB, of which I'll be creating a script to convert them into threads connected to relative emails and attachments. Due to this I'm hoping the JOIN statements won't be anywhere near the 100*100*100, but point well taken and I think I understand it, I'll keep an eye on this.\n- To confirm if understand this right, if I'm pulling 20 threads, with an average of 15 emails each and an average of 5 attachments each that would be a query of 1500? Or will it actually be pulling (all matching threads) * (all matching emails on those threads) * (all matching attachments on this emails) and then limiting down to the main 20, so potentially my queries will always be pulling a lot more records before filtering down to the main 20 limit/offset - am I correct on this thinking?\n- So my concern will be the main query's where statement to ensure its only pulling the necessary association records, in this case, the association records specific to that 1) user and 2) mailbox (of which I've named folder), so if there are 500 records matching this user/folder combination, it will always start at 500 * matching Emails to the 500 * matching Attachments to the Emails - and then pair down to the limit and offset, is correct?\n- If you indicate `separate: true` then you'll get 20 threads (1 query with 20 threads only filtered and limited), then 20 separate queries to get emails then 20*5 separate queries to get attachments.\n- Emails and attachments will be queried only for already filtered and limited threads\n- I created a little video to help explain this concept. loom.com//33bea5a0111a4b54913deb51506c6622\n- @RyanShillington The video is about many-to-many and this question is about 2 simultaneous 1:N from one table to two other tables. It still could be useful though when you use `belongsToMany` you can't do separate queries using `separate: true` option.\n- @Anatoly True! The problem is easier when only using `belongsTo`.\n- Using a view at the database layer might solve this issue for you. When you pull n number of denormalized rows out of the view, you will in fact get the n number of rows which you expect.","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":201,"estimatedTokens":1951}}350{"id":"stack-75821524","source":"stackoverflow","questionId":75821524,"title":"Node.js Sequelize: Cannot delete property 'meta' of [object Array]","tags":["javascript","node.js","database","sequelize.js"],"text":"Title: Node.js Sequelize: Cannot delete property 'meta' of [object Array]\nTags: javascript, node.js, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm learning the Sequelize.js framework and it's pretty awesome. But when I try to remove a column from my test tables in in my migration file, I get this error:\n\n`ERROR: Cannot delete property 'meta' of [object Array]`\n\nThis error occurs when I use the removeColumn function from the query interface but I don't have an idea why ...\n\nMy migration file:\n\n```\n'use strict';\n\nconst {DataTypes} = require(\"sequelize\");\n/** @type {import('sequelize-cli').Migration} */\nmodule.exports = {\n async up (queryInterface, Sequelize) {\n return queryInterface.sequelize.transaction(t => {\n return Promise.all([\n queryInterface.removeColumn('Students', 'bloodStatus', {transaction: t}),\n ]);\n });\n },\n\n async down (queryInterface, Sequelize) {\n return queryInterface.sequelize.transaction(t => {\n return Promise.all([\n queryInterface.addColumn('Students', 'bloodStatus', {\n type: DataTypes.STRING,\n allowNull: false\n }, {transaction: t}),\n ]);\n });\n }\n};\n```\n\nI used the migration file above but I get the error\n\n```\nERROR: Cannot delete property 'meta' of [object Array]\n```\n\nI read the documentation and tried to find a solution, but unfortunately I can't find one.\n\n========================================\n\nTop Answer:\nWhile the solution from Chipmaster5 works, I think it's a bad idea to use mysql dialect, if you're using a mariadb image. Specifically this problem seems to be introduced with v3 of the mariadb package, reverting to 2.x resolved the problem for me.\n\n========================================\n\nCode:\n```js\n'use strict';\n\nconst {DataTypes} = require(\"sequelize\");\n/** @type {import('sequelize-cli').Migration} */\nmodule.exports = {\n  async up (queryInterface, Sequelize) {\n    return queryInterface.sequelize.transaction(t => {\n      return Promise.all([\n        queryInterface.removeColumn('Students', 'bloodStatus', {transaction: t}),\n      ]);\n    });\n  },\n\n  async down (queryInterface, Sequelize) {\n    return queryInterface.sequelize.transaction(t => {\n      return Promise.all([\n        queryInterface.addColumn('Students', 'bloodStatus', {\n          type: DataTypes.STRING,\n          allowNull: false\n        }, {transaction: t}),\n      ]);\n    });\n  }\n};\n```\n\n```text\nERROR: Cannot delete property 'meta' of [object Array]\n```\n\n```text\nERROR: Cannot delete property 'meta' of [object Array]\n```\n\n```js\n{\n  \"development\": {\n    \"username\": \"christian_cornwall\",\n    \"password\": \"hogwarts\",\n    \"database\": \"hogwarts_sequelize\",\n    \"host\": \"172.17.0.3\",\n    \"dialect\": \"mariadb\"\n  },\n  \"test\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"database\": \"database_test\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mariadb\"\n  },\n  \"production\": {\n    \"username\": \"root\",\n    \"password\": null,\n    \"database\": \"database_production\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mariadb\"\n  }\n}\n```\n\n```bash\n% node migrate.js\nRunning migrations...\n{ event: 'migrating', name: '20230628090200-drop-column-id.js' }\nDropping column memberServiceId from table member_service_node\n/myproject/node_modules/umzug/lib/umzug.js:151\n                    throw new MigrationError({ direction: 'up', ...params }, e);\n                          ^\nMigrationError: Migration 20230628090200-drop-column-id.js (up) failed: Original error: Cannot delete property 'meta' of [object Array]\n    at /myproject/node_modules/umzug/lib/umzug.js:151:27\n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n    at async Umzug.runCommand (/myproject/node_modules/umzug/lib/umzug.js:107:20)\n    at async file:///myproject/data/migrate.js:105:3 {\n  cause: TypeError: Cannot delete property 'meta' of [object Array]\n      at Query.formatResults (/myproject/node_modules/sequelize/lib/dialects/mariadb/query.js:110:7)\n      at Query.run (/myproject/node_modules/sequelize/lib/dialects/mariadb/query.js:73:17)\n      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n      at async /myproject/node_modules/sequelize/lib/sequelize.js:315:16\n      at async MySQLQueryInterface.removeColumn (/myproject/node_modules/sequelize/lib/dialects/mysql/query-interface.js:27:23)\n```\n\n```bash\nnpm install mariadb@2 --save\n```\n\n```text\nqueryInterface.sequelize.query([raw query]\n```\n\n```text\nconst data = await Seq.query(\"SELECT * FROM storeImgs\", **{ type: Seq.QueryTypes.SELECT }** );\n```\n\n========================================\n\nComments:\n- Thanks. I have the exact problem. Sequelize 6. What bothers is that mariadb package and dialect works fine in the application only failed in migration. Good catch.\n- Great :) it worked perfectly with `\"mariadb\": \"^3.3.1\"`. I prefer this over reverting to mariadb v2.x.x.","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":155,"estimatedTokens":1198}}351{"id":"stack-57707798","source":"stackoverflow","questionId":57707798,"title":"Setting default value on sequelize ENUM type","tags":["postgresql","sequelize.js","database-migration"],"text":"Title: Setting default value on sequelize ENUM type\nTags: postgresql, sequelize.js, database-migration\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to set default value on a column with type `ENUM`, however if i set the `defaultValue` to `\"employee\"` which is one of the values of the enum, I get the below error message: \n\n```\n$ npx sequelize db:migrate\n\nSequelize CLI [Node: 10.16.0, CLI: 5.5.0, ORM: 5.15.1]\n\nLoaded configuration file \"src\\config\\config.js\".\nUsing environment \"development\".\n== 20190824180419-create-user: migrating =======\n\nERROR: invalid input value for enum \"enum_Users_role\": \"employee\"\n```\n\nFind bellow my user migration file definition\n\n```\n20190824180419-create-user.js\n\nexport default {\n up: (queryInterface, Sequelize) => queryInterface.createTable('Users', {\n uuid: {\n allowNull: false,\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4,\n },\n email: {\n type: Sequelize.STRING\n },\n password: {\n type: Sequelize.STRING\n },\n name: {\n type: Sequelize.STRING\n },\n role: {\n type: Sequelize.ENUM,\n values: ['employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'],\n defaultValue: 'employee'\n }\n}),\ndown: queryInterface => queryInterface.dropTable('Users')\n```\n\n};\n\nFind bellow my user model file definition:\n\n```\nuser.js\n\nexport default (sequelize, DataTypes) => {\n const User = sequelize.define('User', {\n uuid: {\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV4,\n primaryKey: true\n },\n email: DataTypes.STRING,\n password: DataTypes.STRING,\n name: DataTypes.STRING,\n role: {\n type: DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),\n defaultValue: 'employee'\n }\n }, {});\n User.associate = () => {\n // associations can be defined here\n };\n return User;\n};\n```\n\n**Package versions:**\n\n```\nnode: v10.16.0\nnpm: 6.9.0\nsequelize: 5.15.1\nsequelize-cli: 5.5.0\n```\n\n========================================\n\nTop Answer:\nCan you remove the `defaultValue` in the model and change the format as @rkm mentioned. So you have something like this:\n\n```\nrole: DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),\n```\n\nand in your migration file as:\n\n```\nrole: {\n type: Sequelize.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),\ndefaultValue: 'employee'\n }\n```\n\n========================================\n\nCode:\n```text\n$ npx sequelize db:migrate\n\nSequelize CLI [Node: 10.16.0, CLI: 5.5.0, ORM: 5.15.1]\n\nLoaded configuration file \"src\\config\\config.js\".\nUsing environment \"development\".\n== 20190824180419-create-user: migrating =======\n\nERROR: invalid input value for enum \"enum_Users_role\": \"employee\"\n```\n\n```text\n20190824180419-create-user.js\n\n\nexport default {\n  up: (queryInterface, Sequelize) => queryInterface.createTable('Users', {\n    uuid: {\n    allowNull: false,\n    primaryKey: true,\n    type: Sequelize.UUID,\n    defaultValue: Sequelize.UUIDV4,\n  },\n  email: {\n    type: Sequelize.STRING\n  },\n  password: {\n    type: Sequelize.STRING\n  },\n  name: {\n    type: Sequelize.STRING\n  },\n  role: {\n    type: Sequelize.ENUM,\n    values: ['employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'],\n    defaultValue: 'employee'\n  }\n}),\ndown: queryInterface => queryInterface.dropTable('Users')\n```\n\n```text\nuser.js\n\nexport default (sequelize, DataTypes) => {\n  const User = sequelize.define('User', {\n    uuid: {\n      type: DataTypes.UUID,\n      defaultValue: DataTypes.UUIDV4,\n      primaryKey: true\n    },\n    email: DataTypes.STRING,\n    password: DataTypes.STRING,\n    name: DataTypes.STRING,\n    role: {\n      type: DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),\n      defaultValue: 'employee'\n     }\n  }, {});\n  User.associate = () => {\n   // associations can be defined here\n  };\n  return User;\n};\n```\n\n```text\nnode: v10.16.0\nnpm: 6.9.0\nsequelize: 5.15.1\nsequelize-cli: 5.5.0\n```\n\n```text\nENUM\n```\n\n```text\ndefaultValue\n```\n\n```text\n\"employee\"\n```\n\n```text\n{\n  type: Sequelize.DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),\n  defaultValue: 'employee',\n}\n```\n\n```text\nENUM\n```\n\n```text\nrole: {\n    type: Sequelize.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', \n          'manager', 'supplier'),\n    defaultValue: 'employee'\n}\n```\n\n```text\nrole: DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),\n```\n\n```text\nrole: {\n      type: Sequelize.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),\ndefaultValue: 'employee'\n     }\n```\n\n```text\ndefaultValue\n```\n\n========================================\n\nComments:\n- I am getting error `SequelizeDatabaseError: invalid input value for enum`","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":233,"estimatedTokens":1223}}352{"id":"stack-41502699","source":"stackoverflow","questionId":41502699,"title":"Return flat object from sequelize with association","tags":["json","sequelize.js","flatten"],"text":"Title: Return flat object from sequelize with association\nTags: json, sequelize.js, flatten\nSource: Stack Overflow\n\nQuestion:\nI am working on converting all my queries in sequelize. \nThe problem I have come across is that when select queries include associations (ex. one to many), the object I get is an array of nested objects.\n\nIt looks something like:\n\n```\n[ \n {\n \"field1\": \"someval\",\n \"field2\": \"someval1\",\n \"assoc_table\": {\n \"field_a\": 1,\n \"field_b\": \"someval\"\n } \n }, \n {\n \"field1\": \"someval\",\n \"field2\": \"someval3\",\n \"assoc_table\": {\n \"field_a\": 5,\n \"field_b\": \"someval\"\n } \n }, \n {\n \"field1\": \"someval\",\n \"field2\": \"someval3\",\n \"assoc_table\": {\n \"field_a\": 12,\n \"field_b\": \"someval\"\n } \n } \n]\n```\n\nI tried to use different modules to flatten the objects (inside a loop, each object individually), but I always got an error telling that what I was trying to flatten were not just objects.\n\nMoreover, I would prefer avoiding the part where objects are flattened, and simply get a flat result with sequelize.\n\nThe sequelize code looks something like this:\n\n```\nmodels.table1.findAll({\n attributes: ['field1', 'field2'],\n where: {field1: someval},\n include: [{model: models.assoc_table, required: true, attributes:['field_a', 'field_b']}]\n}).then(function (result) {\n res.send(result);\n}).catch(function(error) {\n console.log(error);\n});\n```\n\n========================================\n\nTop Answer:\nOld question, but as I was attempting to do this also and found a pure sequelize solution that does not require the \"after\" mapping, I wanted to add that here. So to have sequelize itself return the desired object format, it would be this, where the `attributes` are explicitly assigned based off column return values from the `include` table:\n\n```\nmodels.table1.findAll({\n attributes: [\n 'field1', \n 'field2',\n [sequelize.col('models.assoc_table.field_a'), 'field_a'], // Set key\n [sequelize.col('models.assoc_table.field_b'), 'field_b'], // Set key\n ],\n where: {field1: someval},\n include: [\n {model: models.assoc_table, \n required: true, \n attributes:[], // Explicitly do not send back nested key's\n }\n ]\n})\n```\n\n========================================\n\nCode:\n```text\n[   \n  {\n    \"field1\": \"someval\",\n    \"field2\": \"someval1\",\n    \"assoc_table\": {\n      \"field_a\": 1,\n      \"field_b\": \"someval\"\n    }   \n  },   \n  {\n    \"field1\": \"someval\",\n    \"field2\": \"someval3\",\n    \"assoc_table\": {\n      \"field_a\": 5,\n      \"field_b\": \"someval\"\n    }   \n  },   \n  {\n    \"field1\": \"someval\",\n    \"field2\": \"someval3\",\n    \"assoc_table\": {\n      \"field_a\": 12,\n      \"field_b\": \"someval\"\n    }   \n   } \n]\n```\n\n```text\nmodels.table1.findAll({\n    attributes: ['field1', 'field2'],\n    where: {field1: someval},\n    include: [{model: models.assoc_table, required: true, attributes:['field_a', 'field_b']}]\n}).then(function (result) {\n    res.send(result);\n}).catch(function(error) {\n    console.log(error);\n});\n```\n\n```text\nresult.forEach(obj => { \n    Object.keys(obj.toJSON()).forEach(k => {\n        if (typeof obj[k] === 'object') {       \n            Object.keys(obj[k]).forEach(j => obj[j] = obj[k][j]);\n        }\n    });\n});\n```\n\n```text\n[   \n  {\n    \"field1\": \"someval\",\n    \"field2\": \"someval1\",\n    \"assoc_table.field_a\": 1,\n    \"assoc_table.field_b\": \"someval\"\n  },\n  ...\n]\n```\n\n```text\nresult\n```\n\n```text\ntoJSON\n```\n\n```text\nraw: true\n```\n\n```text\nfindAll\n```\n\n```js\n/**\n  Simplify keys returned by a sequelize {raw: true} query. Makes sure no values\n  are over-written and gives a way to keep some of string-based nesting (IDs for\n  example).\n\n  @example result.map(r => trimKeys(r))\n*/\nfunction trimKeys(obj, deepin = ['id']) {\n  const keys = Object.keys(obj)\n  const ret = {}\n  for (var i = 0; i < keys.length; i++) {\n    const key = keys[i]\n    const keyParts = key.split('.')\n    let idx = 1\n    let newKey = keyParts[keyParts.length - idx]\n    while((ret[newKey] || deepin.find(d => newKey === d)) && idx >= 0) {\n      idx++\n      newKey = keyParts[keyParts.length - idx] + '.' + newKey\n    }\n    ret[newKey] = obj[key]\n  }\n  return ret\n}\n```\n\n```text\nraw: true\n```\n\n```text\nmodels.table1.findAll({\n    attributes: [\n      'field1', \n      'field2',\n      [sequelize.col('models.assoc_table.field_a'), 'field_a'], // Set key\n      [sequelize.col('models.assoc_table.field_b'), 'field_b'], // Set key\n    ],\n    where: {field1: someval},\n    include: [\n     {model: models.assoc_table, \n      required: true, \n      attributes:[], // Explicitly do not send back nested key's\n     }\n   ]\n})\n```\n\n```text\nattributes\n```\n\n```text\ninclude\n```\n\n```text\nraw:true,\nnest:true\n```\n\n========================================\n\nComments:\n- Related issues: github.com/sequelize/sequelize/issues/4419 | github.com/sequelize/sequelize/issues/11579\n- your solution doesn't work for me. I get run time error \"attr.includes is not a function\". Can you pls look into this question of mine and provide any help if possible? stackoverflow.com/questions/66064626/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":228,"estimatedTokens":1240}}353{"id":"stack-32423097","source":"stackoverflow","questionId":32423097,"title":"Electron and sequelize error: the dialect sqlite is not supported","tags":["node.js","sequelize.js","electron"],"text":"Title: Electron and sequelize error: the dialect sqlite is not supported\nTags: node.js, sequelize.js, electron\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use sequelize and sqlite with electron in a desktop application but get the following error when running the app via `npm start` (which runs `node_modules/.bin/electron .`):\n\n Uncaught Error: The dialect sqlite is not supported. (Error: Please install sqlite3 package manually)\n\nI've installed sequelize and sqlite with `npm install --save sequelize sqlite`. When I run the models file directly via `node models.js`, everything works fine:\n\n```\n$ node models.js\nExecuting (default): CREATE TABLE IF NOT EXISTS `Users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `username` VARCHAR(255), `birthday` DATETIME, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`Users`)\nExecuting (default): INSERT INTO `Users` (`id`,`username`,`birthday`,`updatedAt`,`createdAt`) VALUES (NULL,'janedoe','1980-07-19 22:00:00.000 +00:00','2015-09-06 11:18:52.412 +00:00','2015-09-06 11:18:52.412 +00:00');\n{ id: 1,\n username: 'janedoe',\n birthday: Sun Jul 20 1980 00:00:00 GMT+0200 (CEST),\n updatedAt: Sun Sep 06 2015 13:18:52 GMT+0200 (CEST),\n createdAt: Sun Sep 06 2015 13:18:52 GMT+0200 (CEST) }\n```\n\nSo the problem is specific to using sequelize with electron. All files are shown below.\n\n**package.json**\n\n```\n{\n \"name\": \"example\",\n \"version\": \"0.0.0\",\n \"description\": \"\",\n \"main\": \"app.js\",\n \"scripts\": {\n \"start\": \"node_modules/.bin/electron .\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"devDependencies\": {\n \"electron-prebuilt\": \"^0.31.1\"\n },\n \"dependencies\": {\n \"jquery\": \"^2.1.4\",\n \"sequelize\": \"^3.7.1\",\n \"sqlite3\": \"^3.0.10\"\n }\n}\n```\n\n**app.js**\n\n```\nvar app = require('app');\nvar BrowserWindow = require('browser-window');\n\nrequire('crash-reporter').start();\n\nvar mainWindow = null;\n\napp.on('window-all-closed', function() {\n if (process.platform !== 'darwin') {\n app.quit();\n }\n});\n\napp.on('ready', function() {\n mainWindow = new BrowserWindow({width: 800, height: 600});\n mainWindow.loadUrl('file://' + __dirname + '/index.html');\n mainWindow.on('closed', function() {\n mainWindow = null;\n });\n});\n```\n\n**index.html**\n\n```\n\n \n \n \n \n \n \n \n Example\n\n \n \n\n```\n\n**models.js**\n\n```\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('bdgt', 'username', 'password', {\n dialect: 'sqlite',\n storage: 'example.db',\n});\n\nvar User = sequelize.define('User', {\n username: Sequelize.STRING,\n birthday: Sequelize.DATE\n});\n\nsequelize.sync().then(function() {\n return User.create({\n username: 'janedoe',\n birthday: new Date(1980, 6, 20)\n });\n}).then(function(jane) {\n console.log(jane.get({\n plain: true\n }));\n});\n```\n\nInstall the dependencies using `npm install` and reproduce the problem using `npm start`. Running `node models.js` will show sequelize works one its own.\n\n========================================\n\nTop Answer:\nI know you have `sqlite3` installed and working alone but the problem arise when you try to use `sqlite3` with `electron` together. It's because of ABI version mismatch.\n\nWhen you put a\n\n`console.log(err);` in \n\n`/node_modules/sequelize/lib/dialects/sqlite/connection-manager.js` line 21, \n\njust before `throw new Error('Please install sqlite3 package manually');` you will see an error like following:\n\n```\n{ [Error: Cannot find module '/node_modules/sqlite3/lib/binding/node-v44-linux-x64/node_sqlite3.node'] code: 'MODULE_NOT_FOUND' }\n```\n\nHowever when you check `/node_modules/sqlite3/lib/binding/` folder there will be no `node-v44-linux-x64` folder but something like `node-v11-linux-x64` folder. (Simply renaming the folder won't work.)\n\nThis mismatch occurs because electron uses `io.js v3.1.0` internally as it states here and ABI versions of it and your version of nodejs don't match.\n\nNote that `node-vXX` is decided via your node's ABI version. Check this url for further info: https://github.com/mapbox/node-pre-gyp/issues/167\n\n**Solution**\n\nThe easy way stated here https://github.com/atom/electron/blob/master/docs/tutorial/using-native-node-modules.md#the-easy-way doesn't work as-is with `sqlite` but you can these steps to make it work:\n\nAfter installing `electron-rebuild` via following command\n\n```\nnpm install --save-dev electron-rebuild\n```\n\ngo to `/node_modules/sqlite3/node_modules/node-pre-gyp/lib/util/abi_crosswalk.js` and find your node version, then change `node_abi` value to `44`. Like following:\n\n```\n\"0.12.7\": {\n \"node_abi\": 44,\n \"v8\": \"3.28\"\n},\n```\n\nthen give `./node_modules/.bin/electron-rebuild` command and wait a bit. Then it works.\n\n========================================\n\nCode:\n```text\n$ node models.js\nExecuting (default): CREATE TABLE IF NOT EXISTS `Users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `username` VARCHAR(255), `birthday` DATETIME, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`Users`)\nExecuting (default): INSERT INTO `Users` (`id`,`username`,`birthday`,`updatedAt`,`createdAt`) VALUES (NULL,'janedoe','1980-07-19 22:00:00.000 +00:00','2015-09-06 11:18:52.412 +00:00','2015-09-06 11:18:52.412 +00:00');\n{ id: 1,\n  username: 'janedoe',\n  birthday: Sun Jul 20 1980 00:00:00 GMT+0200 (CEST),\n  updatedAt: Sun Sep 06 2015 13:18:52 GMT+0200 (CEST),\n  createdAt: Sun Sep 06 2015 13:18:52 GMT+0200 (CEST) }\n```\n\n```text\n{\n  \"name\": \"example\",\n  \"version\": \"0.0.0\",\n  \"description\": \"\",\n  \"main\": \"app.js\",\n  \"scripts\": {\n    \"start\": \"node_modules/.bin/electron .\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"\",\n  \"devDependencies\": {\n    \"electron-prebuilt\": \"^0.31.1\"\n  },\n  \"dependencies\": {\n    \"jquery\": \"^2.1.4\",\n    \"sequelize\": \"^3.7.1\",\n    \"sqlite3\": \"^3.0.10\"\n  }\n}\n```\n\n```text\nvar app = require('app');\nvar BrowserWindow = require('browser-window');\n\nrequire('crash-reporter').start();\n\nvar mainWindow = null;\n\napp.on('window-all-closed', function() {\n    if (process.platform !== 'darwin') {\n        app.quit();\n    }\n});\n\napp.on('ready', function() {\n    mainWindow = new BrowserWindow({width: 800, height: 600});\n    mainWindow.loadUrl('file://' + __dirname + '/index.html');\n    mainWindow.on('closed', function() {\n        mainWindow = null;\n    });\n});\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <!-- Required meta tags always come first -->\n        <meta charset=\"utf-8\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n        <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\">\n    </head>\n    <body>\n        <p>Example</p>\n\n        <script src=\"models.js\"></script>\n    </body>\n</html>\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('bdgt', 'username', 'password', {\n    dialect: 'sqlite',\n    storage: 'example.db',\n});\n\nvar User = sequelize.define('User', {\n    username: Sequelize.STRING,\n    birthday: Sequelize.DATE\n});\n\nsequelize.sync().then(function() {\n    return User.create({\n        username: 'janedoe',\n        birthday: new Date(1980, 6, 20)\n    });\n}).then(function(jane) {\n    console.log(jane.get({\n        plain: true\n    }));\n});\n```\n\n```text\nnpm start\n```\n\n```text\nnode_modules/.bin/electron .\n```\n\n```text\nnpm install --save sequelize sqlite\n```\n\n```text\nnode models.js\n```\n\n```text\nnpm install\n```\n\n```text\nnpm start\n```\n\n```text\nnode models.js\n```\n\n```text\nnode-pre-gyp ERR! install error \nnode-pre-gyp ERR! stack Error: Unsupported target version: 0.31.2\nnode-pre-gyp ERR! command \"node\" \"/my/project/dir/node_modules/sqlite3/node_modules/.bin/node-pre-gyp\" \"install\" \"--fallback-to-build\"\nnode-pre-gyp ERR! not ok\n\nnpm ERR! Failed at the sqlite3@3.0.10 install script 'node-pre-gyp install --fallback-to-build'.\nnpm ERR! This is most likely a problem with the sqlite3 package,\nnpm ERR! not with npm itself.\nnpm ERR! Tell the author that this fails on your system:\nnpm ERR!     node-pre-gyp install --fallback-to-build\n```\n\n```text\nnode-gyp rebuild --target=0.31.2 --arch=x64 --dist-url=https://atom.io/download/atom-shell\n```\n\n```text\ngyp: Undefined variable module_name in binding.gyp while trying to load binding.gyp\n```\n\n```text\nnode-gyp configure --module_name=node_sqlite3 --module_path=../lib/binding/node-v44-linux-x64\n```\n\n```text\nnode-gyp rebuild --target=0.29.1 --arch=x64 --target_platform=linux --dist-url=https://atom.io/download/atom-shell --module_name=node_sqlite3 --module_path=../lib/binding/node-v44-linux-x64\n```\n\n```text\nelectron-rebuild\n```\n\n```text\n./node_modules/.bin/electron-rebuild\n```\n\n```text\n./node_modules/sqlite3\n```\n\n```text\n\"electron-prebuilt\": \"0.29.1\"\n```\n\n```text\nelectron-prebuilt\n```\n\n```text\n./node_modules/sqlite3\n```\n\n```text\nnpm run prepublish\n```\n\n```text\nlinux\n```\n\n```text\ndarwin\n```\n\n```text\nx64\n```\n\n```text\nia32\n```\n\n```text\n$npm list sqlite3\n```\n\n```text\nMyAppName@0.0.1 /path/to/MyApp\n└── sqlite3@3.0.10\n```\n\n```text\n{ [Error: Cannot find module '<full_path_to_project>/node_modules/sqlite3/lib/binding/node-v44-linux-x64/node_sqlite3.node'] code: 'MODULE_NOT_FOUND' }\n```\n\n```text\nnpm install --save-dev electron-rebuild\n```\n\n```text\n\"0.12.7\": {\n  \"node_abi\": 44,\n  \"v8\": \"3.28\"\n},\n```\n\n```text\nsqlite3\n```\n\n```text\nsqlite3\n```\n\n```text\nelectron\n```\n\n```text\nconsole.log(err);\n```\n\n```text\n<project>/node_modules/sequelize/lib/dialects/sqlite/connection-manager.js\n```\n\n```text\nthrow new Error('Please install sqlite3 package manually');\n```\n\n```text\n/node_modules/sqlite3/lib/binding/\n```\n\n```text\nnode-v44-linux-x64\n```\n\n```text\nnode-v11-linux-x64\n```\n\n```text\nio.js v3.1.0\n```\n\n```text\nnode-vXX\n```\n\n```text\nsqlite\n```\n\n```text\nelectron-rebuild\n```\n\n```text\n<project path>/node_modules/sqlite3/node_modules/node-pre-gyp/lib/util/abi_crosswalk.js\n```\n\n```text\nnode_abi\n```\n\n```text\n44\n```\n\n```text\n./node_modules/.bin/electron-rebuild\n```\n\n```text\nelectron-rebuild -w sqlite3 -p\n```\n\n```text\nelectron-rebuild\n```\n\n```text\n-p\n```\n\n========================================\n\nComments:\n- @destan has a much better answer than mine or ezrepotein. IMHO you should change accepted answer.\n- It works fine when I run `node models.js`. sqlite3 is installed on the system.\n- Which version of node.js are you using?\n- when I do a `npm install sqlite --save` I get a 404 in NPM. Have you tried `npm install sqlite3 --save`? Also, have you tried installing SQLite3 globally as the Electron and regular Node environments might be different. `npm install -g sqlite3 --save`\n- @ezrepotein I'm using node v0.10.38.\n- @warspite sqlite and sqlite3 are both there for me. I tried it with sqlite3 instead of sqlite, but I get the same problem.\n- @ezrepotein I've installed node v0.12.7, re-run `npm install` but the problem persists.\n- @ezrepotein have you tried my other suggestion, installing sqlite globally?\n- @warspite Installing globally gives the same result, sadly.\n- @Jon please try my updated answer, this should make sqlite3 work properly in electron\n- Spot on. That blog post is perfect.\n- Thanks! For future reference, if the post worked for you you should award points to the answerer. You can always upvote other answers that you like.\n- The blog is dead, but here's the archive web.archive.org/web/20160309223943/http://verysimple.com/201&zwnj;&#8203;5/&hellip;\n- Well, you've written that \"Simply renaming the folder won't work.\" but this was the solution in my case.\n- `App threw an error when running [Error: Please install sqlite3 package manually]`","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":53,"totalLines":488,"estimatedTokens":2861}}354{"id":"stack-44272631","source":"stackoverflow","questionId":44272631,"title":"How to escape in Sequelize?","tags":["sql","escaping","sequelize.js","code-injection"],"text":"Title: How to escape in Sequelize?\nTags: sql, escaping, sequelize.js, code-injection\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize with Node.js/Express and I'm not sure how to escape with Sequelize in the where part.\n\n```\nvar sequelize = ...;\nvar productId = 5; var productName = \"test\";\nvar product = sequelize.define('product',findAll({\n where: {\n $or: [\n {productId: this.mysql.escapeId(productId)},\n {productName: {$like: this.mysql.escapeId('%' + productName + '%')}},\n ]\n }\n })\n .then(result => ...);\n```\n\nThis is not working, I obtain the bellowing query : \n\n```\nSELECT `productId`, `productName` FROM `product` AS `product` WHERE (`product`.`productId` = '`5`' OR `product`.`productName` LIKE '\\'%test%\\'' ORDER BY `product`.`productId` ASC\n```\n\nwhich give me nothing as results.\nSo how to escape with Sequelize ? I also tried the function Sequelize.escape, but I got the error \"TypeError: Sequelize.escape is not a function\".\n\nAnd if there's no need to escape the values thanks to Sequelize, I don't understand how it will stay safe from a SQL injection attack.\nExample : productId = '5; DELETE * FROM SOMETHING;'\n\nThanks a lot for your help !\n\nHave a good day,\n\nvanessa\n\n========================================\n\nTop Answer:\nNo need to escape is this case, Sequelize do it.\n\n========================================\n\nCode:\n```text\nvar sequelize = ...;\nvar productId = 5; var productName = \"test\";\nvar product = sequelize.define('product',findAll({\n       where: {\n           $or: [\n                {productId: this.mysql.escapeId(productId)},\n                {productName: {$like: this.mysql.escapeId('%' + productName + '%')}},\n            ]\n       }\n    })\n   .then(result => ...);\n```\n\n```text\nSELECT `productId`, `productName` FROM `product` AS `product` WHERE (`product`.`productId` = '`5`' OR `product`.`productName` LIKE '\\'%test%\\'' ORDER BY `product`.`productId` ASC\n```\n\n```text\nsequelize.query('SELECT * FROM projects WHERE status = ?',\n  { replacements: ['active'], type: sequelize.QueryTypes.SELECT }\n)\n```\n\n```text\nvar SqlString = require('sequelize/lib/sql-string')\nvar input = SqlString.escape(\"'string'( \\\"value\")\nsequelize.query(\n    `SELECT * FROM projects WHERE regexp_matches(\"status\", '^\\'${input} *\\\\w*\\'')`,\n    {type: sequelize.QueryTypes.SELECT }\n)\n```\n\n========================================\n\nComments:\n- Issue with replacements in Sequelize is that numeric values are quoted.","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":84,"estimatedTokens":606}}355{"id":"stack-29993936","source":"stackoverflow","questionId":29993936,"title":"How do I create a required \"BelongsTo\" association using Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: How do I create a required \"BelongsTo\" association using Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing Sequelize, I've created two models: `User` and `Login`.\n\nUsers can have more than one Login, but a login must have exactly one user.\n\nHow do I specify in the login model that a user must exist before a save can occur?\n\n**Current Code**\n\n```\nvar User = sequelize.define('User', {});\nvar Login = sequelize.define('Login', {});\nLogin.belongsTo(User, { foreignKey: 'userId' });\n```\n\nThis setup would still allow a login to save before a user has been specified. For instance `Login.build().save();` would execute without any validation error.\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {});\nvar Login = sequelize.define('Login', {});\nLogin.belongsTo(User, { foreignKey: 'userId' });\n```\n\n```text\nUser\n```\n\n```text\nLogin\n```\n\n```text\nLogin.build().save();\n```\n\n```text\nLogin.belongsTo(User, {\n  foreignKey: {\n    field: 'userId',\n    allowNull: false\n  },\n  onDelete: 'cascade'\n});\n```\n\n```text\n'userId'\n```\n\n```text\nSET NULL\n```\n\n========================================\n\nComments:\n- Related: github.com/sequelize/sequelize/issues/2837\n- You must put the constraint on both models for this to work.","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":65,"estimatedTokens":322}}356{"id":"stack-49828855","source":"stackoverflow","questionId":49828855,"title":"Create with Include Sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: Create with Include Sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nrecently I discovered this on the sequelize documentation where you can create using include. Now I trying to do it on my program but only creates the records of the \"parent\" model and not for the children. \n\nThis is my model and my controller.\n\n```\nvar MainMenu = sequelize.define('MainMenu', {\n Name: {\n type: DataTypes.STRING(50) \n },\n Day: {\n type: DataTypes.DATE\n },\n RecordStatus:{\n type: DataTypes.BOOLEAN,\n defaultValue: true\n }, \n DeletedAt: {\n type: DataTypes.DATE\n }\n },\n {\n associate: function(models){\n models.MainMenu.hasMany(models.MainMeal, {as: 'Menu'});\n }\n }\n);\n\nexports.createIn = (req, res) => {\n\n let Menu = {\n Name: 'MenuTest',\n MainMeal: [{\n Type: 'Breakfast',\n Name: 'MealTest1'\n }, {\n Type: 'Lunch',\n Name: 'MealTest2'\n }]\n };\n\n db.MainMenu.create(Menu, {\n include: [{\n model: db.MainMeal,\n as: 'Menu'\n }]\n })\n .then( mainmenu => {\n if (!mainmenu) {\n return res.send('users/signup', {\n errors: 'Error al registrar el mainmenu.'\n });\n } else {\n return res.jsonp(mainmenu);\n }\n })\n .catch( err => {\n console.log(err);\n return res.status(400)\n .send({\n message: errorHandler.getErrorMessage(err)\n });\n });\n};\n```\n\nOn my case it only creates the `MainMenu` record and not the `MainMeal` records. What am I doing wrong?\n\n========================================\n\nTop Answer:\nThe main thing is of course the naming of `Menu` should be within the data passed to `.create()` itself, along with the arguments presented there and *if* you really need to specify the alias *\"twice\"*, which you do not. But there are some other things to be aware of.\n\nI'd personally prefer storing the association as it's own export and including that within the statement. This generally becomes a bit clearer when you understand the usage of that association later.\n\nI would also strongly encourage that when you are \"writing\" things across multiple tables, then you implement transactions to ensure all related items are actually created and not left orphaned should any errors arise.\n\nAs a brief listing based on the example:\n\n```\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('sqlite:menu.db',{ logging: console.log });\n\nconst MainMeal = sequelize.define('MainMeal', {\n Type: { type: Sequelize.STRING(50) },\n Name: { type: Sequelize.STRING(50) }\n});\n\nconst MainMenu = sequelize.define('MainMenu', {\n Name: { type: Sequelize.STRING(50) }\n});\n\nMainMenu.Meals = MainMenu.hasMany(MainMeal, { as: 'Menu' });\n\n(async function() {\n\n try {\n\n await sequelize.authenticate();\n await MainMeal.sync({ force: true });\n await MainMenu.sync({ force: true });\n\n let result = await sequelize.transaction(transaction => \n MainMenu.create({\n Name: 'MenuTest',\n Menu: [\n { Type: 'Breakfast', Name: 'MealTest1' },\n { Type: 'Lunch', Name: 'MealTest2' }\n ]\n },{\n include: MainMenu.Meals,\n transaction\n })\n );\n\n } catch(e) {\n console.error(e);\n } finally {\n process.exit();\n }\n})();\n```\n\nWhich would output something like:\n\n```\nExecuting (default): SELECT 1+1 AS result\nExecuting (default): DROP TABLE IF EXISTS `MainMeals`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `MainMeals` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `Type` VARCHAR(50), `Name` VARCHAR(50), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `MainMenuId` INTEGER REFERENCES `MainMenus` (`id`) ON DELETE\nSET NULL ON UPDATE CASCADE);\nExecuting (default): PRAGMA INDEX_LIST(`MainMeals`)\nExecuting (default): DROP TABLE IF EXISTS `MainMenus`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `MainMenus` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `Name` VARCHAR(50), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`MainMenus`)\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): BEGIN DEFERRED TRANSACTION;\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): INSERT INTO `MainMenus` (`id`,`Name`,`createdAt`,`updatedAt`) VALUES (NULL,'MenuTest','2018-04-14 08:08:17.132 +00:00','2018-04-14 08:08:17.132 +00:00');\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): INSERT INTO `MainMeals` (`id`,`Type`,`Name`,`createdAt`,`updatedAt`,`MainMenuId`)\nVALUES (NULL,'Breakfast','MealTest1','2018-04-14 08:08:17.152 +00:00','2018-04-14 08:08:17.152 +00:00',1);\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): INSERT INTO `MainMeals` (`id`,`Type`,`Name`,`createdAt`,`updatedAt`,`MainMenuId`)\nVALUES (NULL,'Lunch','MealTest2','2018-04-14 08:08:17.153 +00:00','2018-04-14 08:08:17.153 +00:00',1);\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): COMMIT;\n```\n\nThe important part there being the transaction `BEGIN` and `COMMIT` wrapping all of those `INSERT` statements as data is created. Even without the transaction implemented, you still see both items being created along with the related \"parent\". But the point of the argument is this is where you *\"should\"* be implementing transactions.\n\nAlso note that the \"aliased\" `Menu` as used in the data creation and for subsequent access, is not actually \"required\" to be included within the `.create()` method on the `include` option. It's \"optional\" and is already defined under the `.hasMany()` arguments, so you don't really need to do it again.\n\nEven if you did, then that part would still be the \"association\" as used with the `model` argument:\n\n```\n{\n include: {\n model: MainMenu.Meals,\n as: 'Menu'\n },\n transaction\n}\n```\n\nSo that's not to be confused with the original name of the model for the \"table\" which is referenced, which also might be another point of confusion.\n\n========================================\n\nCode:\n```text\nvar MainMenu = sequelize.define('MainMenu', {\n    Name: {\n      type: DataTypes.STRING(50)      \n    },\n    Day: {\n      type: DataTypes.DATE\n    },\n    RecordStatus:{\n      type: DataTypes.BOOLEAN,\n      defaultValue: true\n    },    \n    DeletedAt: {\n      type: DataTypes.DATE\n    }\n  },\n  {\n    associate: function(models){\n      models.MainMenu.hasMany(models.MainMeal, {as: 'Menu'});\n    }\n  }\n);\n\nexports.createIn = (req, res) => {\n\n let Menu = {\n   Name: 'MenuTest',\n   MainMeal: [{\n     Type: 'Breakfast',\n     Name: 'MealTest1'\n   }, {\n     Type: 'Lunch',\n     Name: 'MealTest2'\n   }]\n };\n\n  db.MainMenu.create(Menu, {\n    include: [{\n      model: db.MainMeal,\n      as: 'Menu'\n    }]\n  })\n    .then( mainmenu => {\n      if (!mainmenu) {\n        return res.send('users/signup', {\n          errors: 'Error al registrar el mainmenu.'\n        });\n      } else {\n        return res.jsonp(mainmenu);\n      }\n    })\n    .catch( err => {\n      console.log(err);\n      return res.status(400)\n        .send({\n          message: errorHandler.getErrorMessage(err)\n        });\n    });\n};\n```\n\n```text\nMainMenu\n```\n\n```text\nMainMeal\n```\n\n```text\nlet mainMenu = {\n   Name: 'MenuTest',\n   Menu: [{\n     Type: 'Breakfast',\n     Name: 'MealTest1'\n   }, {\n     Type: 'Lunch',\n     Name: 'MealTest2'\n   }]\n };\n```\n\n```text\ndb.MainMenu.create(mainMenu, {\n    include: [{\n      model: db.MainMeal,\n      as: 'Menu'\n    }]\n  })\n    .then( mainmenu => {\n      if (!mainmenu) {\n        return res.send('users/signup', {\n          errors: 'Error al registrar el mainmenu.'\n        });\n      } else {\n        return res.jsonp(mainmenu);\n      }\n    })\n    .catch( err => {\n      console.log(err);\n      return res.status(400)\n        .send({\n          message: errorHandler.getErrorMessage(err)\n        });\n    });\n```\n\n```text\nmenu\n```\n\n```text\nMenu\n```\n\n```text\nMainMeal\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('sqlite:menu.db',{ logging: console.log });\n\nconst MainMeal = sequelize.define('MainMeal', {\n  Type: { type: Sequelize.STRING(50) },\n  Name: { type: Sequelize.STRING(50) }\n});\n\nconst MainMenu = sequelize.define('MainMenu', {\n  Name: { type: Sequelize.STRING(50) }\n});\n\nMainMenu.Meals = MainMenu.hasMany(MainMeal, { as: 'Menu' });\n\n(async function() {\n\n  try {\n\n    await sequelize.authenticate();\n    await MainMeal.sync({ force: true });\n    await MainMenu.sync({ force: true });\n\n    let result = await sequelize.transaction(transaction => \n      MainMenu.create({\n        Name: 'MenuTest',\n        Menu: [\n          { Type: 'Breakfast', Name: 'MealTest1' },\n          { Type: 'Lunch', Name: 'MealTest2' }\n        ]\n      },{\n        include: MainMenu.Meals,\n        transaction\n      })\n    );\n\n  } catch(e) {\n    console.error(e);\n  } finally {\n    process.exit();\n  }\n})();\n```\n\n```text\nExecuting (default): SELECT 1+1 AS result\nExecuting (default): DROP TABLE IF EXISTS `MainMeals`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `MainMeals` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `Type` VARCHAR(50), `Name` VARCHAR(50), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `MainMenuId` INTEGER REFERENCES `MainMenus` (`id`) ON DELETE\nSET NULL ON UPDATE CASCADE);\nExecuting (default): PRAGMA INDEX_LIST(`MainMeals`)\nExecuting (default): DROP TABLE IF EXISTS `MainMenus`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `MainMenus` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `Name` VARCHAR(50), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`MainMenus`)\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): BEGIN DEFERRED TRANSACTION;\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): INSERT INTO `MainMenus` (`id`,`Name`,`createdAt`,`updatedAt`) VALUES (NULL,'MenuTest','2018-04-14 08:08:17.132 +00:00','2018-04-14 08:08:17.132 +00:00');\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): INSERT INTO `MainMeals` (`id`,`Type`,`Name`,`createdAt`,`updatedAt`,`MainMenuId`)\nVALUES (NULL,'Breakfast','MealTest1','2018-04-14 08:08:17.152 +00:00','2018-04-14 08:08:17.152 +00:00',1);\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): INSERT INTO `MainMeals` (`id`,`Type`,`Name`,`createdAt`,`updatedAt`,`MainMenuId`)\nVALUES (NULL,'Lunch','MealTest2','2018-04-14 08:08:17.153 +00:00','2018-04-14 08:08:17.153 +00:00',1);\nExecuting (3d645847-56ca-435a-b786-6be62a05e8d5): COMMIT;\n```\n\n```text\n{\n  include: {\n    model: MainMenu.Meals,\n    as: 'Menu'\n  },\n  transaction\n}\n```\n\n```text\nMenu\n```\n\n```text\n.create()\n```\n\n```text\nBEGIN\n```\n\n```text\nCOMMIT\n```\n\n```text\nINSERT\n```\n\n```text\nMenu\n```\n\n```text\n.create()\n```\n\n```text\ninclude\n```\n\n```text\n.hasMany()\n```\n\n```text\nmodel\n```\n\n========================================\n\nComments:\n- Omg that worked!. Hahaha funny how just the variable name works. Thank you.\n- Now taking advantage of your answer, if I want to do a second `Include` inside MainMenu, first it is possible? do I just add the object or array inside `Menu`?\n- I give the answer to the other guy cause it odes what I want with just a simple change. But I will try your solution with transaction. Thanks for all you explanation.","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":407,"estimatedTokens":2692}}357{"id":"stack-52455507","source":"stackoverflow","questionId":52455507,"title":"Connecting Sequelize to Google Cloud SQL","tags":["postgresql","deployment","sequelize.js","google-cloud-sql"],"text":"Title: Connecting Sequelize to Google Cloud SQL\nTags: postgresql, deployment, sequelize.js, google-cloud-sql\nSource: Stack Overflow\n\nQuestion:\ndoes anyone know how to connect to Google Cloud SQL from Sequelize?\n\n```\nsequelize = new Sequelize(process.env.TEST_DB || 'postgres', 'blah', null, {\n dialect: 'postgres',\n operatorsAliases: Sequelize.Op,\n host: process.env.DB_HOST || 'localhost',\n define: {\n underscored: true\n },\n });\n connected = true;\n```\n\n========================================\n\nTop Answer:\nindex.js\n\n```\nconst sequelize = new Sequelize('{db_name}', '{db_user}', '{db_password}', {\n dialect: 'mysql',\n host: '/cloudsql/{instance}',\n timestamps: false,\n dialectOptions: {\n socketPath: '/cloudsql/{instance}'\n},\n});\n```\n\nadd this in serverless.yml\n\n```\nbeta_settings:\n cloud_sql_instances: {xxxxxxx-xxxxxx:us-central1:xxxxxxxxxxx}\n```\n\n========================================\n\nCode:\n```text\nsequelize = new Sequelize(process.env.TEST_DB || 'postgres', 'blah', null, {\n    dialect: 'postgres',\n    operatorsAliases: Sequelize.Op,\n    host: process.env.DB_HOST || 'localhost',\n    define: {\n      underscored: true\n    },\n  });\n  connected = true;\n```\n\n```text\nconst sequelize = new Sequelize('{db_name}', '{db_user}', '{db_password}', {\n  dialect: 'mysql',\n  host: '/cloudsql/{instance}',\n  timestamps: false,\n  dialectOptions: {\n    socketPath: '/cloudsql/{instance}'\n},\n});\n```\n\n```text\nbeta_settings:\n  cloud_sql_instances: {xxxxxxx-xxxxxx:us-central1:xxxxxxxxxxx}\n```\n\n========================================\n\nComments:\n- Where is your code running? App Engine Standard? Flexible? Your local machine?\n- I'm just trying to use Google Cloud Proxy on my machine. But afterwards I'd like to deploy the app to Google Cloud Compute Engine.\n- Ok, you are using proxy. I updated my answer to be more proxy specific. Please make sure you have followed the proxy setup.\n- Thanks Veikko. I got it working on my local computer. But do you know how I could set this up in Sequelize for production? Sequelize doc seems to suggest to use a uri, in this format: postgres://user:pass@example.com:5432/dbname docs.sequelizejs.com/manual/installation/&hellip; Do you I just add that into the host? And also do you know what should be replacing example.com?\n- You can use the proxy also from compute engine instance, or you can whitelist your compute engine instances static ip in cloud sql. Both work well. You can find specific instructions and recommendations for compute engine at cloud.google.com/sql/docs/postgres/connect-compute-engine.\n- @steph can you how you succeeded connecting it ? I receive the following error: `original: error: pg_hba.conf rejects connection for host \"ip addr\", user \"postgres\", database \"db-name\", no encryption`\n- This solution (using the cloudsql instance name) worked for me when my app ran inside GCP (I'd previously been trying to use external SQL host IP address, which only worked from external networks and did not work inside GCP)\n- I learned that the `dialectOptions` part is required inside of GCP (CloudRun for example), but caused me errors when connecting to the proxy on my local machine (cloud.google.com/sql/docs/mysql/&hellip;) , Just a heads up. I updated my code like so `...(host === '127.0.0.1' ? {} : { dialectOptions: { socketPath: host, }, })`\n- What does the `&#47;cloudsql&#47;{instance}` mean ? does it means the instance identifier ?","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":85,"estimatedTokens":849}}358{"id":"stack-67805007","source":"stackoverflow","questionId":67805007,"title":"How to create a spatial index on a PostgreSQL GEOMETRY field?","tags":["node.js","postgresql","sequelize.js","postgis"],"text":"Title: How to create a spatial index on a PostgreSQL GEOMETRY field?\nTags: node.js, postgresql, sequelize.js, postgis\nSource: Stack Overflow\n\nQuestion:\nI am using PostgreSQL and PostGIS to handle geocoordinates in a table. How to create a spatial index on the `GEOMETRY(POINT)` type field to increase the performance of the distance-based `ST_DWithin` query?\n\nI am using migrations to create indexes.\n\n========================================\n\nCode:\n```text\nGEOMETRY(POINT)\n```\n\n```text\nST_DWithin\n```\n\n```text\nCREATE INDEX idx_any_label ON mytable USING gist (geom_column);\n```\n\n```text\nCREATE TABLE t (geom geometry(point,4326));\nINSERT INTO t \nSELECT ('SRID=4326;POINT('||floor(random() * 50)||' ' ||floor(random() * 50) ||')')\nFROM generate_series(1,50000);\n```\n\n```text\nEXPLAIN ANALYSE\nSELECT * FROM t\nWHERE ST_DWithin('SRID=4326;POINT(1 1)',geom,1);\n    \n Seq Scan on t  (cost=0.00..1252068.48 rows=5 width=32) (actual time=122.091..144.137 rows=98 loops=1)\n   Filter: st_dwithin('0101000020E6100000000000000000F03F000000000000F03F'::geometry, geom, '1'::double precision)\n   Rows Removed by Filter: 49902\n Planning Time: 0.083 ms\n JIT:\n   Functions: 2\n   Options: Inlining true, Optimization true, Expressions true, Deforming true\n   Timing: Generation 0.387 ms, Inlining 83.228 ms, Optimization 30.947 ms, Emission 7.626 ms, Total 122.187 ms\n Execution Time: 186.107 ms\n```\n\n```text\nCREATE INDEX idx_t_geom ON t USING gist (geom);\n\nEXPLAIN ANALYSE\nSELECT * FROM t\nWHERE ST_DWithin('SRID=4326;POINT(1 1)',geom,1);\n                                                           QUERY PLAN                                                           \n--------------------------------------------------------------------------------------------------------------------------------\n Bitmap Heap Scan on t  (cost=4.98..2119.16 rows=5 width=32) (actual time=0.086..0.367 rows=98 loops=1)\n   Filter: st_dwithin('0101000020E6100000000000000000F03F000000000000F03F'::geometry, geom, '1'::double precision)\n   Rows Removed by Filter: 83\n   Heap Blocks: exact=139\n   ->  Bitmap Index Scan on idx_t_geom  (cost=0.00..4.98 rows=77 width=0) (actual time=0.063..0.064 rows=181 loops=1)\n         Index Cond: (geom && st_expand('0101000020E6100000000000000000F03F000000000000F03F'::geometry, '1'::double precision))\n Planning Time: 0.291 ms\n Execution Time: 2.237 ms\n```\n\n```text\ngist\n```\n\n```text\ndb<>fiddle\n```\n\n========================================\n\nComments:\n- For Googlers who might be interested in the built-in PostgreSQL GIST rather than the external PostGIS extension: stackoverflow.com/questions/28292198/&hellip;\n- Is there a way to create this index without executing raw SQL commands? Any Sequelize function?\n- I'm not very familiar with sequelize, but I am pretty sure it is possible to either execute ddl statements such as create index. Can't you run this stamentet yourself directly in the database? It is really short and only has to be fired once.","metadata":{"transformedAt":"2026-08-18T18:33:34.368Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":79,"estimatedTokens":739}}359{"id":"stack-55523422","source":"stackoverflow","questionId":55523422,"title":"Node Sequelize (MSSQL) - Login failed for user ''","tags":["node.js","sql-server","sequelize.js","tedious"],"text":"Title: Node Sequelize (MSSQL) - Login failed for user ''\nTags: node.js, sql-server, sequelize.js, tedious\nSource: Stack Overflow\n\nQuestion:\nI've come across several posts for this question however, none of them seem to have an actual answer. Several ideas, yet none of them work.\n\nAfter digging around both the Sequelize and Tedious packages and watching my config get passed down correctly, I'm at a loss.\n\nI am trying to run migrations against a new database in MSSQL. I have no problem connecting to it with the same creds I'm using here so I know that's not the issue.\n\nI have my config.js that is pulling env vars. With the exception of my custom console statements, this file was auto generated from sequelize and is correctly referenced in my sequelizerc\n\n```\nrequire('dotenv').config()\nconsole.log('[+] Loading database config...')\n\nif (process.env.NODE_ENV === 'production') {\n console.log(`[+] Using database: ${process.env.PROD_DB_DATABASE}`)\n} else if (process.env.NODE_ENV === 'development') {\n console.log(`[+] Using database: ${process.env.DEV_DB_DATABASE}`)\n} else if (process.env.NODE_ENV === 'test') {\n console.log(`[+] Using database: ${process.env.TEST_DB_DATABASE}`)\n} else if (process.env.NODE_ENV === 'local') {\n console.log(`[+] Using database: ${process.env.LOCAL_DB_DATABASE}`)\n} else {\n console.log(`[-] CANNOT LOAD DATABASE FROM ENV: ${process.env.NODE_ENV}`)\n process.exit()\n}\n\nmodule.exports = {\n production: {\n database: process.env.PROD_DB_DATABASE,\n username: process.env.PROD_DB_USERNAME,\n password: process.env.PROD_DB_PASSWORD,\n host: process.env.PROD_DB_HOST,\n port: process.env.PROD_DB_PORT,\n dialect: process.env.PROD_DB_DIALECT,\n storage: process.env.PROD_DB_STORAGE,\n logging: false,\n dialectOptions: {\n instanceName: process.env.PROD_INSTANCE_NAME\n },\n pool: {\n min: 5,\n max: 1,\n acquire: 6000,\n idle: 6000\n }\n },\n development: {\n database: process.env.DEV_DB_DATABASE,\n username: process.env.DEV_DB_USERNAME,\n password: process.env.DEV_DB_PASSWORD,\n host: process.env.DEV_DB_HOST,\n port: process.env.DEV_DB_PORT,\n dialect: process.env.DEV_DB_DIALECT,\n storage: process.env.DEV_DB_STORAGE,\n logging: console.log,\n dialectOptions: {\n instanceName: process.env.DEV_INSTANCE_NAME,\n debug: true\n },\n pool: {\n min: 5,\n max: 1,\n acquire: 6000,\n idle: 6000\n }\n },\n test: {\n database: process.env.TEST_DB_DATABASE,\n username: process.env.TEST_DB_USERNAME,\n password: process.env.TEST_DB_PASSWORD,\n host: process.env.TEST_DB_HOST,\n port: process.env.TEST_DB_PORT,\n dialect: process.env.TEST_DB_DIALECT,\n storage: process.env.TEST_DB_STORAGE,\n logging: false\n },\n local: {\n database: process.env.LOCAL_DB_DATABASE,\n username: process.env.LOCAL_DB_USERNAME,\n password: process.env.LOCAL_DB_PASSWORD,\n host: process.env.LOCAL_DB_HOST,\n port: process.env.LOCAL_DB_PORT,\n dialect: process.env.LOCAL_DB_DIALECT,\n storage: process.env.LOCAL_DB_STORAGE,\n logging: false\n }\n}\n```\n\nWhen i run my migration i get the error:\n\n```\n> node_modules/.bin/sequelize db:migrate\n\n// ERROR: Login failed for user ''.\n```\n\nAs mentioned above I dug through sequelize and tedious and my config is getting passed properly through both so i know it's not an env var issue or a NODE_ENV issue.\n\nAnyone have any ideas here? I'm about to smash my face into my keyboard.\n\n========================================\n\nTop Answer:\nI was getting the same error. The reason was due to explicitly mentioning the name of the DB in the sequelize config file and it did not exist. The reason could be different in your case but a quick look at SQL Server error logs will give you the reason for the failure.\n\n```\nLogin failed for user 'user'. Reason: Failed to open the explicitly specified database 'dbo'. [CLIENT: XX.XX.XX.XX]\n```\n\n========================================\n\nCode:\n```text\nrequire('dotenv').config()\nconsole.log('[+] Loading database config...')\n\nif (process.env.NODE_ENV === 'production') {\n  console.log(`[+] Using database: ${process.env.PROD_DB_DATABASE}`)\n} else if (process.env.NODE_ENV === 'development') {\n  console.log(`[+] Using database: ${process.env.DEV_DB_DATABASE}`)\n} else if (process.env.NODE_ENV === 'test') {\n  console.log(`[+] Using database: ${process.env.TEST_DB_DATABASE}`)\n} else if (process.env.NODE_ENV === 'local') {\n  console.log(`[+] Using database: ${process.env.LOCAL_DB_DATABASE}`)\n} else {\n  console.log(`[-] CANNOT LOAD DATABASE FROM ENV: ${process.env.NODE_ENV}`)\n  process.exit()\n}\n\nmodule.exports = {\n  production: {\n    database: process.env.PROD_DB_DATABASE,\n    username: process.env.PROD_DB_USERNAME,\n    password: process.env.PROD_DB_PASSWORD,\n    host: process.env.PROD_DB_HOST,\n    port: process.env.PROD_DB_PORT,\n    dialect: process.env.PROD_DB_DIALECT,\n    storage: process.env.PROD_DB_STORAGE,\n    logging: false,\n    dialectOptions: {\n      instanceName: process.env.PROD_INSTANCE_NAME\n    },\n    pool: {\n      min: 5,\n      max: 1,\n      acquire: 6000,\n      idle: 6000\n    }\n  },\n  development: {\n    database: process.env.DEV_DB_DATABASE,\n    username: process.env.DEV_DB_USERNAME,\n    password: process.env.DEV_DB_PASSWORD,\n    host: process.env.DEV_DB_HOST,\n    port: process.env.DEV_DB_PORT,\n    dialect: process.env.DEV_DB_DIALECT,\n    storage: process.env.DEV_DB_STORAGE,\n    logging: console.log,\n    dialectOptions: {\n      instanceName: process.env.DEV_INSTANCE_NAME,\n      debug: true\n    },\n    pool: {\n      min: 5,\n      max: 1,\n      acquire: 6000,\n      idle: 6000\n    }\n  },\n  test: {\n    database: process.env.TEST_DB_DATABASE,\n    username: process.env.TEST_DB_USERNAME,\n    password: process.env.TEST_DB_PASSWORD,\n    host: process.env.TEST_DB_HOST,\n    port: process.env.TEST_DB_PORT,\n    dialect: process.env.TEST_DB_DIALECT,\n    storage: process.env.TEST_DB_STORAGE,\n    logging: false\n  },\n  local: {\n    database: process.env.LOCAL_DB_DATABASE,\n    username: process.env.LOCAL_DB_USERNAME,\n    password: process.env.LOCAL_DB_PASSWORD,\n    host: process.env.LOCAL_DB_HOST,\n    port: process.env.LOCAL_DB_PORT,\n    dialect: process.env.LOCAL_DB_DIALECT,\n    storage: process.env.LOCAL_DB_STORAGE,\n    logging: false\n  }\n}\n```\n\n```text\n> node_modules/.bin/sequelize db:migrate\n\n// ERROR: Login failed for user ''.\n```\n\n```text\nsequelize@4\n```\n\n```text\ntedious@<=5\n```\n\n```text\npackage.json\n```\n\n```text\ntedious\n```\n\n```text\ntedious\n```\n\n```text\ntedious\n```\n\n```text\n# One of the following:\n      $ npm install --save pg pg-hstore # Postgres\n      $ npm install --save mysql2\n      $ npm install --save mariadb\n      $ npm install --save sqlite3\n      $ npm install --save tedious # Microsoft SQL Server\n```\n\n```text\nLogin failed for user 'user'. Reason: Failed to open the explicitly specified database 'dbo'. [CLIENT: XX.XX.XX.XX]\n```\n\n========================================\n\nComments:\n- I will give this a shot! Currently putting out a fire in another code base but when i get back to this i'll give it a go.\n- Works for me. I had this error with sequelize 5.22.3 and tedious 3.0.1. Upgraded to tedious 9.2.1 and it fixed the MSSQL connection.\n- *If you are using sequelize@4, then it seems there is a hidden requirement that you must use tedious@<=5.* This saved my day","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":246,"estimatedTokens":1789}}360{"id":"stack-50584682","source":"stackoverflow","questionId":50584682,"title":"sequelize model, migration file and foreign key. which one is right?","tags":["node.js","express","model","sequelize.js"],"text":"Title: sequelize model, migration file and foreign key. which one is right?\nTags: node.js, express, model, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAt first time when I started studying sequelize I just had no idea, just copy and pasted the code when it comes to make relations between two models.\n\nIt really confused me whether I have to insert foreign keys both to the model file and migration file or for only migration file.\n\nI knew that the migrations are files that have commands for changing your database.\n\nso definitely we have to manually insert foreign keys to the migration file so that database can create them.\n\nIn sequelize doc, if we add relations like has many and belongs to, the sequelize will automatically add foreign keys.\n\nso I was really confused whether I have to add them or not.\n\nsome questions I asked before the answers were fifty-fifty.\n\nsome says that we don`t have to manually add foreign keys to the model because sequelize will automatically add them.\n\nbut some says that we have to manually add foreign keys to the model because we have to match(sync) columns between models and migration files.\n\neven worse, the articles explaining about sequelize relations are differ from each other.\n\nso, which one is right??\n\nI really want to get clear answer.\n\nIt will be really thankful to get some reasons (if we have to add foreign key to the model) \n\nnot exaggerated, I have been curious of this issue for about six month.\n\n========================================\n\nTop Answer:\n### How should we create DB schema\n\nWe have two options here. Migrations or Sequelize using `sync`. Always prefer migrations over `sync`. Migrations are more powerful, you can undo, redo and much more with it. `sync` does not reflect table alterations. For example, you define a certain model say `User` and forgot to add `gender`. Now if you want to add this column with Sequelize, you would have to use `force:true` which would drop all of your `User` data which is not desirable in production.\n\n### Who should define the foreign key constraints\n\nFrom software design principles, your database constraints and validations should always be in place irrespective whether application logic (Sequelize) implements the same logic or not. For example, a new developer can write a raw query and can mess up your whole database if you do not have the right constraints.\n\nHowever we also want to use sequelize to make the right queries with all the associations. The only way sequelize can do this if it knows what associations exists in the db and what should be the foreign key.\n\nSo, foreign key constrains should be defined at both migration as well as sequelize level.\n\n### Example of db constraints\n\nhttps://i.sstatic.net/Yd204.png\n\nAs you can see in the image above, the constraints are defined on my database schema.\n\n### Example of sequelize constraints\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Designation = sequelize.define('designation', {\n doctorId: {\n type: DataTypes.STRING,\n allowNull: false,\n field: 'doctor_id',\n },\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n }, {});\n Designation.associate = (models) => {\n models.designation.belongsTo(models.doctor, {\n onDelete: 'cascade',\n });\n };\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = {\nup: function (queryInterface, Sequelize) {\n    return queryInterface.createTable('item_types', {\n        id: {\n            allowNull: false,\n            autoIncrement: true,\n            primaryKey: true,\n            type: Sequelize.INTEGER\n        },\n        item_type: {\n            type: Sequelize.STRING\n        },\n        type_desc: {\n            type: Sequelize.STRING\n        },\n        createdAt: {\n            allowNull: true,\n            type: Sequelize.DATE,\n            defaultValue: Sequelize.NOW\n        },\n        updatedAt: {\n            allowNull: true,\n            type: Sequelize.DATE,\n            defaultValue: Sequelize.NOW\n        }\n    });\n},\ndown: function (queryInterface, Sequelize) {\n    return queryInterface.dropTable('item_types');\n}\n};\n```\n\n```text\n'use strict';\nmodule.exports = {\nup: function (queryInterface, Sequelize) {\n    return queryInterface.createTable('items', {\n        id: {\n            allowNull: false,\n            autoIncrement: true,\n            primaryKey: true,\n            type: Sequelize.INTEGER\n        },\n        item_name: {\n            type: Sequelize.STRING\n        },\n        item_desc: {\n            type: Sequelize.STRING\n        },\n        item_type_id: {\n            type: Sequelize.INTEGER,\n            references: {\n                model: 'item_types',\n                key: 'id'\n            }\n        },\n        createdAt: {\n            allowNull: false,\n            type: Sequelize.DATE\n        },\n        updatedAt: {\n            allowNull: false,\n            type: Sequelize.DATE\n        }\n    });\n},\ndown: function (queryInterface, Sequelize) {\n    return queryInterface.dropTable('items');\n}\n};\n```\n\n```text\n'use strict';\nmodule.exports = function (sequelize, DataTypes) {\nvar item_type = sequelize.define('item_type', {\n    item_type: DataTypes.STRING,\n    type_desc: DataTypes.STRING\n});\nitem_type.associate = function (models) {\n    item_type.hasMany(models.item, {foreignKey: 'item_type_id'});\n};\nreturn item_type;\n};\n```\n\n```text\n'use strict';\n var Logger = require('./../utils/logger');\n\n var log = new Logger('item_type_factory');\n module.exports = function (sequelize, DataTypes) {\n var item = sequelize.define('item', {\n    item_name: DataTypes.STRING,\n    item_desc: DataTypes.STRING\n });\n item.associate = function (models) {\n    item.item_type = item.belongsTo(models.item_type, {foreignKey: 'id', target_key: 'item_type_id'});\n    item.order_details = item.hasMany(models.order_details);\n    item.user = item.belongsToMany(models.user, {through: 'supplier_items'})\n};\n\nitem.addNewItem = function (data) {\n    return item.create(data, {include: [{association: item.item_type}]});\n};\n\nitem.findAndCreate = function (data, item_name) {\n    return new Promise(function (resolve, reject) {\n        item.findOrCreate({\n            where: {'item_name': item_name}, defaults: data\n        }).spread(function (record_data, created) {\n            resolve(record_data);\n        }).catch(function (insert_error) {\n            reject(insert_error);\n        });\n    });\n};\n\nitem.findAllItems = function () {\n    return item.findAll({\n        include: [{association: item.item_type}]\n    });\n};\nreturn item;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Designation = sequelize.define('designation', {\n    doctorId: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      field: 'doctor_id',\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n  }, {});\n  Designation.associate = (models) => {\n    models.designation.belongsTo(models.doctor, {\n      onDelete: 'cascade',\n    });\n  };\n```\n\n```text\nsync\n```\n\n```text\nsync\n```\n\n```text\nsync\n```\n\n```text\nUser\n```\n\n```text\ngender\n```\n\n```text\nforce:true\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- this is really great. appreciate for your detailed explanation with code. still one thing I am wondering is that, according to the answer, stackoverflow.com/questions/50386288/&hellip; even if we don`t add any foreign keys, the db creates foreign key column. ( the case of sync )\n- so if we don`t add foreign key to the model, there is no way to access them.. right?\n- if we maually add foreign key to the migration file, the db will create them. but if we don`t add foreign keys to the model, there is no way to access and manipulate with them. Am I understand correctly?\n- so it is not necessary to write foreign key options to the model. (regards to the db itself). but as we have to access and use that relationships, we have to add foreign keys to the model. I am just re-asking to assure if I am understanding this issue correctly ! thanks ! @Akshay Gadhave\n- If you see the model code that associate function will manage the relationship. While you run the migrations using db.migrate(). It will run it sequentially as per the time. That is why we create the master table 1st.\n- Migrations are basically design to migrate right, So why we add the foreign keys and manage relation ship manually !!. Handle it through the Migrations scripts.\n- sorry for bothering with my lack of understanding.. to rephrase, item_type_id: { type: Sequelize.INTEGER, references: { model: 'item_types', key: 'id' } }, this code for migration file is for ONLY db, and db itself will have relation. contrastly, hasmany, belongsto and foreign key option added to the model file is just for using(querying) that db which has relation already, with js grammar ( not with the raw query). (not managing db. db is managed by migration file).\n- If we don`t add foreign keys to the model, there is no way to access(use) that db. (access mean for orm usage not the db itself for model create.) @Akshay Gadhave\n- Yes you are right. Migrations and model are the two different things, Migrations might be for alter table, Insert default values. That should not be related to the model. As per the definition Model is the updated version of your database table.!!\n- Yes if we don't add the foreign key we can not write the correct query through the orm.\n- Basically while use migration the db contains 1 additional table \"SequelizeMeta\" That contains the migration name that execute properly. You can also downgrade the migrations using migration queries\n- Let us continue this discussion in chat.\n- appreciate for your answer. so purpose of adding foreign keys to the model is to control database with non-query (js grammer). am I understood correctly?\n- stackoverflow.com/questions/50386288/&hellip; according to this article, if I use sync and foreign key columns are automatically created to the db even if I don`t add the foreign key to the model. But even if we use sync, it is recommended to add foreign keys to the model since we have to control the db, right?\n- my confusion will fully be cleared if above those two questions are correct. thank you! @AbhinavD\n- To the first comment: Yes. Sequelize is an ORM and we can use all its power so that our querying becomes easier and so many other benefits sequelize comes with. For comment 2: If you have defined associations, sequelize will try to assume the foreign key name and use that to do associations.\n- now I solved my curiosity. so either using sync or migration, inserting foreign key to the model is just an option. but if we want to querying with orm, we have to. so that optional thing might be necessary. thank you so much.","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":277,"estimatedTokens":2674}}361{"id":"stack-43737590","source":"stackoverflow","questionId":43737590,"title":"How/Where to run sequelize migrations in a serverless project?","tags":["migration","sequelize.js","serverless-framework","sequelize-cli","serverless-architecture"],"text":"Title: How/Where to run sequelize migrations in a serverless project?\nTags: migration, sequelize.js, serverless-framework, sequelize-cli, serverless-architecture\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Sequelize js with Serverless, coming from traditional server background, I am confused where/how to run database migrations.\n\nShould I create a dedicated function for running migration or is there any other way of running migrations?\n\n========================================\n\nTop Answer:\nI found myself with this same question some days ago while structuring a serverless project, so I've decided to develop a simple serverless plugin to manage sequelize migrations through CLI.\n\nWith the plugin you can:\n\n- Create a migration file\n\n- List pending and executed migrations\n\n- Apply pending migrations\n\n- Revert applied migrations\n\n- Reset all applied migrations\n\nI know this question was posted about two years ago but, for those who keep coming here looking for answers, the plugin can be helpful.\n\nThe code and the instructions to use it are on the plugin repository on github and plugin page on npm.\n\nTo install the plugin directly on your project via npm, you can run:\n\n```\nnpm install --save serverless-sequelize-migrations\n```\n\n========================================\n\nCode:\n```text\nnpm install --save serverless-sequelize-migrations\n```\n\n========================================\n\nComments:\n- Did you ever work this one out?\n- Yeah, as described in the answer, I figured the best strategy is to keep migrations separate from lambda function. I run migration from the environment where I have direct access to the database. Hope this helps.\n- You may want to try out github.com/Reckon-Limited/transmogrify\n- The reason why I would want to create a lambda function for that is that database and all the functions are running on a vpc and I wouldn't have direct access from my local machine, but I guess it would be a better idea to do the migrations from a machine that is in the same vpc.\n- I disagree with this answer. The question asked for a `sequelize`-specific answer, so this would be repeatable code, as `sequelize` supports the `db:migrate` command which you could trigger on every deploy. From a security-perspective, I wouldn't want every deployer to have access to the production-database. Furthermore, I wouldn't want to disconnect running migrations from my deployment strategy.\n- @JaapHaagmans triggering migrations on deploy is a great idea, but the problem is that users might not have direct access to the database while deploying, users might have to connect to network where the database is running before deploying.\n- @MananVaghasiya Your application has access to the database, doesn't it? Your users (I assume they are developers) will only need to trigger the deploy, migrations will run as part of your deployment strategy. In your case, e.g. create a Lambda function that triggers the migrations and trigger that function on deploy. Or better yet, if you have some kind of CI setup, use that so you can monitor the migrations and rollback if needed.\n- I don't really get the reason behind this plugin. Why not using the Sequelize command line tool directly? This sls command is run as part of your CI and therefore will not solve the problem of having your database in a VPC and not publically accessible.","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":54,"estimatedTokens":838}}362{"id":"stack-46137371","source":"stackoverflow","questionId":46137371,"title":"sequelize - connection pool size","tags":["node.js","express","sequelize.js","connection-pool"],"text":"Title: sequelize - connection pool size\nTags: node.js, express, sequelize.js, connection-pool\nSource: Stack Overflow\n\nQuestion:\nnow i`m reading an article on http://docs.sequelizejs.com/manual/installation/getting-started.html\n\nand cannot understand this sentences written below.\n\n If you're connecting to the DB from multiple processes, you'll have to\n create one instance per process, but each instance should have a\n **maximum connection pool size** of \"**max connection pool size divided by number of instances**\". So, if you wanted a max connection\n pool size of 90 and you had 3 worker processes, each process's\n instance should have a max connection pool size of 30.\n\n```\npool: {\n max: 5,\n min: 0,\n idle: 10000\n}\n```\n\nwhat the connection pool size? is that meaning the max?\n\ni am now understanding the connection-pool like this.\nif \"max\" is 5, and 3users want to get to the DB, \n3 connections are allocated to the individual user.\n\nand if 6users want to get the DB,\n5connections are all allocated to the individual user, \nand since there is only 5 connections, the 6th user has to wait.\n\nso i cannot make any sense of \n\neach instance should have a **maximum connection pool size** of \"**max connection pool size divided by number of instances**\".\n\ncan anyone please explain about this?\n\n========================================\n\nTop Answer:\nHere is an example demonstrating the effect of `pool.max` and `pool.idle` options.\n\nEnvironment:\n\n- `\"sequelize\": \"^5.21.3\"`\n\n- `node`: `v12.16.1`\n\n- `PostgreSQL`: `9.6`\n\nClient code:\n\n`db.ts`:\n\n```\nconst sequelize = new Sequelize({\n dialect: 'postgres',\n host: envVars.POSTGRES_HOST,\n username: envVars.POSTGRES_USER,\n password: envVars.POSTGRES_PASSWORD,\n database: envVars.POSTGRES_DB,\n port: Number.parseInt(envVars.POSTGRES_PORT, 10),\n define: {\n freezeTableName: true,\n timestamps: false,\n },\n pool: {\n max: 5,\n min: 0,\n idle: 10 * 1000,\n },\n});\nexport { sequelize };\n```\n\n`pool_test.ts`:\n\n```\nimport { sequelize } from '../../db';\n\nfor (let i = 0; i Run a PostgreSQL server by docker container:\n\n```\nCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\n3c9c0fd1bf53 postgres:9.6 \"docker-entrypoint.s…\" 5 months ago Up 27 hours 0.0.0.0:5430->5432/tcp node-sequelize-examples_pg_1\n```\n\nRun the test code:\n\n```\nDEBUG=sequelize* npx ts-node ./pool_test.ts\n```\n\nDebug logs:\n\n```\nsequelize:pool pool created with max/min: 5/0, no replication +0ms\n sequelize:connection:pg connection acquired +0ms\n sequelize:connection:pg connection acquired +38ms\n sequelize:connection:pg connection acquired +3ms\n sequelize:connection:pg connection acquired +0ms\n sequelize:connection:pg connection acquired +1ms\n sequelize:connection:pg connection acquired +1ms\n sequelize:pool connection acquired +97ms\n sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms\nExecuting (default): select pg_sleep(1);\n sequelize:pool connection acquired +2ms\n sequelize:pool connection acquired +0ms\n sequelize:pool connection acquired +0ms\n sequelize:pool connection acquired +0ms\n sequelize:sql:pg Executing (default): select pg_sleep(1); +2ms\nExecuting (default): select pg_sleep(1);\n sequelize:sql:pg Executing (default): select pg_sleep(1); +2ms\nExecuting (default): select pg_sleep(1);\n sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms\nExecuting (default): select pg_sleep(1);\n sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms\nExecuting (default): select pg_sleep(1);\n sequelize:sql:pg Executed (default): select pg_sleep(1); +1s\n sequelize:pool connection released +1s\n sequelize:pool connection acquired +1ms\n sequelize:sql:pg Executed (default): select pg_sleep(1); +2ms\n sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms\n sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms\n sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms\n sequelize:sql:pg Executing (default): select pg_sleep(1); +1ms\nExecuting (default): select pg_sleep(1);\n sequelize:pool connection released +1ms\n sequelize:pool connection released +0ms\n sequelize:pool connection released +0ms\n sequelize:pool connection released +0ms\n sequelize:pool connection acquired +1ms\n sequelize:pool connection acquired +0ms\n sequelize:pool connection acquired +0ms\n sequelize:pool connection acquired +0ms\n```\n\nEnter the docker container, check the connection process:\n\n```\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:51:34 AM\npostgres 13615 0.0 0.7 289496 16064 ? Ss 08:29 0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14335 0.0 0.5 288384 11248 ? Ss 09:51 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45704) SELECT\npostgres 14336 0.0 0.5 288384 11248 ? Ss 09:51 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45706) SELECT\npostgres 14337 0.0 0.5 288384 11252 ? Ss 09:51 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45708) SELECT\npostgres 14338 0.0 0.5 288384 11248 ? Ss 09:51 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45710) SELECT\npostgres 14339 0.0 0.5 288384 11248 ? Ss 09:51 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45712) SELECT\npostgres 86437 0.0 0.6 288804 13704 ? Ss 00:57 0:00 postgres: testuser node-sequelize-examples [local] idle\n```\n\nAs you can see, there are **5(pool.max)** connection processes.\n\nAfter the connection processes IDLE **10(pool.idle)** seconds. The connection processes will be destroyed.\n\n```\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:48 AM\npostgres 13615 0.0 0.7 289496 16064 ? Ss 08:29 0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14352 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle\npostgres 14353 0.0 0.5 288384 11252 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle\npostgres 14354 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) SELECT\npostgres 14355 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle\npostgres 14356 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) SELECT\nroot 14440 0.0 0.0 12784 972 pts/3 S+ 09:53 0:00 grep postgres: testuser\npostgres 86437 0.0 0.6 288804 13704 ? Ss 00:57 0:00 postgres: testuser node-sequelize-examples [local] idle\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:49 AM\npostgres 13615 0.0 0.7 289496 16064 ? Ss 08:29 0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14352 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle\npostgres 14353 0.0 0.5 288384 11252 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle\npostgres 14354 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) idle\npostgres 14355 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle\npostgres 14356 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) idle\npostgres 86437 0.0 0.6 288804 13704 ? Ss 00:57 0:00 postgres: testuser node-sequelize-examples [local] idle\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:55 AM\npostgres 13615 0.0 0.7 289496 16064 ? Ss 08:29 0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14352 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle\npostgres 14353 0.0 0.5 288384 11252 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle\npostgres 14354 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) idle\npostgres 14355 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle\npostgres 14356 0.0 0.5 288384 11248 ? Ss 09:53 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) idle\nroot 14446 0.0 0.0 12784 932 pts/3 S+ 09:53 0:00 grep postgres: testuser\npostgres 86437 0.0 0.6 288804 13704 ? Ss 00:57 0:00 postgres: testuser node-sequelize-examples [local] idle\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:58 AM\npostgres 13615 0.0 0.7 289496 16064 ? Ss 08:29 0:00 postgres: testuser node-sequelize-examples [local] idle\nroot 14449 0.0 0.0 12784 940 pts/3 S+ 09:53 0:00 grep postgres: testuser\npostgres 86437 0.0 0.6 288804 13704 ? Ss 00:57 0:00 postgres: testuser node-sequelize-examples [local] idle\n```\n\nclient debug logs:\n\n```\n...\n sequelize:pool connection released +25ms\n sequelize:pool connection destroy +10s\n sequelize:pool connection destroy +0ms\n sequelize:pool connection destroy +0ms\n sequelize:pool connection destroy +0ms\n sequelize:pool connection destroy +1ms\n```\n\nIf you change `pool.max` to `10`, check the count of connection processes:\n\n```\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:56:51 AM\npostgres 13615 0.0 0.7 289496 16064 ? Ss 08:29 0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14457 0.0 0.5 288384 11248 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45728) SELECT\npostgres 14458 0.0 0.5 288384 11252 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45730) SELECT\npostgres 14459 0.0 0.5 288384 11252 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45732) SELECT\npostgres 14460 0.0 0.5 288384 11248 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45734) SELECT\npostgres 14461 0.0 0.5 288384 11248 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45736) SELECT\npostgres 14462 0.0 0.5 288384 11248 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45738) SELECT\npostgres 14463 0.0 0.5 288384 11244 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45740) SELECT\npostgres 14464 0.0 0.5 288388 11244 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45742) SELECT\npostgres 14465 0.0 0.5 288388 11244 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45744) SELECT\npostgres 14466 0.0 0.5 288388 11248 ? Ss 09:56 0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45746) SELECT\nroot 14472 0.0 0.0 12784 944 pts/3 S+ 09:56 0:00 grep postgres: testuser\npostgres 86437 0.0 0.6 288804 13704 ? Ss 00:57 0:00 postgres: testuser node-sequelize-examples [local] idle\n```\n\n========================================\n\nCode:\n```text\npool: {\n  max: 5,\n  min: 0,\n  idle: 10000\n}\n```\n\n```text\nmax\n```\n\n```js\nconst sequelize = new Sequelize({\n  dialect: 'postgres',\n  host: envVars.POSTGRES_HOST,\n  username: envVars.POSTGRES_USER,\n  password: envVars.POSTGRES_PASSWORD,\n  database: envVars.POSTGRES_DB,\n  port: Number.parseInt(envVars.POSTGRES_PORT, 10),\n  define: {\n    freezeTableName: true,\n    timestamps: false,\n  },\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10 * 1000,\n  },\n});\nexport { sequelize };\n```\n\n```js\nimport { sequelize } from '../../db';\n\nfor (let i = 0; i < 100; i++) {\n  sequelize.query('select pg_sleep(1);');\n}\n```\n\n```sh\nCONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES\n3c9c0fd1bf53        postgres:9.6        \"docker-entrypoint.s…\"   5 months ago        Up 27 hours         0.0.0.0:5430->5432/tcp   node-sequelize-examples_pg_1\n```\n\n```sh\nDEBUG=sequelize* npx ts-node ./pool_test.ts\n```\n\n```text\nsequelize:pool pool created with max/min: 5/0, no replication +0ms\n  sequelize:connection:pg connection acquired +0ms\n  sequelize:connection:pg connection acquired +38ms\n  sequelize:connection:pg connection acquired +3ms\n  sequelize:connection:pg connection acquired +0ms\n  sequelize:connection:pg connection acquired +1ms\n  sequelize:connection:pg connection acquired +1ms\n  sequelize:pool connection acquired +97ms\n  sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms\nExecuting (default): select pg_sleep(1);\n  sequelize:pool connection acquired +2ms\n  sequelize:pool connection acquired +0ms\n  sequelize:pool connection acquired +0ms\n  sequelize:pool connection acquired +0ms\n  sequelize:sql:pg Executing (default): select pg_sleep(1); +2ms\nExecuting (default): select pg_sleep(1);\n  sequelize:sql:pg Executing (default): select pg_sleep(1); +2ms\nExecuting (default): select pg_sleep(1);\n  sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms\nExecuting (default): select pg_sleep(1);\n  sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms\nExecuting (default): select pg_sleep(1);\n  sequelize:sql:pg Executed (default): select pg_sleep(1); +1s\n  sequelize:pool connection released +1s\n  sequelize:pool connection acquired +1ms\n  sequelize:sql:pg Executed (default): select pg_sleep(1); +2ms\n  sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms\n  sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms\n  sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms\n  sequelize:sql:pg Executing (default): select pg_sleep(1); +1ms\nExecuting (default): select pg_sleep(1);\n  sequelize:pool connection released +1ms\n  sequelize:pool connection released +0ms\n  sequelize:pool connection released +0ms\n  sequelize:pool connection released +0ms\n  sequelize:pool connection acquired +1ms\n  sequelize:pool connection acquired +0ms\n  sequelize:pool connection acquired +0ms\n  sequelize:pool connection acquired +0ms\n```\n\n```sh\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:51:34 AM\npostgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14335  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45704) SELECT\npostgres 14336  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45706) SELECT\npostgres 14337  0.0  0.5 288384 11252 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45708) SELECT\npostgres 14338  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45710) SELECT\npostgres 14339  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45712) SELECT\npostgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle\n```\n\n```sh\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:48 AM\npostgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14352  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle\npostgres 14353  0.0  0.5 288384 11252 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle\npostgres 14354  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) SELECT\npostgres 14355  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle\npostgres 14356  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) SELECT\nroot     14440  0.0  0.0  12784   972 pts/3    S+   09:53   0:00 grep postgres: testuser\npostgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:49 AM\npostgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14352  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle\npostgres 14353  0.0  0.5 288384 11252 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle\npostgres 14354  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) idle\npostgres 14355  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle\npostgres 14356  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) idle\npostgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:55 AM\npostgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14352  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle\npostgres 14353  0.0  0.5 288384 11252 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle\npostgres 14354  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) idle\npostgres 14355  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle\npostgres 14356  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) idle\nroot     14446  0.0  0.0  12784   932 pts/3    S+   09:53   0:00 grep postgres: testuser\npostgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:53:58 AM\npostgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle\nroot     14449  0.0  0.0  12784   940 pts/3    S+   09:53   0:00 grep postgres: testuser\npostgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle\n```\n\n```text\n...\n  sequelize:pool connection released +25ms\n  sequelize:pool connection destroy +10s\n  sequelize:pool connection destroy +0ms\n  sequelize:pool connection destroy +0ms\n  sequelize:pool connection destroy +0ms\n  sequelize:pool connection destroy +1ms\n```\n\n```sh\nroot@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep \"postgres: testuser\"\nThursday 31 2020 09:56:51 AM\npostgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle\npostgres 14457  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45728) SELECT\npostgres 14458  0.0  0.5 288384 11252 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45730) SELECT\npostgres 14459  0.0  0.5 288384 11252 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45732) SELECT\npostgres 14460  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45734) SELECT\npostgres 14461  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45736) SELECT\npostgres 14462  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45738) SELECT\npostgres 14463  0.0  0.5 288384 11244 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45740) SELECT\npostgres 14464  0.0  0.5 288388 11244 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45742) SELECT\npostgres 14465  0.0  0.5 288388 11244 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45744) SELECT\npostgres 14466  0.0  0.5 288388 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45746) SELECT\nroot     14472  0.0  0.0  12784   944 pts/3    S+   09:56   0:00 grep postgres: testuser\npostgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle\n```\n\n```text\npool.max\n```\n\n```text\npool.idle\n```\n\n```text\n\"sequelize\": \"^5.21.3\"\n```\n\n```text\nnode\n```\n\n```text\nv12.16.1\n```\n\n```text\nPostgreSQL\n```\n\n```text\n9.6\n```\n\n```text\ndb.ts\n```\n\n```text\npool_test.ts\n```\n\n```text\npool.max\n```\n\n```text\n10\n```\n\n========================================\n\nComments:\n- appreciate for answering this old question. so pool size is a way to saving costs from forking new process every time. sequelize doc has a guide code for connection pool size max:5, but this is anyway guide code. so which max pool size is appropriate for medium size application? (not meaning large services like facebook etc) maybe 100?\n- even if I use connection pool size, if I set connection pool size for very large number and less user, there will be difference whether setting pool size or not. @AbhinavD\n- It is very hard to say what is the right number.Depends on the ratio of read/write queries( as write locks the row), your hardware etc. AS mentioned in the doc I shared, there is `the \"Knee\"` beyond which the db performance will go down if you increase the pool size. Also, when you install db, the db config itself tells it what is the max it can handle. You would have to change that and your app pool size to make it work.\n- thank you so much! can you check my last comment if I am properly get your words in the previous question(sequelize)?\n- I think you got it. Since I never use `sync`, I always create the foreign key in the model also\n- Does this mean that if you have pool.max = 5, and you have 50 users hitting your DB at the same time, 45 of them will have to wait for the first 5 to complete?","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":451,"estimatedTokens":5503}}363{"id":"stack-50354817","source":"stackoverflow","questionId":50354817,"title":"Sequelize decimal data save with 2 decimal points","tags":["node.js","sequelize.js"],"text":"Title: Sequelize decimal data save with 2 decimal points\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequlize ORM for my Node.js project. Below code is one column in a table.\n\n```\nitemPrice: {\n type: DataTypes.DECIMAL,\n allowNull: false,\n field: 'itemPrice'\n },\n```\n\nIt is generate the MYSQL DB column as decimal(10,0). It means it cannot save decimal points data. When I'm going to save 12.26, it is save 12. How to create column with saving 2 decimal points.\n\nI tried below code also. It doesn't execute and occurred an error.\n\n```\nitemPrice: {\n type: DataTypes.DECIMAL(10,2),\n allowNull: false,\n field: 'itemPrice'\n },\n```\n\nPlease show me a direction to do this...\n\n========================================\n\nCode:\n```text\nitemPrice: {\n      type: DataTypes.DECIMAL,\n      allowNull: false,\n      field: 'itemPrice'\n    },\n```\n\n```text\nitemPrice: {\n      type: DataTypes.DECIMAL(10,2),\n      allowNull: false,\n      field: 'itemPrice'\n    },\n```\n\n```text\nsequelize.sync({ force: true })\n  .then(()\n```\n\n```text\ntype: DataTypes.DECIMAL(10,2),\n```\n\n```text\nsync\n```\n\n```text\n{force: true}\n```\n\n```text\nsync\n```\n\n========================================\n\nComments:\n- Thanks... Now Decimal(10,2) worked... I dont know what happened in earlier... Anyway, good to know, if I use { force : true } will drop the table and re-create.... :)\n- That, or `{alter: true}`\n- A bit late to the party, but it's interesting to look into Umzug (github.com/sequelize/umzug) , which allows you to specify migrations.","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":382}}364{"id":"stack-53090294","source":"stackoverflow","questionId":53090294,"title":"How to define sequelize associations in typescript?","tags":["typescript","sequelize.js"],"text":"Title: How to define sequelize associations in typescript?\nTags: typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a Product table and an AccountingPeriod table, with a *belongsTo* relationship from Product.manufacturingPeriodId to AccountingPeriod.id.\n\nThe code below compiles but blows up with **\"Naming collision between attribute 'manufacturingPeriod' and association 'manufacturingPeriod' on model Product. To remedy this, change either foreignKey or as in your association definition\"** at run time.\n\nIf I change `as` in the association code at the very bottom as instructed, I also blow up, but this time with **\"AccountingPeriod is associated to Product using an alias. You've included an alias (accountingPeriod), but it does not match the alias defined in your association\".** That second error message is especially puzzling, since I don't specify an alias named *accountingPeriod*.\n\nDoh! Seems like a Catch-22 to me. \n\nOf course, I can remove `ProductAttributes.manufacturingPeriod`, put back `manufacturingPeriodId: number;` and rename `manufacturingPeriod` back to `manufacturingPeriodId` in the options object in the call to sequelize.define(). That compiles and runs just fine, but then I can't code something like `myproduct.manufacturingPeriod.startDate` in typescript.\n\nI've tried various other approaches. All have failed, so I'm raising the white flag of surrender. Can anyone help me out? I'm experienced with sequelize but relatively new to typescript and I'm just not seein' it. \n\n```\nimport * as Sequelize from 'sequelize';\nimport {ObjectRelationalManager as orm} from '../index';\nimport {AccountingPeriodInstance} from './accounting-period';\n\nexport interface ProductAttributes {\n id?: number;\n name: string;\n manufacturingPeriod: AccountingPeriodInstance;\n}\n\nexport interface ProductInstance extends Sequelize.Instance, ProductAttributes {}\n\nexport default (\n sequelize: Sequelize.Sequelize,\n dataTypes: Sequelize.DataTypes\n): Sequelize.Model => {\n return sequelize.define(\n 'Product',\n {\n id: {\n type: dataTypes.INTEGER,\n field: 'id',\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: dataTypes.STRING(20),\n field: 'name',\n allowNull: false\n },\n manufacturingPeriod: {\n type: dataTypes.INTEGER,\n field: 'manufacturingPeriodId',\n allowNull: false,\n references: {\n model: 'AccountingPeriod',\n key: 'id'\n },\n onDelete: 'NO ACTION',\n onUpdate: 'NO ACTION'\n }\n },\n {\n tableName: 'Product'\n }\n );\n};\n\nexport function createAssociations(): void {\n orm.Product.belongsTo(orm.AccountingPeriod, {\n as: 'manufacturingPeriod',\n // foreignKey: 'manufacturingPeriodId',\n targetKey: 'id',\n onDelete: 'NO ACTION',\n onUpdate: 'NO ACTION'\n });\n}\n```\n\n========================================\n\nCode:\n```text\nimport * as Sequelize from 'sequelize';\nimport {ObjectRelationalManager as orm} from '../index';\nimport {AccountingPeriodInstance} from './accounting-period';\n\nexport interface ProductAttributes {\n    id?: number;\n    name: string;\n    manufacturingPeriod: AccountingPeriodInstance;\n}\n\nexport interface ProductInstance extends Sequelize.Instance<ProductAttributes>, ProductAttributes {}\n\nexport default (\n    sequelize: Sequelize.Sequelize,\n    dataTypes: Sequelize.DataTypes\n): Sequelize.Model<ProductInstance, ProductAttributes> => {\n    return sequelize.define<ProductInstance, ProductAttributes>(\n        'Product',\n        {\n            id: {\n                type: dataTypes.INTEGER,\n                field: 'id',\n                allowNull: false,\n                primaryKey: true,\n                autoIncrement: true\n            },\n            name: {\n                type: dataTypes.STRING(20),\n                field: 'name',\n                allowNull: false\n            },\n            manufacturingPeriod: {\n                type: dataTypes.INTEGER,\n                field: 'manufacturingPeriodId',\n                allowNull: false,\n                references: {\n                    model: 'AccountingPeriod',\n                    key: 'id'\n                },\n                onDelete: 'NO ACTION',\n                onUpdate: 'NO ACTION'\n            }\n        },\n        {\n            tableName: 'Product'\n        }\n    );\n};\n\nexport function createAssociations(): void {\n    orm.Product.belongsTo(orm.AccountingPeriod, {\n        as: 'manufacturingPeriod',\n        // foreignKey: 'manufacturingPeriodId',\n        targetKey: 'id',\n        onDelete: 'NO ACTION',\n        onUpdate: 'NO ACTION'\n    });\n}\n```\n\n```text\nas\n```\n\n```text\nProductAttributes.manufacturingPeriod\n```\n\n```text\nmanufacturingPeriodId: number;\n```\n\n```text\nmanufacturingPeriod\n```\n\n```text\nmanufacturingPeriodId\n```\n\n```text\nmyproduct.manufacturingPeriod.startDate\n```\n\n```text\nexport interface ProductInstance extends Sequelize.Instance<ProductAttributes>, ProductAttributes {\n    manufacturingPeriod: AccountingPeriodInstance;\n}\n```\n\n```text\nexport interface ProductInstance extends Sequelize.Instance<ProductAttributes>, ProductAttributes {\n    manufacturingPeriod: AccountingPeriodInstance;\n    getAccountingPeriod: Sequelize.BelongsToGetAssociationMixin<AccountingPeriodInstance>;\n    setAccountingPeriod: Sequelize.BelongsToSetAssociationMixin<AccountingPeriodInstance, number>;\n    createAccountingPeriod: Sequelize.BelongsToCreateAssociationMixin<AccountingPeriodAttributes>;\n}\n```\n\n```text\n{RelationShipType}{Add}AssociationMixin<TInstance>\n```\n\n```text\n{RelationShipType}{Remove}AssociationMixin<TInstance>\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":188,"estimatedTokens":1364}}365{"id":"stack-26832391","source":"stackoverflow","questionId":26832391,"title":"Sequelize correctly executing multiple creates + updates","tags":["promise","sequelize.js"],"text":"Title: Sequelize correctly executing multiple creates + updates\nTags: promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a cron job that scrapes a list of items on a website and then inserts or updates records in a database. When I scrape the page, I want to create records for new ones that haven't been created yet, otherwise update any existing ones. Currently I'm doing something like this:\n\n```\n// pretend there is a \"Widget\" model defined\n\nfunction createOrUpdateWidget(widgetConfig) {\n return Widget.find(widgetConfig.id)\n .then(function(widget) {\n if (widget === null) {\n return Widget.create(widgetConfig);\n }\n else {\n widget.updateAttributes(widgetConfig);\n }\n });\n}\n\nfunction createOrUpdateWidgets(widgetConfigObjects) {\n var promises = [];\n\n widgetConfigObjects.forEach(function(widgetConfig) {\n promises.push(createOrUpdateWidget(widgetConfig));\n });\n\n return Sequelize.Promise.all(promises);\n}\n\ncreateOrUpdateWidgets([...])\n .done(function() {\n console.log('Done!');\n });\n```\n\nThis seems to work fine, but I'm not sure if I'm doing this \"correctly\" or not. Do all promises that perform DB interactions need to run serially, or is how I have them defined ok? Is there a better way to do this kind of thing?\n\n========================================\n\nCode:\n```text\n// pretend there is a \"Widget\" model defined\n\nfunction createOrUpdateWidget(widgetConfig) {\n    return Widget.find(widgetConfig.id)\n        .then(function(widget) {\n            if (widget === null) {\n                return Widget.create(widgetConfig);\n            }\n            else {\n                widget.updateAttributes(widgetConfig);\n            }\n        });\n}\n\nfunction createOrUpdateWidgets(widgetConfigObjects) {\n    var promises = [];\n\n    widgetConfigObjects.forEach(function(widgetConfig) {\n        promises.push(createOrUpdateWidget(widgetConfig));\n    });\n\n    return Sequelize.Promise.all(promises);\n}\n\n\ncreateOrUpdateWidgets([...])\n    .done(function() {\n        console.log('Done!');\n    });\n```\n\n```text\nfunction createOrUpdateWidgets(widgetConfigObjects) {\n    var promises = [];\n\n    widgetConfigObjects.forEach(function(widgetConfig) {\n        promises.push(createOrUpdateWidget(widgetConfig));\n    });\n\n    return Sequelize.Promise.all(promises);\n}\n```\n\n```text\nfunction createOrUpdateWidgets(widgetConfigObjects) {\n    return Sequelize.Promise.map(widgetConfig, createOrUpdateWidget)\n}\n```\n\n```text\n.map\n```\n\n========================================\n\nComments:\n- Thank you for the logic alone. Struggling with this.\n- In terms of interaction with the database, are having all these separate \"parallel\" promises \"safe\"? As opposed to daisy chaining them in a serial manner.\n- @chinabuffet yes, you have no guarantee on the execution order though - that is one might execute before the other. If you'd like to chain them in a sequential matter, you can swap `Promise.map` for `Promise.each` but I don't think it'd matter much in this case as the updates aren't related.","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":103,"estimatedTokens":745}}366{"id":"stack-17924819","source":"stackoverflow","questionId":17924819,"title":"How to insert a null value in Sequelize with omitNull flag?","tags":["node.js","sequelize.js"],"text":"Title: How to insert a null value in Sequelize with omitNull flag?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an instance of Sequelize with the flag omitNull to insert de defaultValues defined in the DB if i do not define them in the create method of a model. Like this: \n\n```\nvar sequelize = new Sequelize('db', 'user', 'pw', {\n omitNull: true\n})\n```\n\nBut I want to insert null values in other models if I define them as null. Like:\n\n```\nSomeModel.create({some_property: null});\n```\n\nIs there a way to define the omitNull property just for some properties of a model?\n\n========================================\n\nTop Answer:\nIf you're using sequelize < v2.0, a hackier, alternative solution would be to \n\n```\nsequelize.options.omitNull = false;\n\nSomeModel.some_property = null;\nSomeModel.save();\n\nsequelize.options.omitNull = true;\n```\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize('db', 'user', 'pw', {\n  omitNull: true\n})\n```\n\n```text\nSomeModel.create({some_property: null});\n```\n\n```text\nSomeModel.some_property = null;\nSomeModel.save(['some_property']);\n```\n\n```text\nomitNull = true\n```\n\n```text\nsome_property\n```\n\n```text\nsequelize.options.omitNull = false;\n\nSomeModel.some_property = null;\nSomeModel.save();\n\nsequelize.options.omitNull = true;\n```\n\n```text\nawait User.update({\n    someData: null\n  },{\n    omitNull: false,\n    where: id,\n  })\n```\n\n```text\nawait User.create({\n    someData: null\n  },{\n    omitNull: false,\n  })\n```\n\n========================================\n\nComments:\n- I came across this issue today and your solution is working well for me. @vistur: Please accept this answer\n- I could not believe that this is still the only way, but it is actually true...","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":92,"estimatedTokens":437}}367{"id":"stack-47299181","source":"stackoverflow","questionId":47299181,"title":"PostgreSQL - SequelizeDatabaseError with join table (Code: 42P01)","tags":["postgresql","sequelize.js"],"text":"Title: PostgreSQL - SequelizeDatabaseError with join table (Code: 42P01)\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a join table for many to many relationships. \n\nI am getting the following error:\n\n```\n\"name\": \"SequelizeDatabaseError\",\n\"parent\": {\n \"name\": \"error\",\n \"length\": 110,\n \"severity\": \"ERROR\",\n \"code\": \"42P01\",\n \"position\": \"13\",\n \"file\": \"parse_relation.c\",\n \"line\": \"1160\",\n \"routine\": \"parserOpenTable\",\n \"sql\": \"INSERT INTO \\\"user_routes\\\" (\\\"id\\\",\\\"userId\\\",\\\"routeId\\\",\\\"createdAt\\\",\\\"updatedAt\\\") VALUES (DEFAULT,'1','1','2017-11-15 03:57:21.791 +00:00','2017-11-15 03:57:21.791 +00:00') RETURNING *;\"\n},\n```\n\nThe relationship is between `User` and `Route`:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Route = sequelize.define(\"Route\", {\n open: {\n type: DataTypes.BOOLEAN,\n allowNull: true\n }\n });\n\n Route.associate = models => {\n Route.belongsToMany(models.User, {\n through: \"userRoutes\",\n as: \"users\"\n });\n };\n return Route;\n};\n\nmodule.exports = (sequelize, DataTypes) => {\n var User = sequelize.define(\"User\", {\n email: DataTypes.TEXT,\n password: DataTypes.TEXT\n });\n\n User.associate = models => {\n User.belongsToMany(models.Route, {\n through: \"userRoutes\",\n as: \"routes\"\n });\n };\n\n return User;\n};\n```\n\nMigration files for user and route does not have much but just the basics. For join table:\n\n```\n\"use strict\";\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable(\"user_route\", {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n userId: {\n type: Sequelize.INTEGER,\n onDelete: \"CASCADE\",\n references: {\n model: \"Users\",\n key: \"id\"\n }\n },\n routeId: {\n type: Sequelize.INTEGER,\n onDelete: \"CASCADE\",\n references: {\n model: \"Routes\",\n key: \"id\"\n }\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable(\"user_route\");\n }\n};\n```\n\nMy controller and route is as following:\n\n```\ncreate(req, res) {\n return UserRoutes.create({\n userId: req.body.userId,\n routeId: req.body.routeId\n })\n .then(userRoute => res.status(201).send(userRoute))\n .catch(err => res.status(400).send(err));\n },\n\napp.post(\"/api/userRoutes\", userRoutesController.create);\n```\n\nSo when I try to post to that route, I get the error message on the top of the post.\n\n========================================\n\nTop Answer:\nAfter you created db, models and migrations, you need to run\n\n```\nsequelize db:migrate\n```\n\nbefore running your application.\n\nIf not, it will throw **SequelizeDatabaseError** as mentioned above.\n\n========================================\n\nCode:\n```text\n\"name\": \"SequelizeDatabaseError\",\n\"parent\": {\n    \"name\": \"error\",\n    \"length\": 110,\n    \"severity\": \"ERROR\",\n    \"code\": \"42P01\",\n    \"position\": \"13\",\n    \"file\": \"parse_relation.c\",\n    \"line\": \"1160\",\n    \"routine\": \"parserOpenTable\",\n    \"sql\": \"INSERT INTO \\\"user_routes\\\" (\\\"id\\\",\\\"userId\\\",\\\"routeId\\\",\\\"createdAt\\\",\\\"updatedAt\\\") VALUES (DEFAULT,'1','1','2017-11-15 03:57:21.791 +00:00','2017-11-15 03:57:21.791 +00:00') RETURNING *;\"\n},\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Route = sequelize.define(\"Route\", {\n    open: {\n      type: DataTypes.BOOLEAN,\n      allowNull: true\n    }\n  });\n\n  Route.associate = models => {\n    Route.belongsToMany(models.User, {\n      through: \"userRoutes\",\n      as: \"users\"\n    });\n  };\n  return Route;\n};\n\n\nmodule.exports = (sequelize, DataTypes) => {\n  var User = sequelize.define(\"User\", {\n    email: DataTypes.TEXT,\n    password: DataTypes.TEXT\n  });\n\n  User.associate = models => {\n    User.belongsToMany(models.Route, {\n      through: \"userRoutes\",\n      as: \"routes\"\n    });\n  };\n\n  return User;\n};\n```\n\n```text\n\"use strict\";\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable(\"user_route\", {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      userId: {\n        type: Sequelize.INTEGER,\n        onDelete: \"CASCADE\",\n        references: {\n          model: \"Users\",\n          key: \"id\"\n        }\n      },\n      routeId: {\n        type: Sequelize.INTEGER,\n        onDelete: \"CASCADE\",\n        references: {\n          model: \"Routes\",\n          key: \"id\"\n        }\n      }\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable(\"user_route\");\n  }\n};\n```\n\n```text\ncreate(req, res) {\n    return UserRoutes.create({\n      userId: req.body.userId,\n      routeId: req.body.routeId\n    })\n      .then(userRoute => res.status(201).send(userRoute))\n      .catch(err => res.status(400).send(err));\n  },\n\n\n\napp.post(\"/api/userRoutes\", userRoutesController.create);\n```\n\n```text\nUser\n```\n\n```text\nRoute\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\n\"routine\": \"parserOpenTable\"\n```\n\n```text\n\"./models/user.js\"\n```\n\n========================================\n\nComments:\n- I think i kind of figured out the issue. The problem is with the naming convention in sequelize and postgres. Something is not being transfered. It has nothing to do with the many to many relationships. I will update once I resolve the issue.","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":272,"estimatedTokens":1365}}368{"id":"stack-36872345","source":"stackoverflow","questionId":36872345,"title":"Sequelize one to many assocation in multiple files","tags":["node.js","sequelize.js","bluebird"],"text":"Title: Sequelize one to many assocation in multiple files\nTags: node.js, sequelize.js, bluebird\nSource: Stack Overflow\n\nQuestion:\nI am working on one to many assocations with sequelize. Most tutorials and documentation shows examples when both models are defined in the same file.\nI currently have two files, first city.js:\n\n```\nconst Promise = require('bluebird');\nvar Country = require('./country');\n\nvar City = sequelize.define(\"City\", {\n id: {\n type: DataTypes.INTEGER,\n field: 'id',\n primaryKey: true,\n autoIncrement: true\n },...\n}, {\n freezeTableName: true,\n timestamps: false\n});\n\nCity.belongsTo(Country, {foreignKey : 'countryId', as: 'Country'});\n\nPromise.promisifyAll(City);\nmodule.exports = City;\n```\n\nAnd a second file country.js:\n\n```\nconst Promise = require('bluebird');\nvar City = require('./city');\n\nvar Country = sequelize.define(\"Country\", {\n id: {\n type: DataTypes.INTEGER,\n field: 'id',\n primaryKey: true,\n autoIncrement: true\n },\n ...\n}, {\n freezeTableName: true,\n timestamps: false,\n paranoid: false\n});\n\nCountry.hasMany(City, {foreignKey : 'countryId', as: 'Cities'});\n\nPromise.promisifyAll(Country);\nmodule.exports = Country;\n```\n\nWhen I import both modules and try to instantiate object:\n\n```\nvar City = require('../model/external/city');\nvar CountryRepository = require('../repository/external/countryRepository');\n\nCountryRepository.findById(1).then(function(country) {\n var city = City.build();\n city.name = 'Paris';\n city.setCountry(country);\n console.log('OK');\n});\n```\n\nI get the following error:\n\n throw new Error(this.name + '.' +\n Utils.lowercaseFirst(Type.toString()) + ' called with something\n that\\'s not an instance of Sequelize.Model')\n\nIs the problem that models are promisified before they are exported from model or am I missing something?\n\n========================================\n\nTop Answer:\nYou have to declare the associations after having export all your models\n\nI had the same problem!\n\n========================================\n\nCode:\n```text\nconst Promise = require('bluebird');\nvar Country = require('./country');\n\nvar City = sequelize.define(\"City\", {\n  id: {\n    type: DataTypes.INTEGER,\n    field: 'id',\n    primaryKey: true,\n    autoIncrement: true\n  },...\n}, {\n  freezeTableName: true,\n  timestamps: false\n});\n\nCity.belongsTo(Country, {foreignKey : 'countryId', as: 'Country'});\n\nPromise.promisifyAll(City);\nmodule.exports = City;\n```\n\n```text\nconst Promise = require('bluebird');\nvar City = require('./city');\n\nvar Country = sequelize.define(\"Country\", {\n  id: {\n    type: DataTypes.INTEGER,\n    field: 'id',\n    primaryKey: true,\n    autoIncrement: true\n  },\n  ...\n}, {\n  freezeTableName: true,\n  timestamps: false,\n  paranoid: false\n});\n\nCountry.hasMany(City, {foreignKey : 'countryId', as: 'Cities'});\n\nPromise.promisifyAll(Country);\nmodule.exports = Country;\n```\n\n```text\nvar City = require('../model/external/city');\nvar CountryRepository = require('../repository/external/countryRepository');\n\nCountryRepository.findById(1).then(function(country) {\n    var city = City.build();\n    city.name = 'Paris';\n    city.setCountry(country);\n    console.log('OK');\n});\n```\n\n```text\nCity.belongsTo(model.Country, {foreignKey : 'countryId', as: 'Country'});\n```\n\n```text\nindex.js\n```\n\n```text\nmodel\n```\n\n```text\nmodel.Country\n```\n\n```text\nconst { Model, DataTypes } = require('sequelize');\nmodule.exports = function(sequelize){\n    class User extends Model {}\n    return User.init({\n      id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n      },\n      name: {\n          type: DataTypes.STRING,\n          allowNull: false\n      },\n      trading_system_key: {\n          type: DataTypes.STRING,\n          allowNull: false\n      },\n    }, {\n      sequelize,\n      modelName: 'User',\n      indexes: [{ unique: true, fields: ['trading_system_key'] }]\n    });\n};\n```\n\n```text\nconst { Model, DataTypes } = require('sequelize');\nconst User = require('../models/user');\n\nmodule.exports = function(sequelize){\n    class Algorithm extends Model {}\n    UserModel = User(sequelize);//@JA - Gets a defined version of user class\n\n    var AlgorithmFrame = Algorithm.init({\n        id: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false,\n        },\n        user_Id: {\n            type: DataTypes.INTEGER,\n            references: { \n                model: UserModel,\n                key: 'id',\n            },\n        }\n    }, {\n      sequelize,\n      modelName: 'Algorithm',\n      indexes: [{ unique: true, fields: ['name','user_id'] }]\n    });\n\n    return AlgorithmFrame\n};\n```\n\n```text\nconst { Sequelize, DataTypes, Model } = require('sequelize');\nconst User = require('../models/user');\nconst Algorithm = require('../models/algorithm');\n\nconst sequelize = new Sequelize('database', 'username', 'passwordhere', {\n      host: 'db',\n      dialect: 'mysql' /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */\n    });\n\nconst UserModel = User(sequelize);\nconst AlogorithmModel = Algorithm(sequelize);\n\n(async () => {\n      try {\n        await sequelize.authenticate();\n        await UserModel.sync({ alter: true });\n        await AlogorithmModel.sync({ alter: true });\n\n        //Do something with the models now....\n        //Etc...\n\n      } catch (error) {\n        console.error('Unable to connect to the database:', error);\n      }\n\n});\n```\n\n```text\nconst UserModel = User(sequelize);\n```\n\n```text\nalgorithm_id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            onDelete: 'CASCADE',\n            onUpdate: 'CASCADE',\n            references: { \n                model: AlgorithmModel,\n                key: 'id',\n            }\n        },\n```\n\n```text\nindexes: [{ unique: true, fields: ['name','user_id'] }]\n```\n\n```text\nclass user extends model {}\n```\n\n```text\nconst User = require('../models/user');\n```\n\n========================================\n\nComments:\n- Thank you, with a little index.js modification I got the results I wanted\n- Can u elaborate in detail, when I have to put the code as I did exactly same as user.js but can't getting an error like { SequelizeEagerLoadingError: ticket is not associated to ticketComment!\n- I had the same issue and solved it by following this advice (i.e. defining all the associations in one file). But is this really a good idea? To see a model's information, you have to see the model declaration AND the association file. I wonder if both model declarations and associations can be stored in one file\n- Links are dead.\n- The one thing I don't have accounted in this is the onUpdate and onDelete cascade option settings, I'm not sure where to put these yet. So if someone can amend my answer with that I would appreciate it!\n- Ok good news I figured out how to do onUpdate and on Delete cascade options! Will update my answer","metadata":{"transformedAt":"2026-08-18T18:33:34.369Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":290,"estimatedTokens":1730}}369{"id":"stack-48199643","source":"stackoverflow","questionId":48199643,"title":"ERROR: Cannot find \"/config/config.json\". Have you run \"sequelize init\"?","tags":["node.js","docker","docker-compose","sequelize.js","dockerfile"],"text":"Title: ERROR: Cannot find \"/config/config.json\". Have you run \"sequelize init\"?\nTags: node.js, docker, docker-compose, sequelize.js, dockerfile\nSource: Stack Overflow\n\nQuestion:\nI have this Dockerfile for my API project using Node.js - Express.js \n\n**api.dockerfile**\n\n```\nFROM node:9.3.0\n\nCOPY package.json ./\n\nRUN npm set progress=false && npm config set depth 0 && npm cache clean --force\n\n## Storing node modules on a separate layer will prevent unnecessary npm installs at each build\nRUN npm i && npm install nodemon --save \\\n && npm install pm2 -g \\\n && npm install -g sequelize-cli \\\n && mkdir /ng-app \\\n && chown -R node:node /ng-app \\\n && cp -R ./node_modules ./ng-app\n\n# Migration\nRUN sequelize db:migrate\nRUN sequelize db:seed:all\n\nUSER node\n\nWORKDIR /ng-app\n\nCOPY . .\nRUN mv docker.env .env\n\nCMD [\"pm2-runtime\", \"index.js\"]\n```\n\n**docker-compose.yaml**\n\n```\nversion: \"2\"\nservices:\n iproject-api:\n build:\n context: ./api\n dockerfile: api.dockerfile\n image: 'iproject-api'\n ports:\n - '3002:3002'\n iproject-web:\n build:\n context: ./web\n dockerfile: web.dockerfile\n image: 'iproject-web:latest'\n ports:\n - '8080:8080'\n links:\n - iproject-api\n```\n\n**This is the result, I got** \n\n```\n**docker-compose build --no-cache**\n\nBuilding iproject-api\nStep 1/11 : FROM node:9.3.0\n ---> 3d1823068e39\nStep 2/11 : COPY package.json ./\n ---> 68d259bbd036\nRemoving intermediate container 792b207a42ed\nStep 3/11 : RUN npm set progress=false && npm config set depth 0 && npm cache clean --force\n ---> Running in ebd53a0f0e3d\nnpm WARN using --force I sure hope you know what you are doing.\n ---> cd598f62f4e5\nRemoving intermediate container ebd53a0f0e3d\nStep 4/11 : RUN npm i && npm install nodemon --save && npm install pm2 -g && npm install -g sequelize-cli && mkdir /ng-app && chown -R node:node /ng-app && cp -R ./node_modules ./ng-app\n ---> Running in 492ea3c40c22\n\n> bcrypt@1.0.3 install /node_modules/bcrypt\n> node-pre-gyp install --fallback-to-build\n\nnode-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.3/bcrypt_lib-v1.0.3-node-v59-linux-x64.tar.gz \nnode-pre-gyp ERR! Pre-built binaries not found for bcrypt@1.0.3 and node@9.3.0 (node-v59 ABI) (falling back to source compile with node-gyp) \nmake: Entering directory '/node_modules/bcrypt/build'\n CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o\n CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt.o\n CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt_node.o\nIn file included from ../../nan/nan.h:192:0,\n from ../src/bcrypt_node.cc:1:\n../../nan/nan_maybe_43_inl.h: In function 'Nan::Maybe Nan::ForceSet(v8::Local, v8::Local, v8::Local, v8::PropertyAttribute)':\n../../nan/nan_maybe_43_inl.h:112:73: warning: 'v8::Maybe v8::Object::ForceSet(v8::Local, v8::Local, v8::Local, v8::PropertyAttribute)' is deprecated (declared at /root/.node-gyp/9.3.0/include/node/v8.h:3114): Use CreateDataProperty / DefineOwnProperty [-Wdeprecated-declarations]\n return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs);\n ^\n SOLINK_MODULE(target) Release/obj.target/bcrypt_lib.node\n COPY Release/bcrypt_lib.node\n COPY /node_modules/bcrypt/lib/binding/bcrypt_lib.node\n TOUCH Release/obj.target/action_after_build.stamp\nmake: Leaving directory '/node_modules/bcrypt/build'\nnpm notice created a lockfile as package-lock.json. You should commit this file.\nadded 259 packages in 9.9s\n\n> nodemon@1.14.10 postinstall /node_modules/nodemon\n> node -e \"console.log('\\u001b[32mLove nodemon? You can now support the project via the open collective:\\u001b[22m\\u001b[39m\\n > \\u001b[96m\\u001b[1mhttps://opencollective.com/nodemon/donate\\u001b[0m\\n')\" || exit 0\n\nLove nodemon? You can now support the project via the open collective:\n > https://opencollective.com/nodemon/donate\n\nnpm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):\nnpm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n\n+ nodemon@1.14.10\nadded 246 packages in 7.093s\n/usr/local/bin/pm2 -> /usr/local/lib/node_modules/pm2/bin/pm2\n/usr/local/bin/pm2-dev -> /usr/local/lib/node_modules/pm2/bin/pm2-dev\n/usr/local/bin/pm2-runtime -> /usr/local/lib/node_modules/pm2/bin/pm2-runtime\n/usr/local/bin/pm2-docker -> /usr/local/lib/node_modules/pm2/bin/pm2-docker\nnpm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/pm2/node_modules/fsevents):\nnpm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n\n+ pm2@2.9.1\nadded 251 packages in 6.35s\n/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/lib/sequelize\n+ sequelize-cli@3.2.0\nadded 105 packages in 3.718s\n ---> 19c196ba636a\nRemoving intermediate container 492ea3c40c22\nStep 5/11 : RUN sequelize db:migrate\n ---> Running in cc84d0fbfc57\n\nSequelize CLI [Node: 9.3.0, CLI: 3.2.0, ORM: 4.31.0]\n\nWARNING: This version of Sequelize CLI is not fully compatible with Sequelize v4. https://github.com/sequelize/cli#sequelize-support\n```\n\n ERROR: Cannot find \"/config/config.json\". Have you run \"sequelize init\"?\n\nHow would one go about debugging this?\n\n========================================\n\nTop Answer:\nYou can create a **.sequelizerc** config file for **Sequlize** CLI command for your project which tells **Sequlize** where to look for config files.\n\n```\nvar path = require('path')\n\nmodule.exports = {\n 'config': path.resolve('server', 'config', 'database.json'),\n 'migrations-path': path.resolve('server', 'migrations'),\n 'models-path': path.resolve('server', 'models'),\n 'seeders-path': path.resolve('server', 'seeders'),\n}\n```\n\n========================================\n\nCode:\n```text\nFROM node:9.3.0\n\nCOPY package.json ./\n\nRUN npm set progress=false && npm config set depth 0 && npm cache clean --force\n\n## Storing node modules on a separate layer will prevent unnecessary npm installs at each build\nRUN npm i && npm install nodemon --save \\\n    && npm install pm2 -g \\\n    && npm install -g sequelize-cli \\\n    && mkdir /ng-app \\\n    && chown -R node:node /ng-app \\\n    && cp -R ./node_modules ./ng-app\n\n# Migration\nRUN sequelize db:migrate\nRUN sequelize db:seed:all\n\nUSER node\n\nWORKDIR /ng-app\n\nCOPY . .\nRUN mv docker.env .env\n\nCMD [\"pm2-runtime\", \"index.js\"]\n```\n\n```text\nversion: \"2\"\nservices:\n  iproject-api:\n    build:\n      context: ./api\n      dockerfile: api.dockerfile\n    image: 'iproject-api'\n    ports:\n      - '3002:3002'\n  iproject-web:\n    build:\n      context: ./web\n      dockerfile: web.dockerfile\n    image: 'iproject-web:latest'\n    ports:\n      - '8080:8080'\n    links:\n      - iproject-api\n```\n\n```text\n**docker-compose build --no-cache**\n\nBuilding iproject-api\nStep 1/11 : FROM node:9.3.0\n ---> 3d1823068e39\nStep 2/11 : COPY package.json ./\n ---> 68d259bbd036\nRemoving intermediate container 792b207a42ed\nStep 3/11 : RUN npm set progress=false && npm config set depth 0 && npm cache clean --force\n ---> Running in ebd53a0f0e3d\nnpm WARN using --force I sure hope you know what you are doing.\n ---> cd598f62f4e5\nRemoving intermediate container ebd53a0f0e3d\nStep 4/11 : RUN npm i && npm install nodemon --save     && npm install pm2 -g     && npm install -g sequelize-cli     && mkdir /ng-app     && chown -R node:node /ng-app     && cp -R ./node_modules ./ng-app\n ---> Running in 492ea3c40c22\n\n> bcrypt@1.0.3 install /node_modules/bcrypt\n> node-pre-gyp install --fallback-to-build\n\nnode-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.3/bcrypt_lib-v1.0.3-node-v59-linux-x64.tar.gz \nnode-pre-gyp ERR! Pre-built binaries not found for bcrypt@1.0.3 and node@9.3.0 (node-v59 ABI) (falling back to source compile with node-gyp) \nmake: Entering directory '/node_modules/bcrypt/build'\n  CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o\n  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt.o\n  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt_node.o\nIn file included from ../../nan/nan.h:192:0,\n                 from ../src/bcrypt_node.cc:1:\n../../nan/nan_maybe_43_inl.h: In function 'Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object>, v8::Local<v8::Value>, v8::Local<v8::Value>, v8::PropertyAttribute)':\n../../nan/nan_maybe_43_inl.h:112:73: warning: 'v8::Maybe<bool> v8::Object::ForceSet(v8::Local<v8::Context>, v8::Local<v8::Value>, v8::Local<v8::Value>, v8::PropertyAttribute)' is deprecated (declared at /root/.node-gyp/9.3.0/include/node/v8.h:3114): Use CreateDataProperty / DefineOwnProperty [-Wdeprecated-declarations]\n   return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs);\n                                                                         ^\n  SOLINK_MODULE(target) Release/obj.target/bcrypt_lib.node\n  COPY Release/bcrypt_lib.node\n  COPY /node_modules/bcrypt/lib/binding/bcrypt_lib.node\n  TOUCH Release/obj.target/action_after_build.stamp\nmake: Leaving directory '/node_modules/bcrypt/build'\nnpm notice created a lockfile as package-lock.json. You should commit this file.\nadded 259 packages in 9.9s\n\n> nodemon@1.14.10 postinstall /node_modules/nodemon\n> node -e \"console.log('\\u001b[32mLove nodemon? You can now support the project via the open collective:\\u001b[22m\\u001b[39m\\n > \\u001b[96m\\u001b[1mhttps://opencollective.com/nodemon/donate\\u001b[0m\\n')\" || exit 0\n\nLove nodemon? You can now support the project via the open collective:\n > https://opencollective.com/nodemon/donate\n\nnpm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):\nnpm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n\n+ nodemon@1.14.10\nadded 246 packages in 7.093s\n/usr/local/bin/pm2 -> /usr/local/lib/node_modules/pm2/bin/pm2\n/usr/local/bin/pm2-dev -> /usr/local/lib/node_modules/pm2/bin/pm2-dev\n/usr/local/bin/pm2-runtime -> /usr/local/lib/node_modules/pm2/bin/pm2-runtime\n/usr/local/bin/pm2-docker -> /usr/local/lib/node_modules/pm2/bin/pm2-docker\nnpm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/pm2/node_modules/fsevents):\nnpm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"linux\",\"arch\":\"x64\"})\n\n+ pm2@2.9.1\nadded 251 packages in 6.35s\n/usr/local/bin/sequelize -> /usr/local/lib/node_modules/sequelize-cli/lib/sequelize\n+ sequelize-cli@3.2.0\nadded 105 packages in 3.718s\n ---> 19c196ba636a\nRemoving intermediate container 492ea3c40c22\nStep 5/11 : RUN sequelize db:migrate\n ---> Running in cc84d0fbfc57\n\nSequelize CLI [Node: 9.3.0, CLI: 3.2.0, ORM: 4.31.0]\n\nWARNING: This version of Sequelize CLI is not fully compatible with Sequelize v4. https://github.com/sequelize/cli#sequelize-support\n```\n\n```text\nsequelize\n```\n\n```text\nconfig/config.json\n```\n\n```text\n/\n```\n\n```text\n/ng-app\n```\n\n```text\nWORKDIR /ng-app\n```\n\n```text\nsequalize\n```\n\n```text\nvar path = require('path')\n\nmodule.exports = {\n  'config':          path.resolve('server', 'config', 'database.json'),\n  'migrations-path': path.resolve('server', 'migrations'),\n  'models-path':     path.resolve('server', 'models'),\n  'seeders-path':    path.resolve('server', 'seeders'),\n}\n```\n\n```text\nconfig\n```\n\n```text\nmodels\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nsequelize init\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":332,"estimatedTokens":2850}}370{"id":"stack-49465065","source":"stackoverflow","questionId":49465065,"title":"Sequelize: Check and add BelongsToMany (N to N) relation","tags":["javascript","mysql","node.js","orm","sequelize.js"],"text":"Title: Sequelize: Check and add BelongsToMany (N to N) relation\nTags: javascript, mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy application got **many Users** who can **like many Posts** (N to N). That's why I assigned the following \"belongsToMany\" Relations for my Models (Sequelize Doc):\n\n```\n// Post Model\nmodels.Post.belongsToMany(models.User, { through: models.PostLikes});\n\n// User Model\nmodels.User.belongsToMany(models.Post, { through: models.PostLikes});\n```\n\nInside my Post Controller I got the following use case for the \"likePost\" function:\n\n- Check if the Post exists. (seems to work)\n\n- If so, check if the User already liked this Post.\nIf not, assign the N to N relation between User and the Post. (seems to work)\n\n```\n// User likes Post\nexports.likePost = async (req, res) => {\n const postToLike = await Post.findById(req.body.postId);\n // Check if the Post exists\n if (!postToLike) {\n return res.status(404).json({ error: { message: 'Post not found.' }});\n }\n\n // Did user already like the post?\n // HERE IS THE NOT WORKING PART:\n if (await req.user.hasPost(postToLike).isFulfilled()) {\n return res.status(422).json({ error: { message: 'Already liked post.' }});\n }\n\n // add Like\n await req.user.addPost(postToLike);\n return res.send(postToLike);\n};\n```\n\nNow I got the **Problem**, that I am not able to check if a User already liked a Post. \"req.user.hasPost(postToLike).isFulfilled()\" always returns false, even if indeed I can see the correct relation in my \"PostLikes\" DB Table. So how can I correctly:\n\n- Check if a User already liked a Post.\n\n- Assign this relation.\n\n- And remove the relation with Sequelize?\n\nBTW this is how my PostLikes Table looks like:\n\n```\n+----+--------+--------+\n| id | userId | postId |\n+----+--------+--------+\n| 1 | 2 | 3 |\n+----+--------+--------+\n```\n\n========================================\n\nCode:\n```text\n// Post Model\nmodels.Post.belongsToMany(models.User, { through: models.PostLikes});\n\n// User Model\nmodels.User.belongsToMany(models.Post, { through: models.PostLikes});\n```\n\n```text\n// User likes Post\nexports.likePost = async (req, res) => {\n const postToLike = await Post.findById(req.body.postId);\n // Check if the Post exists\n if (!postToLike) {\n  return res.status(404).json({ error: { message: 'Post not found.' }});\n }\n\n // Did user already like the post?\n // HERE IS THE NOT WORKING PART:\n if (await req.user.hasPost(postToLike).isFulfilled()) {\n  return res.status(422).json({ error: { message: 'Already liked post.' }});\n }\n\n // add Like\n await req.user.addPost(postToLike);\n return res.send(postToLike);\n};\n```\n\n```text\n+----+--------+--------+\n| id | userId | postId |\n+----+--------+--------+\n|  1 |      2 |      3 |\n+----+--------+--------+\n```\n\n```text\nreq.user.hasPost(postToLike)\n```\n\n========================================\n\nComments:\n- You need a many-to-many table relating `Users` and `Posts`. That's easy to do in MySQL; I don't know how to convince the abstraction package you are using to do it.\n- I logged `req.user.hasPost(postToLike)` and noticed \"isFulfilled()\" is the result of a pending promise. So I change this part to `await req.user.hasPost(postToLike)`. Basically this fixed the whole problem as it returns the expected result now.\n- isFullfilled() is generally not accessed directly. **await** expects a promise, and by calling isFullfilled(), it was not getting a promise to wait on. Can you please accept the answer if it resolved the issue, Thanks :)\n- Hi, i know its been a while but why is it a many to many relationship, since a user can have many posts but a post belongs to one user?","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":112,"estimatedTokens":904}}371{"id":"stack-36058931","source":"stackoverflow","questionId":36058931,"title":"mongoose Schema to sequelize model","tags":["mysql","node.js","mongodb","mongoose","sequelize.js"],"text":"Title: mongoose Schema to sequelize model\nTags: mysql, node.js, mongodb, mongoose, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI made one app with `mongodb` (mongoose as ODM) but now I want to work with `MySQL` (work obligation) so I took `Sequelize` module for that, but I really don't understand how to convert my userSchema to user model with all its méthodes (I'm working with `passportJs` for authentication, so I have some methods that I'm using for example setpassword ...) \n\nHere my userSchema (mongoose) that works perfectly.\n\n```\nvar mongoose = require('mongoose');\nvar crypto = require('crypto');\nvar jwt = require('jsonwebtoken');\nvar validator = require('node-mongoose-validator');\nvar Schema = mongoose.Schema;\n\nvar userSchema = new Schema({\n name: {\n type: String,\n maxlength: 50\n },\n mail: {\n type: String,\n required: true,\n maxlength: 50,\n index: {\n unique: true\n }\n },\n hash: String,\n salt: String,\n {\n collection: \"user\"\n }\n);\n\nuserSchema.methods.setPassword = function(password) {\n this.salt = crypto.randomBytes(16).toString('hex');\n this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n};\n\nuserSchema.methods.validPassword = function(password) {\n var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n return this.hash === hash;\n};\n\nuserSchema.methods.generateJwt = function() {\n var expiry = new Date();\n expiry.setDate(expiry.getDate() + 7);\n\n return jwt.sign({\n _id: this._id,\n mail: this.mail,\n name: this.name,\n exp: parseInt(expiry.getTime() / 1000),\n }, process.env.JWT_SECRET); // secret code from .env\n};\n\nmodule.exports = mongoose.model('user', userSchema);\n```\n\nand here what I've tried with sequelize:\n\n```\nvar crypto = require('crypto');\n var jwt = require('jsonwebtoken');\n\n var User = sequelize.define('user', {\n name: Sequelize.STRING,\n mail: Sequelize.STRING,\n hash: Sequelize.STRING,\n salt: Sequelize.STRING\n\n });\n\n User.methods.setPassword = function(password) {\n this.salt = crypto.randomBytes(16).toString('hex');\n this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n };\n\n User.methods.validPassword = function(password) {\n var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n return this.hash === hash;\n };\n\n User.methods.generateJwt = function() {\n var expiry = new Date();\n expiry.setDate(expiry.getDate() + 7);\n\n return jwt.sign({\n _id: this._id,\n mail: this.mail,\n name: this.name,\n exp: parseInt(expiry.getTime() / 1000),\n }, process.env.JWT_SECRET); // DO NOT KEEP YOUR SECRET IN THE CODE!\n };\n\nmodule.exports = User;\n```\n\nI did not test that because I need to develop one other part, but I need to know that do you think about that, I feel that its full of errors\n\nThank you in advance\n\n========================================\n\nCode:\n```text\nvar mongoose = require('mongoose');\nvar crypto = require('crypto');\nvar jwt = require('jsonwebtoken');\nvar validator = require('node-mongoose-validator');\nvar Schema = mongoose.Schema;\n\nvar userSchema = new Schema({\n    name: {\n      type: String,\n      maxlength: 50\n    },\n    mail: {\n      type: String,\n      required: true,\n      maxlength: 50,\n      index: {\n        unique: true\n      }\n    },\n    hash: String,\n    salt: String,\n    {\n      collection: \"user\"\n    }\n);\n\nuserSchema.methods.setPassword = function(password) {\n  this.salt = crypto.randomBytes(16).toString('hex');\n  this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n};\n\nuserSchema.methods.validPassword = function(password) {\n  var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n  return this.hash === hash;\n};\n\nuserSchema.methods.generateJwt = function() {\n  var expiry = new Date();\n  expiry.setDate(expiry.getDate() + 7);\n\n  return jwt.sign({\n    _id: this._id,\n    mail: this.mail,\n    name: this.name,\n    exp: parseInt(expiry.getTime() / 1000),\n  }, process.env.JWT_SECRET); // secret code from .env\n};\n\nmodule.exports = mongoose.model('user', userSchema);\n```\n\n```text\nvar crypto = require('crypto');\n    var jwt = require('jsonwebtoken');\n\n    var User = sequelize.define('user', {\n      name: Sequelize.STRING,\n      mail: Sequelize.STRING,\n      hash: Sequelize.STRING,\n      salt: Sequelize.STRING\n\n\n    });\n\n    User.methods.setPassword = function(password) {\n      this.salt = crypto.randomBytes(16).toString('hex');\n      this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n    };\n\n    User.methods.validPassword = function(password) {\n      var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n      return this.hash === hash;\n    };\n\n    User.methods.generateJwt = function() {\n      var expiry = new Date();\n      expiry.setDate(expiry.getDate() + 7);\n\n      return jwt.sign({\n        _id: this._id,\n        mail: this.mail,\n        name: this.name,\n        exp: parseInt(expiry.getTime() / 1000),\n      }, process.env.JWT_SECRET); // DO NOT KEEP YOUR SECRET IN THE CODE!\n    };\n\n\nmodule.exports = User;\n```\n\n```text\nmongodb\n```\n\n```text\nMySQL\n```\n\n```text\nSequelize\n```\n\n```text\npassportJs\n```\n\n```js\nvar User = sequelize.define('user', {\n  name: DataTypes.STRING,\n  mail: DataTypes.STRING,\n  hash: DataTypes.STRING,\n  salt: DataTypes.STRING,\n/* ... */\n});\n\nUser.prototype.validPassword = function(password) {\n  var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n  return this.hash === hash;\n};\n\n/*\nIf you want an equivalent of User.statics.yourStaticMethod = function() {}\nor User.static('yourstaticmethod', function() {})\nYou can use the following\n*/\n\nUser.yourStaticMethod = function() {};\n```\n\n```text\nclass User extends Model {\n  static yourStaticMethod() {} // in mongoose equivalent to User.statics.yourStaticMethod = function() {}\n  validPassword(password) {\n    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');\n    return this.hash === hash;\n  }\n};\n\nUser.init({\n  name: DataTypes.STRING,\n  mail: DataTypes.STRING,\n  hash: DataTypes.STRING,\n  salt: DataTypes.STRING,\n/* ... */\n}, {\n  sequelize,\n  modelName: 'user'\n});\n```\n\n```text\nsequelize.define\n```\n\n```text\nUser.prototype.yourMethod\n```\n\n```text\nUser\n```\n\n```text\nModel\n```\n\n========================================\n\nComments:\n- Very good question, yet no answers :(\n- Can you get Mongoose to show you the generated SQL?","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":279,"estimatedTokens":1582}}372{"id":"stack-59680367","source":"stackoverflow","questionId":59680367,"title":"Using Connection URIs with Read Replication in Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Using Connection URIs with Read Replication in Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIf I have a connection URI, I can use that normally with Sequelize as such:\n\n```\nconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');\n```\n\nHowever, if I want to use Read and Write replication (https://sequelize.org/master/manual/read-replication.html), then there doesn't seem an option to use connection URI. Can I pass connection URI strings to read and write in the replication option as in:\n\n```\nconst sequelize = new Sequelize(null, null, null, {\n dialect: 'postgres',\n replication: {\n read: [\n 'postgres://user:pass@reader.example.com:5432/dbname',\n 'postgres://user:pass@anotherreader.example.com:5432/dbname'\n ],\n write: 'postgres://user:pass@writer.example.com:5432/dbname'\n }\n})\n```\n\n### EDIT:\n\nI have already found a solution to the issue. and that is using an npm library like connection string to parse the connection string as shown below:\n\n```\nconst write_uri = new ConnectionString(uri);\nconst sequelize = new Sequelize(null, null, null, {\n dialect: 'postgres',\n replication: {\n read: [\n 'postgres://user:pass@reader.example.com:5432/dbname',\n 'postgres://user:pass@anotherreader.example.com:5432/dbname'\n ],\n write: {\n host: write_uri.hosts[0].name,\n username: write_uri.user,\n password: write_uri.password,\n database: write_uri.path[0],\n port: write_uri.hosts[0].port\n }\n }\n});\n```\n\nBut, that is not what I'm looking for.\n\n========================================\n\nTop Answer:\nYou can pass config object to sequelize constructor even if you use uri connection.\nLook the example in from the docs:\nhttps://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor\n\n // with uri\n\n \n `const sequelize = new Sequelize('mysql://localhost:3306/database', {})`\n\nLook at the constructor overloading definition:\n\n```\nSequelize(uri: string, options?: Sequelize.Options): Sequelize.Sequelize\n```\n\nJust pass the options you need.\n\n========================================\n\nCode:\n```text\nconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');\n```\n\n```js\nconst sequelize = new Sequelize(null, null, null, {\n  dialect: 'postgres',\n  replication: {\n    read: [\n      'postgres://user:pass@reader.example.com:5432/dbname',\n      'postgres://user:pass@anotherreader.example.com:5432/dbname'\n    ],\n    write: 'postgres://user:pass@writer.example.com:5432/dbname'\n  }\n})\n```\n\n```text\nconst write_uri = new ConnectionString(uri);\nconst sequelize = new Sequelize(null, null, null, {\n  dialect: 'postgres',\n  replication: {\n    read: [\n      'postgres://user:pass@reader.example.com:5432/dbname',\n      'postgres://user:pass@anotherreader.example.com:5432/dbname'\n    ],\n    write: {\n      host: write_uri.hosts[0].name,\n      username: write_uri.user,\n      password: write_uri.password,\n      database: write_uri.path[0],\n      port: write_uri.hosts[0].port\n    }\n  }\n});\n```\n\n```text\nconstructor(database, username, password, options){\n\n}\n```\n\n```text\noptions\n```\n\n```text\noptions.replication\n```\n\n```text\nhost\n```\n\n```text\nport\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\ndatabase\n```\n\n```text\nobjects\n```\n\n```text\nread:[]\n```\n\n```text\nstrings\n```\n\n```js\nSequelize(uri: string, options?: Sequelize.Options): Sequelize.Sequelize\n```\n\n```text\nconst sequelize = new Sequelize('mysql://localhost:3306/database', {})\n```\n\n========================================\n\nComments:\n- That's not what I'm asking. I've edited my question to be more precise\n- I can't understand your problem. Please clarify what's the wanted result.","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":171,"estimatedTokens":911}}373{"id":"stack-58092358","source":"stackoverflow","questionId":58092358,"title":"Sequelize: SQL Injection with sequelize.query","tags":["node.js","postgresql","sequelize.js","sql-injection"],"text":"Title: Sequelize: SQL Injection with sequelize.query\nTags: node.js, postgresql, sequelize.js, sql-injection\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize with PostgreSQL for the first time. It's also my first time using an SQL database in a long time.\n\nI have been researching how to improve the performance and security of some SQL Queries. I came across the `sequelize.query()` method and started using it for this purpose.\n\nIs this way of making raw queries in Sequelize vulnerable to SQL Injection?\n\n========================================\n\nTop Answer:\nIs this vulnerable to SQL injection: The simple answer is \"yes\". \nYou are using a raw query. If that raw query ever gets input from user input, however indirectly, you open up the possibility of SQL injection. Whether the risk is real or not depends on the rest of your code.\n\nPerformance is different. A raw query may be slightly more performant than using the sequalize methods but is MUCH more dependent on database structure and the nature of the query itself. This is a broad topic that can't be answered from the information given.\n\n========================================\n\nCode:\n```text\nsequelize.query()\n```\n\n```text\nreplacements\n```\n\n========================================\n\nComments:\n- Security and performance are two separate questions, it's best if you ask them independently.\n- why are you using `sequelize.query` anyways? Why not use the model files?\n- If sequelize.query gets the work done and does not have any security or performance loopholes then I will use it. Otherwise will move to querying with ORM.\n- \"*or performance loopholes*\" typically what the ORM will just send the query to the DB engine. There is no \"performance\" to speak of, as it's the DB engine that is going to run the query. So, if you supply a bad query, it doesn't matter which library you give it to in order to be handed off to the same DB engine. Second, even with a good query *typically* the larger slowdown comes from the connection to the database - if the roundtrip to the DB itself takes 100ms, then optimising the query from, say, 4ms to 3ms will not save you much time. As I said, performance is a completely separate topic.\n- So does that mean, that sequilize performs proper sanitation for Replacements? Because their documentation says almost nothing on such an important topic. They only mention that \"Bind parameters are like replacements. Except replacements are escaped... \" What do they mean by \"escaped\" - no information at all. Does that mean that only replacements are safe and bind parameters are not? - no information.\n- Unfortunately as best as I can tell this is not actually a prepared query, so theres almost certainly going to be worked around by a dedicated enough hacker, simultaneously proving two axions, 1) JS refuses to learn from the mistakes of earlier languages and 2) Most DB library authors dont understand DBs. We all went through this 20 years ago with PHPs refusal to properly implement prepared queries and the serial failures of mysql escape functions to properly sanitize. Whats old is new I guess.\n- Where should I look for more information on this topic?\n- On which topic? Performance or SQL injection. For SQL injection, checkout OWASP top 10 and read... a lot... You should really be up to speed on everything there. For query performance, you need to understand different database table types, indexes, and spend work optimizing queries. This is a topic worthy of a book, but just reading up on how indexes work and reading some articles on SQL query optimization will do wonders.","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":41,"estimatedTokens":898}}374{"id":"stack-24091661","source":"stackoverflow","questionId":24091661,"title":"Stop execution of a Sequelize promise in Express.js","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: Stop execution of a Sequelize promise in Express.js\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to the world of promises and I'm not sure I fully understand how to use them in some cases. \n\nSequelize recently added support for promises, which really makes my code more readable. A typical scenario is to avoid handling errors several times in infinite callbacks. \n\nThe snippet below always return `204`, while I'd like it to return `404` when the photo cannot be found. \n\nIs there a way to tell Sequelize to \"stop\" the execution of the promise chain after sending 404? Note that `res.send` is asynchronous so it does not stop the execution.\n\n```\n// Find the original photo\nPhoto.find(req.params.id).then(function (photo) {\n if (photo) {\n // Delete the photo in the db\n return photo.destroy();\n } else {\n res.send(404);\n // HOW TO STOP PROMISE CHAIN HERE?\n }\n}).then(function () {\n res.send(204);\n}).catch(function (error) {\n res.send(500, error);\n});\n```\n\nOf course this example is trivial and could easily be written with callbacks. But in most cases the code can become way longer.\n\n========================================\n\nCode:\n```text\n// Find the original photo\nPhoto.find(req.params.id).then(function (photo) {\n    if (photo) {\n        // Delete the photo in the db\n        return photo.destroy();\n    } else {\n        res.send(404);\n        // HOW TO STOP PROMISE CHAIN HERE?\n    }\n}).then(function () {\n    res.send(204);\n}).catch(function (error) {\n    res.send(500, error);\n});\n```\n\n```text\n204\n```\n\n```text\n404\n```\n\n```text\nres.send\n```\n\n```text\nPhoto.find\n          /     \\\n         /       \\\n    (success)   (failure)\n       /           \\\n      /             \\\nphoto.destroy    res.send(404)\n     |\n     |\nres.send(204)\n```\n\n```text\n// Find the original photo\nPhoto.find(req.params.id).then(function (photo) {\n    if (photo) {\n        // Delete the photo in the db\n        return photo.destroy().then(function () {\n            res.send(204);\n        });\n    } else {\n        res.send(404);\n    }\n}).catch(function (error) {\n    res.send(500, error);\n});\n```\n\n```text\n.then()\n```\n\n========================================\n\nComments:\n- What you need is a way to mark the promise as resolved at that point. I am not familiar with sequelize, but I assume there must be a way to do that.\n- Thanks Edwin. The only thing I know is that Sequelize uses Bluebird. However, I don't see anything in their API that allows me do stop a promise chain.\n- If you `throw` inside your `then` handler, that will reject the chain. There's also an (open issue)[github.com/sequelize/sequelize/issues/272] to automatically reject the find call if not result is found. You could voice your support there if you need the feature\n- That sounds great! I will add a comment today. The throw seems to be a good fallback for now too. Thanks for you answer :)\n- Ok I posted into a related pull request and got my final answer. Looks like the best solution is to `throw` inside the `then` as you suggested. github.com/sequelize/sequelize/pull/934\n- Yeah that's pretty much what I ended up doing. I was expecting Sequelize to simply reject my `find()` promise in order to avoid having too much nested code. Last question: do you know if I need to add a `catch()` for the `destroy()` promise too? Or it will handled by the catch at the end? Thanks!\n- @PedroCheckos, unless you define a separate `catch()` block within your `Photo.destroy()` promise chain, any unhandled exceptions should \"bubble up\" to the outer `catch()` block.\n- Awesome, that's all I needed to know! Thanks a lot for the tips :)\n- @PedroCheckos, I just stumbled upon this and remembered this question: Promise Cancellation in bluebird. (Note that bluebird is what sequelize.js appears to be using under the hood.) I didn't know that \"cancellable promises\" were a thing. Further research also led to this question, which has some good information: Status of cancellable promises. Perhaps this will give you some more ideas to try.","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":1008}}375{"id":"stack-52975133","source":"stackoverflow","questionId":52975133,"title":"Javascript: SyntaxError: await is only valid in async function","tags":["javascript","node.js","async-await","sequelize.js","es6-promise"],"text":"Title: Javascript: SyntaxError: await is only valid in async function\nTags: javascript, node.js, async-await, sequelize.js, es6-promise\nSource: Stack Overflow\n\nQuestion:\nI am on Node 8 with Sequelize.js \n\nGtting the following error when trying to use `await`.\n\n`SyntaxError: await is only valid in async function` \n\nCode:\n\n```\nasync function addEvent(req, callback) {\n var db = req.app.get('db');\n var event = req.body.event\n\n db.App.findOne({\n where: {\n owner_id: req.user_id,\n }\n }).then((app) => {\n\n let promise = new Promise((resolve, reject) => {\n setTimeout(() => resolve(\"done!\"), 6000)\n\n })\n\n // I get an error at this point \n let result = await promise;\n\n // let result = await promise;\n // ^^^^^\n // SyntaxError: await is only valid in async function\n }\n })\n}\n```\n\nGetting the following error:\n\n```\nlet result = await promise;\n ^^^^^\n SyntaxError: await is only valid in async function\n```\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nYou can run await statement only under async function.\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\n\nSo, you can write your\n\n```\n}).then((app) => {\n```\n\nas\n\n```\n}).then(async (app) => {\n```\n\n========================================\n\nCode:\n```text\nasync function addEvent(req, callback) {\n    var db = req.app.get('db');\n    var event = req.body.event\n\n    db.App.findOne({\n        where: {\n            owner_id: req.user_id,\n        }\n    }).then((app) => {\n\n                let promise = new Promise((resolve, reject) => {\n                    setTimeout(() => resolve(\"done!\"), 6000)\n\n                })\n\n               // I get an error at this point \n               let result = await promise;\n\n               // let result = await promise;\n               //              ^^^^^\n               // SyntaxError: await is only valid in async function\n            }\n    })\n}\n```\n\n```text\nlet result = await promise;\n                            ^^^^^\n               SyntaxError: await is only valid in async function\n```\n\n```text\nawait\n```\n\n```text\nSyntaxError: await is only valid in async function\n```\n\n```text\nasync function addEvent(req, callback) {\n    var db = req.app.get('db');\n    var event = req.body.event\n\n    const app = await db.App.findOne({\n        where: {\n            owner_id: req.user_id,\n        }\n    });\n\n    let promise = new Promise((resolve, reject) => {\n        setTimeout(() => resolve(\"done!\"), 6000)\n    })\n\n    let result = await promise;\n}\n```\n\n```text\naddEvent\n```\n\n```text\nasync..await\n```\n\n```text\nawait\n```\n\n```text\nthen\n```\n\n```text\ndb.App.findOne(...).then(...)\n```\n\n```text\naddEvent\n```\n\n```text\ncallback\n```\n\n```text\naddEvent\n```\n\n```text\n...\n    }).then(async app => {   // <<<< here\n\n                let promise = new Promise((resolve, reject) => {\n                    setTimeout(() => resolve(\"done!\"), 6000)\n\n                })\n\n               // I get an error at this point \n               let result = await promise;\n\n               // let result = await promise;\n               //              ^^^^^\n               // SyntaxError: await is only valid in async function\n            }\n    })\n```\n\n```text\nasync/await\n```\n\n```text\n}).then((app) => {\n```\n\n```text\n}).then(async (app) => {\n```\n\n========================================\n\nComments:\n- `then((app) => {` this anonymous function is not marked as `async`\n- Probably better to just return the promise in the `then` callback and move it down the chain rather than awaiting it...\n- I find it kinda wierd the way your trying to get the promise resolve, why your not using .then() ?\n- Thank you for your answer! You were the first, but b/c of clarity and depth in @estus answer, I marked it as correct!\n- Yaaaaay you made my day :D :D :D\n- How does this answer the question? You basically just restated what the error message says.","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":203,"estimatedTokens":964}}376{"id":"stack-30264438","source":"stackoverflow","questionId":30264438,"title":"Node.js sequelize associations include","tags":["node.js","sequelize.js"],"text":"Title: Node.js sequelize associations include\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs this a bug when I query models (short versions):\n\n```\nvar User = db.define('User', {\n login: Sequelize.STRING(16),\n password: Sequelize.STRING,\n});\n\nvar Group = db.define('Group', {\n name: Sequelize.STRING,\n});\n\nvar GroupSection = db.define('GroupSection', {\n name: Sequelize.STRING,\n});\n\nGroup.belongsTo(GroupSection, { as: 'GroupSection',\n foreignKey: 'GroupSectionId' });\nGroupSection.hasMany(Group, { as: 'Groups', foreignKey: 'GroupSectionId' });\n\nGroup.belongsTo(Group, { as: 'ParentGroup', foreignKey: 'ParentGroupId' });\nGroup.hasMany(Group, { as: 'ChildGroups', foreignKey: 'ParentGroupId' });\n\nUser.belongsToMany(Group, { as: 'Groups', through: 'UsersToGroups' });\nGroup.belongsToMany(User, { as: 'Users', through: 'UsersToGroups' });\n```\n\nThis query works fine (note include inside include):\n\n```\nUser.findOne({\n include: [{\n model: Group,\n as: 'Groups',\n where: {\n name: 'Group name',\n },\n include: [{\n model: GroupSection,\n as: 'GroupSection',\n }]\n }]\n }).then(function(user) {\n // some code\n })\n```\n\nBut this query gives error (only \"where\" parameter added to the inner include):\n\n```\nUser.findOne({\n include: [{\n model: Group,\n as: 'Groups',\n where: {\n name: 'Group name',\n },\n include: [{\n model: GroupSection,\n as: 'GroupSection',\n where: {\n name: 'Some section name',\n },\n }]\n }]\n }).then(function(user) {\n // some code\n })\n```\n\nCode above gives error:\n\nUnhandled rejection SequelizeDatabaseError: missing FROM-clause entry for table \"Groups\"\n\nI checked the SQL code it produces, i can fix this by not using inner where clause, but adding some raw code to the where clause. How can I do something like this:\n\n```\nUser.findOne({\n include: [{\n model: Group,\n as: 'Groups',\n where: {\n name: 'Admin',\n $somethin_i_need$: 'raw sql goes here',\n },\n include: [{\n model: GroupSection,\n as: 'GroupSection',\n }]\n }]\n}).then(function(user) {\n // some code\n})\n```\n\n### ADDED (code was prettified by an some online service):\n\nCode generated without inner where(working fine):\n\n```\nSELECT \"User\".*,\n \"groups\".\"id\" AS \"Groups.id\",\n \"groups\".\"name\" AS \"Groups.name\",\n \"groups\".\"createdat\" AS \"Groups.createdAt\",\n \"groups\".\"updatedat\" AS \"Groups.updatedAt\",\n \"groups\".\"groupsectionid\" AS \"Groups.GroupSectionId\",\n \"groups\".\"parentgroupid\" AS \"Groups.ParentGroupId\",\n \"Groups.UsersToGroups\".\"createdat\" AS \"Groups.UsersToGroups.createdAt\",\n \"Groups.UsersToGroups\".\"updatedat\" AS \"Groups.UsersToGroups.updatedAt\",\n \"Groups.UsersToGroups\".\"groupid\" AS \"Groups.UsersToGroups.GroupId\",\n \"Groups.UsersToGroups\".\"userid\" AS \"Groups.UsersToGroups.UserId\",\n \"Groups.GroupSection\".\"id\" AS \"Groups.GroupSection.id\",\n \"Groups.GroupSection\".\"name\" AS \"Groups.GroupSection.name\",\n \"Groups.GroupSection\".\"createdat\" AS \"Groups.GroupSection.createdAt\", \n \"Groups.GroupSection\".\"updatedat\" AS \"Groups.GroupSection.updatedAt\"\nFROM (SELECT \"User\".\"id\",\n \"User\".\"login\",\n \"User\".\"password\",\n \"User\".\"createdat\",\n \"User\".\"updatedat\"\n FROM \"users\" AS \"User\"\n WHERE (SELECT \"userstogroups\".\"groupid\"\n FROM \"userstogroups\" AS \"UsersToGroups\"\n INNER JOIN \"groups\" AS \"Group\"\n ON \"userstogroups\".\"groupid\" = \"Group\".\"id\"\n WHERE ( \"User\".\"id\" = \"userstogroups\".\"userid\" )\n LIMIT 1) IS NOT NULL\n LIMIT 1) AS \"User\"\n INNER JOIN (\"userstogroups\" AS \"Groups.UsersToGroups\"\n INNER JOIN \"groups\" AS \"Groups\"\n ON \"groups\".\"id\" = \"Groups.UsersToGroups\".\"groupid\")\n ON \"User\".\"id\" = \"Groups.UsersToGroups\".\"userid\"\n AND \"groups\".\"name\" = 'Group name'\n LEFT OUTER JOIN \"groupsections\" AS \"Groups.GroupSection\"\n ON \"groups\".\"groupsectionid\" = \"Groups.GroupSection\".\"id\";\n```\n\nCode generated WITH inner where(wrong sql generated):\n\n```\nSELECT \"User\".*, \n \"groups\".\"id\" AS \"Groups.id\", \n \"groups\".\"name\" AS \"Groups.name\", \n \"groups\".\"createdat\" AS \"Groups.createdAt\", \n \"groups\".\"updatedat\" AS \"Groups.updatedAt\", \n \"groups\".\"groupsectionid\" AS \"Groups.GroupSectionId\", \n \"groups\".\"parentgroupid\" AS \"Groups.ParentGroupId\", \n \"Groups.UsersToGroups\".\"createdat\" AS \"Groups.UsersToGroups.createdAt\", \n \"Groups.UsersToGroups\".\"updatedat\" AS \"Groups.UsersToGroups.updatedAt\", \n \"Groups.UsersToGroups\".\"groupid\" AS \"Groups.UsersToGroups.GroupId\", \n \"Groups.UsersToGroups\".\"userid\" AS \"Groups.UsersToGroups.UserId\" \nFROM (SELECT \"User\".\"id\", \n \"User\".\"login\", \n \"User\".\"password\", \n \"User\".\"createdat\", \n \"User\".\"updatedat\", \n \"Groups.GroupSection\".\"id\" AS \"Groups.GroupSection.id\", \n \"Groups.GroupSection\".\"name\" AS \"Groups.GroupSection.name\", \n \"Groups.GroupSection\".\"createdat\" AS \n \"Groups.GroupSection.createdAt\", \n \"Groups.GroupSection\".\"updatedat\" AS \n \"Groups.GroupSection.updatedAt\" \n FROM \"users\" AS \"User\" \n INNER JOIN \"groupsections\" AS \"Groups.GroupSection\" \n ON \"groups\".\"GroupSectionId\" = \"Groups.GroupSection\".\"id\" \n AND \"Groups.GroupSection\".\"name\" = 'Section name' \n WHERE (SELECT \"userstogroups\".\"groupid\" \n FROM \"userstogroups\" AS \"UsersToGroups\" \n INNER JOIN \"groups\" AS \"Group\" \n ON \"userstogroups\".\"groupid\" = \"Group\".\"id\" \n WHERE ( \"User\".\"id\" = \"userstogroups\".\"userid\" ) \n LIMIT 1) IS NOT NULL \n LIMIT 1) AS \"User\" \n INNER JOIN (\"userstogroups\" AS \"Groups.UsersToGroups\" \n INNER JOIN \"groups\" AS \"Groups\" \n ON \"groups\".\"id\" = \"Groups.UsersToGroups\".\"groupid\") \n ON \"User\".\"id\" = \"Groups.UsersToGroups\".\"userid\" \n AND \"groups\".\"name\" = 'Group name';\n```\n\n**Note on what really needed**:\n\nI don't need records that have users that are without groups or groups without section and so on. E.g. Attachment of groups to a users happens after that user was found (and it was decided that it will go into the results). Meaning that I need this \"where\" clause to be on the user model (at the same level as the first \"inclusion\" key in the object), but it needs to make check going through several tables (my real database is more complicated).\n\n========================================\n\nCode:\n```text\nvar User = db.define('User', {\n  login: Sequelize.STRING(16),\n  password: Sequelize.STRING,\n});\n\nvar Group = db.define('Group', {\n  name: Sequelize.STRING,\n});\n\nvar GroupSection = db.define('GroupSection', {\n  name: Sequelize.STRING,\n});\n\nGroup.belongsTo(GroupSection, { as: 'GroupSection',\n  foreignKey: 'GroupSectionId' });\nGroupSection.hasMany(Group, { as: 'Groups', foreignKey: 'GroupSectionId' });\n\nGroup.belongsTo(Group, { as: 'ParentGroup', foreignKey: 'ParentGroupId' });\nGroup.hasMany(Group, { as: 'ChildGroups', foreignKey: 'ParentGroupId' });\n\nUser.belongsToMany(Group, { as: 'Groups', through: 'UsersToGroups' });\nGroup.belongsToMany(User, { as: 'Users', through: 'UsersToGroups' });\n```\n\n```text\nUser.findOne({\n    include: [{\n      model: Group,\n      as: 'Groups',\n      where: {\n        name: 'Group name',\n      },\n      include: [{\n        model: GroupSection,\n        as: 'GroupSection',\n      }]\n    }]\n  }).then(function(user) {\n    // some code\n  })\n```\n\n```text\nUser.findOne({\n    include: [{\n      model: Group,\n      as: 'Groups',\n      where: {\n        name: 'Group name',\n      },\n      include: [{\n        model: GroupSection,\n        as: 'GroupSection',\n        where: {\n          name: 'Some section name',\n        },\n      }]\n    }]\n  }).then(function(user) {\n    // some code\n  })\n```\n\n```text\nUser.findOne({\n  include: [{\n    model: Group,\n    as: 'Groups',\n    where: {\n      name: 'Admin',\n      $somethin_i_need$: 'raw sql goes here',\n    },\n    include: [{\n      model: GroupSection,\n      as: 'GroupSection',\n    }]\n  }]\n}).then(function(user) {\n  // some code\n})\n```\n\n```text\nSELECT \"User\".*,\n       \"groups\".\"id\"                      AS \"Groups.id\",\n       \"groups\".\"name\"                    AS \"Groups.name\",\n       \"groups\".\"createdat\"               AS \"Groups.createdAt\",\n       \"groups\".\"updatedat\"               AS \"Groups.updatedAt\",\n       \"groups\".\"groupsectionid\"          AS \"Groups.GroupSectionId\",\n       \"groups\".\"parentgroupid\"           AS \"Groups.ParentGroupId\",\n       \"Groups.UsersToGroups\".\"createdat\" AS \"Groups.UsersToGroups.createdAt\",\n       \"Groups.UsersToGroups\".\"updatedat\" AS \"Groups.UsersToGroups.updatedAt\",\n       \"Groups.UsersToGroups\".\"groupid\"   AS \"Groups.UsersToGroups.GroupId\",\n       \"Groups.UsersToGroups\".\"userid\"    AS \"Groups.UsersToGroups.UserId\",\n       \"Groups.GroupSection\".\"id\"         AS \"Groups.GroupSection.id\",\n       \"Groups.GroupSection\".\"name\"       AS \"Groups.GroupSection.name\",\n       \"Groups.GroupSection\".\"createdat\"  AS \"Groups.GroupSection.createdAt\", \n       \"Groups.GroupSection\".\"updatedat\"  AS \"Groups.GroupSection.updatedAt\"\nFROM   (SELECT \"User\".\"id\",\n               \"User\".\"login\",\n               \"User\".\"password\",\n               \"User\".\"createdat\",\n               \"User\".\"updatedat\"\n        FROM   \"users\" AS \"User\"\n        WHERE  (SELECT \"userstogroups\".\"groupid\"\n                FROM   \"userstogroups\" AS \"UsersToGroups\"\n                       INNER JOIN \"groups\" AS \"Group\"\n                               ON \"userstogroups\".\"groupid\" = \"Group\".\"id\"\n                WHERE  ( \"User\".\"id\" = \"userstogroups\".\"userid\" )\n                LIMIT  1) IS NOT NULL\n        LIMIT  1) AS \"User\"\n       INNER JOIN (\"userstogroups\" AS \"Groups.UsersToGroups\"\n                   INNER JOIN \"groups\" AS \"Groups\"\n                           ON \"groups\".\"id\" = \"Groups.UsersToGroups\".\"groupid\")\n               ON \"User\".\"id\" = \"Groups.UsersToGroups\".\"userid\"\n                  AND \"groups\".\"name\" = 'Group name'\n       LEFT OUTER JOIN \"groupsections\" AS \"Groups.GroupSection\"\n                    ON \"groups\".\"groupsectionid\" = \"Groups.GroupSection\".\"id\";\n```\n\n```text\nSELECT \"User\".*, \n       \"groups\".\"id\"                      AS \"Groups.id\", \n       \"groups\".\"name\"                    AS \"Groups.name\", \n       \"groups\".\"createdat\"               AS \"Groups.createdAt\", \n       \"groups\".\"updatedat\"               AS \"Groups.updatedAt\", \n       \"groups\".\"groupsectionid\"          AS \"Groups.GroupSectionId\", \n       \"groups\".\"parentgroupid\"           AS \"Groups.ParentGroupId\", \n       \"Groups.UsersToGroups\".\"createdat\" AS \"Groups.UsersToGroups.createdAt\", \n       \"Groups.UsersToGroups\".\"updatedat\" AS \"Groups.UsersToGroups.updatedAt\", \n       \"Groups.UsersToGroups\".\"groupid\"   AS \"Groups.UsersToGroups.GroupId\", \n       \"Groups.UsersToGroups\".\"userid\"    AS \"Groups.UsersToGroups.UserId\" \nFROM   (SELECT \"User\".\"id\", \n               \"User\".\"login\", \n               \"User\".\"password\", \n               \"User\".\"createdat\", \n               \"User\".\"updatedat\", \n               \"Groups.GroupSection\".\"id\"        AS \"Groups.GroupSection.id\", \n               \"Groups.GroupSection\".\"name\"      AS \"Groups.GroupSection.name\", \n               \"Groups.GroupSection\".\"createdat\" AS \n               \"Groups.GroupSection.createdAt\", \n               \"Groups.GroupSection\".\"updatedat\" AS \n               \"Groups.GroupSection.updatedAt\" \n        FROM   \"users\" AS \"User\" \n               INNER JOIN \"groupsections\" AS \"Groups.GroupSection\" \n                       ON \"groups\".\"GroupSectionId\" = \"Groups.GroupSection\".\"id\" \n                          AND \"Groups.GroupSection\".\"name\" = 'Section name' \n        WHERE  (SELECT \"userstogroups\".\"groupid\" \n                FROM   \"userstogroups\" AS \"UsersToGroups\" \n                       INNER JOIN \"groups\" AS \"Group\" \n                               ON \"userstogroups\".\"groupid\" = \"Group\".\"id\" \n                WHERE  ( \"User\".\"id\" = \"userstogroups\".\"userid\" ) \n                LIMIT  1) IS NOT NULL \n        LIMIT  1) AS \"User\" \n       INNER JOIN (\"userstogroups\" AS \"Groups.UsersToGroups\" \n                   INNER JOIN \"groups\" AS \"Groups\" \n                           ON \"groups\".\"id\" = \"Groups.UsersToGroups\".\"groupid\") \n               ON \"User\".\"id\" = \"Groups.UsersToGroups\".\"userid\" \n                  AND \"groups\".\"name\" = 'Group name';\n```\n\n```text\nUser.findOne({\n    include: [{\n      model: Group,\n      as: 'Groups',\n      where: {\n        name: 'Group name',\n      },\n      include: [{\n        model: GroupSection,\n        as: 'GroupSection',\n        required: false,\n        where: {\n          name: 'Some section name',\n        },\n      }]\n    }]\n  }).then(function(user) {\n    // some code\n  })\n```\n\n```text\nrequired:false\n```\n\n```text\nwhere\n```\n\n```text\nrequired\n```\n\n```text\nwhere\n```\n\n```text\nrequired\n```\n\n```text\nwhere\n```\n\n```text\nrequired:false\n```\n\n========================================\n\nComments:\n- Can you the SQL that is generated please?\n- The docs link is broken","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":409,"estimatedTokens":3100}}377{"id":"stack-35034685","source":"stackoverflow","questionId":35034685,"title":"Handling rollbacked MySQL transactions in Node.js","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: Handling rollbacked MySQL transactions in Node.js\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm dealing with a promblem for a couple of days, and I'm really hoping, you could help me.\n\nIt's a `node.js` based API using `sequelize` for `MySQL`. \n\nOn certain API calls the code starts `SQL` transactions which lock certain tables, and if I send multiple requests to the API simultaneously, I got `LOCK_WAIT_TIMEOUT` errors. \n\n```\nvar SQLProcess = function () {\n var self = this;\n var _arguments = arguments;\n\n return sequelize.transaction(function (transaction) {\n return doSomething({transaction: transactioin});\n })\n .catch(function (error) {\n if (error && error.original && error.original.code === 'ER_LOCK_WAIT_TIMEOUT') {\n\n return Promise.delay(Math.random() * 1000)\n .then(function () {\n return SQLProcess.apply(self, _arguments);\n });\n\n } else {\n throw error;\n }\n });\n};\n```\n\nMy problem is, the simultaneously running requests lock each other for a long time, and my request returns after a long-long time (~60 seconds).\n\nI hope I could explain it clear and understandable, and you could offer me some solution.\n\n========================================\n\nTop Answer:\nThe main reason for deadlocks is poor database design. Without further information about your database design and which exact queries might or might not lock each other it is impossible to give you a specific solution for your problem. \n\nHowever I can give you a general advice/approach to solve this issue:\n\nI would make sure that your database is normalized at least into **Third Normal Form** or, if that still isnt enough even further. There might be tools to automate this process for you.\n\nAside from reducing the likelihood of deadlocks this also helps keeping your data consistent, which is always a good thing.\n\n- Keep your transactions as slim as possible. If you are inserting new rows into your tables and update other tables accordingly you might want to use a Trigger rather than another SQL statement to do so. The same applies to reading rows and values. Such things can be done before or after your transaction.\nChoose the correct **Isolation Level**. Possible isolation levels are:\n\nREAD_UNCOMMITTED\n\n READ_COMMITTED\n\n REPEATABLE_READ\n\n SERIALIZABLE\n\nSequelize's official documentation describes how you can set the isolation level and lock/unlock transactions by yourself.\n\nAs I said, without further insight about your database and query design thats all I can do for you right now.\n\nHope this helps.\n\n========================================\n\nCode:\n```text\nvar SQLProcess = function () {\n    var self = this;\n    var _arguments = arguments;\n\n    return sequelize.transaction(function (transaction) {\n            return doSomething({transaction: transactioin});\n        })\n        .catch(function (error) {\n            if (error && error.original && error.original.code === 'ER_LOCK_WAIT_TIMEOUT') {\n\n                return Promise.delay(Math.random() * 1000)\n                    .then(function () {\n                        return SQLProcess.apply(self, _arguments);\n                    });\n\n            } else {\n                throw error;\n            }\n        });\n};\n```\n\n```text\nnode.js\n```\n\n```text\nsequelize\n```\n\n```text\nMySQL\n```\n\n```text\nSQL\n```\n\n```text\nLOCK_WAIT_TIMEOUT\n```\n\n========================================\n\nComments:\n- That isn't `node.js` or `sequelize` trouble, it's an error message from MySQL `1205 Lock wait timeout exceeded; try restarting transaction`. You should look at transactions and their states inside MySQL server.\n- It's absolutely clear, why I get this error. I'm looking for a solution how I could handle it.\n- There is only one way to understand what happens and it's `SHOW ENGINE INNODB STATUS\\G`. In my experience, I've got dead-locks transactions in MySQL multiple times.\n- It is not clear what kind of answer do you expect. What do you mean by \"handle\"? Do you want to get rid of lock (in this case it is important what your `doSomething` does)? Or do you want to repeat your transaction (in this case why don't you run `doSomething` again from your handler? Or your `catch` statement doesn't work and you want to make it work? I have a large list of random notes related to deadlocks here, it look puzzling to me now, but check it, maybe you'll find something useful.\n- Thanks! The queuing tool did it! I've set up a `bluebird-queue` and now all the requests run after each other without blocking.","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":120,"estimatedTokens":1123}}378{"id":"stack-38861087","source":"stackoverflow","questionId":38861087,"title":"Sequelize How compare year of a date in query","tags":["javascript","mysql","node.js","datetime","sequelize.js"],"text":"Title: Sequelize How compare year of a date in query\nTags: javascript, mysql, node.js, datetime, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make this query:\n\n```\nSELECT * FROM TABLEA AS A WHERE YEAR(A.dateField)='2016'\n```\n\nHow can I perfome this query above in sequelize style?\n\n```\nTABLEA.findAll({\n where:{}//????\n }\n```\n\nThanks!\n\n========================================\n\nTop Answer:\nyou have to add the `date_part` function to your query:\n\n```\nsequelize.where(sequelize.fn(\"date_part\",'year',sequelize.col('dateField')), 2020)\n```\n\n========================================\n\nCode:\n```text\nSELECT * FROM TABLEA AS A WHERE YEAR(A.dateField)='2016'\n```\n\n```text\nTABLEA.findAll({\n      where:{}//????\n     }\n```\n\n```text\nTABLEA.findAll({\n  where: sequelize.where(sequelize.fn('YEAR', sequelize.col('dateField')), 2016)\n });\n```\n\n```text\nTABLEA.findAll({\n  where: {\n    $and: [\n      sequelize.where(sequelize.fn('YEAR', sequelize.col('dateField')), 2016),\n      { foo: 'bar' }\n    ]\n  }\n });\n```\n\n```text\n.where\n```\n\n```text\nsequelize.where(sequelize.fn(\"date_part\",'year',sequelize.col('dateField')), 2020)\n```\n\n```text\ndate_part\n```\n\n```text\nwhere: { \n  [Op.and]:  [\n    sequelize.where(sequelize.fn('YEAR', sequelize.col('dateField')), 2016)\n  ]\n},\n```\n\n```js\nconst { Op } = require(\"sequelize\");\n```\n\n```text\nsequelize.where\n```\n\n========================================\n\nComments:\n- The solution for multiple where clauses is incorrect, the and operator doesn't take an array. Se my suggestion since the edit to improve this solution was rejected.","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":92,"estimatedTokens":393}}379{"id":"stack-53460754","source":"stackoverflow","questionId":53460754,"title":"Sequelize with MYSQL: Raw query returns a \"duplicate\" result","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize with MYSQL: Raw query returns a \"duplicate\" result\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have this method that performs a raw query:\n\n```\nFriendship.getFriends= async (userId)=>{\n\n const result = await sequelize.query(`select id,email from users where \n users.id in(SELECT friendId FROM friendships where friendships.userId = \n ${userId})`);\n\n return result;\n };\n```\n\nThe result seems to contain the same exact data, but twice:\n\n```\n[ [ TextRow { id: 6, email: 'example3@gmail.com' },\nTextRow { id: 1, email: 'yoyo@gmail.com' } ],\n[ TextRow { id: 6, email: 'example3@gmail.com' },\nTextRow { id: 1, email: 'yoyo@gmail.com' } ] ]\n```\n\nOnly two records should actually be found by this query(id's 1 and 6), yet it returns an array with the same records twice.\n\nCan somebody explain me what's going on here?\n\nEdit: the models:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const User = sequelize.define('User', {\n email: { type: DataTypes.STRING, unique: true }, \n password: DataTypes.STRING,\n isActive:{type:DataTypes.BOOLEAN,defaultValue:true}\n });\n\nmodule.exports = (sequelize, DataTypes) => {\n const Friendship = sequelize.define('Friendship', {\n userId: DataTypes.INTEGER, \n friendId: DataTypes.INTEGER, \n });\n```\n\n========================================\n\nTop Answer:\nI am not sure but try below code.\n\n```\nconst result = await sequelize.query(\"select id,email from users where \n users.id in(SELECT friendId FROM friendships where friendships.userId = \n ${userId})\", {type: sequelize.QueryTypes.SELECT});\n```\n\nOne more thing : Use join instead of in\n\n========================================\n\nCode:\n```text\nFriendship.getFriends= async (userId)=>{\n\n      const result = await sequelize.query(`select id,email from users where \n      users.id in(SELECT friendId FROM friendships where friendships.userId = \n     ${userId})`);\n\n      return result;\n   };\n```\n\n```text\n[ [ TextRow { id: 6, email: 'example3@gmail.com' },\nTextRow { id: 1, email: 'yoyo@gmail.com' } ],\n[ TextRow { id: 6, email: 'example3@gmail.com' },\nTextRow { id: 1, email: 'yoyo@gmail.com' } ] ]\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n   const User = sequelize.define('User', {\n     email: { type: DataTypes.STRING, unique: true },    \n     password: DataTypes.STRING,\n     isActive:{type:DataTypes.BOOLEAN,defaultValue:true}\n  });\n\nmodule.exports = (sequelize, DataTypes) => {\n   const Friendship = sequelize.define('Friendship', {\n     userId: DataTypes.INTEGER,    \n     friendId: DataTypes.INTEGER,      \n  });\n```\n\n```text\nsequelize.query(queryString, {type: sequelize.QueryTypes.SELECT})\n```\n\n```text\nconst result = await sequelize.query(\"select id,email from users where \n      users.id in(SELECT friendId FROM friendships where friendships.userId = \n     ${userId})\", {type: sequelize.QueryTypes.SELECT});\n```\n\n```text\nsequelize.query(yourQuery, {type: QueryTypes.SELECT})\n```\n\n========================================\n\nComments:\n- Why does a raw query do this without the type?\n- As per the documentation of Sequelize, when using raw queries two objects are returned, the second one being metadata about the query. But since this behaviour is dialect specific in MySQL and MSSQL the same object is returned thus resulting in duplicates.\n- Yeah hehe, thats what the previous commenter wrote..it works. About the join: I was trying to construct it correctly, with no success. My SQL is very rusty. Could u write the join version of that query?\n- select id,email from users u inner join friendships f on u.id = f.userId where u.id = ${userId}\n- Well that's actually the query i came up with, before switching to the sub query alternative. This one doesn't work properly. It returns the email of the current user (\"userId\"), instead of the \"friend\"(some other user). So i basically get a list of friends, with \"my own email\"\n- Can you please that two table schema. So, we can write perfect query.\n- select id,email from users u inner join friendships f on u.id = f. friendId where f. userId = ${userId}\n- Yes...silly me...had to use the friendId instead of userId. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":122,"estimatedTokens":1031}}380{"id":"stack-46341495","source":"stackoverflow","questionId":46341495,"title":"How to Create a table in Sequelize to store in Postgressql with NodeJS","tags":["node.js","postgresql","express","sequelize.js","rdbms"],"text":"Title: How to Create a table in Sequelize to store in Postgressql with NodeJS\nTags: node.js, postgresql, express, sequelize.js, rdbms\nSource: Stack Overflow\n\nQuestion:\nAm a newbie to Postgres and Sequelize i have successfully connected to DB trying to create a table in DB that is where am struck am getting an error the tablename doesn't exist\n\n```\nsequelize.authenticate().then(() => {\n console.log(\"Success!\");\n var News = sequelize.define('likes', {\n title: {\n type: Sequelize.STRING\n },\n content: {\n type: Sequelize.STRING\n }\n }, {\n freezeTableName: true\n });\n News.create({\n title: 'Getting Started with PostgreSQL and Sequelize',\n content: 'Hello there'\n });\n News.findAll({}).then((data) => {\n console.log(data);\n }).catch((err) => {\n console.log(err);\n });\n}).catch((err) => {\n console.log(err);\n});\n```\n\nWhere am making a mistake? It says error: relation \"likes\" doesn't exist. Any kind of help is appreciated\n\n========================================\n\nCode:\n```text\nsequelize.authenticate().then(() => {\n  console.log(\"Success!\");\n  var News = sequelize.define('likes', {\n    title: {\n      type: Sequelize.STRING\n    },\n    content: {\n      type: Sequelize.STRING\n    }\n    }, {\n     freezeTableName: true\n   });\n   News.create({\n     title: 'Getting Started with PostgreSQL and Sequelize',\n     content: 'Hello there'\n   });\n   News.findAll({}).then((data) => {\n     console.log(data);\n   }).catch((err) => {\n     console.log(err);\n   });\n}).catch((err) => {\n  console.log(err);\n});\n```\n\n```text\nsync\n```\n\n```text\nNews\n```\n\n```text\nsync\n```\n\n```text\nNews.sync({ force: true })\n```\n\n```text\nNews.sync({ alter: true })\n```\n\n```text\n{alter: true}\n```\n\n========================================\n\nComments:\n- `News.sync({force: false}).then(function (err) { if(err) { console.log('An error occur while creating table'); } else{ console.log('Item table created successfully'); } });`\n- The above comment is the one am trying to do in console it prints An error occured while creating table however the table gets created and i can insert the values too. And by the way can you give me an simple example of that migrations API\n- It doesn't print out any error it consoles the table name \"user\"\n- Ah, I see. `.then` does not report errors. Param one of `.then` is the success result. to look for errors use `.catch`\n- Used catch no errors printed thanks for helping me out bro am newbie to sequelize want to explore more so can you suggest me the resources for the same\n- stackoverflow.com/questions/46454303/&hellip;\n- can you answer that question ?","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":100,"estimatedTokens":639}}381{"id":"stack-51583957","source":"stackoverflow","questionId":51583957,"title":"sequelize-auto TypeError: connection.query(...).on is not a function","tags":["node.js","postgresql","orm","sequelize.js","sequelize-auto"],"text":"Title: sequelize-auto TypeError: connection.query(...).on is not a function\nTags: node.js, postgresql, orm, sequelize.js, sequelize-auto\nSource: Stack Overflow\n\nQuestion:\nI tried to use sequelize-auto to automatically generate models from existing PostgreSQL tables for SequelizeJS.\n\n```\nnpm install -g sequelize-auto pg\nsequelize-auto -o \"./models\" -d myDatabase -h localhost -u myUsername -p 5432 -x myPassword -e postgres\n```\n\nHowever, it failed with error `TypeError: connection.query(...).on is not a function`\n\nNote: I'm using the following library versions:\n\n- sequelize-auto@0.4.29\n\n- pg@7.4.3\n\n========================================\n\nCode:\n```text\nnpm install -g sequelize-auto pg\nsequelize-auto -o \"./models\" -d myDatabase -h localhost -u myUsername -p 5432 -x myPassword -e postgres\n```\n\n```text\nTypeError: connection.query(...).on is not a function\n```\n\n```text\nnpm install -g pg@6.4.2\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":35,"estimatedTokens":226}}382{"id":"stack-43217100","source":"stackoverflow","questionId":43217100,"title":"Make Sequelize show tables","tags":["node.js","sequelize.js"],"text":"Title: Make Sequelize show tables\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm creating a project in node.js and one of my pages will show a list of all the tables in the database. I would like to know if Sequelize has a function like \"Show tables\".\n\nThanks!\n\n========================================\n\nTop Answer:\nUse the Sequelize `showAllSchemas` method:\n\n```\nvar sequelize = new Sequelize('mysql://localhost/mysql');\n\nsequelize.getQueryInterface().showAllSchemas().then((tableObj) => {\n console.log('// Tables in database','==========================');\n console.log(tableObj);\n})\n.catch((err) => {\n console.log('showAllSchemas ERROR',err);\n})\n```\n\nThis would be the \"proper\" Sequelize way to do it as opposed to .query('show tables')\n\n========================================\n\nCode:\n```text\nvar seq = new Sequelize('mysql://localhost/mysql');\nseq.query('show tables').then(function(rows) {\n    console.log(JSON.stringify(rows));\n});\n```\n\n```text\nconsole.log\n```\n\n```text\nvar sequelize = new Sequelize('mysql://localhost/mysql');\n\nsequelize.getQueryInterface().showAllSchemas().then((tableObj) => {\n    console.log('// Tables in database','==========================');\n    console.log(tableObj);\n})\n.catch((err) => {\n    console.log('showAllSchemas ERROR',err);\n})\n```\n\n```text\nshowAllSchemas\n```\n\n```text\nsequelize\n  .query('SHOW Tables', {\n    type: sequelize.QueryTypes.SHOWTABLES\n  })\n  .then(result => {\n    console.log(result)\n  })\n\n// ['table1', 'table2']\n```\n\n```text\nSHOW Tables\n```\n\n```text\nsequelize.QueryTypes.SHOWTABLES\n```\n\n```text\nsequelize.getQueryInterface().showAllTables().then(function (tableNames) {\n  console.log(tableNames);\n});\n```\n\n```text\nsequelize.getQueryInterface().listTables().then(function (tableNames) {\n  console.log(tableNames);\n});\n```\n\n```text\nv6\n```\n\n```text\nqueryInterface\n```\n\n```text\nshowAllTables\n```\n\n```text\nv6\n```\n\n```text\nalpha\n```\n\n```text\nv7\n```\n\n```text\nqueryInterface\n```\n\n```text\nlistTables\n```\n\n```text\nv7\n```\n\n========================================\n\nComments:\n- What database are you using?\n- It is postgresql.\n- This doesn't work for Postgre. Isn't there some common request for all (or most of) the databases?\n- If you use postgres then this will return a list of schemas and not a list of tables.\n- @mmitchell that is also correct for an MS SQL DB, it's retrieving a list of schemas. Is it possible to retrieve a list of tables as requested?\n- this is only correct answer, using query('show ...') will error with some database types like sqliite.\n- Simple, clean and elegant. +1","metadata":{"transformedAt":"2026-08-18T18:33:34.370Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":136,"estimatedTokens":641}}383{"id":"stack-56340151","source":"stackoverflow","questionId":56340151,"title":"How to fetch sequelize js records for today","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: How to fetch sequelize js records for today\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table which looks similar to the below table. I am trying to find the sum of all prices for TODAY.\n\n```\n| id| price | created |\n|---|-------|----------------------|\n| 0 | 500 | 2018-04-02 11:40:48 |\n| 1 | 2000 | 2018-04-02 11:40:48 |\n| 2 | 4000 | 2018-07-02 11:40:48 |\n```\n\nThe below code is what i came up with but it doesn't seem to work.\n\n```\nconst TODAY = new Date();\nconst SUM = await OrdersModel.sum('price', {\n where: {\n created: TODAY,\n },\n});\nconsole.log(SUM);\n```\n\nValue of SUM is 0 even though there are entries for today. I also tried the following but it too didn't work.\n\n```\nconst TODAY = new Date();\nconst SUM = await OrdersModel.sum('price', {\n where: {\n created: Sequelize.DATE(TODAY),\n },\n});\nconsole.log(SUM);\n```\n\nThe SQL statement queried on the terminal is as follows.\n\n Executing (default): SELECT sum(`price`) AS `sum` FROM `orders` AS `orders` WHERE `orders`.`created` = '2019-05-27 18:30:00';\n\n========================================\n\nTop Answer:\nBest way to get **today records**.\n\n```\nconst op = sequelize.Op;\n const moment = require('moment');\n const TODAY_START = moment().format('YYYY-MM-DD 00:00');\n const NOW = moment().format('YYYY-MM-DD 23:59');\n\n const todaysRecord = await OrdersModel.findAll({\n\n where: {\n createdAt: {\n [op.between]: [\n TODAY_START,\n NOW,\n ]\n }\n }\n });\n```\n\n========================================\n\nCode:\n```text\n| id| price |       created        |\n|---|-------|----------------------|\n| 0 |  500  | 2018-04-02 11:40:48  |\n| 1 | 2000  | 2018-04-02 11:40:48  |\n| 2 | 4000  | 2018-07-02 11:40:48  |\n```\n\n```text\nconst TODAY = new Date();\nconst SUM = await OrdersModel.sum('price', {\n    where: {\n      created: TODAY,\n    },\n});\nconsole.log(SUM);\n```\n\n```text\nconst TODAY = new Date();\nconst SUM = await OrdersModel.sum('price', {\n    where: {\n      created: Sequelize.DATE(TODAY),\n    },\n});\nconsole.log(SUM);\n```\n\n```js\nconst Op = Sequelize.Op;\nconst TODAY_START = new Date().setHours(0, 0, 0, 0);\nconst NOW = new Date();\n\nconst SUM = await OrdersModel.sum('price', {\n    where: {\n      created: { \n        [Op.gt]: TODAY_START,\n        [Op.lt]: NOW\n      },\n    },\n });\n console.log(SUM);\n```\n\n```js\nconst SUM = await OrdersModel.sum('price', {\n    where: {\n      sequelize.fn('CURRENT_DATE'): {\n        [Op.eq]:  sequelize.fn('date_trunc', 'day', sequelize.col('created'))\n      }\n    },\n});\nconsole.log(SUM);\n```\n\n```bash\nnpm i sequelize@5.8.6 --s\n```\n\n```text\n'2019-05-27 11:40:48'\n```\n\n```text\n'2019-05-27 18:30:00'\n```\n\n```text\ntrue\n```\n\n```text\ncreated < [NOW] AND created > [TODAY_START]\n```\n\n```text\nNOW\n```\n\n```text\nsequelize.fn()\n```\n\n```text\nconst TODAY = new Date();\nconst SUM = await OrdersModel.sum('price', {\n    where: {\n      sequelize.fn('CURRENT_DATE'): {$eq:  sequelize.fn('date_trunc', 'day', sequelize.col('created'))}\n    },\n});\nconsole.log(SUM);\n```\n\n```text\nconst moment = require('moment');\nconst Op = require('sequelize').Op;\nconst SUM = await OrdersModel.sum('price', {\n    where : {\n                created_at : { [Op.gt] : moment().format('YYYY-MM-DD 00:00')},\n                created_at : { [Op.lte] : moment().format('YYYY-MM-DD 23:59')}\n            },\n});\nconsole.log(SUM);\n```\n\n```text\nconst { Op } = Sequelize;\n    const options = {\n        where: {}\n    };\n\n    options[Op.and] = [\n        sequelize.where(Sequelize.literal('DATE(created) = CURDATE()'))            \n    ] \n\n    const SUM = await OrdersModel.sum('price', options);\n    console.log(SUM);\n```\n\n```text\noptions[Op.and] = [\n        sequelize.where(sequelize.col('created'), {\n            [Op.gt]: Sequelize.literal('DATE_SUB(CURDATE(), INTERVAL 1 DAY)')\n        })            \n    ]\n    const SUM = await OrdersModel.sum('price', options);\n    console.log(SUM);\n```\n\n```text\nSequelize.literal\n```\n\n```text\nconst Op = Sequelize.Op;\nconst START = new Date();\nSTART.setHours(0, 0, 0, 0);\nconst NOW = new Date();\n\nwhere: {\ncreatedAt: {\n    [Op.between]: [START.toISOString(), NOW.toISOString()]\n  }\n}\n```\n\n```text\nconst op = sequelize.Op;\n      const moment = require('moment');\n      const TODAY_START = moment().format('YYYY-MM-DD 00:00');\n      const NOW = moment().format('YYYY-MM-DD 23:59');\n\n      const todaysRecord = await OrdersModel.findAll({\n\n                where: {\n                    createdAt: {\n                        [op.between]: [\n                            TODAY_START,\n                            NOW,\n                        ]\n                    }\n                }\n            });\n```\n\n========================================\n\nComments:\n- I updated the solution so you will not have problems, if you think that is the solution please mark your question as answered.\n- Hi, I am still getting the SUM as 0 and there is no change in the executed SQL query on the terminal.\n- Hey try with less than to see what you get probably the error is in another part\n- Op.lt gives a value. How ever it gives the sum for all the previous dates right.\n- Then try this alternative, I think I know what is going on. Are you comparing exact timestamps?? like `'2019-05-27 11:40:48'` equal to `'2019-05-27 18:30:00'` this comparison will never give you a result because it is the same day (27th of May) but the time is different.\n- Yeah so i tried using Op.gt and using Today date and changing the time to midnight. That works.\n- Check the explanation why do I use `gt` and `lt` and I fixed my mistake. I switch `gt` with `lt`. Now will be working fine.\n- Hi what do you mean by add DATE function ?\n- using DATE function you will compare with the date value and it will ignore the hh:mm:ss values\n- is it a custom function which i should write or part of sequelize ?\n- Ref to updated code in the comment sections, its a built in function sequelize.fn('date_trunc', 'day', sequelize.col('yourdatefiled')) . So it will consider only date part\n- You can't use a function an object key this will cause an error. SyntaxError: Unexpected token '.' sequelize.fn('CURRENT_DATE'): {\n- TODAY has not been used !\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":252,"estimatedTokens":1595}}384{"id":"stack-55322411","source":"stackoverflow","questionId":55322411,"title":"Work around Sequelize’s unique constraints in belongsToMany associations","tags":["database","postgresql","sequelize.js"],"text":"Title: Work around Sequelize’s unique constraints in belongsToMany associations\nTags: database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize in my project. These are the two models:\n\n```\nconst User = db.define('user', {\n name: Sequelize.STRING,\n password: Sequelize.STRING\n})\nconst Product = db.define('product', {\n name: Sequelize.STRING,\n price: Sequelize.INTEGER\n})\n```\n\nNow users can purchase products and I have associations setup like below:\n\n```\nProduct.belongsToMany(User, {through: 'UserProducts'})\nUser.belongsToMany(Product, {through: 'UserProducts'})\n```\n\nI also have this UserProducts table with an additional column.\n\n```\nconst UserProducts = db.define('UserProducts', {\n status: Sequelize.STRING\n})\n```\n\nSequelize creates a composite key with combination of userId and productId and will only allow one record with a combination of userId and productId. So, for example, userId 2 and productId 14. \n\nThis is a problem for me because sometimes people want to purchase multiple times. I need one of the following scenarios to work:\n\nDon't use the composite key and instead have a completely new auto-increment column used as key in UserProducts.\n\nInstead of making key with userId and productId alone, allow me to add one more column into the key such as the `status` so that unique key is a combination of the three.\n\nI do want to use the associations as they provide many powerful methods, but want to alter the unique key to work in such a way that I can add multiple rows with the same combination of user id and product id.\n\nAnd since my models/database is already running, I will need to make use of migrations to make this change.\n\nAny help around this is highly appreciated.\n\n========================================\n\nTop Answer:\nIf anyone else is having problems in **v5 of Sequelize**, it is not enough to specify a primary key on the 'through' model.\n\nYou have to explicitly set the unique property on the through model.\n\n```\nUser.belongsToMany(Product, { through: { model: UserProducts, unique: false } });\nProduct.belongsToMany(User, { through: { model: UserProducts, unique: false } });\n```\n\n========================================\n\nCode:\n```text\nconst User = db.define('user', {\n  name: Sequelize.STRING,\n  password: Sequelize.STRING\n})\nconst Product = db.define('product', {\n  name: Sequelize.STRING,\n  price: Sequelize.INTEGER\n})\n```\n\n```text\nProduct.belongsToMany(User, {through: 'UserProducts'})\nUser.belongsToMany(Product, {through: 'UserProducts'})\n```\n\n```text\nconst UserProducts = db.define('UserProducts', {\n  status: Sequelize.STRING\n})\n```\n\n```text\nstatus\n```\n\n```text\nclass User extends Model {}\nUser.init({\n    name: Sequelize.STRING,\n    password: Sequelize.STRING\n}, { sequelize })\n\nclass Product extends Model {}\nProjProductect.init({\n    name: Sequelize.STRING,\n    price: Sequelize.INTEGER\n}, { sequelize })\n\nclass UserProducts extends Model {}\nUserProducts.init({\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  status: DataTypes.STRING\n}, { sequelize })\n\nUser.belongsToMany(Project, { through: UserProducts })\nProduct.belongsToMany(User, { through: UserProducts })\n```\n\n```text\nUserProducts = db.define('UserProducts', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  status: DataTypes.STRING\n})\n```\n\n```text\nUserProducts\n```\n\n```text\nUserProducts\n```\n\n```text\nUserProducts\n```\n\n```text\nUser.belongsToMany(Product, { through: { model: UserProducts, unique: false } });\nProduct.belongsToMany(User, { through: { model: UserProducts, unique: false } });\n```\n\n```text\nUser.hasMany(UserProducts);\nUserProducts.belongsTo(User);\n\nProduct.hasMany(UserProducts);\nUserProducts.belongsTo(Product);\n```\n\n```text\nconst user = await User.create(user_data);\nconst product = await Product.create(product_data);\nconst up = await UserProduct.create(up_data);\nawait up.setUser(user);\nawait up.setProduct(product);\n```\n\n========================================\n\nComments:\n- Well the relation that you really need then is `1:N` - `User:Products`. M:N works like that, always a comination of 2 keys. Now if you want to keep your model like that and use 3 keys, you have to change manually on the database and add the constraint, Sequelize does not support that.\n- @Ellebkey can you help explain how I can do this manually?\n- I'm not very sure to do it, You could use `ALTER TABLE dbo.yourtablename ADD CONSTRAINT uq_yourtablename UNIQUE(column1, column2, column3);` But this only create your 3 field restriction, still you will have 2 primary keys on the table.\n- I believe this will work. But because my model is already there and I have data in it, how can I use migrations to make this change in primary key? Another worry I have is - since my table already has data, how will the auto-increment work on the existing records?\n- I'm not sure about how to add primary key using migration. I suggest you to try this `migration.addColumn('Table', 'column', { type: STRING, primaryKey : true });` also refer to this issue on github #3918\n- unique: false is not working. It still shows a single child even if multiple duplicate children are present. Do you have a fix?\n- @AayushTaneja just in case you were doing the same mistake I was, it is `{ through: { model: UserProducts, unique: false } }` NOT `{ through: UserProducts, unique: false }`\n- What dialect are you using? Neo answer works on MySQL and Postgres with v6 :-)\n- @Adrien seems like I was tired, it actually works on Postgres","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":171,"estimatedTokens":1383}}385{"id":"stack-54929244","source":"stackoverflow","questionId":54929244,"title":"How to return only specific attributes when using Sequelize Create method","tags":["javascript","sequelize.js","sequelize-cli"],"text":"Title: How to return only specific attributes when using Sequelize Create method\nTags: javascript, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI have been searching through Sequelize documentation and forums for the correct syntax and it seems I am doing it the right way, but for some reason the password field is still being returned in the response payload...\n\nThe following link shows the attributes exclude syntax I am using was added in version 3.11 of Sequelize: https://github.com/sequelize/sequelize/issues/4074\n\nAnyone know what I might be missing here? Below is the `Create` method and the console log from the `Insert` statement.\n\n**`Create` method**\n\n```\nasync create(req, res) {\ntry {\n let user = await User.create({\n firstName: req.body.firstName,\n lastName: req.body.lastName,\n email: req.body.email,\n password: req.body.password\n }, {\n attributes: {\n exclude: ['password']\n }\n });\n\n console.log(\"USER: \", user);\n\n res.status(201).send(user.toJSON());\n}\ncatch (error) {\n res.status(500).send(error)\n};\n```\n\n}\n\n**Console Log**\n\n Executing (default): INSERT INTO \"Users\"\n (\"id\",\"firstName\",\"lastName\",\"email\",\"password\",\"createdAt\",\"updatedAt\")\n VALUES\n (DEFAULT,'James','Martineau','test@gmail.com','$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2','2019-02-28\n 15:18:15.856 +00:00','2019-02-28 15:18:15.856 +00:00') RETURNING *;\n\n \n USER: User { dataValues:\n { id: 6,\n firstName: 'James',\n lastName: 'Martineau',\n email: 'test@gmail.com',\n password:\n '$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2',\n updatedAt: 2019-02-28T15:18:15.856Z,\n createdAt: 2019-02-28T15:18:15.856Z }...\n\n========================================\n\nTop Answer:\nThe proper way to handle this is to leverage the afterCreate and afterUpdate hooks on the actual data model, that Sequelize exposes. These hooks are fired after the record is persisted, so any mutations to the dataValues will only be reflected in the return.\n\n```\nsequelize.define(\n 'User',\n {\n id: { type: DataType.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true },\n username: { type: DataType.STRING, allowNull: false },\n password: { type: DataType.STRING, allowNull: false }\n },\n {\n hooks: {\n afterCreate: (record) => {\n delete record.dataValues.password;\n },\n afterUpdate: (record) => {\n delete record.dataValues.password;\n },\n }\n }\n);\n```\n\nHere is a link to the documentation: https://sequelize.org/master/manual/hooks.html\n\n========================================\n\nCode:\n```text\nasync create(req, res) {\ntry {\n    let user = await User.create({\n        firstName: req.body.firstName,\n        lastName: req.body.lastName,\n        email: req.body.email,\n        password: req.body.password\n    }, {\n        attributes: {\n            exclude: ['password']\n        }\n    });\n\n    console.log(\"USER: \", user);\n\n    res.status(201).send(user.toJSON());\n}\ncatch (error) {\n    res.status(500).send(error)\n};\n```\n\n```text\nCreate\n```\n\n```text\nInsert\n```\n\n```text\nCreate\n```\n\n```js\nasync create(req, res);\n{\n    try {\n        let user = await User.create({\n            firstName: req.body.firstName,\n            lastName: req.body.lastName,\n            email: req.body.email,\n            password: req.body.password\n        });\n        delete user[\"password\"];//delete field password\n        console.log(\"USER: \", user);\n\n        res.status(201).send(user.toJSON());\n    }\n    catch (error) {\n        res.status(500).send(error);\n    };\n}\n```\n\n```text\nModel.findAll({\n  attributes: { exclude: ['baz'] }\n});\n```\n\n```text\nlet user = await User.create({\n    firstName: req.body.firstName,\n    lastName: req.body.lastName,\n    email: req.body.email,\n    password: req.body.password\n}, {\n    fields: ['firstName', 'lastName', 'email']\n});\n```\n\n```text\nattributes\n```\n\n```text\npassword\n```\n\n```text\ncreate\n```\n\n```js\nUser.create(req.body).then(user => {\n    delete user.dataValues.password\n    res.json(user)\n  }).catch(error => {\n   // do something with error\n  })\n```\n\n```js\nimport {Model} from 'sequelize';\n\nconst toJSON = Model.prototype.toJSON;\n\nModel.prototype.toJSON = function ({attributes = []} = {}) {\n    const obj = toJSON.call(this);\n\n    if (!attributes.length) {\n      return obj;\n    }\n\n    return attributes.reduce((result, attribute) => {\n      result[attribute] = obj[attribute];\n\n      return result;\n    }, {});\n  };\n```\n\n```text\nattributes\n```\n\n```text\nUser.toJSON({attributes: ['name', 'etc...']})\n```\n\n```text\nsequelize.define(\n    'User',\n    {\n        id: { type: DataType.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true },\n        username: { type: DataType.STRING, allowNull: false },\n        password: { type: DataType.STRING, allowNull: false }\n    },\n    {\n        hooks: {\n            afterCreate: (record) => {\n                delete record.dataValues.password;\n            },\n            afterUpdate: (record) => {\n                delete record.dataValues.password;\n            },\n        }\n    }\n);\n```\n\n```text\ntry {\n    const { firstName, lastName, email } = await User.create({\n        firstName: req.body.firstName,\n        lastName: req.body.lastName,\n        email: req.body.email,\n        password: req.body.password\n    })\n    const user = { firstName, lastName, email }\n\n}\n\n     console.log(\"USER: \", user);\n\n     res.status(201).send(user.toJSON());\n}\ncatch (error) {\n     res.status(500).send(error)\n};\n```\n\n========================================\n\nComments:\n- i'm still looking for this like you needed. You finded one way to do this without property.delete? delete all my properties seems not to be a dry solution\n- Thanks Scott, but I don't think your response is correct. The documentation seems to state that the `fields` parameter dictates what fields will be set. This further makes sense as when i attempted to implement your suggestion by Sequelize User model blew up because the password was not provided, only the 3 fields defined were.\n- Ah, perhaps I misunderstood your intent. Have you tried: `User.create({ &#47;&#47;... {include: ['firstName', 'lastName', 'email']} })`?\n- The include parameter is used for model associations. Since this is simply a Create function and no associations are being added here, the include parameter would not be appropriate. I am basically trying to add the `attributes` parameter for the Sequelize.create but apparently there's a different way to do it...?\n- Hmm...the only thing I can think of now is to first `create` then query for the same record with `findOne` and return that. That way you can use `attributes` to `exclude` `password`.\n- Seems like it should also be possible to use `findOrCreate`; e.g., `let [user] = await User.findOrCreate({ firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, password: req.body.password }, { attributes: { exclude: ['password'] } });` Let me know if that works and I'll gladly edit the answer.\n- Here was the final result `delete user.dataValues.password` Querying the database again to get the specific attributes would be more costly.\n- Better solution and practical approach","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":263,"estimatedTokens":1762}}386{"id":"stack-33745804","source":"stackoverflow","questionId":33745804,"title":"SequelizeUniqueConstraintError during seed","tags":["sequelize.js"],"text":"Title: SequelizeUniqueConstraintError during seed\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a node.js application that uses Sequelize. I'm currently targeting SQLite for easy dev setup and testing but will be moving to MySQL for production. I used the sequelize-cli to create the models and migrations and all worked without any issues, I have confirmed that the tables were created using a SQLite browser tool. The problem I have now is when running the seed file that I have below (The database is currently empty) I receive the following error.\n\nError:\n\n```\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\nat Query.formatError (/Users/abc/repos/myProject/node_modules/sequelize/lib/dialects/sqlite/query.js:231:14)\nat Statement. (/Users/abc/repos/myProject/node_modules/sequelize/lib/dialects/sqlite/query.js:47:29)\nat Statement.replacement (/Users/abc/repos/myProject/node_modules/sqlite3/lib/trace.js:20:31)\n```\n\nThe migration:\n\n```\n'use strict';\nmodule.exports = {\n up: function(queryInterface, Sequelize) {\n return queryInterface.createTable('Questions', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n type: {\n allowNull: false,\n type: Sequelize.INTEGER\n },\n text: {\n allowNull: false,\n type: Sequelize.STRING\n },\n nextQuestionId: {\n type: Sequelize.INTEGER\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: function(queryInterface, Sequelize) {\n return queryInterface.dropTable('Questions');\n }\n};\n```\n\nThe model:\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var Question = sequelize.define('Question', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: DataTypes.INTEGER\n },\n type: {\n allowNull: false,\n type: DataTypes.INTEGER\n },\n text: {\n allowNull: false,\n type: DataTypes.STRING\n },\n nextQuestionId: {\n type: DataTypes.INTEGER\n }\n }, {\n classMethods: {\n associate: function(models) {\n Question.belongsTo(Question, {as: 'nextQuestion', foreignKey: 'nextQuestionId'});\n Question.hasMany(models.Answer);\n Question.hasMany(models.questionoption, {as: 'options'});\n }\n }\n });\n return Question;\n};\n```\n\nThe seed:\n\n```\n'use strict';\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert('Questions', [\n {type: 0, text: 'Question A'},\n {type: 5, text: 'Question B', nextQuestionId: 4},\n {type: 5, text: 'Question C', nextQuestionId: 4},\n {type: 0, text: 'Question D'},\n {type: 0, text: 'Question E'},\n {type: 0, text: 'Question F'},\n {type: 0, text: 'Question G'},\n {type: 0, text: 'Question H'},\n {type: 0, text: 'Question I'}\n ], {});\n } ...\n```\n\nI have tried looking though the documentation and googling for answers, nothing seems to hint at this being a common problem. I didn't define any unique columns (other than the primary key of course, but it's an autoIncrement) If I had more information or clues as to which column was causing the issue from the cli then I would at least be able to try some different things, but no help there. I've tried running the equivalent inserts manually in SQL and they work, so I don't think it's the DB rejecting the insert, it appears to be something internal to Sequelize.\n\nAny help would be greatly appreciated as I have been trying a few options for a few days now with no luck.\n\n========================================\n\nTop Answer:\nHad the same problem.\nI added missing `createdAt` and `updatedAt` columns but error still presist.\nI was missing `;` at the end of the `bulkInsert` function.\n\n========================================\n\nCode:\n```text\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\nat Query.formatError (/Users/abc/repos/myProject/node_modules/sequelize/lib/dialects/sqlite/query.js:231:14)\nat Statement.<anonymous> (/Users/abc/repos/myProject/node_modules/sequelize/lib/dialects/sqlite/query.js:47:29)\nat Statement.replacement (/Users/abc/repos/myProject/node_modules/sqlite3/lib/trace.js:20:31)\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n    return queryInterface.createTable('Questions', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      type: {\n        allowNull: false,\n        type: Sequelize.INTEGER\n      },\n      text: {\n        allowNull: false,\n        type: Sequelize.STRING\n      },\n      nextQuestionId: {\n        type: Sequelize.INTEGER\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  down: function(queryInterface, Sequelize) {\n    return queryInterface.dropTable('Questions');\n  }\n};\n```\n\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var Question = sequelize.define('Question', {\n    id: {\n      allowNull: false,\n      autoIncrement: true,\n      primaryKey: true,\n      type: DataTypes.INTEGER\n    },\n    type: {\n      allowNull: false,\n      type: DataTypes.INTEGER\n    },\n    text: {\n      allowNull: false,\n      type: DataTypes.STRING\n    },\n    nextQuestionId: {\n      type: DataTypes.INTEGER\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Question.belongsTo(Question, {as: 'nextQuestion', foreignKey: 'nextQuestionId'});\n        Question.hasMany(models.Answer);\n        Question.hasMany(models.questionoption, {as: 'options'});\n      }\n    }\n  });\n  return Question;\n};\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.bulkInsert('Questions', [\n      {type: 0, text: 'Question A'},\n      {type: 5, text: 'Question B', nextQuestionId: 4},\n      {type: 5, text: 'Question C', nextQuestionId: 4},\n      {type: 0, text: 'Question D'},\n      {type: 0, text: 'Question E'},\n      {type: 0, text: 'Question F'},\n      {type: 0, text: 'Question G'},\n      {type: 0, text: 'Question H'},\n      {type: 0, text: 'Question I'}\n    ], {});\n  } ...\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.bulkInsert('Questions', [\n      {type: 0, text: 'Question A', createdAt: new Date(), updatedAt: new Date()},\n      {type: 5, text: 'Question B', nextQuestionId: 4, createdAt: new Date(), updatedAt: new Date()},\n      {type: 5, text: 'Question C', nextQuestionId: 4, createdAt: new Date(), updatedAt: new Date()},\n      {type: 0, text: 'Question D', createdAt: new Date(), updatedAt: new Date()},\n      {type: 0, text: 'Question E', createdAt: new Date(), updatedAt: new Date()},\n      {type: 0, text: 'Question F', createdAt: new Date(), updatedAt: new Date()},\n      {type: 0, text: 'Question G', createdAt: new Date(), updatedAt: new Date()},\n      {type: 0, text: 'Question H', createdAt: new Date(), updatedAt: new Date()},\n      {type: 0, text: 'Question I', createdAt: new Date(), updatedAt: new Date()}\n    ], {});\n  }, ...\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\n;\n```\n\n```text\nbulkInsert\n```\n\n```text\nmodule.exports = {\n   ......\n   .......\n   updatedAt: {\n    allowNull: false,\n    type: Sequelize.DATE\n  }\n}, {\n  timeStamps: true  // -> Add this\n }\n}\n```\n\n```text\ntimeStamps:true\n```\n\n========================================\n\nComments:\n- Very misleading error, and your solution helped me solve it. Thanks\n- It is true by default.","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":281,"estimatedTokens":1877}}387{"id":"stack-43047530","source":"stackoverflow","questionId":43047530,"title":"How to create a Sequelize model instance, without saving it in the database?","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: How to create a Sequelize model instance, without saving it in the database?\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet's assume we have an Sequelize model called `Person`—how can we create an instance of `Person`, without saving it into the database?\n\nThis will create the record in the database:\n\n```\nPerson.create({ name: \"Alice\" }).then(..., ...);\n```\n\nHow to create a model instance without creating a record for it into the database?\n\nThe use-case is for creating multiple documents:\n\n```\nmyFamily.addPersons([person1, person2, ...]);\n```\n\nWhen I try to pass raw objects into that array, an error appears: `val.replace is not a function` and as suggested here, the reason could be the fact I pass raw objects.\n\nWhile I'm interested to know how to solve the problem, I'd want to know how to create Sequelize model instances, without saving them in the database.\n\n========================================\n\nCode:\n```text\nPerson.create({ name: \"Alice\" }).then(..., ...);\n```\n\n```text\nmyFamily.addPersons([person1, person2, ...]);\n```\n\n```text\nPerson\n```\n\n```text\nPerson\n```\n\n```text\nval.replace is not a function\n```\n\n```text\nvar person = Person.build({ name: \"Alice\" });\n```\n\n```text\nconst person = new Person({ name: \"Alice\" })\n```\n\n```text\nbuild\n```\n\n```text\nPerson\n```\n\n========================================\n\nComments:\n- That worked! Thanks! Would be handy to leave a link to the docs as well.\n- Just a note: for my use case (adding persons to the family), I should use `create`, according to this, otherwise the `Person`s won't be created.\n- How can you get the model's instance of a table that is already in a remote database. Im able to connect to a remote db. But instead of directly using query method to write extensive plain sql queries, can I use the ORM like functionality to query data from an existing table without defining the model in my node app?\n- Is there a way to get an object back that has all the fields in the model? Say the model/table has 15 fields, can you get back an instance such that if you at least called toJSON on it, you'd get all 15 fields defined, even if they're empty?\n- The recommended way to create an instance is to use the public static `build` method. They recommend against using the `new` operator. source","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":72,"estimatedTokens":577}}388{"id":"stack-65267623","source":"stackoverflow","questionId":65267623,"title":"sequelize - order by column from included model","tags":["sequelize.js","sql-order-by"],"text":"Title: sequelize - order by column from included model\nTags: sequelize.js, sql-order-by\nSource: Stack Overflow\n\nQuestion:\nI can't figure out how to order by a column that is in my included model. But I'm not even returning that field in the attributes. I just want to order by it if that is possible. Or I can return it and not use as long as I can sort by it.\n\n```\nconst users = await db.User.findAll({\n raw: true,\n attributes: [\n 'id',\n 'first_name',\n 'last_name',\n 'email',\n 'Permission.type'\n ],\n include: [\n {\n model: db.Permission,\n where: { id: { [Op.lte]: 2 } },\n attributes: [],\n order: [[{ model: db.Permission }, 'id', 'DESC']]\n }\n ]\n});\n```\n\nIn the `include` block the `order` block does nothing right now. But I have an attribute in my Permission model called `id` that I want to order all results by. I am fine with adding `Permission.id` to my `attributes` if that is necessary. But I tried it and it still didn't work.\n\n========================================\n\nTop Answer:\nI have a very similar situation and was glad to find this post. However, the answer does not appear to work for me. My query looks like:\n\n```\nconst favSpaces = await FavoriteSpace.findAll({\n transaction: ctx.transaction,\n attributes: ['uid', 'space_id', 'is_favorite', 'last_visited'],\n include: [\n {\n model: Space,\n as: 'space',\n attributes: ['key', 'display_name', 'description', 'type'],\n },\n ],\n where: {\n uid,\n is_favorite: true,\n },\n order: [[{ model: Space }, 'display_name', 'ASC']],\n});\n```\n\nWhen I run that query, I get:\n\n```\nError: Unable to find a valid association for model, 'Space'\n```\n\nAm I doing something obviously wrong? If I comment out the `order:` line, the query works fine.\n\n========================================\n\nCode:\n```text\nconst users = await db.User.findAll({\n    raw: true,\n    attributes: [\n        'id',\n        'first_name',\n        'last_name',\n        'email',\n        'Permission.type'\n    ],\n    include: [\n    {\n        model: db.Permission,\n        where: { id: { [Op.lte]: 2 } },\n        attributes: [],\n        order: [[{ model: db.Permission }, 'id', 'DESC']]\n    }\n    ]\n});\n```\n\n```text\ninclude\n```\n\n```text\norder\n```\n\n```text\nid\n```\n\n```text\nPermission.id\n```\n\n```text\nattributes\n```\n\n```text\nconst users = await db.User.findAll({\n    raw: true,\n    attributes: [\n        'id',\n        'first_name',\n        'last_name',\n        'email',\n        'Permission.type'\n    ],\n    include: [\n    {\n        model: db.Permission,\n        where: { id: { [Op.lte]: 2 } },\n        attributes: []\n    }\n    ],\n    order: [[{ model: db.Permission }, 'id', 'DESC']]\n});\n```\n\n```text\norder\n```\n\n```text\ninclude\n```\n\n```text\nid\n```\n\n```text\ninclude\n```\n\n```text\nconst favSpaces = await FavoriteSpace.findAll({\n  transaction: ctx.transaction,\n  attributes: ['uid', 'space_id', 'is_favorite', 'last_visited'],\n  include: [\n    {\n      model: Space,\n      as: 'space',\n      attributes: ['key', 'display_name', 'description', 'type'],\n    },\n  ],\n  where: {\n    uid,\n    is_favorite: true,\n  },\n  order: [[{ model: Space }, 'display_name', 'ASC']],\n});\n```\n\n```text\nError: Unable to find a valid association for model, 'Space'\n```\n\n```text\norder:\n```\n\n========================================\n\nComments:\n- OK, that worked! I couldn't get it to work before but I was changing several things at the same time. I had to return the id in the main attributes as well. If I tried returning it in the include attributes it broke and I got no results back.\n- Please never try to change several things at once. That way you cannot say what exactly caused an issue.\n- According to this github.com/sequelize/sequelize/issues/4553, your order would need to look like `order: [[{ model: Space, as: 'space' }, 'display_name', 'ASC']],`","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":176,"estimatedTokens":936}}389{"id":"stack-18168312","source":"stackoverflow","questionId":18168312,"title":"How do I install the sequelize.js binary?","tags":["node.js","sequelize.js"],"text":"Title: How do I install the sequelize.js binary?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am referencing the sequelize.js documentation at:\nhttp://sequelizejs.com/documentation#migrations-the-binary\n\nAfter running 'sequelize -V', I receive:\n\n```\n$ sequelize -V\nsequelize: command not found\n```\n\nI have searched online and cannot find any references on how to install the binary\n\n========================================\n\nTop Answer:\nIf you install locally, there are links to binaries at `./node_modules/.bin` . This path applies to all your local binaries, and you can output this on your CLI with `npm bin` . \n\nYou can also do `ls -laF node_modules/.bin` to view where the links point to.\n\nSee this stack question for more\n\n========================================\n\nCode:\n```text\n$ sequelize -V\nsequelize: command not found\n```\n\n```text\nnpm install -g sequelize-cli\n```\n\n```text\nsequelize-cli\n```\n\n```text\nnpm install sequelize\n```\n\n```text\n./node_modules/.bin\n```\n\n```text\nnpm bin\n```\n\n```text\nls -laF node_modules/.bin\n```\n\n```text\nyarn sequelize init\n```\n\n```text\nnpx sequelize init\n```\n\n========================================\n\nComments:\n- All you need to do is add the `-g` flag when installing it.\n- Neither one of these facts is documented by sequelize's site. Wasted 30 minutes poking around to find it. Following through their site's docs, the installation step doesn't use the global flag.\n- @thaspius It would probably help if they mentioned the different installation as well, but it's primarily documented by NPM itself: `npm-folders(5)`.\n- Its worth noting that at the actual time of the posting, I could not figure the issue out and this answer was actually what fixed it. Downvoting what was at that time an actual legitimate answer seems absurd...\n- This answer wasn't mentioned for a year after the question had been posted. Was it available at that time?\n- Or `yarn global add sequelize-cli`","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":75,"estimatedTokens":484}}390{"id":"stack-58067349","source":"stackoverflow","questionId":58067349,"title":"how to solve \"sequelize: command not found\"?","tags":["node.js","terminal","sequelize.js"],"text":"Title: how to solve \"sequelize: command not found\"?\nTags: node.js, terminal, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThis is so frustrating.. I am trying to install sequalize for node.js. I installed it locally with success, but I cant install it globally (I am getting permission denied errors for:\n\n```\n\\'../lib/node_modules/sequelize-cli/lib/sequelize\\').\n```\n\nI actually don't really want it globally installed, but when have it locally and should configure and initialize the sequelize module (by typing ***sequelize init:models & sequelize init:config*** in terminal) I get the following error:\n\n```\n-bash: sequelize: command not found\n```\n\nSo I did my homework and found out that the command not found error could be solved with globally install (-bash: sequelize: command not found) and to fix the error in enabling globally install I changed my user access (Error: EACCES: permission denied, access '/usr/local/lib/node_modules' react), but this didnt do the trick, I still getting permission denied.\n\nSo my question is how could I run ***sequelize init:models & sequelize init:config*** in terminal without getting command not found?\n\n========================================\n\nTop Answer:\nYou need to install\n\n```\nnpm install --save sequelize\nnpm install --save sequelize-cli\n```\n\nAnd then according to documentation you can run the CLI. No need to install it globally.\n\n```\n$ npx sequelize --help\n\nSequelize CLI [Node: 10.0.0, CLI: 5.5.1, ORM: 5.19.0]\n\nsequelize [command]\n\nCommands:\n sequelize db:migrate Run pending migrations\n sequelize db:migrate:schema:timestamps:add Update migration table to have timestamps\n sequelize db:migrate:status List the status of all migrations\n sequelize db:migrate:undo Reverts a migration\n sequelize db:migrate:undo:all Revert all migrations ran\n sequelize db:seed Run specified seeder\n sequelize db:seed:undo Deletes data from the database\n sequelize db:seed:all Run every seeder\n sequelize db:seed:undo:all Deletes data from the database\n sequelize db:create Create database specified by configuration\n sequelize db:drop Drop database specified by configuration\n sequelize init Initializes project\n sequelize init:config Initializes configuration\n sequelize init:migrations Initializes migrations\n sequelize init:models Initializes models\n sequelize init:seeders Initializes seeders\n sequelize migration:generate Generates a new migration file [aliases: migration:create]\n sequelize model:generate Generates a model and its migration [aliases: model:create]\n sequelize seed:generate Generates a new seed file [aliases: seed:create]\n\nOptions:\n --help Show help [boolean]\n --version Show version number [boolean]\n```\n\n========================================\n\nCode:\n```text\n\\'../lib/node_modules/sequelize-cli/lib/sequelize\\').\n```\n\n```text\n-bash: sequelize: command not found\n```\n\n```text\nsudo npm install -g sequelize\n```\n\n```text\nsudo npm i -g sequelize-cli\n```\n\n```text\nnpm install --save sequelize\nnpm install --save sequelize-cli\n```\n\n```text\n$ npx sequelize --help\n\nSequelize CLI [Node: 10.0.0, CLI: 5.5.1, ORM: 5.19.0]\n\nsequelize [command]\n\nCommands:\n  sequelize db:migrate                        Run pending migrations\n  sequelize db:migrate:schema:timestamps:add  Update migration table to have timestamps\n  sequelize db:migrate:status                 List the status of all migrations\n  sequelize db:migrate:undo                   Reverts a migration\n  sequelize db:migrate:undo:all               Revert all migrations ran\n  sequelize db:seed                           Run specified seeder\n  sequelize db:seed:undo                      Deletes data from the database\n  sequelize db:seed:all                       Run every seeder\n  sequelize db:seed:undo:all                  Deletes data from the database\n  sequelize db:create                         Create database specified by configuration\n  sequelize db:drop                           Drop database specified by configuration\n  sequelize init                              Initializes project\n  sequelize init:config                       Initializes configuration\n  sequelize init:migrations                   Initializes migrations\n  sequelize init:models                       Initializes models\n  sequelize init:seeders                      Initializes seeders\n  sequelize migration:generate                Generates a new migration file   [aliases: migration:create]\n  sequelize model:generate                    Generates a model and its migration  [aliases: model:create]\n  sequelize seed:generate                     Generates a new seed file             [aliases: seed:create]\n\nOptions:\n  --help     Show help                                                                           [boolean]\n  --version  Show version number                                                                 [boolean]\n```\n\n```text\nnpm install --save sequelize\nnpm install --save sequelize-cli\n```\n\n```text\nnpx sequelize init\n```\n\n```text\nSet-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted\n```\n\n```text\nnpm install -g sequelize-auto\n```\n\n```text\nnpm install mysql2 -g\n```\n\n========================================\n\nComments:\n- To install packages globally, most of the times you need root privileges so you need to use sudo and insert your password $sudo npm install -g sequelize.\n- It worked! I used sudo on both npm install -g sequelize and npm install sequelize-cli and then it worked. thanks!\n- Possible duplicate of -bash: sequelize: command not found\n- @vitomadio quick tip: if you have to use sudo when you're using npm, something is wrong. I recommend you get that fixed quickly. That is super dangerous. If someone put a script in their \"postinstall\" for rm -rf /, it runs automatically after installation, and you've just run it with sudo and given it permission to delete your entire hard drive.\n- I have done that, it still says \"sequelize: command not found”\n- what is the output of this command `npm ls | grep sequelize` ?\n- And did you try to run it like this `npx sequelize init:models`?\n- Hi, thanks a lot for your help, I solved it with using sudo on both npm install -g sequelize and npm install sequelize-cli.\n- 1.npm install --save sequelize 2.npm install --save sequelize-cli 3.npx sequelize init\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":157,"estimatedTokens":1632}}391{"id":"stack-43962899","source":"stackoverflow","questionId":43962899,"title":"how to append item to an array value with Sequelize + PostgreSQL","tags":["arrays","postgresql","promise","append","sequelize.js"],"text":"Title: how to append item to an array value with Sequelize + PostgreSQL\nTags: arrays, postgresql, promise, append, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a posgresql database, table has a column which is an array: `Sequelize.ARRAY(Sequelize.BIGINT)`. \n\nWhat is the right way to append a new item to the array?\n\nI am new to posgresql, sequelize and nodejs. May be it is a trivial question.\nFrom reading around I think I know how to use Promise.all to read all rows, append, and update back.\nThe question, isn't there any useful shortcut.\n\nPostreSQL documentation mentions a function `array_append(anyarray, anyelement)`.\n\nSequelize documentation offers a function fn, which `Creates an object representing a database function`, but only seems to be working in `where and order parts`\n\nAny way to combine those for an append-like update?\n\n========================================\n\nCode:\n```text\nSequelize.ARRAY(Sequelize.BIGINT)\n```\n\n```text\narray_append(anyarray, anyelement)\n```\n\n```text\nCreates an object representing a database function\n```\n\n```text\nwhere and order parts\n```\n\n```text\nRoom.update(\n {'job_ids': sequelize.fn('array_append', sequelize.col('job_ids'), new_jobId)},\n {'where': {'id': roomId}}\n);\n```\n\n```text\narray_append\n```\n\n```text\nRoom\n```\n\n```text\njob_ids\n```\n\n```text\nsequelize\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":60,"estimatedTokens":330}}392{"id":"stack-45937174","source":"stackoverflow","questionId":45937174,"title":"How to define an NVARCHAR(MAX) field with sequelize?","tags":["sql-server","node.js","sequelize.js"],"text":"Title: How to define an NVARCHAR(MAX) field with sequelize?\nTags: sql-server, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing node.js and sequelize vis-a-vis MSSQL, how do I define an NVARCHAR(MAX) field?\n\n========================================\n\nTop Answer:\njust use `Sequelize.STRING('MAX')` as type\n\n========================================\n\nCode:\n```text\nTEXT.prototype.toSql = function toSql() {\n    // TEXT is deprecated in mssql and it would normally be saved as a non-unicode string.\n    // Using unicode is just future proof\n    if (this._length) {\n      if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8\n        warn('MSSQL does not support TEXT with the `length` = `tiny` option. `NVARCHAR(256)` will be used instead.');\n        return 'NVARCHAR(256)';\n      }\n      warn('MSSQL does not support TEXT with the `length` option. `NVARCHAR(MAX)` will be used instead.');\n    }\n    return 'NVARCHAR(MAX)';\n  };\n```\n\n```text\nNVARCHAR(MAX\n```\n\n```text\nNVARCHAR(MAX)\n```\n\n```text\nSequelize.STRING('MAX')\n```\n\n```text\nDataTypes.STRING(65535)\n```\n\n========================================\n\nComments:\n- to convert a data item in MSSQL would be: convert(varchar(max),field) as field - using max is not great practice however as this is only available as text if used in associated MS products like access - I would limit the available chars to max 255 where possible\n- thanks, but I specifically need nvarchar(max) (for storing JSON)\n- Nope, not working: `ERROR: syntax error at or near \"MAX\"` (\"sequelize\": \"4.41.1\")\n- `{ type: DataTypes.STRING('MAX') }` works for me in version 6.37.1","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":53,"estimatedTokens":403}}393{"id":"stack-52496842","source":"stackoverflow","questionId":52496842,"title":"Sequelize 'hasMany' associated(model) count in attributes in query execution","tags":["mysql","associations","sequelize.js"],"text":"Title: Sequelize 'hasMany' associated(model) count in attributes in query execution\nTags: mysql, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSequelize version: 4.22.6,\nMySql version:5.7.8\n**I want to 'hasMany' associated(CompanyUser) count in attibutes(at place of _user_count_) in query execution**\n\n```\n/**\n* Company user associate with Company with belongsTo relation\n*/\n`CompanyUser.belongsTo(Company, { foreignKey: 'company_id', targetKey: 'id'});`\n\n/**\n* Company associate with Company user with hasMany relation\n*/\n`Company.hasMany(CompanyUser, { foreignKey: 'company_id', sourceKey: 'id'});`\n\n`return Company.findAll({\n attributes: [\n 'id', 'title', 'is_enabled', '_user_count_'\n ]\n include: [\n {\n model: sqConn.CompanyUser,\n attributes: ['id'],\n },\n {\n model: sqConn.CompanyLogo,\n attributes:['file_object'],\n }\n ],\n}).then(function(model) {\n return sequelize.Promise.resolve(model);\n}).catch(function(err) {\n return sequelize.Promise.reject(err);\n});`\n```\n\nSimple MySQL query with left-join works fine and give count.\n\n========================================\n\nTop Answer:\nthis is something that works for me:\n\n```\nawait PostModel.findAll({\n group: ['posts.id'],\n order: [['createdAt', 'DESC']],\n include: [\n {\n model: CategoryModel,\n attributes: ['title'],\n where: { title: categoryTitle }\n },\n { model: CommentModel },\n { model: UserModel, attributes: ['fullname', 'id'] }\n ],\n attributes: [\n 'title', 'content', 'description', 'thumbnail', 'baner', 'createdAt', 'updatedAt',\n [Sequelize.fn('COUNT', 'comment.id'), 'commentsCounter']\n ]\n});\n```\n\n**Associations:**\n\n- Post M:N Category\n\n- Post 1:N Comment\n\n- Post N:1 User\n\nplease note to this part `'comment.id'` not `'comments.id'`.\n\nif you use `'comments.id'` it throws this error for you: `SequelizeDatabaseError: missing FROM-clause entry for table \"comments\"`\n\n**MY MODELS - UPDATE:**\nhttps://i.sstatic.net/vY5WG.png\nand comment\n\n```\nconst { sequelize } = require('./index');\nconst { Model, DataTypes } = require('sequelize');\nclass CommentModel extends Model {};\nCommentModel.init({\n id: {\n primaryKey: true,\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV4\n },\n content: {\n type: DataTypes.TEXT,\n allowNull: false\n }\n}, {\n sequelize,\n modelName: 'comments',\n timestamps: true,\n paranoid: false\n});\n\nmodule.exports = CommentModel;\n```\n\n========================================\n\nCode:\n```text\n/**\n* Company user associate with Company with belongsTo relation\n*/\n`CompanyUser.belongsTo(Company, { foreignKey: 'company_id', targetKey: 'id'});`\n\n/**\n* Company  associate with Company user with hasMany relation\n*/\n`Company.hasMany(CompanyUser, { foreignKey: 'company_id', sourceKey: 'id'});`\n\n`return Company.findAll({\n    attributes: [\n        'id', 'title', 'is_enabled', '_user_count_'\n    ]\n    include: [\n        {\n            model: sqConn.CompanyUser,\n            attributes: ['id'],\n        },\n        {\n            model: sqConn.CompanyLogo,\n            attributes:['file_object'],\n        }\n    ],\n}).then(function(model) {\n    return sequelize.Promise.resolve(model);\n}).catch(function(err) {\n    return sequelize.Promise.reject(err);\n});`\n```\n\n```text\nCompany.findAll({\n    attributes: [\n        'id', 'title', 'is_enabled',\n        [sequelize.fn('count', sequelize.col('company_users.id')) ,'user_count'] // <---- Here you will get the total count of user\n    ],\n    include: [\n        {\n            model: sqConn.CompanyUser,\n            attributes: [] // <----- Make sure , this should be empty\n        }\n    ],\n    group: ['companies.id'] // <---- You might require this one also\n}).then(data => { \n    console.log(data); // <---- Check the output\n})\n```\n\n```text\nsequelize.fn\n```\n\n```text\nawait PostModel.findAll({\n  group: ['posts.id'],\n  order: [['createdAt', 'DESC']],\n  include: [\n    {\n      model: CategoryModel,\n      attributes: ['title'],\n      where: { title: categoryTitle }\n    },\n    { model: CommentModel },\n    { model: UserModel, attributes: ['fullname', 'id'] }\n  ],\n  attributes: [\n    'title', 'content', 'description', 'thumbnail', 'baner', 'createdAt', 'updatedAt',\n    [Sequelize.fn('COUNT', 'comment.id'), 'commentsCounter']\n  ]\n});\n```\n\n```text\nconst { sequelize } = require('./index');\nconst { Model, DataTypes } = require('sequelize');\nclass CommentModel extends Model {};\nCommentModel.init({\n    id: {\n        primaryKey: true,\n        type: DataTypes.UUID,\n        defaultValue: DataTypes.UUIDV4\n    },\n    content: {\n        type: DataTypes.TEXT,\n        allowNull: false\n    }\n}, {\n    sequelize,\n    modelName: 'comments',\n    timestamps: true,\n    paranoid: false\n});\n\nmodule.exports = CommentModel;\n```\n\n```text\n'comment.id'\n```\n\n```text\n'comments.id'\n```\n\n```text\n'comments.id'\n```\n\n```text\nSequelizeDatabaseError: missing FROM-clause entry for table \"comments\"\n```\n\n========================================\n\nComments:\n- Getting error : `]^ SyntaxError: Unexpected token ]` at `attributes: [ 'id','title', 'is_enabled', [ sequelize.fn('count', sequelize.col('company_users.id')) ,'user_count']], ]`\n- remove one extra `]` , inside attribute , please check updated answer.\n- It's works fine, Only remaning thing is `group:['companies.id']`\n- How did you set your models? This solution doesn't work for me\n- hello @cylee. I add my models in my answer. you can see them","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":233,"estimatedTokens":1326}}394{"id":"stack-49700623","source":"stackoverflow","questionId":49700623,"title":"How to use the $in operator with SequelizeJS?","tags":["javascript","mysql","node.js","sequelize.js","in-operator"],"text":"Title: How to use the $in operator with SequelizeJS?\nTags: javascript, mysql, node.js, sequelize.js, in-operator\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use the $in operator in SequelizeJS as you would in a MySQL statement:\n\n```\nSELECT column_name(s)\nFROM table_name\nWHERE column_name IN (value1, value2, ...);\n```\n\nIn my case, I've joined three tables, but I don't believe that's related to the issue. I keep getting this error `Error: Invalid value { '$in': ['12345','67890','15948'] }` with the following code:\n\n```\ndefinedTable.findAll({\n include: [{\n model: definedTableTwo,\n where: {\n zip_code: {\n $in: ['12345','67890','15948']\n }\n },\n required: true,\n plain: true\n },\n {\n model: definedTableThree,\n required: true,\n plain: true\n }]\n})\n```\n\nCan someone provide some insight on how to use the $in operator? The only examples I've seen are with integers within the array when searching Ids.\n\n========================================\n\nCode:\n```text\nSELECT column_name(s)\nFROM table_name\nWHERE column_name IN (value1, value2, ...);\n```\n\n```text\ndefinedTable.findAll({\n  include: [{\n    model: definedTableTwo,\n    where: {\n      zip_code: {\n        $in: ['12345','67890','15948']\n      }\n    },\n    required: true,\n    plain: true\n  },\n  {\n    model: definedTableThree,\n    required: true,\n    plain: true\n  }]\n})\n```\n\n```text\nError: Invalid value { '$in': ['12345','67890','15948'] }\n```\n\n```text\nconst Op = Sequelize.Op;\ndefinedTable.findAll({\n  include: [{\n    model: definedTableTwo,\n    where: {\n      zip_code: {\n        [Op.in]: ['12345','67890','15948']\n          }\n    },\n    required: true,\n    plain: true\n  },\n  {\n    model: definedTableThree,\n    required: true,\n    plain: true\n  }]\n})\n```\n\n========================================\n\nComments:\n- Hi @pierreaurelemartin, the `$in` is essentially `[Op.in]`. `$in` is an alias for that operator. I'm questioning whether I'm providing the values in the correct format. At least that is what the error indicates.\n- I just realized that the alias `$in` was **NOT** included in my file, that ended up being the issue. Basically user error. I'll mark your comment as the answer since it's technically correct and brought my user error to light. Thanks\n- Hey guys, I have the same problem. Instead, I need to add and condition on zip code. Do you have any idea?\n- Link to doc is broken. Found this sequelize.org/docs/v6/core-concepts/model-querying-basics/&hellip; It shows as well that this shorthand syntax `zip_code: ['12345','67890','15948']` should work too 👍","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":98,"estimatedTokens":633}}395{"id":"stack-35822800","source":"stackoverflow","questionId":35822800,"title":"Sequelize - How do I fix \"DataTypes is not defined\"?","tags":["mysql","sequelize.js"],"text":"Title: Sequelize - How do I fix \"DataTypes is not defined\"?\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to have a model in sequelize generate a unique ID using `DataTypes.UUID`. This throws an error when I serve up my application\n\n`ReferenceError: DataTypes is not defined`\n\n**Here's my code**\n\n```\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('uppersphere', '****', '***', {\n logging: false\n});\n...\nvar Peak = sequelize.define('peak', {\n id: {\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV1,\n primaryKey: true\n },\n```\n\n**Here's the documentation**\n\n```\nsequelize.define('model', {\n uuid: {\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV1,\n primaryKey: true\n }\n })\n```\n\nThe obvious answer is that it's not my code, but there's some `require()` that I need. However, I don't see any documentation on what to require to get DataTypes.\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('uppersphere', '****', '***', {\n  logging: false\n});\n...\nvar Peak = sequelize.define('peak', {\n  id: {\n    type: DataTypes.UUID,\n    defaultValue: DataTypes.UUIDV1,\n    primaryKey: true\n  },\n```\n\n```text\nsequelize.define('model', {\n    uuid: {\n      type: DataTypes.UUID,\n      defaultValue: DataTypes.UUIDV1,\n      primaryKey: true\n    }\n  })\n```\n\n```text\nDataTypes.UUID\n```\n\n```text\nReferenceError: DataTypes is not defined\n```\n\n```text\nrequire()\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar Peak = sequelize.define('peak', {\n  id: {\n    type: Sequelize.UUID,\n    defaultValue: Sequelize.UUIDV1,\n    primaryKey: true\n  },\n```\n\n```text\nvar DataTypes = require('sequelize/lib/data-types');\n```\n\n```text\nSequelize\n```\n\n```text\nDataTypes\n```\n\n```text\nDataTypes\n```\n\n========================================\n\nComments:\n- I already have that in my code. It is implied with the `...` But thank you for trying. It looks like stackoverflow kinda formatted it weird, so that may not have been noticeable. I'll actually go ahead and make it more clear to avoid further confusion.\n- @DanielBreen updated the answer with some more details. Hope that at least set you on the correct path. Thanks.\n- Thanks for the updated answer @alecxe. That was the missing link!","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":110,"estimatedTokens":572}}396{"id":"stack-64250923","source":"stackoverflow","questionId":64250923,"title":"Change value of createdAt in Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: Change value of createdAt in Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI would like to set the value of `createdAt` to some time in the past.\n\nHowever, all of my attempts fail to change the `createdAt` date in the database. The value remains the same.\n\n```\nconst yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);\n\n// failed attempts\nhang.createAt = yesterday;\nhang.set('createdAt', yesterday);\nhang.changed('createdAt', yesterday);\n\nawait hang.save();\n```\n\nI also tried\n\n```\nconst yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);\n\n// failed attempt\nawait hang.update({ createdAt: yesterday });\n```\n\nProof of issue\n\n```\n2020-10-07T19:24:29.058Z // before\n2020-10-07T19:24:29.058Z // after\n```\n\n*How can I change the `createdAt` value of an instance?*\n\n========================================\n\nCode:\n```js\nconst yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);\n\n// failed attempts\nhang.createAt = yesterday;\nhang.set('createdAt', yesterday);\nhang.changed('createdAt', yesterday);\n\nawait hang.save();\n```\n\n```js\nconst yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);\n\n// failed attempt\nawait hang.update({ createdAt: yesterday });\n```\n\n```js\n2020-10-07T19:24:29.058Z // before\n2020-10-07T19:24:29.058Z // after\n```\n\n```text\ncreatedAt\n```\n\n```text\ncreatedAt\n```\n\n```text\ncreatedAt\n```\n\n```text\nconst yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);\n\nhang.changed('createdAt', true);\nhang.set('createdAt', yesterday,{raw: true});\nawait hang.save({\n        silent: true,\n        fields: ['createdAt']\n });\n```\n\n```text\nraw: true\n```\n\n```text\nsilent: true\n```\n\n========================================\n\nComments:\n- Thank you! It works. Sequelize documenation s****s sometimes","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":99,"estimatedTokens":449}}397{"id":"stack-43735418","source":"stackoverflow","questionId":43735418,"title":"Sequelize how to return destroyed row","tags":["node.js","row","sequelize.js","destroy"],"text":"Title: Sequelize how to return destroyed row\nTags: node.js, row, sequelize.js, destroy\nSource: Stack Overflow\n\nQuestion:\nHere is my code for deleting rows in database\n\n```\nModel.destroy({\n where: {\n ...\n }\n}).then((response) => {\n console.log(response)\n})\n```\n\nWhat I am getting in `console.log` is `0` or `1` whether record deleted or not.. \n\nIs it any way to return destroyed row in promise?\n\nSo response should be like this { id:123, ... }\n\n========================================\n\nCode:\n```text\nModel.destroy({\n  where: {\n    ...\n  }\n}).then((response) => {\n    console.log(response)\n})\n```\n\n```text\nconsole.log\n```\n\n```text\n0\n```\n\n```text\n1\n```\n\n```text\nModel.find({\n   where: {...}\n}).then((result) => {\n    return Model.destroy({where: ..})\n              .then((u) => {return result});\n});\n```\n\n```text\nfunction deleteRow() {\n    return Model.find({\n        where: { ...}\n    }).then((result) => {\n        return Model.destroy({ where: ..})\n            .then((u) => { return result });\n    });\n}\n```\n\n```text\ndeleteRow().then(findResult => console.log(JSON.stringify(findResult));\n```\n\n```text\nUpdate\n```\n\n```text\nDestroy\n```\n\n```text\nModel.destroy\n```\n\n```text\nresult\n```\n\n```text\nModel.find\n```\n\n```text\ndeleteRow\n```\n\n```text\ndeleteRow\n```\n\n========================================\n\nComments:\n- Added some updates.\n- Thank you Suhail.. have't implemented yet but I believe it will be fine... So are you sure that there is no way of retrieve deleted record without 2 query?\n- You could use a backup file, perhaps. I am not aware of any recovery tools available. But this is good.\n- Actually `update` works that way with Postgres. See `returnign: true` option\n- This answer is incorrect because of concurrency. The number of records during the find() and the destroy() operations aren't always the same.\n- two queries have to be made just to get the returning data, not really optimize as I see","metadata":{"transformedAt":"2026-08-18T18:33:34.371Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":109,"estimatedTokens":476}}398{"id":"stack-54895133","source":"stackoverflow","questionId":54895133,"title":"Sequelize Migrations: Adding a foreign key constraint to a column on same table","tags":["node.js","foreign-keys","sequelize.js","database-migration"],"text":"Title: Sequelize Migrations: Adding a foreign key constraint to a column on same table\nTags: node.js, foreign-keys, sequelize.js, database-migration\nSource: Stack Overflow\n\nQuestion:\nSo I'm trying to create a table with foreign key constraints to itself in migrations file.\n\nI tried what I could following the sequelize docs and down below is the code I've tried, and I've also tried to move the foreign key references up to where the attributes were defined but it does not work there as well. Is there a way to do what I want to do here?\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('comments', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n root_id: {\n defaultValue: null,\n type: Sequelize.INTEGER\n },\n parent_id: {\n defaultValue: null,\n type: Sequelize.INTEGER\n },\n }).then(() => queryInterface.addConstraint(\n 'comments',\n ['root_id'],\n {\n type: 'foreign key',\n name: 'root_id_fk',\n references: {\n table: 'comments',\n field: 'root_id'\n },\n onDelete: 'cascade',\n onUpdate: 'cascade'\n }\n )).then(() => queryInterface.addConstraint(\n 'comments',\n ['parent_id'],\n {\n type: 'foreign key',\n name: 'parent_id_fk',\n references: {\n table: 'comments',\n field: 'parent_id'\n },\n onDelete: 'cascade',\n onUpdate: 'cascade'\n }\n ))\n },\n```\n\n========================================\n\nTop Answer:\nShashikant Pandit's answer is good, but it is not cross-db compatible.\n\nI ran into a problem using that migration because I have a PostgreSQL as the main DB, and an in-memory SQLite database for my tests. Running the migrations in the test environment (the tests start with a blank DB and run the migrations to get to current) produced an error in SQLite.\n\nHere is a version that uses Sequelizes `addConstraint` built-in and should be cross-db compatible.\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => queryInterface\n .addConstraint('app_users', {\n type: 'UNIQUE',\n fields: ['email', 'column2', 'column3'],\n name: 'unique_user_email',\n }),\n down: (queryInterface, Sequelize) => queryInterface\n .removeConstraint('app_users', 'unique_user_email'),\n};\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('comments', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      root_id: {\n        defaultValue: null,\n        type: Sequelize.INTEGER\n      },\n      parent_id: {\n        defaultValue: null,\n        type: Sequelize.INTEGER\n      },\n    }).then(() => queryInterface.addConstraint(\n      'comments',\n      ['root_id'],\n      {\n        type: 'foreign key',\n        name: 'root_id_fk',\n        references: {\n          table: 'comments',\n          field: 'root_id'\n        },\n        onDelete: 'cascade',\n        onUpdate: 'cascade'\n      }\n    )).then(() => queryInterface.addConstraint(\n      'comments',\n      ['parent_id'],\n      {\n        type: 'foreign key',\n        name: 'parent_id_fk',\n        references: {\n          table: 'comments',\n          field: 'parent_id'\n        },\n        onDelete: 'cascade',\n        onUpdate: 'cascade'\n      }\n    ))\n  },\n```\n\n```text\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n    return queryInterface.sequelize.query(\"ALTER TABLE app_users ADD CONSTRAINT unique_user_email UNIQUE (email,column2,column3);\")\n  },\n  down: function(queryInterface, Sequelize) {\n    return queryInterface.sequelize.query(\"ALTER TABLE app_users DROP INDEX unique_user_email;\")\n  }\n};\n```\n\n```js\nmodule.exports = {\n  up: (queryInterface, Sequelize) => queryInterface\n    .addConstraint('app_users', {\n      type: 'UNIQUE',\n      fields: ['email', 'column2', 'column3'],\n      name: 'unique_user_email',\n    }),\n  down: (queryInterface, Sequelize) => queryInterface\n    .removeConstraint('app_users', 'unique_user_email'),\n};\n```\n\n```text\naddConstraint\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":157,"estimatedTokens":998}}399{"id":"stack-29615889","source":"stackoverflow","questionId":29615889,"title":"Sequelize can't create table but when I run the same in MySQL CLI it works","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize can't create table but when I run the same in MySQL CLI it works\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize and have run into a weird error:\n\n```\nExecuting (default): CREATE TABLE IF NOT EXISTS `groups` (`id` INTEGER NOT NULL auto_increment , `groupname` VARCHAR(255), `groupkey` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `username` VARCHAR(255) UNIQUE, `password` VARCHAR(255), `salt` VARCHAR(255), `token` VARCHAR(255), `group_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`)) ENGINE=InnoDB;\nExecuting (default): CREATE TABLE IF NOT EXISTS `messages` (`id` INTEGER NOT NULL auto_increment , `message` VARCHAR(255), `group_id` INTEGER, `user_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`), FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) ENGINE=InnoDB;\nPossibly unhandled SequelizeDatabaseError: ER_CANT_CREATE_TABLE: Can't create table 'crew.users' (errno: 150)\n at module.exports.Query.formatError (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:160:16)\n at Query._callback (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:38:23)\n at Query.Sequence.end (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n at Query.ErrorPacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Query.js:94:8)\n at Protocol._parsePacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:271:23)\n at Parser.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Parser.js:77:12)\n at Protocol.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n at Socket. (/home/ubuntu/public/server/node_modules/mysql/lib/Connection.js:82:28)\n at Socket.EventEmitter.emit (events.js:95:17)\n at Socket. (_stream_readable.js:746:14)\nPossibly unhandled SequelizeDatabaseError: ER_CANT_CREATE_TABLE: Can't create table 'crew.messages' (errno: 150)\n at module.exports.Query.formatError (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:160:16)\n at Query._callback (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:38:23)\n at Query.Sequence.end (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n at Query.ErrorPacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Query.js:94:8)\n at Protocol._parsePacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:271:23)\n at Parser.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Parser.js:77:12)\n at Protocol.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n at Socket. (/home/ubuntu/public/server/node_modules/mysql/lib/Connection.js:82:28)\n at Socket.EventEmitter.emit (events.js:95:17)\n at Socket. (_stream_readable.js:746:14)\n```\n\nThe weird part is, when I try executing those commands in MySQL CLI, it works perfectly:\n\n```\nmysql> show tables;\nEmpty set (0.00 sec)\n\nmysql> CREATE TABLE IF NOT EXISTS `groups` (`id` INTEGER NOT NULL auto_increment , `groupname` VARCHAR(255), `groupkey` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `username` VARCHAR(255) UNIQUE, `password` VARCHAR(255), `salt` VARCHAR(255), `token` VARCHAR(255), `group_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`)) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `messages` (`id` INTEGER NOT NULL auto_increment , `message` VARCHAR(255), `group_id` INTEGER, `user_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`), FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) ENGINE=InnoDB;\nQuery OK, 0 rows affected (0.00 sec)\n\nQuery OK, 0 rows affected (0.00 sec)\n\nQuery OK, 0 rows affected (0.01 sec)\n```\n\nHere is how I am defining the tables:\n\n```\nvar dbconfig = {};\ndbconfig.database = process.env.database || 'crew';\ndbconfig.username = process.env.username || 'root';\ndbconfig.password = process.env.password || '';\ndbconfig.hostname = process.env.hostname || 'localhost';\n\nvar sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, {\n host: dbconfig.hostname\n});\n\nvar User = sequelize.define('users', {\n username: {\n type: Sequelize.STRING, \n unique: true\n },\n password: Sequelize.STRING,\n salt: Sequelize.STRING,\n token: Sequelize.STRING,\n group_id: {\n type: Sequelize.INTEGER,\n references: 'groups',\n referencesKey: 'id'\n }\n});\n\nvar Message = sequelize.define('message', {\n message: Sequelize.STRING,\n group_id: {\n type: Sequelize.INTEGER,\n references: 'groups',\n referencesKey: 'id'\n },\n user_id: {\n type: Sequelize.INTEGER,\n references: 'users',\n referencesKey: 'id'\n }\n});\n\nvar Group = sequelize.define('groups', {\n groupname: Sequelize.STRING,\n groupkey: Sequelize.STRING\n});\n\nGroup.sync({force: true});\nUser.sync({force: true});\nMessage.sync({force: true});\n```\n\n========================================\n\nTop Answer:\n```\nconst sequelize = new Sequelize(database, user, password, {\n host,\n port,\n dialect: \"postgres\",\n logging: false,\n sync: true, //create the table if it not exists\n});\n```\n\n========================================\n\nCode:\n```text\nExecuting (default): CREATE TABLE IF NOT EXISTS `groups` (`id` INTEGER NOT NULL auto_increment , `groupname` VARCHAR(255), `groupkey` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `username` VARCHAR(255) UNIQUE, `password` VARCHAR(255), `salt` VARCHAR(255), `token` VARCHAR(255), `group_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`)) ENGINE=InnoDB;\nExecuting (default): CREATE TABLE IF NOT EXISTS `messages` (`id` INTEGER NOT NULL auto_increment , `message` VARCHAR(255), `group_id` INTEGER, `user_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`), FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) ENGINE=InnoDB;\nPossibly unhandled SequelizeDatabaseError: ER_CANT_CREATE_TABLE: Can't create table 'crew.users' (errno: 150)\n    at module.exports.Query.formatError (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:160:16)\n    at Query._callback (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:38:23)\n    at Query.Sequence.end (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n    at Query.ErrorPacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Query.js:94:8)\n    at Protocol._parsePacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:271:23)\n    at Parser.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Parser.js:77:12)\n    at Protocol.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n    at Socket.<anonymous> (/home/ubuntu/public/server/node_modules/mysql/lib/Connection.js:82:28)\n    at Socket.EventEmitter.emit (events.js:95:17)\n    at Socket.<anonymous> (_stream_readable.js:746:14)\nPossibly unhandled SequelizeDatabaseError: ER_CANT_CREATE_TABLE: Can't create table 'crew.messages' (errno: 150)\n    at module.exports.Query.formatError (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:160:16)\n    at Query._callback (/home/ubuntu/public/server/node_modules/sequelize/lib/dialects/mysql/query.js:38:23)\n    at Query.Sequence.end (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n    at Query.ErrorPacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/sequences/Query.js:94:8)\n    at Protocol._parsePacket (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:271:23)\n    at Parser.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Parser.js:77:12)\n    at Protocol.write (/home/ubuntu/public/server/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n    at Socket.<anonymous> (/home/ubuntu/public/server/node_modules/mysql/lib/Connection.js:82:28)\n    at Socket.EventEmitter.emit (events.js:95:17)\n    at Socket.<anonymous> (_stream_readable.js:746:14)\n```\n\n```text\nmysql> show tables;\nEmpty set (0.00 sec)\n\nmysql> CREATE TABLE IF NOT EXISTS `groups` (`id` INTEGER NOT NULL auto_increment , `groupname` VARCHAR(255), `groupkey` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `username` VARCHAR(255) UNIQUE, `password` VARCHAR(255), `salt` VARCHAR(255), `token` VARCHAR(255), `group_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`)) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `messages` (`id` INTEGER NOT NULL auto_increment , `message` VARCHAR(255), `group_id` INTEGER, `user_id` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`), FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) ENGINE=InnoDB;\nQuery OK, 0 rows affected (0.00 sec)\n\nQuery OK, 0 rows affected (0.00 sec)\n\nQuery OK, 0 rows affected (0.01 sec)\n```\n\n```text\nvar dbconfig = {};\ndbconfig.database = process.env.database || 'crew';\ndbconfig.username = process.env.username || 'root';\ndbconfig.password = process.env.password || '';\ndbconfig.hostname = process.env.hostname || 'localhost';\n\nvar sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password, {\n  host: dbconfig.hostname\n});\n\nvar User = sequelize.define('users', {\n  username: {\n    type: Sequelize.STRING, \n    unique: true\n  },\n  password: Sequelize.STRING,\n  salt: Sequelize.STRING,\n  token: Sequelize.STRING,\n  group_id: {\n    type: Sequelize.INTEGER,\n    references: 'groups',\n    referencesKey: 'id'\n  }\n});\n\nvar Message = sequelize.define('message', {\n  message: Sequelize.STRING,\n  group_id: {\n    type: Sequelize.INTEGER,\n    references: 'groups',\n    referencesKey: 'id'\n  },\n  user_id: {\n    type: Sequelize.INTEGER,\n    references: 'users',\n    referencesKey: 'id'\n  }\n});\n\nvar Group = sequelize.define('groups', {\n  groupname: Sequelize.STRING,\n  groupkey: Sequelize.STRING\n});\n\n\nGroup.sync({force: true});\nUser.sync({force: true});\nMessage.sync({force: true});\n```\n\n```text\nGroup.sync({force: true});\nUser.sync({force: true});\nMessage.sync({force: true});\n```\n\n```text\nsequelize.sync();\n```\n\n```text\nsync()\n```\n\n```text\nsequelize\n```\n\n```text\nconst sequelize = new Sequelize(database, user, password, {\n  host,\n  port,\n  dialect: \"postgres\",\n  logging: false,\n  sync: true, //create the table if it not exists\n});\n```\n\n========================================\n\nComments:\n- I was really confused before seeing this. Now it suddenly makes complete sense. Really helped me out as I'm just learning how to use Sequelize.\n- I have separate files for each model so where should i call `sequelize.sync();`\n- @Argon call the sequelize.sync() in your entry file ( app.js )\n- did not work for me","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":243,"estimatedTokens":2969}}400{"id":"stack-45286429","source":"stackoverflow","questionId":45286429,"title":"Custom query on sequelize seeder","tags":["postgresql","sequelize.js","postgresql-9.4","sequelize-cli"],"text":"Title: Custom query on sequelize seeder\nTags: postgresql, sequelize.js, postgresql-9.4, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nAny one know how to custom select query on sequelize seeder\n\nI have tried two ways, but no one work\n\n**First attempt**\n\n```\nup: function(queryInterface, Sequelize) {\n return queryInterface.sequelize.query(\n 'SELECT * FROM \"Users\" WHERE username = \"admin\"',\n { type: queryInterface.sequelize.QueryTypes.SELECT }\n ).then(function(users) {});\n },\n```\n\nand then got error\n\n```\nSequelizeDatabaseError: column \"admin\" does not exist\n```\n\nI do not understand why admin is column here ???\n\n**Second attempt**\n\n```\nreturn queryInterface.sequelize.query('SELECT * FROM \"Users\" WHERE username = :admin', {\n replacement: {\n admin: 'admin'\n },\n type: queryInterface.sequelize.QueryTypes.SELECT\n}).then(function(users) {\n});\n```\n\nBelow error occurred\n\n`SequelizeDatabaseError: syntax error at or near \":\"`\n\n**Third attempt** \n\n```\nreturn queryInterface.sequelize.query(\n 'SELECT * FROM \"Users\" WHERE username = ' admin '',\n {type: queryInterface.sequelize.QueryTypes.SELECT})\n.then(function(users) { })\n```\n\nError:\n\n```\nSyntaxError: missing ) after argument list\n```\n\n**UPDATED**\n\n**Fourth attempt**\n\n```\nreturn queryInterface.sequelize.query(\n 'SELECT * FROM Users WHERE username = \"admin\"',\n { type: queryInterface.sequelize.QueryTypes.SELECT }\n ).then(function(users) {});\n```\n\nAnother error appear:\n\n```\nSequelizeDatabaseError: relation \"Users\" does not exist\n```\n\n**`queryInterface.sequelize.query('SELECT * FROM \"Users\"')` works without any error. I think the problem here is WHERE querying**\n\nIt's driving me to crazy :)\n\nThank you for any help in advance!\n\n========================================\n\nTop Answer:\nIn relation to @Toan Tran answer, to update your migration:\n\n```\nawait queryInterface.sequelize.query(`\n UPDATE public.\"Table\"\n SET \"column_to_be_updated\" = :column::uuid\n WHERE public.\"Permissions\".\"column_to_check\" = :column_to_check\n `, {\n replacements: { column_to_be_updated: r.uuid, column_to_check: r.name },\n type: Sequelize.QueryTypes.UPDATE\n });\n```\n\nThis is for Sequelize, using PostgresSQL. Note that this update also is for the `column` with type `Sequelize.UUID`.\n\n========================================\n\nCode:\n```text\nup: function(queryInterface, Sequelize) {\n    return queryInterface.sequelize.query(\n      'SELECT * FROM \"Users\" WHERE username = \"admin\"',\n      { type: queryInterface.sequelize.QueryTypes.SELECT }\n    ).then(function(users) {});\n    },\n```\n\n```text\nSequelizeDatabaseError: column \"admin\" does not exist\n```\n\n```text\nreturn queryInterface.sequelize.query('SELECT * FROM \"Users\" WHERE username = :admin', {\n  replacement: {\n    admin: 'admin'\n  },\n  type: queryInterface.sequelize.QueryTypes.SELECT\n}).then(function(users) {\n});\n```\n\n```text\nreturn queryInterface.sequelize.query(\n  'SELECT * FROM \"Users\" WHERE username = ' admin '',\n  {type: queryInterface.sequelize.QueryTypes.SELECT})\n.then(function(users) { })\n```\n\n```text\nSyntaxError: missing ) after argument list\n```\n\n```text\nreturn queryInterface.sequelize.query(\n      'SELECT * FROM Users WHERE username = \"admin\"',\n      { type: queryInterface.sequelize.QueryTypes.SELECT }\n    ).then(function(users) {});\n```\n\n```text\nSequelizeDatabaseError: relation \"Users\" does not exist\n```\n\n```text\nSequelizeDatabaseError: syntax error at or near \":\"\n```\n\n```text\nqueryInterface.sequelize.query('SELECT * FROM \"Users\"')\n```\n\n```text\nreturn queryInterface.sequelize.query(\n  'SELECT * FROM \"Users\" WHERE username = ? ', {\n    replacements: ['admin'],\n    type: queryInterface.sequelize.QueryTypes.SELECT\n  }).then(users => {\n```\n\n```text\nawait queryInterface.sequelize.query(`\n      UPDATE public.\"Table\"\n      SET \"column_to_be_updated\" = :column::uuid\n      WHERE public.\"Permissions\".\"column_to_check\" = :column_to_check\n    `, {\n        replacements: { column_to_be_updated: r.uuid, column_to_check: r.name },\n        type: Sequelize.QueryTypes.UPDATE\n      });\n```\n\n```text\ncolumn\n```\n\n```text\nSequelize.UUID\n```\n\n========================================\n\nComments:\n- In the first attempt, you should remove the quote around users\n- It does not work. See my updated Shivam :)\n- Don't use double quotes in a query unless you want to create/use an identifier. Your query should be written: `\"SELECT * FROM Users WHERE username = 'admin'\"`\n- @JorgeCampos Sorry. but an error as same as third attempt.\n- @ToanTran Regarding your fourth attempt. Have you tried putting `Users` in quotes in the SQL statement?\n- Yes, I have tried it but `SequelizeDatabaseError: column \"admin\" does not exist`. Anyway, I have founded the solution when I read docs carefully. Let's me update the answer :)\n- sequelize.org/docs/v6/core-concepts/raw-queries/#replacement&zwnj;&#8203;s updated link","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":193,"estimatedTokens":1201}}401{"id":"stack-56330631","source":"stackoverflow","questionId":56330631,"title":"How to define default schema for sequelize migrations when using postgres and umzug?","tags":["postgresql","sequelize.js","umzug"],"text":"Title: How to define default schema for sequelize migrations when using postgres and umzug?\nTags: postgresql, sequelize.js, umzug\nSource: Stack Overflow\n\nQuestion:\nI am trying to always run migrations with sequelize and umzug to a specific postgresql database schema. Lets call it `custom` schema. By default all queries go to `public` schema.\n**Is there any way to define the default schema to run all migrations to in sequelize or umzug?**\n\n- http://docs.sequelizejs.com/\n\n- https://github.com/sequelize/umzug\n\n### Background:\n\nWith the following code I am able to define the schema for a single query in a migration:\n\n```\n// schema defined according to https://sequelize.readthedocs.io/en/latest/docs/migrations/\nmodule.exports = {\n up: async (queryInterface, Sequelize) => {\n return Sequelize.transaction(async transaction => {\n await queryInterface.renameTable({ tableName: 'oldtablename', schema: \"custom\"}, 'newtablename', { transaction })\n })\n },\n\n down: async () => {\n }\n}\n```\n\nAnd it reports that it is a success and uses the correct schema:\n\n```\nMigration {\n path:\n 'path/to/migrations/migration_test.js',\n file: 'migration_test.js',\n options:\n { storage: 'sequelize',\n storageOptions: [Object],\n logging: [Function: bound consoleCall],\n upName: 'up',\n downName: 'down',\n migrations: [Object],\n schema: 'custom' } } ]\n```\n\nHowever what I require is to be able to define the default schema that all queries in all migrations always run to instead of defining the schema I need in every single query I want to run.\n\nI tried searching, reading the documentation of the libraries and copy pasting `schema: 'custom'` everywhere, but nothing else worked so far except the above example.\n\nI am using the following code to run the migrations:\n\n```\nconst sequelizeConn = new Sequelize(ENV_DB_URL, {\n schema: 'custom',\n logging: false\n})\n\n const migrator = new Umzug({\n storage: 'sequelize',\n storageOptions: {\n sequelize: sequelizeConn,\n tableName: 'migrations',\n schema: 'custom'\n },\n logging: console.log,\n migrations: {\n params: [\n sequelizeConn.getQueryInterface(),\n sequelizeConn\n ],\n path: `${process.cwd()}/src/database/migrations`,\n pattern: /\\.js$/\n }\n })\n migrator.up()\n```\n\nMy umzug is `2.2.0` and sequelize is `5.3.0`.\nThe `migrations` table is correctly created to the `custom` schema, but migrations still run in `public` schema.\n\nI get the following error when running migrations that do not specify the schema in the query itself. From the error we can see that the schema is undefined:\n\n```\n{ SequelizeDatabaseError: relation \"oldtablename\" does not exist\n at Query.formatError (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:354:16)\n at query.catch.err (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:71:18)\n at tryCatcher (/usr/src/app/node_modules/bluebird/js/release/util.js:16:23)\n at Promise._settlePromiseFromHandler (/usr/src/app/node_modules/bluebird/js/release/promise.js:512:31)\n at Promise._settlePromise (/usr/src/app/node_modules/bluebird/js/release/promise.js:569:18)\n at Promise._settlePromise0 (/usr/src/app/node_modules/bluebird/js/release/promise.js:614:10)\n at Promise._settlePromises (/usr/src/app/node_modules/bluebird/js/release/promise.js:690:18)\n at _drainQueueStep (/usr/src/app/node_modules/bluebird/js/release/async.js:138:12)\n at _drainQueue (/usr/src/app/node_modules/bluebird/js/release/async.js:131:9)\n at Async._drainQueues (/usr/src/app/node_modules/bluebird/js/release/async.js:147:5)\n at Immediate.Async.drainQueues [as _onImmediate] (/usr/src/app/node_modules/bluebird/js/release/async.js:17:14)\n at runCallback (timers.js:705:18)\n at tryOnImmediate (timers.js:676:5)\n at processImmediate (timers.js:658:5)\n at process.topLevelDomainCallback (domain.js:120:23)\nname: 'SequelizeDatabaseError',\nparent:\n { error: relation \"oldtablename\" does not exist\n at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)\n at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)\n at Socket. (/usr/src/app/node_modules/pg/lib/connection.js:119:22)\n at Socket.emit (events.js:189:13)\n at Socket.EventEmitter.emit (domain.js:441:20)\n at addChunk (_stream_readable.js:284:12)\n at readableAddChunk (_stream_readable.js:265:11)\n at Socket.Readable.push (_stream_readable.js:220:10)\n at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\n name: 'error',\n length: 118,\n severity: 'ERROR',\n code: '42P01',\n detail: undefined,\n hint: undefined,\n position: undefined,\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'namespace.c',\n line: '420',\n routine: 'RangeVarGetRelidExtended',\n sql:\n 'ALTER TABLE \"oldtablename\" RENAME TO \"newtablename\";' },\noriginal:\n { error: relation \"oldtablename\" does not exist\n at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)\n at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)\n at Socket. (/usr/src/app/node_modules/pg/lib/connection.js:119:22)\n at Socket.emit (events.js:189:13)\n at Socket.EventEmitter.emit (domain.js:441:20)\n at addChunk (_stream_readable.js:284:12)\n at readableAddChunk (_stream_readable.js:265:11)\n at Socket.Readable.push (_stream_readable.js:220:10)\n at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\n name: 'error',\n length: 118,\n severity: 'ERROR',\n code: '42P01',\n detail: undefined,\n hint: undefined,\n position: undefined,\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'namespace.c',\n line: '420',\n routine: 'RangeVarGetRelidExtended',\n sql:\n 'ALTER TABLE \"oldtablename\" RENAME TO \"newtablename\";' },\nsql:\n 'ALTER TABLE \"oldtablename\" RENAME TO \"newtablename\";' }\n```\n\n========================================\n\nCode:\n```text\n// schema defined according to https://sequelize.readthedocs.io/en/latest/docs/migrations/\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    return Sequelize.transaction(async transaction => {\n      await queryInterface.renameTable({ tableName: 'oldtablename', schema: \"custom\"}, 'newtablename', { transaction })\n    })\n  },\n\n  down: async () => {\n  }\n}\n```\n\n```text\nMigration {\n  path:\n   'path/to/migrations/migration_test.js',\n  file: 'migration_test.js',\n  options:\n   { storage: 'sequelize',\n     storageOptions: [Object],\n     logging: [Function: bound consoleCall],\n     upName: 'up',\n     downName: 'down',\n     migrations: [Object],\n     schema: 'custom' } } ]\n```\n\n```text\nconst sequelizeConn = new Sequelize(ENV_DB_URL, {\n  schema: 'custom',\n  logging: false\n})\n\n    const migrator = new Umzug({\n      storage: 'sequelize',\n      storageOptions: {\n        sequelize: sequelizeConn,\n        tableName: 'migrations',\n        schema: 'custom'\n      },\n      logging: console.log,\n      migrations: {\n        params: [\n          sequelizeConn.getQueryInterface(),\n          sequelizeConn\n        ],\n        path: `${process.cwd()}/src/database/migrations`,\n        pattern: /\\.js$/\n      }\n    })\n    migrator.up()\n```\n\n```text\n{ SequelizeDatabaseError: relation \"oldtablename\" does not exist\n  at Query.formatError (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:354:16)\n  at query.catch.err (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:71:18)\n  at tryCatcher (/usr/src/app/node_modules/bluebird/js/release/util.js:16:23)\n  at Promise._settlePromiseFromHandler (/usr/src/app/node_modules/bluebird/js/release/promise.js:512:31)\n  at Promise._settlePromise (/usr/src/app/node_modules/bluebird/js/release/promise.js:569:18)\n  at Promise._settlePromise0 (/usr/src/app/node_modules/bluebird/js/release/promise.js:614:10)\n  at Promise._settlePromises (/usr/src/app/node_modules/bluebird/js/release/promise.js:690:18)\n  at _drainQueueStep (/usr/src/app/node_modules/bluebird/js/release/async.js:138:12)\n  at _drainQueue (/usr/src/app/node_modules/bluebird/js/release/async.js:131:9)\n  at Async._drainQueues (/usr/src/app/node_modules/bluebird/js/release/async.js:147:5)\n  at Immediate.Async.drainQueues [as _onImmediate] (/usr/src/app/node_modules/bluebird/js/release/async.js:17:14)\n  at runCallback (timers.js:705:18)\n  at tryOnImmediate (timers.js:676:5)\n  at processImmediate (timers.js:658:5)\n  at process.topLevelDomainCallback (domain.js:120:23)\nname: 'SequelizeDatabaseError',\nparent:\n { error: relation \"oldtablename\" does not exist\n     at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)\n     at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)\n     at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:119:22)\n     at Socket.emit (events.js:189:13)\n     at Socket.EventEmitter.emit (domain.js:441:20)\n     at addChunk (_stream_readable.js:284:12)\n     at readableAddChunk (_stream_readable.js:265:11)\n     at Socket.Readable.push (_stream_readable.js:220:10)\n     at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\n   name: 'error',\n   length: 118,\n   severity: 'ERROR',\n   code: '42P01',\n   detail: undefined,\n   hint: undefined,\n   position: undefined,\n   internalPosition: undefined,\n   internalQuery: undefined,\n   where: undefined,\n   schema: undefined,\n   table: undefined,\n   column: undefined,\n   dataType: undefined,\n   constraint: undefined,\n   file: 'namespace.c',\n   line: '420',\n   routine: 'RangeVarGetRelidExtended',\n   sql:\n    'ALTER TABLE \"oldtablename\" RENAME TO \"newtablename\";' },\noriginal:\n { error: relation \"oldtablename\" does not exist\n     at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)\n     at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)\n     at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:119:22)\n     at Socket.emit (events.js:189:13)\n     at Socket.EventEmitter.emit (domain.js:441:20)\n     at addChunk (_stream_readable.js:284:12)\n     at readableAddChunk (_stream_readable.js:265:11)\n     at Socket.Readable.push (_stream_readable.js:220:10)\n     at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\n   name: 'error',\n   length: 118,\n   severity: 'ERROR',\n   code: '42P01',\n   detail: undefined,\n   hint: undefined,\n   position: undefined,\n   internalPosition: undefined,\n   internalQuery: undefined,\n   where: undefined,\n   schema: undefined,\n   table: undefined,\n   column: undefined,\n   dataType: undefined,\n   constraint: undefined,\n   file: 'namespace.c',\n   line: '420',\n   routine: 'RangeVarGetRelidExtended',\n   sql:\n    'ALTER TABLE \"oldtablename\" RENAME TO \"newtablename\";' },\nsql:\n 'ALTER TABLE \"oldtablename\" RENAME TO \"newtablename\";' }\n```\n\n```text\ncustom\n```\n\n```text\npublic\n```\n\n```text\nschema: 'custom'\n```\n\n```text\n2.2.0\n```\n\n```text\n5.3.0\n```\n\n```text\nmigrations\n```\n\n```text\ncustom\n```\n\n```text\npublic\n```\n\n```text\nconst sequelizeConn = new Sequelize(ENV_DB_URL, {\n  schema: 'custom',\n  logging: false,\n  searchPath: 'custom',\n  dialectOptions: {\n    prependSearchPath: true\n}\n})\n```\n\n========================================\n\nComments:\n- It seems that using `prependSearchPath: true` causes `Model.update` to fail with `Cannot insert multiple commands into prepared statement`. Here is the related issue: github.com/sequelize/sequelize/issues/10875\n- Is this still in production???\n- Works with sequelize version `6.21.3`\n- Works with sequelize version `6.37.7`","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":360,"estimatedTokens":2894}}402{"id":"stack-20882230","source":"stackoverflow","questionId":20882230,"title":"Prevent sequelize to drop database in node.js app","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Prevent sequelize to drop database in node.js app\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nFirst of all, I am using node.js with sequelize ORM and Postgres SQL.\n\nI have 2 simple questions:\n\nEvery time I rerun my node application sequelize is dropping and creating all tables in database. How to prevent it from doing that (I don't want my records in database to be deleted)? I have tried to set my NODE_ENV to test but it didn't help.\n\nHow does sequelize migration knows where it stopped (which migration have executed and which not). \nWhen I was using database migration in Grails framework, for example, it automatically created a table in the database where it kept all migration timestamps that executed before and when I rerun my application it looks at that table and knows which migrations are already done and which are not. \nI don't see any table when using node/sequelize, so how it works? :)\n\nThanks,\nIvan\n\n========================================\n\nCode:\n```text\nsequelize.sync({ force: true })\n```\n\n```text\nsequelize_meta\n```\n\n========================================\n\nComments:\n- Can you include some code? I'm using sequelize with postgresql and haven't had that problem.\n- I copied they express example on sequelize.js web page and only put postgre database instead of mysql (like they did in example) github.com/sequelize/sequelize-expressjs-example (link of their example)\n- I figured out. They put sync: { force: true } in some part of code in app.js and that override my sync (false) that I defined when connecting to database...now second question is all that bothers me :)","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":35,"estimatedTokens":409}}403{"id":"stack-49225930","source":"stackoverflow","questionId":49225930,"title":"Sequelize Multiple counts for one table","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize Multiple counts for one table\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nFrom one column in my table I want to get the sum count for the value types in these columns. As an example, one column are:\n\n```\n|paymentGateway |\n---------------\n| Paystack |\n| Flutterwave |\n| NIBSS |\n| PAGA |\n| Interswitch |\n| Paystack |\n| Flutterwave |\n| NIBSS |\n| PAGA |\n| Interswitch |\n| Paystack |\n| Flutterwave |\n| NIBSS |\n| PAGA |\n| Interswitch |\n```\n\nI ran the query in `Progress DB Viewer` and it works fine. This is the query:\n\n```\nSELECT\n \"paymentGateway\",\n SUM(1) FILTER (WHERE \"paymentGateway\" = 'Paystack') AS paystack,\n SUM(1) FILTER (WHERE \"paymentGateway\" = 'NIBSS') AS nibss,\n SUM(1) FILTER (WHERE \"paymentGateway\" = 'Flutterwave') AS flutterwave,\n SUM(1) FILTER (WHERE \"paymentGateway\" = 'Interswitch') AS interswitch,\n SUM(1) FILTER (WHERE \"paymentGateway\" = 'PAGA') AS paga\nFROM\n \"Transactions\"\nGROUP BY\n \"paymentGateway\"\n```\n\nThe above query works fine and gives me this result here:\n\nhttps://i.sstatic.net/Yw05j.png\n\nNow, I'm trying to execute the same query in my code. So, I tried running the raw query first:\n\n```\ndb.sequelize.query('SELECT \"paymentGateway\", SUM(1) FILTER (WHERE \"paymentGateway\" = \"Paystack\") AS paystack, SUM(1) FILTER (WHERE \"paymentGateway\" = \"NIBSS\") AS nibss, SUM(1) FILTER (WHERE \"paymentGateway\" = \"Flutterwave\") AS flutterwave, SUM(1) FILTER (WHERE \"paymentGateway\" = \"Interswitch\") AS interswitch, SUM(1) FILTER (WHERE \"paymentGateway\" = \"PAGA\") AS paga FROM \"Transactions\" GROUP BY \"paymentGateway\"').then(data => {\n console.log('Query Result', data)\n return res.status(200).send({ message: 'Completed Successfully' })\n}).catch(err => {\n console.log('Query Error: ', err)\n return res.status(200).send({ message: 'Completed Successfully' })\n})\n```\n\nWhich was giving me `SequelizeDatabaseError: column \"Paystack\" does not exist`\n\nI decided to do some googling and read through `Sequelize` docs. That was where I got this:\n\n```\nTransaction.findAndCountAll({\n attributes: [\n [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'NIBSS'), 'nibss'],\n [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'Paystack'), 'paystack'],\n [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'Flutterwave'), 'flutterwave'],\n [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'Interswitch'), 'interswitch'],\n [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'PAGA'), 'paga']\n ],\n group: '\"paymentGateway\"'\n }).then(data => {\n // console.log('Query Result', data)\n console.log('Query Length', data.count)\n console.log('Query Datavalues', data.rows.map(obj => obj.dataValues))\n return res.status(200).send({ message: 'Completed Successfully' })\n }).catch(err => {\n console.log('Query Error: ', err)\n return res.status(200).send({ message: 'Completed Successfully' })\n })\n```\n\nThe query above, gave me a result that I understand, but wasn't that meaningful to interact with.\n\n```\nQuery Length [ { count: '3940' },\n { count: '3838' },\n { count: '4066' },\n { count: '4092' },\n { count: '4065' } ]\nQuery Datavalues [ { nibss: '3940',\n paystack: '3940',\n flutterwave: '3940',\n interswitch: '3940',\n paga: '3940' },\n { nibss: '3838',\n paystack: '3838',\n flutterwave: '3838',\n interswitch: '3838',\n paga: '3838' },\n { nibss: '4066',\n paystack: '4066',\n flutterwave: '4066',\n interswitch: '4066',\n paga: '4066' },\n { nibss: '4092',\n paystack: '4092',\n flutterwave: '4092',\n interswitch: '4092',\n paga: '4092' },\n { nibss: '4065',\n paystack: '4065',\n flutterwave: '4065',\n interswitch: '4065',\n paga: '4065' } ]\n```\n\nI would really appreciate it, if anyone can help me understand what I'm doing wrong. Thanks\n\n========================================\n\nCode:\n```text\n|paymentGateway |\n---------------\n|   Paystack    |\n|   Flutterwave |\n|   NIBSS       |\n|   PAGA        |\n|   Interswitch |\n|   Paystack    |\n|   Flutterwave |\n|   NIBSS       |\n|   PAGA        |\n|   Interswitch |\n|   Paystack    |\n|   Flutterwave |\n|   NIBSS       |\n|   PAGA        |\n|   Interswitch |\n```\n\n```text\nSELECT\n  \"paymentGateway\",\n  SUM(1) FILTER (WHERE \"paymentGateway\" = 'Paystack') AS paystack,\n  SUM(1) FILTER (WHERE \"paymentGateway\" = 'NIBSS') AS nibss,\n  SUM(1) FILTER (WHERE \"paymentGateway\" = 'Flutterwave') AS flutterwave,\n  SUM(1) FILTER (WHERE \"paymentGateway\" = 'Interswitch') AS interswitch,\n  SUM(1) FILTER (WHERE \"paymentGateway\" = 'PAGA') AS paga\nFROM\n  \"Transactions\"\nGROUP BY\n  \"paymentGateway\"\n```\n\n```text\ndb.sequelize.query('SELECT  \"paymentGateway\",   SUM(1) FILTER (WHERE \"paymentGateway\" = \"Paystack\") AS paystack,    SUM(1) FILTER (WHERE \"paymentGateway\" = \"NIBSS\") AS nibss,  SUM(1) FILTER (WHERE \"paymentGateway\" = \"Flutterwave\") AS flutterwave,  SUM(1) FILTER (WHERE \"paymentGateway\" = \"Interswitch\") AS interswitch,  SUM(1) FILTER (WHERE \"paymentGateway\" = \"PAGA\") AS paga FROM    \"Transactions\" GROUP BY     \"paymentGateway\"').then(data => {\n  console.log('Query Result', data)\n  return res.status(200).send({ message: 'Completed Successfully' })\n}).catch(err => {\n  console.log('Query Error: ', err)\n  return res.status(200).send({ message: 'Completed Successfully' })\n})\n```\n\n```text\nTransaction.findAndCountAll({\n    attributes: [\n      [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'NIBSS'), 'nibss'],\n      [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'Paystack'), 'paystack'],\n      [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'Flutterwave'), 'flutterwave'],\n      [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'Interswitch'), 'interswitch'],\n      [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway') === 'PAGA'), 'paga']\n    ],\n    group: '\"paymentGateway\"'\n  }).then(data => {\n    // console.log('Query Result', data)\n    console.log('Query Length', data.count)\n    console.log('Query Datavalues', data.rows.map(obj => obj.dataValues))\n    return res.status(200).send({ message: 'Completed Successfully' })\n  }).catch(err => {\n    console.log('Query Error: ', err)\n    return res.status(200).send({ message: 'Completed Successfully' })\n  })\n```\n\n```text\nQuery Length [ { count: '3940' },\n  { count: '3838' },\n  { count: '4066' },\n  { count: '4092' },\n  { count: '4065' } ]\nQuery Datavalues [ { nibss: '3940',\n    paystack: '3940',\n    flutterwave: '3940',\n    interswitch: '3940',\n    paga: '3940' },\n  { nibss: '3838',\n    paystack: '3838',\n    flutterwave: '3838',\n    interswitch: '3838',\n    paga: '3838' },\n  { nibss: '4066',\n    paystack: '4066',\n    flutterwave: '4066',\n    interswitch: '4066',\n    paga: '4066' },\n  { nibss: '4092',\n    paystack: '4092',\n    flutterwave: '4092',\n    interswitch: '4092',\n    paga: '4092' },\n  { nibss: '4065',\n    paystack: '4065',\n    flutterwave: '4065',\n    interswitch: '4065',\n    paga: '4065' } ]\n```\n\n```text\nProgress DB Viewer\n```\n\n```text\nSequelizeDatabaseError: column \"Paystack\" does not exist\n```\n\n```text\nSequelize\n```\n\n```text\nTransaction.findAll({\n  attributes: [\n    'paymentGateway',\n    [db.sequelize.fn('COUNT', db.sequelize.col('paymentGateway')), 'count']\n  ],\n  group: 'paymentGateway',\n  raw: true,\n  logging: true\n}).then(data => {\n  console.log('Query Result', data)\n  return res.status(200).send({ message: 'Completed Successfully' })\n})\n```\n\n```text\nQuery Result \n[ \n  { paymentGateway: 'Paystack', count: '3966' },\n  { paymentGateway: 'PAGA', count: '3954' },\n  { paymentGateway: 'Flutterwave', count: '3995' },\n  { paymentGateway: 'Interswitch', count: '4118' },\n  { paymentGateway: 'NIBSS', count: '3968' } \n]\n```\n\n========================================\n\nComments:\n- Great, but how can I get the total count?\n- @IhtishamKhan if you want the total count of all the rows in the Transaction Model then try this: `Transaction.count();` Refer","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":265,"estimatedTokens":1959}}404{"id":"stack-24309893","source":"stackoverflow","questionId":24309893,"title":"Foreign keys with Sequelize are not created","tags":["node.js","sequelize.js"],"text":"Title: Foreign keys with Sequelize are not created\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI use Sequelize for my Server (with mysql dialect); in Sequelize's documentation is written that this:\n\n```\nvar Task = this.sequelize.define('Task', { title: Sequelize.STRING })\n, User = this.sequelize.define('User', { username: Sequelize.STRING })\n\nUser.hasMany(Task)\nTask.belongsTo(User)\n```\n\ncreates automatically foreign key references with constraints;\nbut for me this doesn't happen:\n\n```\nvar Shop = sequelize.define('Shop', {\n name: Sequelize.STRING,\n address: Sequelize.STRING,\n phone: Sequelize.STRING,\n email: Sequelize.STRING,\n percentage: Sequelize.FLOAT,\n text: Sequelize.TEXT,\n categories: Sequelize.TEXT,\n start: Sequelize.DATE,\n end: Sequelize.DATE\n});\n\nvar Offer = sequelize.define('Offer', {\n name: Sequelize.STRING,\n deadline: Sequelize.DATE,\n optionDuration: Sequelize.INTEGER\n});\n\nShop.hasMany(Offer);\nOffer.belongsTo(Shop);\n```\n\nThis creates the two tables shops and offers, both of them with only \"id\" primary key\n\nI also have some n:m associations like:\n\n```\nGroup.hasMany(Accesslevel);\nAccesslevel.hasMany(Group);\n```\n\nbut also in this case, in the join table that Sequelize creates, there are no foreign key;\nso if I delete for ex. an acccesslevel, than the corresponding records in the join table accesslevelsgroups are not deleted.\n\nDoes anybody know if I'm doing something wrong or missing something?\nWhat I need is to create all the foreign keys for the associations and the possibility to specify the behaviour 'onDelete' and 'onUpdate' (cascade)\n\n-- UPDATE\nI've created a route for executing sync:\n\n```\nmyServer.get('/sync', function (req, res) {\n sequelize.sync({force: true}).success(function() {\n console.log('sync done');\n res.send(200, 'sync done');\n }).error(function(error) {\n console.log('there was a problem');\n res.send(200, 'there was a problem');\n });\n});\n```\n\nSo then in the browser I type 127.0.0.1:port/sync to create the db structure\n\n========================================\n\nTop Answer:\nYou should give foreign keys like that, it is not related to sync.\n\n```\nOffer.associate = function (models) {\n models. Offer.belongsTo(models. Offer, {\n onDelete: \"CASCADE\",\n foreignKey: 'shopId',\n targetKey: 'id'\n });\n};\n```\n\n========================================\n\nCode:\n```text\nvar Task = this.sequelize.define('Task', { title: Sequelize.STRING })\n, User = this.sequelize.define('User', { username: Sequelize.STRING })\n\nUser.hasMany(Task)\nTask.belongsTo(User)\n```\n\n```text\nvar Shop = sequelize.define('Shop', {\n    name: Sequelize.STRING,\n    address: Sequelize.STRING,\n    phone: Sequelize.STRING,\n    email: Sequelize.STRING,\n    percentage: Sequelize.FLOAT,\n    text: Sequelize.TEXT,\n    categories: Sequelize.TEXT,\n    start: Sequelize.DATE,\n    end: Sequelize.DATE\n});\n\nvar Offer = sequelize.define('Offer', {\n    name: Sequelize.STRING,\n    deadline: Sequelize.DATE,\n    optionDuration: Sequelize.INTEGER\n});\n\nShop.hasMany(Offer);\nOffer.belongsTo(Shop);\n```\n\n```text\nGroup.hasMany(Accesslevel);\nAccesslevel.hasMany(Group);\n```\n\n```text\nmyServer.get('/sync', function (req, res) {\n    sequelize.sync({force: true}).success(function() {\n        console.log('sync done');\n        res.send(200, 'sync done');\n    }).error(function(error) {\n        console.log('there was a problem');\n        res.send(200, 'there was a problem');\n    });\n});\n```\n\n```text\n.sync({ force: true })\n```\n\n```text\nOffer.associate = function (models) {\n    models. Offer.belongsTo(models. Offer, {\n        onDelete: \"CASCADE\",\n        foreignKey: 'shopId',\n        targetKey: 'id'\n    });\n};\n```\n\n========================================\n\nComments:\n- sequelize doesnt support foreign keys.You need to create them yourself.\n- @mpm That is blatelnly incorrect, sequelizejs.com/docs/1.7.8/associations#foreign-keys\n- @WillemD'haeseleer well that was the case when I used it,glad it is now supported.\n- Yes, I was just linking the same doc page... But do you know why in my case the foreign keys are not created automatically as the doc says?\n- did you add the relation after creating the table ? did you call `sync`, you need `force: true` to update tables ( will drop the table ). Are you using InnoDB ?\n- You mean after the sync()?\n- I think problem is with versions. See my answer here stackoverflow.com/questions/45394449/&hellip;\n- I define all associations right after the models, as wrote in the first post; then I've created a route /sync in the server that executed the sync({force: true}), and another route /dummy-data that inserts automatically some records; so I run /sync and then /dummy-data... I use InnoDB...\n- @CerealKiller What version are you using, seems like this might be an issue in `< 1.7.6` github.com/sequelize/sequelize/pull/1818\n- I'm using the latest Sequelize 2.0.0-dev9 - Thank you for this, I'll the issue too\n- Ok in the end the problem is due to an issue regarding n:m association; in other cases (1:n) works","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":167,"estimatedTokens":1244}}405{"id":"stack-27929488","source":"stackoverflow","questionId":27929488,"title":"Sequelize includes reference table row in result when using include","tags":["sequelize.js"],"text":"Title: Sequelize includes reference table row in result when using include\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have `Track` and `Artist` models defined, with association as follows:\n\n```\ndb.Track.belongsToMany(db.Artist, {through: 'TracksArtists'});\ndb.Artist.belongsToMany(db.Track, {through: 'TracksArtists'});\n```\n\nI want to search for Tracks and include Artist.name in the results:\n\n```\ndb.Track\n findAll({ \n attributes: ['title','year'], \n where: { title: { like: '%' + string + '%' } },\n include: [{model: db.Artist, attributes: ['name']}]\n })\n .complete(function(err, tracks){ /*...*/});\n```\n\nHowever, Sequelize also includes a row from TracksArtists reference table in the results:\n\n```\n[{\"title\":\"Nightcall\",\"year\":2010,\"Artists\":[{\"name\":\"Kavinsky\",\"TracksArtists\":{\"createdAt\":\"2015-01-13T18:41:31.850Z\",\"updatedAt\":\"2015-01-13T18:41:31.850Z\",\"ArtistId\":1,\"TrackId\":1}}]}]\n```\n\nwhich is unnecessary. How can I make it not to return info from TracksArtists, instead of having to remove it on my own?\n\n========================================\n\nTop Answer:\nI have `Faq` and `Artist` models defined, with association as follows:\n\n```\nFaq.belongsToMany(Version, { through: FaqVersion, foreignKey: 'faqId' });\nVersion.belongsToMany(Faq, { through: FaqVersion, foreignKey: 'verId' });\n```\n\nI encountered the same problem with the author, but i add: \n\n```\nmodels.Version.findAll({\n raw: true,\n attributes: ['id', 'version'],\n include: [{\n model: models.Faq,\n attributes: [],\n through: { attributes: [] },\n where: {\n id: faq.id\n }\n }]\n})\n```\n\nHowever, Sequelize also includes a row from FaqVersion reference table in the results:\n\n```\nFaqs.FaqVersion.createdAt:\"2017-01-10T05:22:06.000Z\",\nFaqs.FaqVersion.faqId:2,\nFaqs.FaqVersion.id:3,\nFaqs.FaqVersion.updatedAt:\"2017-01-10T05:22:06.000Z\",\nFaqs.FaqVersion.verId:2,\nid:2,\nversion:\"5.2.6\"\n```\n\nI think `through` does not work\n\n========================================\n\nCode:\n```text\ndb.Track.belongsToMany(db.Artist, {through: 'TracksArtists'});\ndb.Artist.belongsToMany(db.Track, {through: 'TracksArtists'});\n```\n\n```text\ndb.Track\n    findAll({ \n        attributes: ['title','year'], \n        where: { title: { like: '%' + string + '%' } },\n        include: [{model: db.Artist, attributes: ['name']}]\n    })\n    .complete(function(err, tracks){ /*...*/});\n```\n\n```text\n[{\"title\":\"Nightcall\",\"year\":2010,\"Artists\":[{\"name\":\"Kavinsky\",\"TracksArtists\":{\"createdAt\":\"2015-01-13T18:41:31.850Z\",\"updatedAt\":\"2015-01-13T18:41:31.850Z\",\"ArtistId\":1,\"TrackId\":1}}]}]\n```\n\n```text\nTrack\n```\n\n```text\nArtist\n```\n\n```text\ninclude: [{model: db.Artist, attributes: ['name'], through: {attributes: []}}]\n```\n\n```text\nFaq.belongsToMany(Version, { through: FaqVersion, foreignKey: 'faqId' });\nVersion.belongsToMany(Faq, { through: FaqVersion, foreignKey: 'verId' });\n```\n\n```text\nmodels.Version.findAll({\n  raw: true,\n  attributes: ['id', 'version'],\n  include: [{\n    model: models.Faq,\n    attributes: [],\n    through: { attributes: [] },\n    where: {\n    id: faq.id\n    }\n }]\n})\n```\n\n```text\nFaqs.FaqVersion.createdAt:\"2017-01-10T05:22:06.000Z\",\nFaqs.FaqVersion.faqId:2,\nFaqs.FaqVersion.id:3,\nFaqs.FaqVersion.updatedAt:\"2017-01-10T05:22:06.000Z\",\nFaqs.FaqVersion.verId:2,\nid:2,\nversion:\"5.2.6\"\n```\n\n```text\nFaq\n```\n\n```text\nArtist\n```\n\n```text\nthrough\n```\n\n```text\ninclude: [\n            {\n                model: ModelName,\n                through: {attributes: []}\n            }\n    ]\n```\n\n========================================\n\nComments:\n- Try `include: [{model: db.Artist, attributes: ['name'], through: {attributes: []}}]`\n- In my scenario, one of the attributes in the `through` table is a foreign key for another model. I tried including the name in the `attributes: []` but get the index, not the model. Any thoughts on how to include a model in the `through` table?","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":163,"estimatedTokens":958}}406{"id":"stack-34929041","source":"stackoverflow","questionId":34929041,"title":"Data Type of field from sequelize model","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Data Type of field from sequelize model\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to get the datatype of a given field from a sequelize model. Assume we have a module defined like so\n\n```\nUser = sequelize.define 'User',\n{\n id:\n type: DataTypes.UUID\n primaryKey: true\n defaultValue: DataTypes.UUIDV4\n firstName:\n type: DataTypes.STRING\n allowNull: false\n middleName:\n type: DataTypes.STRING\n allowNull: true\n defaultValue: null\n lastName:\n type: DataTypes.STRING\n allowNull: true\n defaultValue: null\n}\n```\n\nI need to say figure out the data type for firstName. Is there any method within model which can achieve this?\n\n========================================\n\nCode:\n```text\nUser = sequelize.define 'User',\n{\n id:\n   type: DataTypes.UUID\n   primaryKey: true\n   defaultValue: DataTypes.UUIDV4\n firstName:\n   type: DataTypes.STRING\n   allowNull: false\n middleName:\n   type: DataTypes.STRING\n   allowNull: true\n   defaultValue: null\n lastName:\n   type: DataTypes.STRING\n   allowNull: true\n   defaultValue: null\n}\n```\n\n```text\nUser.tableAttributes.firstName.type.constructor.key\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":57,"estimatedTokens":284}}407{"id":"stack-50950358","source":"stackoverflow","questionId":50950358,"title":"Sequelize Migration: relation does not exist","tags":["postgresql","sequelize.js","sequelize-cli"],"text":"Title: Sequelize Migration: relation does not exist\nTags: postgresql, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI'm working through an Author hasMany Books example and am attempting to run a sequelize-cli migration, but am getting the following issue when I run the following migration:\n\n```\nERROR: relation \"authors\" does not exist\n```\n\nThis is the first migration to create an author:\n\n```\n'use strict';\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Authors', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n firstName: {\n type: Sequelize.STRING\n },\n lastName: {\n type: Sequelize.STRING\n },\n dateOfBirth: {\n type: Sequelize.DATEONLY\n },\n dateOfDeath: {\n type: Sequelize.DATEONLY\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Authors');\n }\n};\n```\n\nThe second migration to create a book:\n\n```\n'use strict';\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Books', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n title: {\n type: Sequelize.STRING\n },\n summary: {\n type: Sequelize.STRING\n },\n isbn: {\n type: Sequelize.STRING\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Books');\n }\n};\n```\n\nThe migration to create the relationship between Author and Book:\n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.addColumn(\n 'Books', // name of source model\n 'AuthorId',\n {\n type: Sequelize.INTEGER,\n references: {\n model: 'authors',\n key: 'id'\n },\n onUpdate: 'CASCADE',\n onDelete: 'SET NULL'\n }\n )\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.removeColumn(\n 'Books',\n 'AuthorId'\n )\n }\n};\n```\n\nAnd these are my models:\n\nauthor.js:\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n var Author = sequelize.define('Author', {\n firstName: { type: DataTypes.STRING, allowNull: false, len: [2, 100] },\n lastName: { type: DataTypes.STRING, allowNull: false },\n dateOfBirth: { type: DataTypes.DATEONLY },\n dateOfDeath: { type: DataTypes.DATEONLY }\n }, {});\n Author.associate = function (models) {\n // associations can be defined here\n Author.hasMany(models.Book);\n };\n return Author;\n};\n```\n\nbook.js:\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n var Book = sequelize.define('Book', {\n title: { type: DataTypes.STRING, allowNull: false, len: [2, 100], trim: true },\n summary: { type: DataTypes.STRING, allowNull: false },\n isbn: { type: DataTypes.STRING, allowNull: false }\n }, {});\n\n Book.associate = function (models) {\n // associations can be defined here\n Book.belongsTo(models.Author);\n };\n return Book;\n};\n```\n\nI've tried all sorts of things to no avail. My guess would be that it is attempting to alter the table in an asynchronous manner, but the previous migrations ran and finished:\n\nhttps://i.sstatic.net/Nqlv9.png\n\nI'm using the following:\n\n```\n\"pg\": \"^7.4.3\"\n\"sequelize\": \"^4.37.10\"\n\"sequelize-cli\": \"^4.0.0\"\n \"express\": \"~4.16.0\"\n```\n\nI'm very new to sequelize and any help would be appreciated!\n\n========================================\n\nTop Answer:\nI had a similar issue and I resolved it following the \"Model Synchronization\" explained here.\n\nIn the documentation explains that with MODELNAME.sync() sequelize checks if the table exists and if not exists this function create the table. This function has some options:\n\n`User.sync()` - This creates the table if it doesn't exist (and does nothing if it already exists)\n`User.sync({ force: true })` - This creates the table, dropping it first if it already existed\n`User.sync({ alter: true })` - This checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model.\n\nYou can use `sequelize.sync()` to automatically synchronize all models.\n\n========================================\n\nCode:\n```text\nERROR: relation \"authors\" does not exist\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('Authors', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      firstName: {\n        type: Sequelize.STRING\n      },\n      lastName: {\n        type: Sequelize.STRING\n      },\n      dateOfBirth: {\n        type: Sequelize.DATEONLY\n      },\n      dateOfDeath: {\n        type: Sequelize.DATEONLY\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable('Authors');\n  }\n};\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('Books', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      title: {\n        type: Sequelize.STRING\n      },\n      summary: {\n        type: Sequelize.STRING\n      },\n      isbn: {\n        type: Sequelize.STRING\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable('Books');\n  }\n};\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.addColumn(\n      'Books', // name of source model\n      'AuthorId',\n      {\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'authors',\n          key: 'id'\n        },\n        onUpdate: 'CASCADE',\n        onDelete: 'SET NULL'\n      }\n    )\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.removeColumn(\n      'Books',\n      'AuthorId'\n    )\n  }\n};\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n  var Author = sequelize.define('Author', {\n    firstName: { type: DataTypes.STRING, allowNull: false, len: [2, 100] },\n    lastName: { type: DataTypes.STRING, allowNull: false },\n    dateOfBirth: { type: DataTypes.DATEONLY },\n    dateOfDeath: { type: DataTypes.DATEONLY }\n  }, {});\n  Author.associate = function (models) {\n    // associations can be defined here\n    Author.hasMany(models.Book);\n  };\n  return Author;\n};\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n  var Book = sequelize.define('Book', {\n    title: { type: DataTypes.STRING, allowNull: false, len: [2, 100], trim: true },\n    summary: { type: DataTypes.STRING, allowNull: false },\n    isbn: { type: DataTypes.STRING, allowNull: false }\n  }, {});\n\n  Book.associate = function (models) {\n    // associations can be defined here\n    Book.belongsTo(models.Author);\n  };\n  return Book;\n};\n```\n\n```text\n\"pg\": \"^7.4.3\"\n\"sequelize\": \"^4.37.10\"\n\"sequelize-cli\": \"^4.0.0\"\n \"express\": \"~4.16.0\"\n```\n\n```text\nreferences: {\n  model: 'Authors',\n  key: 'id'\n},\n```\n\n```text\nAuthors\n```\n\n```text\na\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nUser.sync()\n```\n\n```text\nUser.sync({ force: true })\n```\n\n```text\nUser.sync({ alter: true })\n```\n\n```text\nsequelize.sync()\n```\n\n========================================\n\nComments:\n- As per the accepted answer, the issue was caused by a typo , `'author'`, instead of `'Author'`. I'm voting to close the question as **Cause by a typo**.","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":380,"estimatedTokens":1971}}408{"id":"stack-30632779","source":"stackoverflow","questionId":30632779,"title":"Tedious or Sequelize uses the wrong syntax for `findOne()`","tags":["node.js","sql-server-2008","sequelize.js","tedious"],"text":"Title: Tedious or Sequelize uses the wrong syntax for `findOne()`\nTags: node.js, sql-server-2008, sequelize.js, tedious\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize with Tedious to access SQL Server 2008.\n\nWhen I do a `sequelizeModel.findOne()` I get this exception - \n\n Unhandled rejection SequelizeDatabaseError: Invalid usage of the option NEXT in the FETCH statement.\n\nI know SQL Server 2008 doesn't support `OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY` and that is why the exception is thrown. \n\nBut I have also explicitly set the `tdsVersion` in the tedious options to `7_3_B`. \n\nAs described here -\n\nhttp://pekim.github.io/tedious/api-connection.html \n\nI've tried all the tds versions and the query syntax that is generated always contains the `FETCH/NEXT` syntax. \n\nAm I missing something? \n\nShouldn't the syntax be specific to the tds version? \n\nI've also verified that the `tdsVersion` option is being passed successfully to the tedious connection library from sequelize. \n\nExample of query syntax generated - \n\n```\nSELECT \n [id], [FIRST_NAME], [LAST_NAME] \nFROM \n [USERs] AS [USERS] \nORDER BY \n [id] \n OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;\n```\n\n========================================\n\nTop Answer:\nChecking code `node_modules/sequelize/lib/dialects/mssql/query-generator.js`\nsaw that part\n\n```\nconst dbVersion = this.sequelize.options.databaseVersion;\nconst isSQLServer2008 = semver.valid(dbVersion) && semver.lt(dbVersion, '11.0.0');\n```\n\nSo I just added my connection configuration:\n\n```\nproduction: {\n dialect: 'mssql',\n databaseVersion: '10.50.6000',\n host: process.env.DB_HOST,\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n database: process.env.DB_NAME,\n dialectOptions: {\n options: {\n useUTC: false,\n dateFirst: 1,\n enableArithAbort: true,\n encrypt: false,\n },\n },\n },\n```\n\n========================================\n\nCode:\n```text\nSELECT \n    [id], [FIRST_NAME], [LAST_NAME]  \nFROM  \n    [USERs] AS [USERS] \nORDER BY \n    [id]  \n    OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;\n```\n\n```text\nsequelizeModel.findOne()\n```\n\n```text\nOFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY\n```\n\n```text\ntdsVersion\n```\n\n```text\n7_3_B\n```\n\n```text\nFETCH/NEXT\n```\n\n```text\ntdsVersion\n```\n\n```js\nThing.findAll({\n  where: {id: id}\n}).then( function(things) {\n  if (things.length == 0) {\n    // handle error\n  }\n  doSomething(things[0])\n}).catch( function(err) {\n  // handle error\n});\n```\n\n```text\nfindById\n```\n\n```text\nfindAll\n```\n\n```text\nwhere\n```\n\n```text\nfragment += ` OFFSET ${this.escape(offset)} ROWS`;\n```\n\n```text\nfragment += ` ORDER BY ${this.quoteTable(options.tableAs || model.name)}.${this.quoteIdentifier(model.primaryKeyField)}`;\n```\n\n```text\nfragment += ` ORDER BY ${this.quoteTable(options.tableAs || model.name)}.${this.quoteIdentifier(model.primaryKeyField)}`;\n\n    fragment += ` OFFSET ${this.escape(offset)} ROWS`;\n```\n\n```text\nSequelizeDatabaseError: Invalid usage of the option NEXT in the FETCH statement.\n    at Query.formatError (C:\\xampp\\htdocs\\Benoit\\node_modules\\sequelize\\lib\\dialects\\mssql\\query.js:315:12)\n    at Request.connection.lib.Request [as userCallback] (C:\\xampp\\htdocs\\Benoit\\node_modules\\sequelize\\lib\\dialects\\mssql\\query.js:107:25)\n    at Request._this.callback (C:\\xampp\\htdocs\\Benoit\\node_modules\\tedious\\lib\\request.js:60:27)\n    at Connection.endOfMessageMarkerReceived (C:\\xampp\\htdocs\\Benoit\\node_modules\\tedious\\lib\\connection.js:1922:20)\n    at Connection.dispatchEvent (C:\\xampp\\htdocs\\Benoit\\node_modules\\tedious\\lib\\connection.js:1004:38)\n    at Parser.<anonymous> (C:\\xampp\\htdocs\\Benoit\\node_modules\\tedious\\lib\\connection.js:805:18)\n    at emitOne (events.js:116:13)\n    at Parser.emit (events.js:211:7)\n    at Parser.<anonymous> (C:\\xampp\\htdocs\\Benoit\\node_modules\\tedious\\lib\\token\\token-stream-parser.js:54:15)\n    at emitOne (events.js:116:13)\n    at Parser.emit (events.js:211:7)\n    at addChunk (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_readable.js:291:12)\n    at readableAddChunk (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_readable.js:278:11)\n    at Parser.Readable.push (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_readable.js:245:10)\n    at Parser.Transform.push (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_transform.js:148:32)\n    at Parser.afterTransform (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_transform.js:91:10)\n    at Parser._transform (C:\\xampp\\htdocs\\Benoit\\node_modules\\tedious\\lib\\token\\stream-parser.js:69:9)\n    at Parser.Transform._read (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_transform.js:184:10)\n    at Parser.Transform._write (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_transform.js:172:83)\n    at doWrite (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_writable.js:428:64)\n    at writeOrBuffer (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_writable.js:417:5)\n    at Parser.Writable.write (C:\\xampp\\htdocs\\Benoit\\node_modules\\readable-stream\\lib\\_stream_writable.js:334:11)\n```\n\n```text\n// Handle SQL Server 2008 with TOP instead of LIMIT\nif (semver.valid(this.sequelize.options.databaseVersion) && semver.lt(this.sequelize.options.databaseVersion, '11.0.0')) {\n```\n\n```text\nMicrosoft SQL Server 2014 - 12.0.2000.8 (X64) \n    Feb 20 2014 20:04:26 \n    Copyright (c) Microsoft Corporation\n    Express Edition (64-bit) on Windows NT 6.3 <X64> (Build 17134: ) (Hypervisor)\n```\n\n```text\nselect @@version\n```\n\n```text\nsequelize.authenticate()\n```\n\n```text\nconst dbVersion = this.sequelize.options.databaseVersion;\nconst isSQLServer2008 = semver.valid(dbVersion) && semver.lt(dbVersion, '11.0.0');\n```\n\n```text\nproduction: {\n        dialect: 'mssql',\n        databaseVersion: '10.50.6000',\n        host: process.env.DB_HOST,\n        username: process.env.DB_USER,\n        password: process.env.DB_PASS,\n        database: process.env.DB_NAME,\n        dialectOptions: {\n            options: {\n                useUTC: false,\n                dateFirst: 1,\n                enableArithAbort: true,\n                encrypt: false,\n            },\n        },\n    },\n```\n\n```text\nnode_modules/sequelize/lib/dialects/mssql/query-generator.js\n```\n\n========================================\n\nComments:\n- did you ever figure this one out? I'm in the exact same boat as you.\n- @Marc - I didn't find a resolution, so I ended up using `findAll()` then taking the first result.\n- This happens to me with `findAll({ limit: 10, offset: 10 })` cause it uses Fetch and Next to paginate, but I get the error since using msssql 2008\n- I'm getting this same error in SQL 2012, and the issue is solved with using findAll. so what's up? why isn't it working in 2012?\n- judging by the query the problem in sql server 2012 is that OFFSET should always be used with ORDER BY and for some reason sequelize is not making the query with an ORDER BY clause (or tedious)\n- Dude... You just saved me! I couldn't find this 'databaseVersion' property anywhere on documentation. This just did the thing!","metadata":{"transformedAt":"2026-08-18T18:33:34.372Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":230,"estimatedTokens":1760}}409{"id":"stack-29892752","source":"stackoverflow","questionId":29892752,"title":"Sequelize join query with condition","tags":["join","sequelize.js"],"text":"Title: Sequelize join query with condition\nTags: join, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using the following syntax to select some records:\n\n```\nmodels.account.findAll({\n attributes: ['password'],\n include: [{\n model: models.user,\n as : 'user'\n }],\n where: {\n 'password': password,\n 'user.email': email\n }\n}).then(function(res){\n console.log(res);\n});\n```\n\nIt's generating the following query:\n\n```\nSELECT * \nFROM `accounts` AS `account` \n LEFT OUTER JOIN `users` AS `user` \n ON `account`.`user_id` = `user`.`id` \nWHERE `account`.`password` = 'PASSWORD' \n AND `account`.`user.email` = 'xyz@gmail.com';\n ^^^^^^^^^^^^^^^^^^^^^^\n```\n\nSo it's giving me an error: `Unknown column 'account.user.email' in 'where clause'`. I want only `user.email` in the WHERE clause. The expected query should be:\n\n```\nSELECT * \nFROM `accounts` AS `account` \n LEFT OUTER JOIN `users` AS `user` \n ON `account`.`user_id` = `user`.`id` \nWHERE `account`.`password` = 'PASSWORD' \n AND `user`.`email` = 'xyz@gmail.com';\n```\n\nWhat am i doing wrong?\n\n========================================\n\nCode:\n```js\nmodels.account.findAll({\n  attributes: ['password'],\n  include: [{\n    model: models.user,\n    as : 'user'\n  }],\n  where: {\n    'password': password,\n    'user.email': email\n  }\n}).then(function(res){\n  console.log(res);\n});\n```\n\n```sql\nSELECT * \nFROM   `accounts` AS `account` \n    LEFT OUTER JOIN `users` AS `user` \n        ON `account`.`user_id` = `user`.`id` \nWHERE  `account`.`password` = 'PASSWORD' \n    AND `account`.`user.email` = 'xyz@gmail.com';\n        ^^^^^^^^^^^^^^^^^^^^^^\n```\n\n```sql\nSELECT * \nFROM   `accounts` AS `account` \n    LEFT OUTER JOIN `users` AS `user` \n        ON `account`.`user_id` = `user`.`id` \nWHERE  `account`.`password` = 'PASSWORD' \n    AND `user`.`email` = 'xyz@gmail.com';\n```\n\n```text\nUnknown column 'account.user.email' in 'where clause'\n```\n\n```text\nuser.email\n```\n\n```js\nmodels.account.findAll({\n      attributes: ['password'],\n      include: [{\n        model: models.user,\n        where: {\n          email: email\n        }\n      }],\n      where: {\n        password: password\n      }\n    }).then(function(res){\n      console.log(res);\n    });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":110,"estimatedTokens":545}}410{"id":"stack-63586468","source":"stackoverflow","questionId":63586468,"title":"Sequelize Run Script File","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize Run Script File\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a project which is using Sequelize to manage a set of MySQL databases. Thus far I've been able to run simple queries to create new databases, insert parameters into a table, and select data... however, I have a very long .sql file (+1,700 lines) which when executed will set up a database with a specific schema (ie. tables, views, etc.). The problem is that I can not figure out how to execute a script like this using sequelize. I know the script works on a new database because I can execute the sql file from MySQL Workbench, however I do not know how to execute the script from javascript file using sequelize. I've searched forums but can't seem to find any resources either. Can this be done?\n\n========================================\n\nCode:\n```text\nvar sql_string = fs.readFileSync('path to file', 'utf8');\nconst sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,\n  dialectOptions: {\n    multipleStatements: true\n  }\n});\n\nsequelize.query(sql_string);\n```\n\n```text\nSequelize\n```\n\n```text\nsequelize.query(sql_string)\n```\n\n```text\nfs\n```\n\n```text\nfs-extra\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- it is a bit tricky see stackoverflow.com/a/49741899/5193536\n- Hmm. thanks for the link. I'll look into this (although it seems like it *should* be easier than that :)\n- i don't think so, all link in SO point that way, this was on&#246;ly the \"easiest\" with out much changes to do, but the qiestion is young\n- Thanks. This looks promising. However, this answer assumes that the database already exists. I'm creating a new database and then want to run the schema script on the newly created database. Do I need to create two instances of 'sequelize' where one creates the new database and then other executes the sql_string sequence you provided? Or is there a cleaner way to do that?\n- actually it will run your entire sql file, `database` is just an initial config of Sequelize which you can be skipped and you are able to build every thing from scratch and just make a connection to your Database instance, I will update the answer in few seconds BTW. hope it help you","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":51,"estimatedTokens":580}}411{"id":"stack-28921074","source":"stackoverflow","questionId":28921074,"title":"Node.js / Sequelize.js / Express.js - How to insert into many-to-many association? (sync/async?)","tags":["javascript","node.js","promise","sequelize.js"],"text":"Title: Node.js / Sequelize.js / Express.js - How to insert into many-to-many association? (sync/async?)\nTags: javascript, node.js, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two models (Individual, Email) and am trying to insert into the created 'Individual_Email' table using the Sequelize commands. While Sequelize is creating the desired table, it returns the following error when trying to add/get/set to/from that table: \"Object [object Promise] has no method 'addEmail'\". What am I missing? \n\nThe Sequelize documentation says if the models are User and Project, \"This will add methods getUsers, setUsers, addUsers to Project, and getProjects, setProjects and addProject to User.\"\n\nThis leads me to believe (looking at promises) that I'm likely misunderstanding how to use the asynchronous features of Node. I've tried both a synchronous and async version of insertion, both returning the same message above.\n\nSequelize Documentation: http://docs.sequelizejs.com/en/latest/docs/associations/\n\nCode:\n\n**routes/index.js**\n\n```\nvar express = require('express');\nvar router = express.Router();\nvar models = require('../models');\n\n/* GET home page. */\nrouter.get('/', function(req, res, next) {\n 'use strict';\n\n var tIndividual, tEmail;\n tIndividual = models.Individual.create({\n name: \"Test\"\n });\n tEmail = models.Email.create({\n address: \"test@gmail.com\"\n });\n console.log(tEmail);\n\n res.render('index', { title: 'Express' });\n});\n\nmodule.exports = router;\n```\n\nOR\n\n```\n/* GET home page. */\nrouter.get('/', function(req, res, next) {\n 'use strict';\n\n var tIndividual, tEmail; \n tIndividual = models.Individual.create({\n name: \"Test\"\n }).then(function(){\n tEmail = models.Email.create({\n address: \"test@gmail.com\"\n }).then(function(){\n tIndividual.addEmail(tEmail).then(function(){\n console.log(\"Success\");\n });\n })\n });\n\n res.render('index', { title: 'Express' });\n});\n\nmodule.exports = router;\n```\n\n**models/index.js**\n\n```\ndb.Individual.hasMany(db.Email, {\n as: 'Email',\n through: 'Individual_Email'\n});\ndb.Email.hasMany(db.Individual, {\n as: 'Individual',\n through: 'Individual_Email'\n});\n```\n\nHow can I add to the table 'Individual_Email' in the best way? I'm assuming I need to do it synchronously to wait for the update, but I'm open to any suggestions. Thanks!\n\n========================================\n\nTop Answer:\nYou can mitigate the \"**Pyramid of Doom**\" using promises of the best way:\n\n```\nvar createdIndividual;\nmodels.Individual.create({\n name: \"Test\"\n}).then(function(createdIn) { // note the argument\n createdIndividual = createdIn;\n return models.Email.create({\n address: \"test@gmail.com\"\n });\n}).then(function(createdEmail) { // note the argument\n return createdIndividual.addEmail(createdEmail);\n}).then(function(addedEmail) { // note th-- well you get the idea :)\n console.log(\"Success\");\n});\n```\n\n========================================\n\nCode:\n```text\nvar express = require('express');\nvar router = express.Router();\nvar models  = require('../models');\n\n/* GET home page. */\nrouter.get('/', function(req, res, next) {\n    'use strict';\n\n    var tIndividual, tEmail;\n    tIndividual = models.Individual.create({\n        name: \"Test\"\n    });\n    tEmail = models.Email.create({\n        address: \"test@gmail.com\"\n    });\n    console.log(tEmail);\n\n    res.render('index', { title: 'Express' });\n});\n\nmodule.exports = router;\n```\n\n```text\n/* GET home page. */\nrouter.get('/', function(req, res, next) {\n    'use strict';\n\n    var tIndividual, tEmail;    \n    tIndividual = models.Individual.create({\n        name: \"Test\"\n    }).then(function(){\n        tEmail = models.Email.create({\n            address: \"test@gmail.com\"\n        }).then(function(){\n            tIndividual.addEmail(tEmail).then(function(){\n                console.log(\"Success\");\n            });\n        })\n    });\n\n    res.render('index', { title: 'Express' });\n});\n\nmodule.exports = router;\n```\n\n```text\ndb.Individual.hasMany(db.Email, {\n    as: 'Email',\n    through: 'Individual_Email'\n});\ndb.Email.hasMany(db.Individual, {\n    as: 'Individual',\n    through: 'Individual_Email'\n});\n```\n\n```text\nmodels.Individual.create({\n  name: \"Test\"\n}).then(function(createdIndividual) { // note the argument\n  models.Email.create({\n    address: \"test@gmail.com\"\n  }).then(function(createdEmail) { // note the argument\n    createdIndividual.addEmail(createdEmail)\n      .then(function(addedEmail) { // note th-- well you get the idea :)\n        console.log(\"Success\");\n      });\n  })\n});\n```\n\n```text\n.save()\n```\n\n```text\n.create()\n```\n\n```text\n.then()\n```\n\n```text\nthen\n```\n\n```text\nreturn\n```\n\n```text\nvar tIndividual, tEmail;\ntIndividual = models.Individual.build({\n    name: \"Test\"\n});\ntEmail = models.Email.build({\n    address: 'test@gmail.com'\n});\ntIndividual.save()\n    .success(function(){\n        tEmail.save()\n        .success(function(){\n            tIndividual.addEmail(tEmail);\n        });\n});\n```\n\n```text\nvar createdIndividual;\nmodels.Individual.create({\n  name: \"Test\"\n}).then(function(createdIn) { // note the argument\n  createdIndividual = createdIn;\n  return models.Email.create({\n    address: \"test@gmail.com\"\n  });\n}).then(function(createdEmail) { // note the argument\n  return createdIndividual.addEmail(createdEmail);\n}).then(function(addedEmail) { // note th-- well you get the idea :)\n  console.log(\"Success\");\n});\n```\n\n========================================\n\nComments:\n- It's probably bette to chain the thens instead of nesting them for no reasons.\n- Hey Can you addEmail while you are building the object, before it is actually created? The reason I ask is I wan to make sure if whole insert succeeds go for it otherwise don't even bother creating anything in any table\n- Can you add the while the Email is being created in one shot? instead of first create then addEmail?\n- @MortezaShahriariNia Note that this association is N:M, since both the Individual and the Email have been configured with `hasMany`. So there are three tables in the end (Emails, Individuals, and EmailIndividual). The above code will, in practice, generate three INSERT statements, and you can't get less than that because there are three tables to populate.\n- @MortezaShahriariNia That said, I once had a similar situation that I solved in this question: stackoverflow.com/questions/28751483/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":241,"estimatedTokens":1576}}412{"id":"stack-42046052","source":"stackoverflow","questionId":42046052,"title":"Sequelize include array of nested object - node.js","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize include array of nested object - node.js\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have relations:\n\n(Track) -- M:1 --> (TrackChannel) (UserChannel) \n\n- `Channel` model include object `Track` as `current_track_id` with relation one to one.\n\n- `Track` and `Channel` is related many to many through `TrackChannel`\n\n- `User` and `Channel` is related many to many through `UserChannel`\n\n/* Channel.js: */\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('channel', {\n id: {\n allowNull: false,\n primaryKey: true,\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV4,\n },\n current_counter: {\n type: DataTypes.INTEGER,\n allowNull: false,\n defaultValue: 0\n },\n track_counter: {\n type: DataTypes.INTEGER,\n allowNull: false,\n defaultValue: 0\n },\n track_id: {\n type: DataTypes.STRING,\n allowNull: true,\n references: {\n model: 'track',\n key: 'id'\n }\n },\n createdAt: {\n type: DataTypes.TIME,\n allowNull: true,\n defaultValue: sequelize.fn('now')\n },\n updatedAt: {\n type: DataTypes.TIME,\n allowNull: true,\n defaultValue: sequelize.fn('now')\n }\n }, {\n tableName: 'channel',\n classMethods:{\n associate:function(models){\n this.belongsToMany(models.user, { onDelete: \"CASCADE\", foreignKey: 'user_id', otherKey: 'channel_id', through: 'userChannel' })\n this.belongsToMany(models.track, { onDelete: \"CASCADE\", foreignKey: 'track_id', otherKey: 'channel_id', through: 'trackChannel' })\n this.belongsTo(models.track, {foreignKey: 'current_track_id' , foreignKeyConstraint: true})\n }\n }\n });\n};\n```\n\n### What you are doing?\n\nThat is my query for the channel. I use repository pattern:\n\n```\nreturn db.channel.findOne({\n raw:true,\n include: [\n { model: db.track, attributes: ['id', 'name','artist_name' ,'album_name'], where: {track_id, }, paranoid: true, required: false}\n ],\n where: {\n id: id\n }\n });\n```\n\n### What do you expect to happen?\n\nI want to get:\n\n```\n{\n \"id\": \"ce183d0a-e702-49a3-83b5-2912bbcf5283\",\n \"current_counter\": 0,\n \"track_counter\": 0,\n \"current_track_id\": {} // object or null,\n \"createdAt\": \"21:26:56.487217\",\n \"updatedAt\": \"21:26:56.487217\",\n \"tracks: [] // array or null\n}\n```\n\n### What is actually happening?\n\nI try to create query to get one channel where is included current track object and list of track. Now it looks like that:\n\n```\n{\n \"id\": \"ce183d0a-e702-49a3-83b5-2912bbcf5283\",\n \"current_counter\": 0,\n \"track_counter\": 0,\n \"track_id\": null,\n \"createdAt\": \"21:26:56.487217\",\n \"updatedAt\": \"21:26:56.487217\",\n \"tracks.id\": null,\n \"tracks.name\": null,\n \"tracks.artist_name\": null,\n \"tracks.album_name\": null,\n \"tracks.trackChannel.id\": null,\n \"tracks.trackChannel.channel_id\": null,\n \"tracks.trackChannel.createdAt\": null,\n \"tracks.trackChannel.updatedAt\": null,\n \"tracks.trackChannel.track_id\": null\n}\n```\n\nDialect: postgres \nDatabase version: 9.6\nSequelize version: 3.3.0\n\n========================================\n\nTop Answer:\nGuess it'll help someone so giving another option.\n\nYou can use `nest:true` along with `raw:true` property given by sequelize.\n\nresult:\n\nbefore:\n\n```\n{\n id: 1,\n createdBy: 1,\n 'Section.id': 1,\n 'Section.name': 'Breakfast',\n}\n```\n\nAfter:\n\n```\n{\n id: 1,\n createdBy: 1,\n Section: {\n id: 1,\n name: ''\n }\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('channel', {\n    id: {\n      allowNull: false,\n      primaryKey: true,\n      type: DataTypes.UUID,\n      defaultValue: DataTypes.UUIDV4,\n    },\n    current_counter: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      defaultValue: 0\n    },\n    track_counter: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      defaultValue: 0\n    },\n    track_id: {\n      type: DataTypes.STRING,\n      allowNull: true,\n      references: {\n        model: 'track',\n        key: 'id'\n      }\n    },\n    createdAt: {\n      type: DataTypes.TIME,\n      allowNull: true,\n      defaultValue: sequelize.fn('now')\n    },\n    updatedAt: {\n      type: DataTypes.TIME,\n      allowNull: true,\n      defaultValue: sequelize.fn('now')\n    }\n  }, {\n    tableName: 'channel',\n    classMethods:{\n      associate:function(models){\n        this.belongsToMany(models.user, { onDelete: \"CASCADE\", foreignKey: 'user_id', otherKey: 'channel_id', through: 'userChannel' })\n        this.belongsToMany(models.track, { onDelete: \"CASCADE\", foreignKey: 'track_id', otherKey: 'channel_id', through: 'trackChannel' })\n        this.belongsTo(models.track, {foreignKey: 'current_track_id' , foreignKeyConstraint: true})\n      }\n    }\n  });\n};\n```\n\n```text\nreturn db.channel.findOne({\n            raw:true,\n            include: [\n                { model: db.track, attributes: ['id', 'name','artist_name' ,'album_name'], where: {track_id, }, paranoid: true, required: false}\n            ],\n            where: {\n                id: id\n            }\n        });\n```\n\n```text\n{\n  \"id\": \"ce183d0a-e702-49a3-83b5-2912bbcf5283\",\n  \"current_counter\": 0,\n  \"track_counter\": 0,\n  \"current_track_id\": {} // object or null,\n  \"createdAt\": \"21:26:56.487217\",\n  \"updatedAt\": \"21:26:56.487217\",\n  \"tracks: [] // array or null\n}\n```\n\n```text\n{\n  \"id\": \"ce183d0a-e702-49a3-83b5-2912bbcf5283\",\n  \"current_counter\": 0,\n  \"track_counter\": 0,\n  \"track_id\": null,\n  \"createdAt\": \"21:26:56.487217\",\n  \"updatedAt\": \"21:26:56.487217\",\n  \"tracks.id\": null,\n  \"tracks.name\": null,\n  \"tracks.artist_name\": null,\n  \"tracks.album_name\": null,\n  \"tracks.trackChannel.id\": null,\n  \"tracks.trackChannel.channel_id\": null,\n  \"tracks.trackChannel.createdAt\": null,\n  \"tracks.trackChannel.updatedAt\": null,\n  \"tracks.trackChannel.track_id\": null\n}\n```\n\n```text\nChannel\n```\n\n```text\nTrack\n```\n\n```text\ncurrent_track_id\n```\n\n```text\nTrack\n```\n\n```text\nChannel\n```\n\n```text\nTrackChannel\n```\n\n```text\nUser\n```\n\n```text\nChannel\n```\n\n```text\nUserChannel\n```\n\n```text\nfindById: function(id) {\n        return db.channel.findOne({\n            logging: true,\n            include: [\n                { model: db.track, attributes: ['id', 'name','artist_name' ,'album_name'], as: 'track'},\n                { model: db.track, attributes: ['id', 'name','artist_name' ,'album_name'], as: 'tracks', paranoid: true, required: false}\n            ],\n            where: {\n                id: id\n            }\n        });\n    },\n```\n\n```text\n{\n        id: 1,\n        createdBy: 1,\n        'Section.id': 1,\n        'Section.name': 'Breakfast',\n}\n```\n\n```text\n{\n  id: 1,\n  createdBy: 1,\n  Section: {\n      id: 1,\n      name: ''\n      }\n}\n```\n\n```text\nnest:true\n```\n\n```text\nraw:true\n```\n\n========================================\n\nComments:\n- github.com/sequelize/sequelize/issues/4973 - that is solution to get `track` as array. But how to get related tracks\n- In case you get completely stuck with the `sequelize`, there is pg-promise, which perfectly supports the repository pattern, as shown in pg-promise-demo, which can happily coexist with your sequelize code ;)\n- Thx I will take a look. But it does help me clean my code :)\n- You need to set `nest: true` github.com/sequelize/sequelize/issues/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":343,"estimatedTokens":1770}}413{"id":"stack-58893809","source":"stackoverflow","questionId":58893809,"title":"How can i fix an async forEach push?","tags":["javascript","node.js","asynchronous","foreach","sequelize.js"],"text":"Title: How can i fix an async forEach push?\nTags: javascript, node.js, asynchronous, foreach, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen i call my own api developed using node.js, connection on postgres (Sequelize) database, it's return the JSON:\n\n```\n[\n {\n \"id\": 1,\n \"name\": \"Wallet Name\",\n \"wallet_type\": \"MN\",\n \"icon\": \"fa fa-bank\",\n \"color\": \"#000000\",\n \"credit_limit\": 3000,\n \"due_day\": 22\n }\n]\n```\n\nI just need, it return one more line (account_value) on each object, that's info is inside another javascript function, so it's should look as:\n\n```\n[\n {\n \"id\": 1,\n \"name\": \"Wallet Name\",\n \"wallet_type\": \"MN\",\n \"icon\": \"fa fa-bank\",\n \"color\": \"#000000\",\n \"credit_limit\": 3000,\n \"account_value\": 1200.55,\n \"due_day\": 22\n }\n]\n```\n\nMy current code is: \n\n```\nasync index(req, res) {\n const wallets = await Wallet.findAll({\n where: {},\n attributes: [\n 'id',\n 'name',\n 'wallet_type',\n 'icon',\n 'color',\n 'credit_limit',\n 'due_day',\n ],\n order: [['name', 'ASC']],\n });\n\n const finalObject = [];\n\n wallets.forEach(async wallet => {\n const currentItem = wallet.dataValues;\n const { id } = await currentItem;\n const { sum_credits } = await WalletsResume.sumCredits(id);\n const { sum_debits } = await WalletsResume.sumDebits(id);\n const sum_account_value = (sum_credits - sum_debits).toFixed(2);\n currentItem.account_value = sum_account_value;\n finalObject.push(currentItem);\n console.log(`pushed ${id}`);\n });\n\n console.log(`-------------------------`);\n console.log(finalObject);\n return res.json(finalObject);\n }\n```\n\nBut, when its return a empty array:\n\n```\n[]\n```\n\nDo you can help me please?\n\nI have no idea how to fix it (i can change all my code)\n\nThank you so much!\n\n========================================\n\nCode:\n```text\n[\n  {\n    \"id\": 1,\n    \"name\": \"Wallet Name\",\n    \"wallet_type\": \"MN\",\n    \"icon\": \"fa fa-bank\",\n    \"color\": \"#000000\",\n    \"credit_limit\": 3000,\n    \"due_day\": 22\n  }\n]\n```\n\n```text\n[\n  {\n    \"id\": 1,\n    \"name\": \"Wallet Name\",\n    \"wallet_type\": \"MN\",\n    \"icon\": \"fa fa-bank\",\n    \"color\": \"#000000\",\n    \"credit_limit\": 3000,\n    \"account_value\": 1200.55,\n    \"due_day\": 22\n  }\n]\n```\n\n```js\nasync index(req, res) {\n    const wallets = await Wallet.findAll({\n      where: {},\n      attributes: [\n        'id',\n        'name',\n        'wallet_type',\n        'icon',\n        'color',\n        'credit_limit',\n        'due_day',\n      ],\n      order: [['name', 'ASC']],\n    });\n\n    const finalObject = [];\n\n    wallets.forEach(async wallet => {\n      const currentItem = wallet.dataValues;\n      const { id } = await currentItem;\n      const { sum_credits } = await WalletsResume.sumCredits(id);\n      const { sum_debits } = await WalletsResume.sumDebits(id);\n      const sum_account_value = (sum_credits - sum_debits).toFixed(2);\n      currentItem.account_value = sum_account_value;\n      finalObject.push(currentItem);\n      console.log(`pushed ${id}`);\n    });\n\n    console.log(`-------------------------`);\n    console.log(finalObject);\n    return res.json(finalObject);\n  }\n```\n\n```text\n[]\n```\n\n```js\nasync index() {\n  // Fetch wallets here\n\n  for (const wallet of wallets) {\n    const currentItem = wallet.dataValues;\n    const { id } = await currentItem;\n    const { sum_credits } = await WalletsResume.sumCredits(id);\n    const { sum_debits } = await WalletsResume.sumDebits(id);\n    const sum_account_value = (sum_credits - sum_debits).toFixed(2);\n    currentItem.account_value = sum_account_value;\n    finalObject.push(currentItem);\n    console.log(`pushed ${id}`);\n  }\n\n  // Then continue normally\n}\n```\n\n```js\nasync index() {\n  // Fetch wallets here\n\n  for (const walletIndex in wallets) {\n    const currentItem = wallets[walletIndex].dataValues;\n    // rest of code as above\n  }\n\n}\n```\n\n```text\nfor..in\n```\n\n```text\nfor..of\n```\n\n========================================\n\nComments:\n- Sorry, i'm just learning node. I tryied for(wallet in wallets) but its broken my code (as i seen on developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/&hellip;) You can tell me please, how i do it?\n- My example uses for-of not for-in\n- Ohhh, thank you so much!!! I'll try! :D\n- See this for difference between for-in and for-of. One sets the index of the value to the const, and the other uses the actual value. stackoverflow.com/a/41910537/6086851\n- OMG! it's work! I'll need fix a eslint problem now, but, work very well, ty!!!! ``` iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.eslint(no-restricted-syntax) ```\n- With for-in you have to use const currentItem = wallets[wallet].dataValues;, because wallet in this case is the index\n- I am not sure about eslint warning part, personally, I would have disabled it for that line. Add this one line before the for-of loop. `&#47;&#47; eslint-disable-next-line no-restricted-syntax`\n- done! will be disabled - Really, thank you so much Abido, helped me a lot! I learned soo much here ;)\n- Glad to hear, you're very welcome.","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":209,"estimatedTokens":1258}}414{"id":"stack-67765749","source":"stackoverflow","questionId":67765749,"title":"How to run Sequelize migrations inside Docker","tags":["mysql","node.js","docker","docker-compose","sequelize.js"],"text":"Title: How to run Sequelize migrations inside Docker\nTags: mysql, node.js, docker, docker-compose, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to docerize my NodeJS API together with a MySQL image. Before the initial run, I want to run Sequelize migrations and seeds to have the tables up and ready to be served.\n\nHere's my `docker-compose.yaml`:\n\n```\nversion: '3.8'\nservices: \n mysqldb:\n image: mysql\n restart: unless-stopped\n environment:\n MYSQL_ROOT_USER: myuser\n MYSQL_ROOT_PASSWORD: mypassword\n MYSQL_DATABASE: mydb\n ports:\n - '3306:3306'\n networks:\n - app-connect\n volumes: \n - db-config:/etc/mysql\n - db-data:/var/lib/mysql\n - ./db/backup/files/:/data_backup/data\n app:\n build:\n context: .\n dockerfile: ./Dockerfile\n image: node-mysql-app\n depends_on:\n - mysqldb\n ports:\n - '3030:3030'\n networks:\n - app-connect\n stdin_open: true\n tty: true\nvolumes: \n db-config:\n db-data:\nnetworks:\n app-connect:\n driver: bridge\n```\n\nHere's my app's `Dockerfile`:\n\n```\nFROM node:lts-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCOPY . .\nEXPOSE 3030\nENV PORT 3030\nENV NODE_ENV docker\nRUN npm run db:migrate:up\nRUN npm run db:seeds:up\nCMD [ \"npm\", \"start\" ]\n```\n\nAnd here's my `default.db.json` that the Sequelize migration uses (shortened):\n\n```\n{\n \"development\": {\n \n },\n \"production\": {\n \n },\n \"docker\": {\n \"username\": \"myuser\",\n \"password\": \"mypassword\",\n \"database\": \"mydb\",\n \"host\": \"mysqldb\",\n \"port\": \"3306\",\n \"dialect\": \"mysql\"\n }\n}\n```\n\nUpon running `compose up` the DB installs well, the image deploys, but when it reaches the `RUN npm run db:migrate:up` (which translates into `npx sequelize-cli db:migrate`) I get the error:\n\n```\nnpx: installed 81 in 13.108s\n\nSequelize CLI [Node: 14.17.0, CLI: 6.2.0, ORM: 6.6.2]\n\nLoaded configuration file \"default.db.json\".\nUsing environment \"docker\".\n\nERROR: getaddrinfo EAI_AGAIN mysqldb\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\n```\n\nIf I change the `\"host\"` in the `default.db.json` to `\"127.0.0.1\"`, I get `ERROR: connect ECONNREFUSED 127.0.0.1:3306` in place of the `ERROR: getaddrinfo EAI_AGAIN mysqldb`.\n\nWhat am i doing wrong, and what host should I specify so the app can see the MySQL container? Should I remove the network? Should I change ports? (I tried combinations of both to no avail, so far).\n\n========================================\n\nTop Answer:\nThe following configuration worked for me, I am adding the .env, sequelize configuration along with mysql database and docker. And finally don't forget to run **docker-compose up --build** cheers 🎁 🎁 🎁\n\n**.env**\n\n```\nDB_NAME=\"testdb\"\nDB_USER=\"root\"\nDB_PASS=\"root\"\nDB_HOST=\"mysql\"\n```\n\n**.sequelizerc** now we can use *config.js* rather than *config.json* for sequelize\n\n```\nconst path = require('path');\n\nmodule.exports = {\n 'config': path.resolve('config', 'config.js')\n}\n```\n\n**config.js**\n\n```\nrequire(\"dotenv\").config();\n\nmodule.exports = {\n development: {\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n database: process.env.DB_NAME,\n host: process.env.DB_HOST,\n dialect: \"mysql\"\n },\n test: {\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n database: process.env.DB_NAME,\n host: process.env.DB_HOST,\n dialect: \"mysql\"\n },\n production: {\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n database: process.env.DB_NAME,\n host: process.env.DB_HOST,\n dialect: \"mysql\"\n }\n}\n```\n\n**database-connection with sequelize**\n\n```\nimport Sequelize from 'sequelize';\nimport dbConfig from './config/config';\n\nconst conf = dbConfig.development;\n\nconst sequelize = new Sequelize(\n conf.database,\n conf.username,\n conf.password,\n {\n host: conf.host,\n dialect: \"mysql\",\n operatorsAliases: 0,\n logging: 0\n }\n);\n\nsequelize.sync();\n\n(async () => {\n try {\n await sequelize.authenticate();\n console.log(\"Database connection setup successfully!\");\n } catch (error) {\n console.log(\"Unable to connect to the database\", error);\n }\n})();\n\nexport default sequelize;\nglobal.sequelize = sequelize;\n```\n\n**docker-compose.yaml**\n\n```\nversion: \"3.8\"\n\nnetworks:\n proxy:\n name: proxy\n\nservices:\n mysql:\n image: mysql\n networks:\n - proxy\n ports:\n - 3306:3306\n environment:\n - MYSQL_ROOT_PASSWORD=root\n - MYSQL_DATABASE=testdb\n healthcheck:\n test: \"mysql -uroot -p$$MYSQL_ROOT_PASSWORD -e 'SHOW databases'\"\n interval: 10s\n retries: 3\n api:\n build: ./node-backend\n networks:\n - proxy\n ports:\n - 3000:3000\n depends_on:\n mysql:\n condition: service_healthy\n```\n\n**Dockerfile**\n\n```\nFROM node:16\n\nWORKDIR /api\nCOPY . /api\nRUN npm i\nEXPOSE 3000\nRUN chmod +x startup.sh\nRUN npm i -g sequelize-cli\nRUN npm i -g nodemon\n\nENTRYPOINT [ \"./startup.sh\" ]\n```\n\n**startup.sh**\n\n```\n#!/bin/bash\n\nnpm run migrate-db\nnpm run start\n```\n\n========================================\n\nCode:\n```yaml\nversion: '3.8'\nservices: \n  mysqldb:\n    image: mysql\n    restart: unless-stopped\n    environment:\n      MYSQL_ROOT_USER: myuser\n      MYSQL_ROOT_PASSWORD: mypassword\n      MYSQL_DATABASE: mydb\n    ports:\n      - '3306:3306'\n    networks:\n      - app-connect\n    volumes: \n      - db-config:/etc/mysql\n      - db-data:/var/lib/mysql\n      - ./db/backup/files/:/data_backup/data\n  app:\n    build:\n      context: .\n      dockerfile: ./Dockerfile\n    image: node-mysql-app\n    depends_on:\n      - mysqldb\n    ports:\n      - '3030:3030'\n    networks:\n      - app-connect\n    stdin_open: true\n    tty: true\nvolumes: \n  db-config:\n  db-data:\nnetworks:\n  app-connect:\n      driver: bridge\n```\n\n```text\nFROM node:lts-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCOPY . .\nEXPOSE 3030\nENV PORT 3030\nENV NODE_ENV docker\nRUN npm run db:migrate:up\nRUN npm run db:seeds:up\nCMD [ \"npm\", \"start\" ]\n```\n\n```json\n{\n  \"development\": {\n    \n  },\n  \"production\": {\n    \n  },\n  \"docker\": {\n    \"username\": \"myuser\",\n    \"password\": \"mypassword\",\n    \"database\": \"mydb\",\n    \"host\": \"mysqldb\",\n    \"port\": \"3306\",\n    \"dialect\": \"mysql\"\n  }\n}\n```\n\n```text\nnpx: installed 81 in 13.108s\n\nSequelize CLI [Node: 14.17.0, CLI: 6.2.0, ORM: 6.6.2]\n\nLoaded configuration file \"default.db.json\".\nUsing environment \"docker\".\n\n\nERROR: getaddrinfo EAI_AGAIN mysqldb\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\n```\n\n```text\ndocker-compose.yaml\n```\n\n```text\nDockerfile\n```\n\n```text\ndefault.db.json\n```\n\n```text\ncompose up\n```\n\n```text\nRUN npm run db:migrate:up\n```\n\n```text\nnpx sequelize-cli db:migrate\n```\n\n```text\n\"host\"\n```\n\n```text\ndefault.db.json\n```\n\n```text\n\"127.0.0.1\"\n```\n\n```text\nERROR: connect ECONNREFUSED 127.0.0.1:3306\n```\n\n```text\nERROR: getaddrinfo EAI_AGAIN mysqldb\n```\n\n```text\ntouch\n```\n\n```text\nFROM node:current-alpine\nWORKDIR /app\nCOPY . ./\nCOPY .env.development ./.env\n\n\nRUN npm install\nRUN npm install -g typescript\n\nRUN npm install -g sequelize-cli\nRUN npm install -g nodemon\n\nRUN npm run build\nRUN rm -f .npmrc\n\nRUN cp -R res/ dist/\nRUN chmod 755 docker/entrypoint.sh\nEXPOSE 8000\n\nEXPOSE 3000\nEXPOSE 9229\nCMD [\"sh\", \"-c\",\"--\",\"echo 'started';while true; do sleep 1000; done\"]\n```\n\n```text\nversion: '3'\n\nservices:\n  app:\n    build:\n      context: ..\n      dockerfile: docker/Dockerfile.development\n    entrypoint: docker/development-entrypoint.sh\n    ports:\n      - 3000:3000\n    env_file:\n      - ../.env.development\n    depends_on:\n      - postgres\n      \n  \n  postgres:\n    image: postgres:alpine\n    environment:\n      - POSTGRES_USER=postgres\n      - POSTGRES_PASSWORD=test\n    volumes:\n      - ./docker_postgres_init.sql:/docker-entrypoint-initdb.d/docker_postgres_init.sql\n```\n\n```text\n#!/bin/sh\n\necho \"Starting get ready!!!\"\nsequelize db:migrate\nnodemon ./dist/index.js\n```\n\n```text\nDB_NAME=\"testdb\"\nDB_USER=\"root\"\nDB_PASS=\"root\"\nDB_HOST=\"mysql\"\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n  'config': path.resolve('config', 'config.js')\n}\n```\n\n```text\nrequire(\"dotenv\").config();\n\nmodule.exports = {\n  development: {\n    username: process.env.DB_USER,\n    password: process.env.DB_PASS,\n    database: process.env.DB_NAME,\n    host: process.env.DB_HOST,\n    dialect: \"mysql\"\n  },\n  test: {\n    username: process.env.DB_USER,\n    password: process.env.DB_PASS,\n    database: process.env.DB_NAME,\n    host: process.env.DB_HOST,\n    dialect: \"mysql\"\n  },\n  production: {\n    username: process.env.DB_USER,\n    password: process.env.DB_PASS,\n    database: process.env.DB_NAME,\n    host: process.env.DB_HOST,\n    dialect: \"mysql\"\n  }\n}\n```\n\n```text\nimport Sequelize from 'sequelize';\nimport dbConfig from './config/config';\n\nconst conf = dbConfig.development;\n\nconst sequelize = new Sequelize(\n  conf.database,\n  conf.username,\n  conf.password,\n  {\n    host: conf.host,\n    dialect: \"mysql\",\n    operatorsAliases: 0,\n    logging: 0\n  }\n);\n\nsequelize.sync();\n\n(async () => {\n  try {\n    await sequelize.authenticate();\n    console.log(\"Database connection setup successfully!\");\n  } catch (error) {\n    console.log(\"Unable to connect to the database\", error);\n  }\n})();\n\nexport default sequelize;\nglobal.sequelize = sequelize;\n```\n\n```text\nversion: \"3.8\"\n\nnetworks:\n  proxy:\n    name: proxy\n\nservices:\n  mysql:\n    image: mysql\n    networks:\n      - proxy\n    ports:\n      - 3306:3306\n    environment:\n      - MYSQL_ROOT_PASSWORD=root\n      - MYSQL_DATABASE=testdb\n    healthcheck:\n      test: \"mysql -uroot -p$$MYSQL_ROOT_PASSWORD  -e 'SHOW databases'\"\n      interval: 10s\n      retries: 3\n  api:\n    build: ./node-backend\n    networks:\n      - proxy\n    ports:\n      - 3000:3000\n    depends_on:\n      mysql:\n        condition: service_healthy\n```\n\n```text\nFROM node:16\n\nWORKDIR /api\nCOPY . /api\nRUN npm i\nEXPOSE 3000\nRUN chmod +x startup.sh\nRUN npm i -g sequelize-cli\nRUN npm i -g nodemon\n\nENTRYPOINT [ \"./startup.sh\" ]\n```\n\n```text\n#!/bin/bash\n\nnpm run migrate-db\nnpm run start\n```\n\n```text\n\"scripts\": {\n    \"start\": \"npm run migrate-db && node index.js\"\n  }\n```\n\n```text\n# Dockerfile\n\nFROM node:22-alpine\nWORKDIR /usr/app\n\nRUN npm i -g pnpm\n\nCOPY ./ ./\nRUN pnpm i\n\nRUN chmod +x ./scripts/your-service-entry.sh\n\nENTRYPOINT [ \"./scripts/your-service-entry.sh\" ]\n\n# This is a temp command to run in dev mode\n# in principle we might have separate docker files for dev and prod\nCMD [ \"pnpm\", \"dev\" ]\n```\n\n```bash\n#!/bin/sh\n\necho \">>>> Setup DB Migration before container starts <<<<\"\n\necho $PG_HOST\necho $PG_PORT\necho $PG_USER\necho $PG_PASS\necho $PG_DB_NAME\n\n# Construct the DATABASE_URL\nexport DATABASE_URL=\"postgres://${PG_USER}:${PG_PASS}@${PG_HOST}:${PG_PORT}/${PG_DB_NAME}\"\n\n# Output the DATABASE_URL to verify\necho \"DATABASE_URL=${DATABASE_URL}\"\n\nnpx node-pg-migrate up\n\necho \">>>> DB migrations work done <<<<\"\n\n# make sure everything after this entry point script will run\nexec \"$@\"\n```\n\n```text\nchmod +x ./scripts/your-service-entry.sh\n```\n\n========================================\n\nComments:\n- I hope i can help. I found something similar here. stackoverflow.com/questions/60916919/&hellip;\n- Could you how you made it work?","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":637,"estimatedTokens":2694}}415{"id":"stack-42309960","source":"stackoverflow","questionId":42309960,"title":"How do I require something from index.js in the same directory?","tags":["javascript","node.js","sequelize.js"],"text":"Title: How do I require something from index.js in the same directory?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following file structure: \n\n```\nmodels/\n index.js\n something.js\n user.js\n```\n\nIn `index.js` (this is generated by Sequalize and importing stuff from here works in other directories):\n\n```\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(module.filename);\nvar env = process.env.NODE_ENV || 'development';\nvar config = require(__dirname + '/../config/config')[env];\nvar db = {};\n\nif (config.use_env_variable) {\n var sequelize = new Sequelize(process.env[config.use_env_variable]);\n} else {\n var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n .forEach(function(file) {\n var model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function(modelName) {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db; // `user.js`:\n\n```\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n const User = sequelize.define('User', {\n username: { type: DataTypes.STRING, allowNull: false, unique: true },\n password: { type: DataTypes.STRING, allowNull: false },\n }, {\n classMethods: {\n associate() {},\n },\n });\n\n return User;\n};\n```\n\n`something.js`:\n\n```\n'use strict';\n\n// this all logs an empty object\nconsole.log(require('./index'));\nconsole.log(require('.'));\nconsole.log(require('./'));\nconsole.log(require('../models'));\nconsole.log(require('../models/'));\nconsole.log(require('../models/index'));\n\nmodule.exports = (sequelize, DataTypes) => {\n const Something = sequelize.define('Something', {\n name: DataTypes.STRING,\n }, {\n classMethods: {\n associate(models) {\n },\n },\n });\n return Something;\n};\n```\n\nIf I require `db` from files in other directories it works so I guess it's not a problem with exporting.\n\nHow can I require `db` in `something.js` so it's not undefined?\n\n========================================\n\nTop Answer:\n```\nconst neededStuff = require('./'); // the best\n```\n\nor:\n\n```\nconst neededStuff = require('./index');\n```\n\nor:\n\n```\nconst neededStuff = require('../models/');\n```\n\n========================================\n\nCode:\n```text\nmodels/\n  index.js\n  something.js\n  user.js\n```\n\n```text\n'use strict';\n\nvar fs        = require('fs');\nvar path      = require('path');\nvar Sequelize = require('sequelize');\nvar basename  = path.basename(module.filename);\nvar env       = process.env.NODE_ENV || 'development';\nvar config    = require(__dirname + '/../config/config')[env];\nvar db        = {};\n\nif (config.use_env_variable) {\n  var sequelize = new Sequelize(process.env[config.use_env_variable]);\n} else {\n  var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n  })\n  .forEach(function(file) {\n    var model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(function(modelName) {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db; // <<< I want to import that in something.js\n```\n\n```text\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n  const User = sequelize.define('User', {\n    username: { type: DataTypes.STRING, allowNull: false, unique: true },\n    password: { type: DataTypes.STRING, allowNull: false },\n  }, {\n    classMethods: {\n      associate() {},\n    },\n  });\n\n  return User;\n};\n```\n\n```text\n'use strict';\n\n// this all logs an empty object\nconsole.log(require('./index'));\nconsole.log(require('.'));\nconsole.log(require('./'));\nconsole.log(require('../models'));\nconsole.log(require('../models/'));\nconsole.log(require('../models/index'));\n\nmodule.exports = (sequelize, DataTypes) => {\n  const Something = sequelize.define('Something', {\n    name: DataTypes.STRING,\n  }, {\n    classMethods: {\n      associate(models) {\n      },\n    },\n  });\n  return Something;\n};\n```\n\n```text\nindex.js\n```\n\n```text\nuser.js\n```\n\n```text\nsomething.js\n```\n\n```text\ndb\n```\n\n```text\ndb\n```\n\n```text\nsomething.js\n```\n\n```text\nindex.js\n```\n\n```text\nsomething.js\n```\n\n```text\nindex.js\n```\n\n```text\nsomething.js\n```\n\n```text\nsequelize.models.Something\n```\n\n```text\nconst neededStuff = require('./'); // the best\n```\n\n```text\nconst neededStuff = require('./index');\n```\n\n```text\nconst neededStuff = require('../models/');\n```\n\n========================================\n\nComments:\n- `const { neededStuff } = require('.&#47;index');` should certainly work.\n- Log `db` in `index.js`! Put `console.log(db);` just before `module.exports = db;`! What does it log?\n- `console.log(Object.keys(db));` logs `[ 'Something', 'User', 'sequelize', 'Sequelize' ]`\n- Anyway, what do you need the `db` object for inside `something.js`?\n- it's an empty object in all those cases\n- @mrowa44 I've just tested it and it's working! Post more code!","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":275,"estimatedTokens":1340}}416{"id":"stack-60355504","source":"stackoverflow","questionId":60355504,"title":"How to get all records from the last 7 days sequelize","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: How to get all records from the last 7 days sequelize\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am trying to get all records from a mysql Database with sequelize and I have tried following approaches:\n\n```\nshops.findAndCountAll({\n where: {\n createdAt: {\n [Op.gte]: moment().subtract(7, 'days').toDate()\n }\n }\n})\n```\n\nand when I use this, I get the error:\n`ReferenceError: moment is not defined`\n\nSo I tried this approach:\n\n```\nshops.findAndCountAll({\n where: {\n createdAt: {\n [Op.gte]: Sequelize.literal('NOW() - INTERVAL \"7d\"'),\n }\n }\n})\n```\n\nBut I get the following error\n\n```\ncode: 'ER_PARSE_ERROR',\n errno: 1064,\n sqlState: '42000',\n sqlMessage: \"You have an error in your SQL syntax; check the manual that corresponds to \n\nyour MySQL server version for the right syntax to use near '' at line 1\",\n sql: \"SELECT count(*) AS `count` FROM `shop` AS `shops` WHERE `shops`.`createdAt` >= NOW() - INTERVAL '7d';\"\n },\n sql: \"SELECT count(*) AS `count` FROM `shop` AS `shops` WHERE `shops`.`createdAt` >= NOW() - INTERVAL '7d';\"\n }\n```\n\nHow can I fix this issue. I do not mind which of the approaches I use, as long as I get it to work.\n\nThank you in advance\n\n========================================\n\nTop Answer:\nUsing DATE_ADD() or DATE_SUB()\n\n```\nSELECT * FROM Table_Name\nWHERE connect_time >= DATE_ADD(CURDATE(),INTERVAL -7 DAY);\n```\n\nor\n\n```\nSELECT * FROM Table_Name\nWHERE connect_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY);\n```\n\nWithout those functions, you can also do\n\n```\nSELECT * FROM Table_Name\nWHERE connect_time >= (CURDATE() + INTERVAL -7 DAY);\n```\n\nor\n\n```\nSELECT * FROM Table_Name\nWHERE connect_time >= (CURDATE() - INTERVAL 7 DAY);\n```\n\n========================================\n\nCode:\n```text\nshops.findAndCountAll({\n  where: {\n    createdAt: {\n      [Op.gte]: moment().subtract(7, 'days').toDate()\n    }\n  }\n})\n```\n\n```text\nshops.findAndCountAll({\n  where: {\n    createdAt: {\n      [Op.gte]: Sequelize.literal('NOW() - INTERVAL \"7d\"'),\n    }\n  }\n})\n```\n\n```text\ncode: 'ER_PARSE_ERROR',\n    errno: 1064,\n    sqlState: '42000',\n    sqlMessage: \"You have an error in your SQL syntax; check the manual that corresponds to \n\nyour MySQL server version for the right syntax to use near '' at line 1\",\n        sql: \"SELECT count(*) AS `count` FROM `shop` AS `shops` WHERE `shops`.`createdAt` >= NOW() - INTERVAL '7d';\"\n      },\n      sql: \"SELECT count(*) AS `count` FROM `shop` AS `shops` WHERE `shops`.`createdAt` >= NOW() - INTERVAL '7d';\"\n    }\n```\n\n```text\nReferenceError: moment is not defined\n```\n\n```text\nconst moment = require('moment') //<es6\n```\n\n```text\nimport moment from 'moment'\n```\n\n```text\nmoment\n```\n\n```text\nmoment\n```\n\n```text\nSELECT * FROM Table_Name\nWHERE connect_time >= DATE_ADD(CURDATE(),INTERVAL -7 DAY);\n```\n\n```text\nSELECT * FROM Table_Name\nWHERE connect_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY);\n```\n\n```text\nSELECT * FROM Table_Name\nWHERE connect_time >= (CURDATE() + INTERVAL -7 DAY);\n```\n\n```text\nSELECT * FROM Table_Name\nWHERE connect_time >= (CURDATE() - INTERVAL 7 DAY);\n```\n\n```text\nconst dayCount = '7d';\n\nshops.findAndCountAll({\n  where: {\n    createdAt: {\n      [Op.gte]: Sequelize.literal(`NOW() - INTERVAL '${dayCount}'`),\n    }\n  }\n})\n```\n\n```text\ndayCount\n```\n\n========================================\n\nComments:\n- import moment for the first error? also you are adding to the string","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":178,"estimatedTokens":845}}417{"id":"stack-36216166","source":"stackoverflow","questionId":36216166,"title":"Sequelize : How to map a custom attribute in a pivot table","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize : How to map a custom attribute in a pivot table\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got this pivot table, which represents a many to many relationship with the models Person and Movie.\n\nhttps://i.sstatic.net/Sjx3D.png\n\nThe thing is I want to get the role when I call the movies that get the persons associated. I tried this but it doesn't show the role :\n\n```\nmodels.Movie.findAll({\n include: [{\n model: models.Person,\n as: 'persons',\n through: {attributes: [\"role\"]}\n }]\n}).then(function(movies) {\n res.json(movies);\n});\n```\n\nDo I have to specify something in the models for the `role` ?\n\n========================================\n\nTop Answer:\nFor the purpose of those who will need this, there is a new method called 'magic methods'. I believe you have declared your many-to-many asociation\n\n```\nconst movies = Movie.findAll();\n const person = Person.findbyPk(personId);\n const moviesPerson = movies.getPersons(person);\n```\n\n========================================\n\nCode:\n```text\nmodels.Movie.findAll({\n    include: [{\n        model: models.Person,\n        as: 'persons',\n        through: {attributes: [\"role\"]}\n    }]\n}).then(function(movies) {\n    res.json(movies);\n});\n```\n\n```text\nrole\n```\n\n```text\nvar MoviePerson = sequelize.define(\"MoviePerson\", {\n    role: DataTypes.STRING\n},\n{\n    tableName: 'movie_person',\n    underscored: true\n});\n```\n\n```text\nMovie.belongsToMany(models.Person, {\n    through: models.MoviePerson,\n    foreignKey: 'movie_id',\n    as: 'persons'\n});\n```\n\n```text\nmovie_person\n```\n\n```text\nrole\n```\n\n```text\nMovie\n```\n\n```text\nconst movies = Movie.findAll();\n    const person = Person.findbyPk(personId);\n    const moviesPerson = movies.getPersons(person);\n```\n\n========================================\n\nComments:\n- did you end up figuring this one out?\n- @MichaelSchinis I actually did, see my answer below\n- hmm. Interesting, thanks!\n- btw with the new version it is possible in a easier way docs.sequelizejs.com/manual/tutorial/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":98,"estimatedTokens":506}}418{"id":"stack-47263577","source":"stackoverflow","questionId":47263577,"title":"How to use an operator in where clause with an optional include?","tags":["mysql","sequelize.js"],"text":"Title: How to use an operator in where clause with an optional include?\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following Model:\n\n```\nAuthorModel.hasMany(BookModel);\nBookModel.belongsTo(AuthorModel);\n```\n\nSome authors have no books.\n\nI want to select an author whose name or title of one of his books matches the search string.\n\nI can achieve this with the following statement, but only for authors with books in their BookModel\n\n```\nAuthor.findOne({\n include: [{\n model: Book,\n where: {\n [Op.or]: [\n {'$author.name$': 'search string'},\n { title: 'search string'}\n ]\n },\n }]\n })\n```\n\nThis gives me more or less the following `mysql` query:\n\n```\nSELECT \n `author`.`name`,\n `book`.`title`\nFROM `author` INNER JOIN `book` \n ON `author`.`id` = `book`.`authorId`\n AND ( `author`.`name` = 'search string' OR `book`.`title` = 'search string');\n```\n\nThe problem here is, if an author has no books, then the result is empty. Even if there is an author that matches the search criteria.\n\nI tried to set the include to `required: false`, which gives a `left outer join`. In that case, I get some not matching results. The where clause is omitted.\n\nHow do I have to change my `sequelize` query, or what would be the proper `mysql` query?\n\n========================================\n\nCode:\n```text\nAuthorModel.hasMany(BookModel);\nBookModel.belongsTo(AuthorModel);\n```\n\n```text\nAuthor.findOne({\n         include: [{\n            model: Book,\n            where: {\n              [Op.or]: [\n                  {'$author.name$': 'search string'},\n                  { title: 'search string'}\n                 ]\n               },\n             }]\n           })\n```\n\n```text\nSELECT \n    `author`.`name`,\n    `book`.`title`\nFROM `author` INNER JOIN `book` \n     ON `author`.`id` = `book`.`authorId`\n     AND ( `author`.`name` = 'search string' OR `book`.`title` = 'search string');\n```\n\n```text\nmysql\n```\n\n```text\nrequired: false\n```\n\n```text\nleft outer join\n```\n\n```text\nsequelize\n```\n\n```text\nmysql\n```\n\n```text\nSELECT \n    `author`.`name`,\n    `book`.`title`\nFROM `author` LEFT JOIN `book` \n     ON `author`.`id` = `book`.`authorId`\nWHERE ( `author`.`name` = 'search string' OR `book`.`title` = 'search string')\n```\n\n```text\nAuthor.findOne({\n    where: {\n          [Op.or]: [\n              {'$author.name$': 'search string'},\n              { '$Book.title$': 'search string'}\n             ]\n           },\n    include: [{\n        model: Book,           \n        required: false\n       }]})\n```\n\n```text\nWHERE\n```\n\n```text\nJOIN ... ON\n```\n\n========================================\n\nComments:\n- Thank you, but this does not solve my problem. If the author has no books, your MySQL will give 0 results, even if the search string will match the name of the author. The sequelize statement is also wrong on several points and will not work out for me. The where clause has to be inside the include, otherwise you can not access `Book` in it.\n- @henk, have you tried my SQL query against some real data? AFAICS here it seems to work OK unless I misunderstood your requirements. As for the sequelize query, syntax might be wrong in some details as I haven't tried it but if you look at the link I referenced in the answer, you'll see that you can put the `where` clause outside of the `include` and still reference the joined table with syntax similar to my query.\n- After checking again, in fact, your MySQL statement is right, thanks. The issue was with the `.findOne` It gives a kind of strange MySQL statement, with a `select ... from (select ... as author .. where ...) left outer join ...`. For that reason, the `where` clause outside the `include` will go inside the parentheses, and `books` are not defined there. The solution for now is `.findAll`. That also misled me while checking your MySQL statement.\n- @henk, so does my answer eventually help or doesn't?\n- well the problem is solved, so I would say yes :D. Was just thinking if I should leave this open, in case someone can explain the issue behind using `.findOne` and how to use it right for my purpose. But maybe that is another question","metadata":{"transformedAt":"2026-08-18T18:33:34.373Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":139,"estimatedTokens":1026}}419{"id":"stack-51769034","source":"stackoverflow","questionId":51769034,"title":"How to use sqlite3 with docker compose","tags":["node.js","docker","sqlite","docker-compose","sequelize.js"],"text":"Title: How to use sqlite3 with docker compose\nTags: node.js, docker, sqlite, docker-compose, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nBetween the following tutorials;\n\n- Dockerizing create-react-app\n\n- Developing microservices - Node, react & docker\n\nI have been able to convert my nodejs app to dockerized micro-services which is up and running and connecting to services. However, my app uses Sqlite/Sequelize and this was working perfectly prior to dockerizing.\n\nWith the new setup, I get error;\n\n```\n/usr/src/app/node_modules/sequelize/lib/dialects/sqlite/connection-manager.js:31\nthrow new Error('Please install sqlite3 package manually');\nError: Please install sqlite3 package manually at new ConnectionManager \n(/usr/src/app/node_modules/sequelize/lib/dialects/sqlite/connection-manager.js:31:15)\n```\n\nMy question is;\n\n- Is it possible to use Sqlite3 with Docker\n\n- If so, anyone able to sample docker-compose.yml and Dockerfile combo that works for this please.\n\n***My docker-compose.yml***\n\n```\nversion: '3.5'\n\nservices:\n user-service:\n container_name: user-service\n build: ./services/user/\n volumes:\n - './services/user:/usr/src/app'\n - './services/user/package.json:/usr/src/package.json'\n ports:\n - '9000:9000' # expose ports - HOST:CONTAINER\n\n web-service:\n container_name: web-service\n build:\n context: ./services/web\n dockerfile: Dockerfile\n volumes:\n - './services/web:/usr/src/app'\n - '/usr/src/app/node_modules'\n ports:\n - '3000:3000' # expose ports - HOST:CONTAINER\n environment:\n - NODE_ENV=development\n depends_on:\n - user-service\n```\n\n***My user/ Dockerfile***\n\n```\nFROM node:latest\n\n# set working directory\nRUN mkdir /usr/src/app\nWORKDIR /usr/src/app\n\n# add `/usr/src/node_modules/.bin` to $PATH\nENV PATH /usr/src/app/node_modules/.bin:$PATH\n\n# install and cache app dependencies\nADD package.json /usr/src/package.json\nRUN npm install\n\n# start app\nCMD [\"npm\", \"start\"]\n```\n\n***My web/ Dockerfile***\n\n```\nFROM node:latest\n\n# set working directory\nRUN mkdir /usr/src/app\nWORKDIR /usr/src/app\n\n# add `/usr/src/app/node_modules/.bin` to $PATH\nENV PATH /usr/src/app/node_modules/.bin:$PATH\n\n# install and cache app dependencies\nCOPY package.json /usr/src/app/package.json\nRUN npm install\nRUN npm install react-scripts@1.1.4\nRUN npm install gulp -g\n\n# start app\nCMD [\"npm\", \"start\"]\n```\n\nMany thanks.\n\n========================================\n\nCode:\n```text\n/usr/src/app/node_modules/sequelize/lib/dialects/sqlite/connection-manager.js:31\nthrow new Error('Please install sqlite3 package manually');\nError: Please install sqlite3 package manually at new ConnectionManager \n(/usr/src/app/node_modules/sequelize/lib/dialects/sqlite/connection-manager.js:31:15)\n```\n\n```text\nversion: '3.5'\n\nservices:\n  user-service:\n    container_name: user-service\n    build: ./services/user/\n    volumes:\n      - './services/user:/usr/src/app'\n      - './services/user/package.json:/usr/src/package.json'\n    ports:\n      - '9000:9000' # expose ports - HOST:CONTAINER\n\n  web-service:\n    container_name: web-service\n    build:\n      context: ./services/web\n      dockerfile: Dockerfile\n    volumes:\n      - './services/web:/usr/src/app'\n      - '/usr/src/app/node_modules'\n    ports:\n      - '3000:3000' # expose ports - HOST:CONTAINER\n    environment:\n      - NODE_ENV=development\n    depends_on:\n      - user-service\n```\n\n```text\nFROM node:latest\n\n# set working directory\nRUN mkdir /usr/src/app\nWORKDIR /usr/src/app\n\n# add `/usr/src/node_modules/.bin` to $PATH\nENV PATH /usr/src/app/node_modules/.bin:$PATH\n\n# install and cache app dependencies\nADD package.json /usr/src/package.json\nRUN npm install\n\n# start app\nCMD [\"npm\", \"start\"]\n```\n\n```text\nFROM node:latest\n\n# set working directory\nRUN mkdir /usr/src/app\nWORKDIR /usr/src/app\n\n# add `/usr/src/app/node_modules/.bin` to $PATH\nENV PATH /usr/src/app/node_modules/.bin:$PATH\n\n# install and cache app dependencies\nCOPY package.json /usr/src/app/package.json\nRUN npm install\nRUN npm install react-scripts@1.1.4\nRUN npm install gulp -g\n\n# start app\nCMD [\"npm\", \"start\"]\n```\n\n```text\nservices:\n  user-service:\n    container_name: user-service\n    build: \n      context: ./services/user/\n      dockerfile: Dockerfile\n    volumes:\n      - './services/user:/usr/src/app'\n      - '/usr/src/node_modules'\n    ports:\n      - '9000:9000' # expose ports - HOST:CONTAINER\n\n  web-service:\n    container_name: web-service\n    build:\n      context: ./services/web/\n      dockerfile: Dockerfile\n    volumes:\n      - './services/web:/usr/src/app'\n      - '/usr/src/app/node_modules'\n    ports:\n      - '3000:3000' # expose ports - HOST:CONTAINER\n    environment:\n      - NODE_ENV=development\n    depends_on:\n      - user-service\n```\n\n```text\nFROM node:latest\n\n# set working directory\nRUN mkdir /usr/src/app\nWORKDIR /usr/src/app\n\n# add `/usr/src/node_modules/.bin` to $PATH\nENV PATH /usr/src/node_modules/.bin:$PATH\n\n# install and cache app dependencies\nADD package.json /usr/src/package.json\nRUN npm install\n\n# start app\nCMD [\"npm\", \"start\"]\n```\n\n========================================\n\nComments:\n- Can you please post the contents of your current `Dockerfile` and `docker-compose.yml`","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":231,"estimatedTokens":1283}}420{"id":"stack-32762409","source":"stackoverflow","questionId":32762409,"title":"Error while Accessing mysql through Sequelize (Express/NodeJS)","tags":["node.js","express","sequelize.js"],"text":"Title: Error while Accessing mysql through Sequelize (Express/NodeJS)\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to start using Sequelize. I am facing some errors though figured and cleared some of them but this one I am unable to figure out.\n\nProject Structure:\n\n```\nProject\n -Client\n -Server\n --models\n ---index.js\n ---Sid.js\n --router\n ---routes\n ----signup.js\n ---index.js\n app.js\n```\n\nmy config varriable:\n\n```\n\"Lexstart\": {\n \"dbConfig\": {\n \"driver\": \"mysql\",\n \"user\": \"root\",\n \"database\": \"sid1\",\n \"password\": \"sid1\",\n \"host\": \"127.0.0.1\",\n \"port\": \"3306\"\n }\n}\n```\n\nMy models/index.js:\n\n```\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar Sequelize = require('sequelize');\nvar config = require('config'); // we use node-config to handle environments\n\nvar dbConfig = config.get('Lexstart.dbConfig');\n\n// initialize database connection\nvar sequelize = new Sequelize(\n dbConfig.database,\n dbConfig.username,\n dbConfig.password,{\n host: dbConfig.host,\n dialect: dbConfig.driver\n}\n);\nvar db = {};\n\nfs\n.readdirSync(__dirname)\n.filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n})\n.forEach(function(file) {\n var model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n});\n\nObject.keys(db).forEach(function(modelName) {\nif (\"associate\" in db[modelName]) {\n db[modelName].associate(db);\n}\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nmodels/Sid.js\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var Sid = sequelize.define(\"Sid\", {\n username: DataTypes.STRING,\n password: DataTypes.STRING\n });\n\nreturn Sid;\n};\n```\n\nmy router/index.js\n\n```\n/**\n* The Index of Routes\n*/\n\nmodule.exports = function (app) {\n\n// The signup route\napp.use('/signup', require('./routes/signup'));\n}\n```\n\nmy router/routes/signup.js\n\n```\nvar models = require('../../models');\nvar Sid = models.Sid;\n// Include Express\nvar express = require('express');\n// Initialize the Router\nvar router = express.Router();\nvar config = require('config'); // we use node-config to handle environments\n\n// Setup the Route\nrouter.get('/', function (req, res) {\n\nSid.findAll().then(function(users) {\n console.log(users);;\n});\n\n// return a json response to angular\nres.json({\n 'msg': users\n});\n});\n\nrouter.get('/sid', function (req, res) {\n\n// return a json response to angular\nres.json({\n 'msg': \"sid\"\n});\n});\n\n// Expose the module\nmodule.exports = router;\n```\n\nThe route localhost:3000/signup/sid is working fine. But the /signup is giving up error. As you can see in the error text below it showing that connection is being tried without the config supplied variable value (username, password, host)(The config variable are working and fetching fine). I can't figure this out while debugging also.\n\n```\nUnhandled rejection SequelizeAccessDeniedError: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'localhost' (using password: YES)\nat Handshake._callback (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:51:20)\nat Handshake.Sequence.end (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\nat Handshake.ErrorPacket (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/sequences/Handshake.js:103:8)\nat Protocol._parsePacket (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/Protocol.js:274:23)\nat Parser.write (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/Parser.js:77:12)\nat Protocol.write (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/Protocol.js:39:16)\nat Socket. (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/Connection.js:96:28)\nat Socket.emit (events.js:107:17)\nat readableAddChunk (_stream_readable.js:163:16)\nat Socket.Readable.push (_stream_readable.js:126:10)\nat TCP.onread (net.js:538:20)\n```\n\nPlease guide.\n\nSiddharth\n\n========================================\n\nTop Answer:\nGo to config.json and change user to username and restart your app. Sometimes there are no errors and app just doesn't work. \n\n```\n\"Lexstart\": {\n \"dbConfig\": {\n \"driver\": \"mysql\",\n \"username\": \"root\",\n \"database\": \"sid1\",\n \"password\": \"sid1\",\n \"host\": \"127.0.0.1\",\n \"port\": \"3306\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nProject\n -Client\n -Server\n  --models\n    ---index.js\n    ---Sid.js\n  --router\n    ---routes\n       ----signup.js\n    ---index.js\n  app.js\n```\n\n```text\n\"Lexstart\": {\n  \"dbConfig\": {\n     \"driver\": \"mysql\",\n     \"user\": \"root\",\n     \"database\": \"sid1\",\n     \"password\": \"sid1\",\n     \"host\": \"127.0.0.1\",\n     \"port\": \"3306\"\n  }\n}\n```\n\n```text\nvar fs        = require(\"fs\");\nvar path      = require(\"path\");\nvar Sequelize = require('sequelize');\nvar config    = require('config');  // we use node-config to handle environments\n\nvar dbConfig = config.get('Lexstart.dbConfig');\n\n// initialize database connection\nvar sequelize = new Sequelize(\n    dbConfig.database,\n    dbConfig.username,\n    dbConfig.password,{\n      host: dbConfig.host,\n      dialect: dbConfig.driver\n}\n);\nvar db        = {};\n\nfs\n.readdirSync(__dirname)\n.filter(function(file) {\n    return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n})\n.forEach(function(file) {\n    var model = sequelize.import(path.join(__dirname, file));\n    db[model.name] = model;\n});\n\nObject.keys(db).forEach(function(modelName) {\nif (\"associate\" in db[modelName]) {\n    db[modelName].associate(db);\n}\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var Sid = sequelize.define(\"Sid\", {\n        username: DataTypes.STRING,\n        password: DataTypes.STRING\n     });\n\nreturn Sid;\n};\n```\n\n```text\n/**\n* The Index of Routes\n*/\n\nmodule.exports = function (app) {\n\n// The signup route\napp.use('/signup', require('./routes/signup'));\n}\n```\n\n```text\nvar models = require('../../models');\nvar Sid = models.Sid;\n// Include Express\nvar express = require('express');\n// Initialize the Router\nvar router = express.Router();\nvar config    = require('config');  // we use node-config to handle environments\n\n\n// Setup the Route\nrouter.get('/', function (req, res) {\n\nSid.findAll().then(function(users) {\n    console.log(users);;\n});\n\n// return a json response to angular\nres.json({\n    'msg': users\n});\n});\n\nrouter.get('/sid', function (req, res) {\n\n// return a json response to angular\nres.json({\n    'msg': \"sid\"\n});\n});\n\n\n\n// Expose the module\nmodule.exports = router;\n```\n\n```text\nUnhandled rejection SequelizeAccessDeniedError: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'localhost' (using password: YES)\nat Handshake._callback (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:51:20)\nat Handshake.Sequence.end (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\nat Handshake.ErrorPacket (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/sequences/Handshake.js:103:8)\nat Protocol._parsePacket (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/Protocol.js:274:23)\nat Parser.write (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/Parser.js:77:12)\nat Protocol.write (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/protocol/Protocol.js:39:16)\nat Socket.<anonymous> (/Users/siddharthsrivastava/Documents/sites/express/LexStart/server/node_modules/mysql/lib/Connection.js:96:28)\nat Socket.emit (events.js:107:17)\nat readableAddChunk (_stream_readable.js:163:16)\nat Socket.Readable.push (_stream_readable.js:126:10)\nat TCP.onread (net.js:538:20)\n```\n\n```text\n\"dbConfig\": {\n       \"driver\": \"mysql\",\n       \"user\": \"root\",\n    ...\n    var sequelize = new Sequelize(\n      dbConfig.database,\n      dbConfig.username,\n```\n\n```text\n\"Lexstart\": {\n  \"dbConfig\": {\n     \"driver\": \"mysql\",\n     \"username\": \"root\",\n     \"database\": \"sid1\",\n     \"password\": \"sid1\",\n     \"host\": \"127.0.0.1\",\n     \"port\": \"3306\"\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":351,"estimatedTokens":2112}}421{"id":"stack-68197033","source":"stackoverflow","questionId":68197033,"title":"Specified type of property cannot be automatically resolved to a sequelize data type. Please define the data type manually","tags":["mysql","typescript","express","sequelize.js","sequelize-typescript"],"text":"Title: Specified type of property cannot be automatically resolved to a sequelize data type. Please define the data type manually\nTags: mysql, typescript, express, sequelize.js, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI'm defining one to many relationship between a `User` and a `Product` in sequelize-typescript.\n\nHere are the Models:\n\nProduct.ts\n\n```\n@Table\nexport class Product extends Model {\n @Column({ primaryKey: true })\n id!: string\n\n @Column\n title!: string\n\n @Column({ type: DataType.DOUBLE })\n price!: number\n\n @Column\n imageUrl!: string\n\n @Column\n description?: string\n\n @ForeignKey(() => User)\n @Column\n userId?: string\n\n @BelongsTo(() => User)\n user?: User\n}\n```\n\nUser.ts\n\n```\n@Table\nexport class User extends Model {\n @Column({ primaryKey: true })\n id!: string\n\n @Column\n name!: string\n\n @Column\n email!: string\n\n @Column\n @HasMany(() => Product)\n products?: Product[]\n}\n```\n\nI'm getting the following error:\n\n```\nSpecified type of property 'products' cannot be automatically resolved to a sequelize data type. Please define the data type manually\n```\n\nHere's the complete stack trace:\n\n```\n*ProjectPath*/node_modules/sequelize-typescript/dist/model/shared/model-service.js:64\n throw new Error(`Specified type of property '${propertyName}'\n ^\nError: Specified type of property 'products'\n cannot be automatically resolved to a sequelize data type. Please\n define the data type manually\n at Object.getSequelizeTypeByDesignType (*ProjectPath*/node_modules/sequelize-typescript/dist/model/shared/model-service.js:64:11)\n at annotate (*ProjectPath*/node_modules/sequelize-typescript/dist/model/column/column.js:32:44)\n at Column (*ProjectPath*/node_modules/sequelize-typescript/dist/model/column/column.js:14:9)\n at DecorateProperty (*ProjectPath*/node_modules/reflect-metadata/Reflect.js:553:33)\n at Object.decorate (*ProjectPath*/node_modules/reflect-metadata/Reflect.js:123:24)\n at __decorate (*ProjectPath*/src/models/user.ts:4:92)\n at Object. (*ProjectPath*/src/models/user.ts:27:5)\n at Module._compile (internal/modules/cjs/loader.js:1156:30)\n at Module.m._compile (*ProjectPath*/node_modules/ts-node/src/index.ts:1043:23)\n at Module._extensions..js (internal/modules/cjs/loader.js:1176:10)\n```\n\nAny input would be much appreciated.\n\n========================================\n\nTop Answer:\nhttps://i.sstatic.net/Qqh3f.png Another thing is to pass sequelize datatype to the column function\n\n========================================\n\nCode:\n```text\n@Table\nexport class Product extends Model {\n    @Column({ primaryKey: true })\n    id!: string\n\n    @Column\n    title!: string\n\n    @Column({ type: DataType.DOUBLE })\n    price!: number\n\n    @Column\n    imageUrl!: string\n\n    @Column\n    description?: string\n\n    @ForeignKey(() => User)\n    @Column\n    userId?: string\n\n    @BelongsTo(() => User)\n    user?: User\n}\n```\n\n```text\n@Table\nexport class User extends Model {\n    @Column({ primaryKey: true })\n    id!: string\n\n    @Column\n    name!: string\n\n    @Column\n    email!: string\n\n    @Column\n    @HasMany(() => Product)\n    products?: Product[]\n}\n```\n\n```text\nSpecified type of property 'products' cannot be automatically resolved to a sequelize data type. Please define the data type manually\n```\n\n```text\n*ProjectPath*/node_modules/sequelize-typescript/dist/model/shared/model-service.js:64\n    throw new Error(`Specified type of property '${propertyName}'\n          ^\nError: Specified type of property 'products'\n            cannot be automatically resolved to a sequelize data type. Please\n            define the data type manually\n    at Object.getSequelizeTypeByDesignType (*ProjectPath*/node_modules/sequelize-typescript/dist/model/shared/model-service.js:64:11)\n    at annotate (*ProjectPath*/node_modules/sequelize-typescript/dist/model/column/column.js:32:44)\n    at Column (*ProjectPath*/node_modules/sequelize-typescript/dist/model/column/column.js:14:9)\n    at DecorateProperty (*ProjectPath*/node_modules/reflect-metadata/Reflect.js:553:33)\n    at Object.decorate (*ProjectPath*/node_modules/reflect-metadata/Reflect.js:123:24)\n    at __decorate (*ProjectPath*/src/models/user.ts:4:92)\n    at Object.<anonymous> (*ProjectPath*/src/models/user.ts:27:5)\n    at Module._compile (internal/modules/cjs/loader.js:1156:30)\n    at Module.m._compile (*ProjectPath*/node_modules/ts-node/src/index.ts:1043:23)\n    at Module._extensions..js (internal/modules/cjs/loader.js:1176:10)\n```\n\n```text\nUser\n```\n\n```text\nProduct\n```\n\n```text\nproducts\n```\n\n```text\n@Column\n```\n\n```text\nproducts\n```\n\n========================================\n\nComments:\n- You seem to mean this as an answer, right? Would you like to explain a little on how to do that exactly, what effect it has and why that sovles the problem? Try for How to Answer. Maybe taket the tour.","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":187,"estimatedTokens":1195}}422{"id":"stack-54478953","source":"stackoverflow","questionId":54478953,"title":"Creating instance methods in a Sequelize Model using Typescript","tags":["node.js","typescript","model","sequelize.js"],"text":"Title: Creating instance methods in a Sequelize Model using Typescript\nTags: node.js, typescript, model, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to extend a Sequelize Model class to add other instance methods but typescript keeps complaining that \"Property 'prototype' does not exist on type 'Model'\"\n\n```\nconst MyModel = (sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes) => {\n const User = sequelize.define(\n \"users\",\n {\n id: {\n type: dataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n },\n email: {\n type: dataTypes.STRING\n },\n ...\n },\n {\n tableName: \"users\",\n ...\n },\n );\n\n User.prototype.verifyUser = function(password: string) {\n ...\n };\n\n return User;\n};\n```\n\nI expect `User.prototype.verifyUser` to work but typescript complains. How to add to typings?\n\n========================================\n\nTop Answer:\nFollowing @Shadrech comment, I've an alternative (less hacky and abstract). \n\n```\nexport interface UserAttributes {\n ...\n}\n\nexport interface UserInstance extends Sequelize.Instance, UserAttributes {\n}\n\ninterface UserModelInstanceMethods extends Sequelize.Model {\n\n // Came to this question looking for a better approach to this\n // You'll need root's definitions for invocation and prototype's for creation\n verifyPassword: (password: string) => Promise;\n prototype: {\n verifyPassword: (password: string) => Promise;\n };\n}\n\nconst MyModel = (sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes): UserModelInstanceMethods => {\n const User = sequelize.define(\n ...\n ) as UserModelInstanceMethods;\n\n User.prototype.verifyUser = function(password: string) {\n ...\n };\n\n return User;\n}\n```\n\nUsing your model:\n\n```\nsequelize.query(\"SELECT ...\").then((user: UserInstance & UserModelInstanceMethods) => {\n user.verifyPassword(req.body.password) // <= from UserModelInstanceMethods\n user.getDataValue('name') // <= from UserInstance\n})\n```\n\n========================================\n\nCode:\n```text\nconst MyModel = (sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes) => {\n  const User = sequelize.define<Instance, Attribute>(\n    \"users\",\n    {\n      id: {\n        type: dataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true,\n      },\n      email: {\n        type: dataTypes.STRING\n      },\n      ...\n    },\n    {\n      tableName: \"users\",\n      ...\n    },\n  );\n\n  User.prototype.verifyUser = function(password: string) {\n    ...\n  };\n\n  return User;\n};\n```\n\n```text\nUser.prototype.verifyUser\n```\n\n```text\ninterface UserModelInstanceMethods extends Sequelize.Model<Instance, Attributes> {\n  prototype: {\n    verifyPassword: (password: string) => Promise<boolean>;\n  };\n}\n\nconst MyModel = (sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes) => {\n  const User = sequelize.define<Instance, Attribute>(\n    \"users\",\n    {\n      id: {\n        type: dataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true,\n      },\n      email: {\n        type: dataTypes.STRING\n      },\n      ...\n    },\n    {\n      tableName: \"users\",\n      ...\n    },\n  );\n\n  User.prototype.verifyUser = function(password: string) {\n    ...\n  };\n\n  return User;\n} as Sequelize.Model<Instance, Attributes> & UserModelInstanceMethods;\n```\n\n```js\nexport interface UserAttributes {\n   ...\n}\n\nexport interface UserInstance extends Sequelize.Instance<UserAttributes>, UserAttributes {\n}\n\ninterface UserModelInstanceMethods extends Sequelize.Model<UserInstance, UserAttributes> {\n\n  // Came to this question looking for a better approach to this\n  // You'll need root's definitions for invocation and prototype's for creation\n  verifyPassword: (password: string) => Promise<boolean>;\n  prototype: {\n    verifyPassword: (password: string) => Promise<boolean>;\n  };\n}\n\nconst MyModel = (sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes): UserModelInstanceMethods => {\n  const User = sequelize.define<UserInstance, UserAttributes>(\n      ...\n  ) as UserModelInstanceMethods;\n\n  User.prototype.verifyUser = function(password: string) {\n    ...\n  };\n\n  return User;\n}\n```\n\n```js\nsequelize.query(\"SELECT ...\").then((user: UserInstance & UserModelInstanceMethods) => {\n  user.verifyPassword(req.body.password) // <= from UserModelInstanceMethods\n  user.getDataValue('name') // <= from UserInstance\n})\n```\n\n```js\n// Step 0: Declarations\nconst connection: Sequelize = new Sequelize({...});\nconst modelName: string = '...';\nconst definition: ModelAttributes = {...};\nconst options: ModelOptions = {...};\ninterface MyInterface {...}; // Should describe table data\n\n// Step 1\ntype DefinedModel<T> = typeof Model & {\n  new(values?: object, options?: BuildOptions): T;\n}\n\n// Step 2\nconst model: DefinedModel<Model> = <DefinedModel<Model>>connection.define(modelName, definition, options);\n\n// Step 2 with Interface definition\nconst iModel: DefinedModel<MyInterface & Model> = <DefinedModel<MyInterface & Model>> connection.define(modelName, definition, options);\n```\n\n```text\nDefinedModel\n```\n\n```text\nT\n```\n\n```text\nconnection.define\n```\n\n```text\nDefinedModel\n```\n\n```js\nimport {\n  Sequelize,\n  Model,\n  ModelDefined,\n  DataTypes,\n  Optional,\n  // ...\n} from 'sequelize';\n\ninterface ProjectAttributes {\n  id: number;\n  ownerId: number;\n  name: string;\n  readonly createdAt: Date;\n  readonly updatedAt: Date;\n\n  // #region Methods\n  \n  myMethod(name: string): Promise<void>; // <<<===\n\n  // #endregion\n}\n\ninterface ProjectCreationAttributes extends Omit< // <<<===\n  Optional<\n    ProjectAttributes,\n    | 'id'\n    | 'createdAt'\n  >,\n  'myMethod' // <<<===\n> {}\n\nclass Project extends Model<ProjectAttributes, ProjectCreationAttributes>\n  implements ProjectAttributes {\n  public id: ProjectAttributes['id'];\n  public ownerId: ProjectAttributes['ownerId'];\n  public name: ProjectAttributes['name'];\n  public readonly createdAt: ProjectAttributes['createdAt'];\n  public readonly updatedAt: ProjectAttributes['updatedAt'];\n\n  public readonly myMethod: ProjectAttributes['myMethod'] // <<<===\n\n   /**\n   * Initialization to fix Sequelize Issue #11675.\n   *\n   * @see https://stackoverflow.com/questions/66515762/configuring-babel-typescript-for-sequelize-orm-causes-undefined-properties\n   * @see https://github.com/sequelize/sequelize/issues/11675\n   * @ref #SEQUELIZE-11675\n   */\n  constructor(values?: TCreationAttributes, options?: BuildOptions) {\n    super(values, options);\n\n    // All fields should be here!\n    this.id = this.getDataValue('id');\n    this.ownerId = this.getDataValue('ownerId');\n    this.name = this.getDataValue('name');\n    this.createdAt = this.getDataValue('createdAt');\n    this.updatedAt = this.getDataValue('updatedAt');\n\n    this.myMethod = async (name) => { // <<<===\n      // Implementation example!\n      await this.update({\n        name,\n      });\n    };\n  }\n\n  // #region Methods\n\n  public toString() {\n    return `@${this.name} [${this.ownerId}] #${this.id}`;\n  }\n\n  // #endregion\n}\n\nProject.init(\n  {\n    id: {\n      type: DataTypes.INTEGER.UNSIGNED,\n      autoIncrement: true,\n      primaryKey: true,\n    },\n    ownerId: {\n      type: DataTypes.INTEGER.UNSIGNED,\n      allowNull: false,\n    },\n    name: {\n      type: new DataTypes.STRING(128),\n      allowNull: false,\n    },\n\n\n    myMethod: { // <<<===\n      type: DataTypes.VIRTUAL(DataTypes.ABSTRACT),\n    }\n  },\n  {\n    sequelize,\n    tableName: \"projects\",\n  }\n);\n```\n\n```text\nDataTypes.VIRTUAL\n```\n\n```text\nOmit\n```\n\n========================================\n\nComments:\n- Thanks for this example, I have ben running into the issue #11675 but did not yet know how to solve. One nit: Your constructor uses a type 'TCreationAttributes' and I believe you meant for it to be 'ProjectCreationAttributes'","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":345,"estimatedTokens":1914}}423{"id":"stack-39928452","source":"stackoverflow","questionId":39928452,"title":"Execute Sequelize queries synchronously","tags":["javascript","node.js","postgresql","asynchronous","sequelize.js"],"text":"Title: Execute Sequelize queries synchronously\nTags: javascript, node.js, postgresql, asynchronous, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am building a website using Node.js and Sequelize (with a Postgres backend). I have a query that returns many objects with a foreign key, and I want to pass to the view a list of the objects that the foreign key references.\n\nIn the example, Attendances contains Hackathon keys, and I want to return a list of hackathons. Since the code is async, the following thing of course does not work in Node:\n\n```\nmodels.Attendance.findAll({\n where: {\n UserId: req.user.id\n }\n}).then(function (data) {\n var hacks = [];\n for (var d in data) {\n models.Hackathon.findOne({\n where: {\n id: data[d].id\n }\n }).then(function (data1) {\n hacks.append(data1);\n });\n }\n res.render('dashboard/index.ejs', {title: 'My Hackathons', user: req.user, hacks: hacks});\n});\n```\n\nIs there any way to do that query in a synchronous way, meaning that I don't return the view untill I have the \"hacks\" list filled with all the objects?\n\nThanks!\n\n========================================\n\nTop Answer:\nThe Sequelize library has the **include** parameter which merges models in one call. Adjust your where statement to bring the *Hackathons* model into *Attendance*. If this does not work, take the necessary time to setup Sequelize correctly, their documentation is constantly being improved. In the end, you'll save loads of time by reducing error and making your code readable for other programmers.\n\nLook how much cleaner this can be...\n\n```\nmodels.Attendance.findAll({\n include: [{\n model: Hackathon,\n as: 'hackathon'\n },\n where: {\n UserId: req.user.id\n }\n}).then(function (data) {\n // hackathon id\n console.log(data.hackathon.id)\n\n // attendance id\n console.log(data.id)\n})\n```\n\nAlso..\n\n```\nHackathon.belongsTo(Attendance)\nAttendance.hasMany(Hackathon)\nsequelize.sync().then(() => {\n // this is where we continue ...\n})\n```\n\nLearn more about Sequelize includes here:\nhttp://docs.sequelizejs.com/en/latest/docs/models-usage/\n\n========================================\n\nCode:\n```text\nmodels.Attendance.findAll({\n    where: {\n        UserId: req.user.id\n    }\n}).then(function (data) {\n    var hacks = [];\n    for (var d in data) {\n        models.Hackathon.findOne({\n            where: {\n                id: data[d].id\n            }\n        }).then(function (data1) {\n            hacks.append(data1);\n        });\n    }\n    res.render('dashboard/index.ejs', {title: 'My Hackathons', user: req.user, hacks: hacks});\n});\n```\n\n```js\nmodels.Attendance.findAll({\n    where: {\n        UserId: req.user.id\n    }\n}).then(function (data) {\n    // get an array of the data keys, (not sure if you need to do this)\n    // it is unclear whether data is an object of users or an array. I assume\n    // it's an object as you used a `for in` loop\n    const keys = Object.keys(data)\n    // map the data keys to [Promise(query), Promise(query), {...}]\n    const hacks = keys.map((d) => {\n      return models.Hackathon.findOne({\n        where: {\n          id: data[d].id\n        }\n      })\n    })\n    // user Promise.all to resolve all of the promises asynchronously\n    Promise.all(hacks)\n      // this will be called once all promises have resolved so\n      // you can modify your data. it will be an array of the returned values\n      .then((users) => {\n        const [user1, user2, {...}] = users\n        res.render('dashboard/index.ejs', {\n          title: 'My Hackathons', \n          user: req.user, \n          hacks: users\n        });\n      })\n});\n```\n\n```text\nPromise.all\n```\n\n```text\nmodels.Attendance.findAll({\n    include: [{\n        model: Hackathon,\n        as: 'hackathon'\n    },\n    where: {\n        UserId: req.user.id\n    }\n}).then(function (data) {\n    // hackathon id\n    console.log(data.hackathon.id)\n\n    // attendance id\n    console.log(data.id)\n})\n```\n\n```text\nHackathon.belongsTo(Attendance)\nAttendance.hasMany(Hackathon)\nsequelize.sync().then(() => {\n  // this is where we continue ...\n})\n```\n\n```text\nconst assert = require('assert');\nconst { Sequelize, DataTypes } = require('sequelize');\n\nconst sequelize = new Sequelize({\n  dialect: 'sqlite',\n  storage: 'db.sqlite',\n});\nconst IntegerNames = sequelize.define(\n  'IntegerNames', {\n  value: { type: DataTypes.INTEGER, allowNull: false },\n  name: { type: DataTypes.STRING, },\n}, {});\n\n(async () => {\nawait IntegerNames.sync({force: true})\nawait IntegerNames.create({value: 2, name: 'two'});\nawait IntegerNames.create({value: 3, name: 'three'});\nawait IntegerNames.create({value: 5, name: 'five'});\n\n// Fill array.\nlet integerNames = [];\nintegerNames.push(await IntegerNames.findOne({\n  where: {value: 2}\n}));\nintegerNames.push(await IntegerNames.findOne({\n  where: {value: 3}\n}));\n\n// Use array.\nassert(integerNames[0].name === 'two');\nassert(integerNames[1].name === 'three');\n\nawait sequelize.close();\n})();\n```\n\n========================================\n\nComments:\n- Did you try async module with waterfall? that can help you\n- Finding one record in a loop is a terrible design either way. It should be just one query.\n- you literally can be too safe. if you're just wrapping everything in a parseInt() call because \"maybe\", you're cargo culting.\n- @theraccoonbear - updated code, no need for parseInt(), Sequelize handles that when the column is specified as type: INTEGER","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":201,"estimatedTokens":1337}}424{"id":"stack-57517793","source":"stackoverflow","questionId":57517793,"title":"graphql server side validation","tags":["validation","graphql","sequelize.js","apollo-server"],"text":"Title: graphql server side validation\nTags: validation, graphql, sequelize.js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI just want to get a gauge of what people think is the best practice for doing validation of user input fileds (such as url or email address) on the server with a graphql / orm setup.\n\nMy application is using apollo server / gql and sequelize as the orm.\n\nI've seen some who do validation on the model in sequelize and other examples of validation in the graphql resolver with with a validation library or using custom scalars.\n\nIs any one way preferable? Thanks.\n\n========================================\n\nCode:\n```text\nif (validationPass) {...} else {..}\n```\n\n```text\ninfo\n```\n\n========================================\n\nComments:\n- thanks for the overview. i ended up doing it in the model layer since it was already supported by Sequelize.","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":28,"estimatedTokens":218}}425{"id":"stack-37730090","source":"stackoverflow","questionId":37730090,"title":"Get id of inserted row from upsert (insertOrUpdate) Sequelize Node.js","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: Get id of inserted row from upsert (insertOrUpdate) Sequelize Node.js\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm creating a REST API.\nI would like to implement an indepotent PUT operation, that either creates or updates the specific resource in database.\n\nI'm using node.js, postgreSQL and sequelize.\nThe problem is that sequelize `upsert` returns either `true` or `false` depending on wheter the resource got updated or created.\n\nBut I need to be able to send unique identifier (column id) back to the client, if the resource got created.\n\nOne solution that I tried was trying to find the exact same resource by specifing every single column send from client in \"where\" property of sequelize findOne query. But it throws errors, if client send additional columns that are not in database. And this shouldn't be the case in my implementation.\n\nIs it possible to implement this? Optimally without some performance overhead.\nThanks\n\n========================================\n\nCode:\n```text\nupsert\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\nupsert\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":36,"estimatedTokens":277}}426{"id":"stack-56103890","source":"stackoverflow","questionId":56103890,"title":"Need working example of a custom Sequelize Postgres datatype","tags":["postgresql","sequelize.js"],"text":"Title: Need working example of a custom Sequelize Postgres datatype\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a custom type in Postgres that I want to use in Sequelize. I've written code based on the example in the Sequelize docs, except for call to a function (\"inherits\") which I can't find in Sequelize or elsewhere. However, using sequelize.define to create a model with an attribute of this custom type throws an exception inside Sequelize. Is there an error in my code that stands out? Or is there another good example or tutorial for implementing a custom datatype? Also, what's up with the \"inherits\" function shown in the doc example -- are the docs leaving out an import/requires, or is that call erroneous?\n\nDocs I'm following are here: http://docs.sequelizejs.com/manual/data-types.html#extending-datatypes\n\nThe type as defined in Postgres:\n\n```\nCREATE TYPE public.measurement AS\n(\n unit text,\n value double precision\n);\n```\n\nMy test code in NodeJS:\n\n```\nconst Sequelize = require('sequelize');\n\nlet dataTypes = Sequelize.DataTypes;\n\n// Create class for custom datatype\nclass MEASUREMENT extends dataTypes.ABSTRACT {\n toSql() {\n console.log('MEASUREMENT toSql');\n return 'MEASUREMENT';\n }\n static parse(value) {\n console.log('MEASUREMENT parse value=', value);\n return value;\n }\n};\n\n// Set key\nMEASUREMENT.prototype.key = 'MEASUREMENT';\nMEASUREMENT.key = MEASUREMENT.prototype.key;\n\n// Add to DataTypes\ndataTypes.MEASUREMENT = MEASUREMENT;\n\n// Add to Sequelize\nSequelize.MEASUREMENT = Sequelize.Utils.classToInvokable(MEASUREMENT);\n\nlet pgTypes = dataTypes.postgres;\n\n// Map dialects\ndataTypes.MEASUREMENT.types.postgres = ['MEASUREMENT']\n\npgTypes.MEASUREMENT = function MEASUREMENT() {\n if (!(this instanceof pgTypes.MEASUREMENT)) return new pgTypes.MEASUREMENT();\n DataTypes.MEASUREMENT.apply(this, arguments);\n}\n\n// inherits(pgTypes.MEASUREMENT, dataTypes.MEASUREMENT);\n// Node throws a parse error. This is in the example in the Sequelize docs, however.\n\npgTypes.MEASUREMENT.parse = dataTypes.MEASUREMENT.parse;\n\n// ------------------------------\n\nconst sequelize = new Sequelize('test', 'test', 'test', {\n host: 'localhost',\n dialect: 'postgres'\n});\n\nconst Thing = sequelize.define('thing', {\n name: Sequelize.STRING,\n weight: Sequelize.MEASUREMENT\n});\n```\n\nCall stack when run:\n\n```\nC:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\abstract\\connection-manager.js:48\n if (dataType.types[this.dialectName]) { \n ^ \n\nTypeError: Cannot read property 'postgres' of undefined \n at _.each.dataType (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\abstract\\connection-manager.js:48:27) \n at C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:4911:15 \n at baseForOwn (C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:2996:24) \n at C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:4880:18 \n at Function.forEach (C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:9344:14) \n at ConnectionManager.refreshTypeParser (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\abstract\\connection-manager.js:46:7) \n at new ConnectionManager (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\postgres\\connection-manager.js:23:10) \n at new PostgresDialect (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\postgres\\index.js:14:30) \n at new Sequelize (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\sequelize.js:320:20) \n at Object. (C:\\Workspaces\\nebula\\server\\testsequelizecustom.js:58:19) \n at Module._compile (internal/modules/cjs/loader.js:689:30) \n at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10) \n at Module.load (internal/modules/cjs/loader.js:599:32) \n at tryModuleLoad (internal/modules/cjs/loader.js:538:12) \n at Function.Module._load (internal/modules/cjs/loader.js:530:3) \n at Function.Module.runMain (internal/modules/cjs/loader.js:742:12) \n at startup (internal/bootstrap/node.js:279:19) \n at bootstrapNodeJSCore (internal/bootstrap/node.js:752:3)\n```\n\n========================================\n\nCode:\n```sql\nCREATE TYPE public.measurement AS\n(\n    unit text,\n    value double precision\n);\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nlet dataTypes = Sequelize.DataTypes;\n\n// Create class for custom datatype\nclass MEASUREMENT extends dataTypes.ABSTRACT {\n    toSql() {\n        console.log('MEASUREMENT toSql');\n        return 'MEASUREMENT';\n    }\n    static parse(value) {\n        console.log('MEASUREMENT parse value=', value);\n        return value;\n    }\n};\n\n// Set key\nMEASUREMENT.prototype.key = 'MEASUREMENT';\nMEASUREMENT.key = MEASUREMENT.prototype.key;\n\n// Add to DataTypes\ndataTypes.MEASUREMENT = MEASUREMENT;\n\n// Add to Sequelize\nSequelize.MEASUREMENT = Sequelize.Utils.classToInvokable(MEASUREMENT);\n\nlet pgTypes = dataTypes.postgres;\n\n// Map dialects\ndataTypes.MEASUREMENT.types.postgres = ['MEASUREMENT']\n\npgTypes.MEASUREMENT = function MEASUREMENT() {\n    if (!(this instanceof pgTypes.MEASUREMENT)) return new pgTypes.MEASUREMENT();\n    DataTypes.MEASUREMENT.apply(this, arguments);\n}\n\n// inherits(pgTypes.MEASUREMENT, dataTypes.MEASUREMENT);\n// Node throws a parse error. This is in the example in the Sequelize docs, however.\n\npgTypes.MEASUREMENT.parse = dataTypes.MEASUREMENT.parse;\n\n\n// ------------------------------\n\nconst sequelize = new Sequelize('test', 'test', 'test', {\n    host: 'localhost',\n    dialect: 'postgres'\n});\n\nconst Thing = sequelize.define('thing', {\n    name: Sequelize.STRING,\n    weight: Sequelize.MEASUREMENT\n});\n```\n\n```text\nC:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\abstract\\connection-manager.js:48\n        if (dataType.types[this.dialectName]) {                                                                         \n                          ^                                                                                             \n\nTypeError: Cannot read property 'postgres' of undefined                                                                 \n    at _.each.dataType (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\abstract\\connection-manager.js:48:27)                                                                                                                   \n    at C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:4911:15                                                \n    at baseForOwn (C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:2996:24)                                   \n    at C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:4880:18                                                \n    at Function.forEach (C:\\Workspaces\\nebula\\server\\node_modules\\lodash\\lodash.js:9344:14)                             \n    at ConnectionManager.refreshTypeParser (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\abstract\\connection-manager.js:46:7)                                                                                                \n    at new ConnectionManager (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\postgres\\connection-manager.js:23:10)                                                                                                             \n    at new PostgresDialect (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\dialects\\postgres\\index.js:14:30)    \n    at new Sequelize (C:\\Workspaces\\nebula\\server\\node_modules\\sequelize\\lib\\sequelize.js:320:20)                       \n    at Object.<anonymous> (C:\\Workspaces\\nebula\\server\\testsequelizecustom.js:58:19)                                    \n    at Module._compile (internal/modules/cjs/loader.js:689:30)                                                          \n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)                                            \n    at Module.load (internal/modules/cjs/loader.js:599:32)                                                              \n    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)                                                            \n    at Function.Module._load (internal/modules/cjs/loader.js:530:3)                                                     \n    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)                                                  \n    at startup (internal/bootstrap/node.js:279:19)                                                                      \n    at bootstrapNodeJSCore (internal/bootstrap/node.js:752:3)\n```\n\n```text\npgTypes.MEASUREMENT.parse = dataTypes.MEASUREMENT.parse;\n```\n\n```text\npgTypes.MEASUREMENT.types = {postgres:[‘MEASUREMENT’]};\n```\n\n```text\ndataTypes.postgres.MEASUREMENT.key = ‘MEASUREMENT’;\n```\n\n```text\n[...]/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:36\nif (dataType.key.toLowerCase() === 'range') {\n                         ^\n    \nTypeError: Cannot read property 'toLowerCase' of undefined\n```\n\n```text\npostgres\n```\n\n```text\ndataType.types\n```\n\n========================================\n\nComments:\n- I agree the docs could be improved. This is how I got inherits to work: const util = require('util'); // Built-in Node package util.inherits(PgTypes.MEASUREMENT, DataTypes.MEASUREMENT);","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":229,"estimatedTokens":2305}}427{"id":"stack-57009357","source":"stackoverflow","questionId":57009357,"title":"Sequelize Postgres - How to use ON CONFLICT for unique?","tags":["sql","node.js","postgresql","sequelize.js"],"text":"Title: Sequelize Postgres - How to use ON CONFLICT for unique?\nTags: sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am implementing `sequelize` into my NodeJS application. Before this, I was using a written INSERT query that used `ON CONFLICT (field) DO NOTHING` to handle not inserting records where a value needed to be unique.\n\n```\nconst sql = 'INSERT INTO communications (firstname, lastname, age, department, campus, state, message_uuid) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (message_uuid) DO NOTHING';\n\nconst values = [val.firstName, val.lastName, val.age, val.department, val.campus, val.state, message_uuid];\n```\n\nIs there support for this in sequelize where I can define the same thing within a model? Or perhaps a better way to handle it?\n\nEssentially, if a record already exists in the table in the column with `message_uuid` = 123 and another record try's to insert that has that same value, it ignores it and does nothing.\n\n========================================\n\nTop Answer:\nsee the new **UPSERT** feature in Sequelize **v6**:\n\nhttps://sequelize.org/api/v6/class/src/model.js~model#static-method-upsert\n\n**Implementation details:**\n\n- MySQL - Implemented with ON DUPLICATE KEY UPDATE`\nPostgreSQL - Implemented with ON CONFLICT DO UPDATE.\nIf update data contains PK field, then PK is selected as the default conflict\nkey. Otherwise first unique constraint/index will be selected, which\ncan satisfy conflict key requirements.\n\n- SQLite - Implemented with ON CONFLICT DO UPDATE\n\n- MSSQL - Implemented as a single query using MERGE and WHEN (NOT) MATCHED THEN\n\n========================================\n\nCode:\n```text\nconst sql = 'INSERT INTO communications (firstname, lastname, age, department, campus, state, message_uuid) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (message_uuid) DO NOTHING';\n\nconst values = [val.firstName, val.lastName, val.age, val.department, val.campus, val.state, message_uuid];\n```\n\n```text\nsequelize\n```\n\n```text\nON CONFLICT (field) DO NOTHING\n```\n\n```text\nmessage_uuid\n```\n\n```js\nimport { sequelize } from '../../db';\nimport { Model, DataTypes } from 'sequelize';\n\nclass Communication extends Model {}\nCommunication.init(\n  {\n    firstname: DataTypes.STRING,\n    lastname: DataTypes.STRING,\n    age: DataTypes.INTEGER,\n    message_uuid: {\n      type: DataTypes.INTEGER,\n      unique: true,\n    },\n  },\n  { sequelize, tableName: 'communications' },\n);\n\n(async function test() {\n  try {\n    await sequelize.sync({ force: true });\n    // seed\n    await Communication.create({ firstname: 'teresa', lastname: 'teng', age: 32, message_uuid: 123 });\n    // test\n    await Communication.bulkCreate([{ firstname: 'teresa', lastname: 'teng', age: 32, message_uuid: 123 }], {\n      ignoreDuplicates: true,\n    });\n  } catch (error) {\n    console.log(error);\n  } finally {\n    await sequelize.close();\n  }\n})();\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS \"communications\" CASCADE;\nExecuting (default): DROP TABLE IF EXISTS \"communications\" CASCADE;\nExecuting (default): CREATE TABLE IF NOT EXISTS \"communications\" (\"id\"   SERIAL , \"firstname\" VARCHAR(255), \"lastname\" VARCHAR(255), \"age\" INTEGER, \"message_uuid\" INTEGER UNIQUE, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'communications' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): INSERT INTO \"communications\" (\"id\",\"firstname\",\"lastname\",\"age\",\"message_uuid\") VALUES (DEFAULT,$1,$2,$3,$4) RETURNING *;\nExecuting (default): INSERT INTO \"communications\" (\"id\",\"firstname\",\"lastname\",\"age\",\"message_uuid\") VALUES (DEFAULT,'teresa','teng',32,123) ON CONFLICT DO NOTHING RETURNING *;\n```\n\n```text\nnode-sequelize-examples=# select * from communications;\n id | firstname | lastname | age | message_uuid \n----+-----------+----------+-----+--------------\n  1 | teresa    | teng     |  32 |          123\n(1 row)\n```\n\n```text\noptions.ignoreDuplicates\n```\n\n```text\nunique\n```\n\n```text\nmessage_uuid\n```\n\n```text\nON CONFLICT DO NOTHING\n```\n\n```text\n\"sequelize\": \"^5.21.3\"\n```\n\n```text\npostgres:9.6\n```\n\n```text\nModel.create\n```\n\n```text\nonConflict\n```\n\n========================================\n\nComments:\n- Did you ever figure this out? I'm wondering how to do the same.\n- There's also `ON CONFLICT DO UPDATE` support with `updateOnDuplicate`: stackoverflow.com/questions/55531860/&hellip;\n- Here's github search results for \"onConflict\" within sequelize source code: github.com/&hellip; Here's proof something like it exists, though: github.com/sequelize/sequelize/blob/master/lib/dialects/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":147,"estimatedTokens":1247}}428{"id":"stack-51338171","source":"stackoverflow","questionId":51338171,"title":"Postgres Foreign-key constraints in non public schema","tags":["postgresql","foreign-keys","sequelize.js"],"text":"Title: Postgres Foreign-key constraints in non public schema\nTags: postgresql, foreign-keys, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a question regarding *constraints* on custom schemas.\nMy app creates a new/separate schema for each clients corresponding with clients' name (i.e .***clienta***, ***clientb***,...). Some of the tables have a *foreign-key* constraints but, they don't work on schemas other than the default ***public*** schema. For example, let's say there is schema called *clienta* and it has *projects* and *tasks* tables, model *Task* has a belongsTo(models.Project) association (i.e ***projects*** table `primary_key` is a `foreign_key` for table ***tasks***. The issue starts here: when trying to create a record in table ***tasks*** there comes an error saying `foreign key violation error... Key (project_id)=(1) is not present in table \"projects...` even though ***projects*** table has the respective record with id = 1. I am wording if this is a limitation of `sequelize` library itself or am I missing something in the configs?\n\n**Sequelize config**\n\n```\n\"development\": {\n \"database\": \"my_app\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"postgres\",\n \"operatorsAliases\": \"Sequelize.Op\",\n \"dialectOptions\": {\n \"prependSearchPath\": true\n },\n \"define\": {\n \"underscored\": true\n }\n }\n```\n\n**Example of create function:**\n\n`models.Task.create({...args}, { searchPath: 'clienta' })`\n\n***N.B*** Everything works as expected in *public* schema.\n\n========================================\n\nCode:\n```text\n\"development\": {\n    \"database\": \"my_app\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"postgres\",\n    \"operatorsAliases\": \"Sequelize.Op\",\n    \"dialectOptions\": {\n      \"prependSearchPath\": true\n    },\n    \"define\": {\n      \"underscored\": true\n    }\n  }\n```\n\n```text\nprimary_key\n```\n\n```text\nforeign_key\n```\n\n```text\nforeign key violation error... Key (project_id)=(1) is not present in table \"projects...\n```\n\n```text\nsequelize\n```\n\n```text\nmodels.Task.create({...args}, { searchPath: 'clienta' })\n```\n\n========================================\n\nComments:\n- Please post the exact DDL that fails, and the error you while tryng to execute it.\n- The main message in the error log the one I posted above. The question is not specific to one issue. It is more of a config/setup or knowing what sequelize library can offer and cant'.\n- @bir_ham The problem seems to be that the tables that are created have constraints that are not correctly lined up if they have a schema that is different from public. The minimum information required would be how you have defined the constraints there. If I were a betting man, I would guess that your constraints for 'clienta' tables actually depend on tables with schema 'public' - but that constitutes gambling (this can be checked rather easily using pgAdmin or any tool like that).\n- @Koen That was also my initial assumption and removed the constraints for tables in public schema. However, constraints of tables within the same schemas keeps on falling. As I stated in my question table *projects* and *tasks* lives in same schema (*clienta*, *clientb*, or any schema)\n- @bir_ham - the question is - when you define the constraint - do you refer to the public table or to the specific table within the same schema? Hence the request for the definition.\n- @Koen You're very right! My constraints were prefixed with 'public'. I created my tables dynamically using sequelize's model `sync` helper (e.g Project.sync({schema: testa})) and this indeed creates a table however, not enough to assign constraints to corresponding schema. I added the `searchPath` options to `sync` (e.g `Model.sync({schema: testa, searchPath: testa})`) and now got it work. Thanks! You deserve the bounty prize!","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":78,"estimatedTokens":936}}429{"id":"stack-39176419","source":"stackoverflow","questionId":39176419,"title":"What is the difference between connection pooling and max_connections?","tags":["database","postgresql","sequelize.js","amazon-rds"],"text":"Title: What is the difference between connection pooling and max_connections?\nTags: database, postgresql, sequelize.js, amazon-rds\nSource: Stack Overflow\n\nQuestion:\nI am using Postgres with Sequelize as the ORM / query interface. Recently we started hitting some errors:\n\n```\nSequelizeConnectionError: remaining connection slots are reserved for non-replication superuser connections\n```\n\nLooking into it, the problem seems to be related to the connection limits set for Postgres, but I was having some trouble figuring out how to relate the client-side pooling settings with the Postgres settings:\n\nOn my postgres 9.4 database (on Amazon RDS), my `max_connections` is defaulted to 26:\n\n```\nSELECT name, setting FROM pg_settings WHERE name='max_connections';\n+-----------------+---------+\n| name | setting |\n+-----------------+---------+\n| max_connections | 26 |\n+-----------------+---------+\n```\n\nIn Sequelize, I have my pool set to:\n\n```\npool: {\n max: 10,\n min: 0,\n idle: 10000\n},\n```\n\nSome questions:\n\n- In general how does the pool relate to `max_connections`?\n\n- Does each connection in the pool take 1 count out of the `max_connections`?\n\n- Does this mean that the pool max must always be smaller than the `max_connections`?\n\n- Would lowering the idle timeout on the pool help free connections faster?\n\n========================================\n\nCode:\n```text\nSequelizeConnectionError: remaining connection slots are reserved for non-replication superuser connections\n```\n\n```text\nSELECT name, setting FROM pg_settings WHERE name='max_connections';\n+-----------------+---------+\n| name            | setting |\n+-----------------+---------+\n| max_connections | 26      |\n+-----------------+---------+\n```\n\n```text\npool: {\n  max: 10,\n  min: 0,\n  idle: 10000\n},\n```\n\n```text\nmax_connections\n```\n\n```text\nmax_connections\n```\n\n```text\nmax_connections\n```\n\n```text\nmax_connections\n```\n\n```text\nSELECT * FROM pg_stat_activity\n```\n\n```text\nmax_connections\n```\n\n```text\nmax_connections\n```\n\n```text\nmax_connections\n```\n\n```text\nsuperuser_reserved_connections\n```\n\n========================================\n\nComments:\n- Thanks! This was very helpful. We are not using heroku, our apps are deployed on EC2.","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":108,"estimatedTokens":550}}430{"id":"stack-60774899","source":"stackoverflow","questionId":60774899,"title":"Set optimistic locking as global option in node , sequelize","tags":["node.js","sequelize.js"],"text":"Title: Set optimistic locking as global option in node , sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to set up sequelize in my node project and for now I have\n\n```\n//sequelize init\nconst { DataTypes } = Sequelize;\nconst sequelize = new Sequelize({\n database: database,\n username: user,\n host: server, \n password: password,\n dialect: 'mssql',\n dialectOptions: {\n options: {\n useUTC: true,\n dateFirst: 1,\n }\n },\n define:{\n timestamps:false,\n paranoid:false,\n freezeTableName: true\n }\n});\n\n//and my Model \n const User= sequelize.define('User', {\n // attributes\n id: {\n field:'Id',\n type: Sequelize.INTEGER,\n allowNull: false,\n primaryKey: true\n } ,\n startTime: {\n field:'startTime',\n type: Sequelize.DATE\n } \n });\n```\n\nI try to setup `version:true` to enable Optimistic Locking\nI put it in model\n\n```\nconst Vessel = sequelize.define('FDMData', {\n // attributes\n id: {\n field:'vesselId',\n type: Sequelize.INTEGER,\n allowNull: false,\n primaryKey: true\n } ,\n startTime: {\n field:'startTime',\n type: Sequelize.DATE\n } \n },{\n version:true\n }\n);\n```\n\nand I get `Unhandled rejection SequelizeDatabaseError: Invalid column name 'version'.`\n\nI also tried to set it as global while init\n\n```\nconst { DataTypes } = Sequelize;\nconst sequelize = new Sequelize({\n database: database,\n username: user,\n host: server, \n password: password,\n dialect: 'mssql',\n dialectOptions: {\n options: {\n useUTC: true,\n dateFirst: 1,\n }\n },\n define:{\n timestamps:false,\n paranoid:false,\n freezeTableName: true,\n version: true\n }\n});\n```\n\nand again, I get `Unhandled rejection SequelizeDatabaseError: Invalid column name 'version'.`\n\nWhat am I missing? How can I fix this?\n\nThanks\n\n========================================\n\nTop Answer:\nyou are almost there, based on the docs, setting version to true or set it to whatever name you want do the trick\n\n Enable optimistic locking. When enabled, sequelize will add a version count attribute\n to the model and throw an OptimisticLockingError error when stale instances are saved.\n Set to true or a string with the attribute name you want to use to enable.\n\nhowever, just in the next section to optimistic locking -Database synchronization- it says\n\n When starting a new project you won't have a database structure and using Sequelize you won't need to\n\nmeaning, sequelize doesn't depend on a sql structure already set in your database for this purpose if you sync your models after you define them except for the database definition, it will automatically create it for you including the version field, here is an example\n\n```\nconst Sequelize = require('sequelize');\nconst config = {\n username: \"root\",\n password: \"123\",\n tableName: \"test\",\n options: {\n host: '127.0.0.1',\n dialect: 'mysql',\n pool: {\n max: 3,\n min: 1,\n acquire: 30000,\n idle: 10000\n },\n define: {\n timestamps:false,\n paranoid:false,\n freezeTableName: true,\n version: true\n }\n }\n};\nconst sequelize = new Sequelize(config.tableName, config.username, config.password, config.options);\n\n//and my Model \n const User= sequelize.define('User', {\n // attributes\n id: {\n field:'Id',\n type: Sequelize.INTEGER,\n allowNull: false,\n primaryKey: true\n } ,\n startTime: {\n field:'startTime',\n type: Sequelize.DATE\n } \n });\n\nUser.sync();\n```\n\nif you run this script you will see the following sql statements executed\n\n Executing (default): CREATE TABLE IF NOT EXISTS `User` (`Id` INTEGER\n NOT NULL , `startTime` DATETIME, `version` INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (`Id`)) ENGINE=InnoDB; \n Executing (default): SHOW INDEX FROM `User`\n\nhowever, if you don't want sequelize to sync your models, you have to explicitly have that field in your already established tables, but not explicitly defined in sequelize model as it will automatically know its there.\n\n========================================\n\nCode:\n```text\n//sequelize init\nconst { DataTypes } = Sequelize;\nconst sequelize = new Sequelize({\n  database: database,\n  username: user,\n  host: server, \n  password: password,\n  dialect: 'mssql',\n  dialectOptions: {\n    options: {\n      useUTC: true,\n      dateFirst: 1,\n    }\n  },\n  define:{\n      timestamps:false,\n      paranoid:false,\n      freezeTableName: true\n  }\n});\n\n//and my Model \n  const User= sequelize.define('User', {\n    // attributes\n    id: {\n      field:'Id',\n      type: Sequelize.INTEGER,\n      allowNull: false,\n      primaryKey: true\n    } ,\n    startTime: {\n      field:'startTime',\n      type: Sequelize.DATE\n    } \n  });\n```\n\n```text\nconst Vessel = sequelize.define('FDMData', {\n    // attributes\n    id: {\n      field:'vesselId',\n      type: Sequelize.INTEGER,\n      allowNull: false,\n      primaryKey: true\n    } ,\n    startTime: {\n      field:'startTime',\n      type: Sequelize.DATE\n    } \n  },{\n    version:true\n   }\n);\n```\n\n```text\nconst { DataTypes } = Sequelize;\nconst sequelize = new Sequelize({\n  database: database,\n  username: user,\n  host: server, \n  password: password,\n  dialect: 'mssql',\n  dialectOptions: {\n    options: {\n      useUTC: true,\n      dateFirst: 1,\n    }\n  },\n  define:{\n      timestamps:false,\n      paranoid:false,\n      freezeTableName: true,\n      version: true\n  }\n});\n```\n\n```text\nversion:true\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: Invalid column name 'version'.\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: Invalid column name 'version'.\n```\n\n```text\nCREATE TABLE IF NOT EXISTS FDMData (\n    vesselId INTEGER NOT NULL , \n    startTime DATETIME, \n    version INTEGER NOT NULL DEFAULT 0, \n    PRIMARY KEY (vesselId)\n)\n```\n\n```text\nVessel.sync().then(model=> {\n// or sequelize.sync()\n    console.log(model)\n}).catch(error=> {\n    console.log(error)\n})\n```\n\n```text\nversion: true\n```\n\n```text\nversion\n```\n\n```text\nversion INTEGER NOT NULL DEFAULT 0\n```\n\n```text\nversion: \"myVersionColumn\"\n```\n\n```text\nFDMData\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst config = {\n  username: \"root\",\n  password: \"123\",\n  tableName: \"test\",\n  options: {\n      host: '127.0.0.1',\n      dialect: 'mysql',\n      pool: {\n        max: 3,\n        min: 1,\n        acquire: 30000,\n        idle: 10000\n      },\n      define: {\n        timestamps:false,\n        paranoid:false,\n        freezeTableName: true,\n        version: true\n      }\n    }\n};\nconst sequelize = new Sequelize(config.tableName, config.username, config.password, config.options);\n\n//and my Model \n  const User= sequelize.define('User', {\n    // attributes\n    id: {\n      field:'Id',\n      type: Sequelize.INTEGER,\n      allowNull: false,\n      primaryKey: true\n    } ,\n    startTime: {\n      field:'startTime',\n      type: Sequelize.DATE\n    } \n  });\n\nUser.sync();\n```\n\n```text\nUser\n```\n\n```text\nId\n```\n\n```text\nstartTime\n```\n\n```text\nversion\n```\n\n```text\nId\n```\n\n```text\nUser\n```\n\n```text\nconst { Sequelize, Model, DataTypes, Deferrable, DatabaseError } = require('sequelize');\nconst sequelize = require('../lib/db.sequelize').db;\n\nclass User extends Model {\n\n}\n\nUser.init({\n    // The following specification of the 'id' attribute could be omitted\n    // since it is the default.\n    id: {\n        allowNull: false,\n        primaryKey: true,\n        type: DataTypes.UUID,\n        defaultValue: DataTypes.UUIDV4,\n    },\n    version: { // Optimistic Locking\n        allowNull: false,\n        type: DataTypes.INTEGER,\n        defaultValue: 0\n    },\n    name: {\n        allowNull: false,\n        type: DataTypes.STRING,\n    },\n    email: {\n        allowNull: false,\n        type: DataTypes.STRING,\n        unique: true,\n        validate: {\n            isEmail: true\n        }\n    }\n}, {\n    sequelize,\n    modelName: 'user',\n    version: true, // Optimistic Locking\n    indexes: [\n        {\n            name: 'user_id_index',\n            method: 'BTREE',\n            fields: ['id'],\n        },\n        {\n            name: 'user_email_index',\n            method: 'BTREE',\n            fields: ['email'],\n        }\n    ],\n    freezeTableName: true\n});\n\nmodule.exports = User;\n```\n\n```text\ncolumn \"version\" does not exist\n```\n\n```text\nversion: true\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nversion\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nversion: true\n```\n\n========================================\n\nComments:\n- Which OS and DB server are you using?\n- What is your sequelize version?\n- This didn't work for me. I created a version-column and set version equal to the respective column in the database. The DDL is generated the way your table is, but inserting values into the the table does not modify the version-column","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":457,"estimatedTokens":2124}}431{"id":"stack-54857436","source":"stackoverflow","questionId":54857436,"title":"Get error connect ECONNREFUSED 127.0.0.1:3306 when start my node.js app","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Get error connect ECONNREFUSED 127.0.0.1:3306 when start my node.js app\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen I start my node.js app I get this error:\n\n```\nSequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306\n```\n\nWhat I was doing:\n\n```\n- create a user:\nCREATE USER 'main'@'localhost' IDENTIFIED BY 'myPass';\n\n - give this user all privileges\nGRANT ALL PRIVILEGES ON *.* TO 'main'@'localhost' WITH GRANT OPTION;\nFLUSH PRIVILEGES;\n```\n\nI then try to connect through my code on production and it gives me an error: connect ECONNREFUSED 127.0.0.1:3306.\n\nBut in my localhost environment it connects well. And when I try to connect to DB using command line on VPS it works too:\n`mysql -umain -p`\n\nI can't connect with code. But on my localhost it connects. Double checked my loggin and pass for DB user in .env.\n\n========================================\n\nTop Answer:\nTry restarting the MySQL service.\n\n========================================\n\nCode:\n```text\nSequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306\n```\n\n```text\n- create a user:\nCREATE USER 'main'@'localhost' IDENTIFIED BY 'myPass';\n\n - give this user all privileges\nGRANT ALL PRIVILEGES ON *.* TO 'main'@'localhost' WITH GRANT OPTION;\nFLUSH PRIVILEGES;\n```\n\n```text\nmysql -umain -p\n```\n\n```text\nbind-address = my VPS ip\n```\n\n```text\nconst sequelize = new Sequelize('db-name', 'user', 'password', {\n  host: 'localhost',\n  dialect: 'mysql',\n  dialectOptions: {\n    socketPath: 'your socket path',\n    supportBigNumbers: true,\n    bigNumberStrings: true\n  },\n});\n```\n\n```text\nuser        = mysql\n# pid-file  = /var/run/mysqld/mysqld.pid\n# socket    = /var/run/mysqld/mysqld.sock\n# port      = 3306\n# datadir   = /var/lib/mysql\n```\n\n========================================\n\nComments:\n- Could you show us the code that connects. And also, how do you start your app.?\n- This worked for me. I had to restart both mysql and nginx and then try to start the server again.","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":502}}432{"id":"stack-31464074","source":"stackoverflow","questionId":31464074,"title":"Updating error in sequelize","tags":["mysql","sequelize.js"],"text":"Title: Updating error in sequelize\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhat kind of error is this?\n\n```\nUnhandled rejection SequelizeDatabaseError: ER_EMPTY_QUERY: Query was empty\n at Query.formatError (node_modules/sequelize/lib/dialects/mysql/query.js:159:14)\n at Query._callback (node_modules/sequelize/lib/dialects/mysql/query.js:35:21)\n at Query.Sequence.end (node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n at Query.ErrorPacket (node_modules/mysql/lib/protocol/sequences/Query.js:94:8)\n at Protocol._parsePacket (node_modules/mysql/lib/protocol/Protocol.js:274:23)\n at Parser.write (node_modules/mysql/lib/protocol/Parser.js:77:12)\n at Protocol.write (node_modules/mysql/lib/protocol/Protocol.js:39:16)\n at Socket. (node_modules/mysql/lib/Connection.js:96:28)\n at Socket.emit (events.js:107:17)\n at readableAddChunk (_stream_readable.js:163:16)\n at Socket.Readable.push (_stream_readable.js:126:10)\n at TCP.onread (net.js:538:20)\n```\n\nI'm trying to update an entity with the following code:\n\n```\ndb.Account.update({\n 'post_id': data.id\n }, {\n where: { id: account.id }\n })\n .spread(account => {\n\n next();\n });\n```\n\nbut it doesn't work. Any idea?\n\n========================================\n\nCode:\n```text\nUnhandled rejection SequelizeDatabaseError: ER_EMPTY_QUERY: Query was empty\n    at Query.formatError (node_modules/sequelize/lib/dialects/mysql/query.js:159:14)\n    at Query._callback (node_modules/sequelize/lib/dialects/mysql/query.js:35:21)\n    at Query.Sequence.end (node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n    at Query.ErrorPacket (node_modules/mysql/lib/protocol/sequences/Query.js:94:8)\n    at Protocol._parsePacket (node_modules/mysql/lib/protocol/Protocol.js:274:23)\n    at Parser.write (node_modules/mysql/lib/protocol/Parser.js:77:12)\n    at Protocol.write (node_modules/mysql/lib/protocol/Protocol.js:39:16)\n    at Socket.<anonymous> (node_modules/mysql/lib/Connection.js:96:28)\n    at Socket.emit (events.js:107:17)\n    at readableAddChunk (_stream_readable.js:163:16)\n    at Socket.Readable.push (_stream_readable.js:126:10)\n    at TCP.onread (net.js:538:20)\n```\n\n```text\ndb.Account.update({\n                    'post_id': data.id\n                }, {\n                  where: { id: account.id }\n                })\n                .spread(account => {\n\n                  next();\n                });\n```\n\n========================================\n\nComments:\n- Are you sure the column is called `post_id` - maybe its actually `postId` ?\n- Having this error as well, did you came up with some solution?\n- sounds like something is undefined. either data.id or account.id is undefined and it can't create a query.\n- I had misspelled a column name by not capitalizing a letter correctly (facepalm moment) -- check your casing and spelling!\n- Just for reference of others - This \"Query was Empty\" error occurs in case there is no change in the data. Ref.- stackoverflow.com/questions/48061748/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.374Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":78,"estimatedTokens":744}}433{"id":"stack-66315022","source":"stackoverflow","questionId":66315022,"title":"TypeError: Class constructor model cannot be invoked without 'new'","tags":["javascript","node.js","ecmascript-6","sequelize.js","babeljs"],"text":"Title: TypeError: Class constructor model cannot be invoked without 'new'\nTags: javascript, node.js, ecmascript-6, sequelize.js, babeljs\nSource: Stack Overflow\n\nQuestion:\nI'm using **Sequelize** together with **Node** and **JavaScript** in one app. As you know when you execute `sequelize-init` it creates *config*, *migrations*, *models* and *seeders* folder. Inside of the *models* folder, there is an `index.js` file (generated by the cli), which is responsible for reading all of the models and their associations from the current folder:\n\nindex.js\n\n```\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst sequelize = require('../database/connection');\nconst db = {};\n\nfs\n .readdirSync(__dirname)\n .filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n .forEach(file => {\n const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nWhen I run my app, an error appears: **TypeError: Class constructor model cannot be invoked without 'new'** at line 17 which is the statement: **var model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);** Reading some of the posts related to this problem I found out that I need to install the `@babel/preset-env` package along with `@babel/cli, @babel/core, @babel/node`. I also created a `.babelrc` file in the root directory, containing the following code:\n\n.babelrc\n\n```\n{\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"targets\": {\n \"esmodules\": true\n }\n }\n ]\n ]\n}\n```\n\nand updated my `start` option of the `scripts` tag inside `package.json` to: `\"nodemon --exec babel-node app.js\"` (I don't use webpack)\n\nBut when I run the app the error still appears. What do I miss or haven't set correctly?\n\n========================================\n\nTop Answer:\nIf you have \"es5\" in \"target\" in tsconfig.json file, changes to \"es6\". (that worked for me, and I needed the es6 in compiler.)\n\n```\n\"compilerOptions\": {\n \"target\": \"es6\"\n}\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst sequelize = require('../database/connection');\nconst db = {};\n\nfs\n  .readdirSync(__dirname)\n  .filter(file => {\n    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n  })\n  .forEach(file => {\n    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(modelName => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n{\n    \"presets\": [\n      [\n        \"@babel/preset-env\",\n        {\n          \"targets\": {\n            \"esmodules\": true\n          }\n        }\n      ]\n    ]\n}\n```\n\n```text\nsequelize-init\n```\n\n```text\nindex.js\n```\n\n```text\n@babel/preset-env\n```\n\n```text\n@babel/cli, @babel/core, @babel/node\n```\n\n```text\n.babelrc\n```\n\n```text\nstart\n```\n\n```text\nscripts\n```\n\n```text\npackage.json\n```\n\n```text\n\"nodemon --exec babel-node app.js\"\n```\n\n```text\nexport class Course extends Model {} // <== ES6 classes\n\nCourse.init({\n```\n\n```json\n{\n  \"presets\": [\n    [\"env\", {\n      \"targets\": {\n        \"node\": \"current\"\n      }\n    }]\n  ]\n}\n```\n\n```json\n{\n  \"presets\": [\n    [\n      \"@babel/preset-env\",\n      {\n        \"targets\": {\n          \"node\": true\n        }\n      }\n    ]\n  ]\n}\n```\n\n```text\nexport const User = sequelize.define('User', {\n  // Model attributes are defined here\n  firstName: {\n    type: DataTypes.STRING,\n    allowNull: false\n  },\n```\n\n```json\n\"target\": \"ES2021\",\n```\n\n```text\nSequelize.import\n```\n\n```text\nsequelize.define()\n```\n\n```text\nrequire\n```\n\n```text\nimport\n```\n\n```text\nES5\n```\n\n```text\ntranspilation of ES6 Class to ES5 can be done to support full features and compatiblity\n```\n\n```text\n\"compilerOptions\": {\n    \"target\": \"es6\"\n}\n```\n\n```text\n@Table\nexport class Kondo extends Model {\n\nconstructor(partial?: Partial<Kondo>) {\n  super();\n    \n  if (partial)\n    Object.assign(this, partial);\n}\n```\n\n========================================\n\nComments:\n- You don't need to install babel for a node.js program! You just need to use new instead of calling a class as a function (just like the error is telling you): `const ThingThatIsAClass = require(path.join(__dirname, file)); const model = new ThingThatIsAClass(sequelize, Sequelize.DataTypes);` Don't try to cram so much on to a single line of code. It's hard to read, and makes it easy to miss trivial mistakes like this one.\n- I apologize for my incompetence, I didn't know that. I understood that the error is with the way of invoking the constructor, but never though to split the statement. Thank you!\n- You don't have to split the statement, you can also write `new (require(…))(…)` but that's even harder to understand.\n- @CodiClone no apology needed, programming is hard and inexperience is not a moral failing :)\n- Thank you for the detailed explanation!","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":257,"estimatedTokens":1348}}434{"id":"stack-43151613","source":"stackoverflow","questionId":43151613,"title":"Sequelize dynamic seeding","tags":["javascript","sequelize.js","seeding"],"text":"Title: Sequelize dynamic seeding\nTags: javascript, sequelize.js, seeding\nSource: Stack Overflow\n\nQuestion:\nI'm currently seeding data with Sequelize.js and using hard coded values for association IDs. This is not ideal because I really should be able to do this dynamically right? For example, associating users and profiles with a \"has one\" and \"belongs to\" association. I don't necessarily want to seed users with a hard coded `profileId`. I'd rather do that in the profiles seeds after I create profiles. Adding the `profileId` to a user dynamically once profiles have been created. Is this possible and the normal convention when working with Sequelize.js? Or is it more common to just hard code association IDs when seeding with Sequelize?\n\nPerhaps I'm going about seeding wrong? Should I have a one-to-one number of seeds files with migrations files using Sequelize? In Rails, there is usually only 1 seeds file you have the option of breaking out into multiple files if you want.\n\nIn general, just looking for guidance and advice here. These are my files:\n\nusers.js\n\n```\n// User seeds\n\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n /*\n Add altering commands here.\n Return a promise to correctly handle asynchronicity.\n\n Example:\n return queryInterface.bulkInsert('Person', [{\n name: 'John Doe',\n isBetaMember: false\n }], {});\n */\n\n var users = [];\n for (let i = 0; i profiles.js\n\n```\n// Profile seeds\n\n'use strict';\nvar models = require('./../models');\nvar User = models.User;\nvar Profile = models.Profile;\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n /*\n Add altering commands here.\n Return a promise to correctly handle asynchronicity.\n\n Example:\n return queryInterface.bulkInsert('Person', [{\n name: 'John Doe',\n isBetaMember: false\n }], {});\n */\n\n var profiles = [];\n var genders = ['m', 'f'];\n for (let i = 0; i As you can see I'm just using a hard coded `for` loop for both (not ideal).\n\n========================================\n\nTop Answer:\nWARNING: after working with sequelize for over a year, I've come to realize that my suggestion is a very bad practice. I'll explain at the bottom.\n\ntl;dr:\n\n- never use seeders, only use migrations\n\n- never use your sequelize models in migrations, only write explicit SQL\n\nMy other suggestion still holds up that you use some \"configuration\" to drive the generation of seed data. (But that seed data should be inserted via migration.)\n\n**vv DO NOT DO THIS vv**\n\nHere's another pattern, which I prefer, because I believe it is more flexible and more readily understood. I offer it here as an alternative to the accepted answer (which seems fine to me, btw), in case others find it a better fit for their circumstances.\n\nThe strategy is to leverage the sqlz models you've already defined to fetch data that was created by other seeders, use that data to generate whatever new associations you want, and then use `bulkInsert` to insert the new rows.\n\nIn this example, I'm tracking a set of people and the cars they own. My models/tables:\n\n- `Driver`: a real person, who may own one or more real cars\n\n- `Car`: not a specific car, but a *type* of car that could be owned by someone (i.e. `make` + `model`)\n\n- `DriverCar`: a real car owned by a real person, with a color and a year they bought it\n\nWe will assume a previous seeder has stocked the database with all known `Car` types: that information is already available and we don't want to burden users with unnecessary data entry when we can bundle that data in the system. We will also assume there are already `Driver` rows in there, either through seeding or because the system is in-use.\n\nThe goal is to generate a whole bunch of fake-but-plausible `DriverCar` relationships from those two data sources, in an automated way.\n\n```\nconst {\n Driver,\n Car\n} = require('models')\n\nmodule.exports = {\n\n up: async (queryInterface, Sequelize) => {\n\n // fetch base entities that were created by previous seeders\n // these will be used to create seed relationships\n\n const [ drivers , cars ] = await Promise.all([\n Driver.findAll({ /* limit ? */ order: Sequelize.fn( 'RANDOM' ) }),\n Car.findAll({ /* limit ? */ order: Sequelize.fn( 'RANDOM' ) })\n ])\n\n const fakeDriverCars = Array(30).fill().map((_, i) => {\n // create new tuples that reference drivers & cars,\n // and which reflect the schema of the DriverCar table\n })\n\n return queryInterface.bulkInsert( 'DriverCar', fakeDriverCars );\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.bulkDelete('DriverCar');\n }\n}\n```\n\nThat's a partial implementation. However, it omits some key details, because there are a million ways to skin that cat. Those pieces can all be gathered under the heading \"configuration,\" and we should talk about it now.\n\nWhen you generate seed data, you usually have requirements like:\n\n- I want to create at least a hundred of them, or\n\n- I want their properties determined randomly from an acceptable set, or\n\n- I want to create a web of relationships shaped exactly like *this*\n\nYou could try to hard-code that stuff into your algorithm, but that's the hard way. What I like to do is declare \"configuration\" at the top of the seeder, to capture the skeleton of the desired seed data. Then, within the tuple-generation function, I use that config to procedurally generate real rows. That configuration can obviously be expressed however you like. I try to put it all into a single `CONFIG` object so it all stays together and so I can easily locate all the references within the seeder implementation.\n\nYour configuration will probably imply reasonable `limit` values for your `findAll` calls. It will also probably specify all the factors that should be used to calculate the number of seed rows to generate (either by explicitly stating `quantity: 30`, or through a combinatoric algorithm).\n\nAs food for thought, here is an example of a *very* simple config that I used with this DriverCar system to ensure that I had 2 drivers who each owned one overlapping car (with the specific cars to be chosen randomly at runtime):\n\n```\nconst CONFIG = {\n ownership: [\n [ 'a', 'b', 'c', 'd' ], // driver 1 linked to cars a, b, c, and d\n [ 'b' ], // driver 2 linked to car b\n [ 'b', 'b' ] // driver 3 has two of the same kind of car\n ]\n};\n```\n\nI actually used those letters, too. At runtime, the seeder implementation would determine that only 3 unique `Driver` rows and 4 unique `Car` rows were needed, and apply `limit: 3` to `Driver.findAll`, and `limit: 4` to `Car.findAll`. Then it would assign a real, randomly-chosen `Car` instance to each unique string. Finally, when generating association tuples, it uses the string to look up the chosen `Car` from which to pull foreign keys and other values.\n\nThere are undoubtedly fancier ways of specifying a template for seed data. Skin that cat however you like. Hopefully this makes it clear how you'd marry your chosen algorithm to your actual sqlz implementation to generate coherent seed data.\n\n### Why the above is bad\n\nIf you use your sequelize models in migration or seeder files, you will inevitably create a situation in which the application will not build successfully from a clean slate.\n\nHow to avoid madness:\n\n- **Never use seeders, only use migrations**\n\n(Anything you can do in a seeder, you can do in a migration. Bear that in mind as I enumerate the problems with seeders, because that means none of these problems gain you anything.)\n\nBy default, sequelize does not keep records of which seeders have been run. Yes, you can configure it to keep records, but if the app has already been deployed without that setting, then when you deploy your app with the new setting, it'll still re-run all your seeders one last time. If that's not safe, your app will blow up. My experience is that seed data can't and shouldn't be duplicated: if it doesn't immediately violate uniqueness constraints, it'll create duplicate rows.\n\nRunning seeders is a separate command, which you then need to integrate into your startup scripts. It's easy for that to lead to a proliferation of npm scripts that make app startup harder to . In one project, I converted the only 2 seeders into migrations, and reduced the number of startup-related npm scripts from 13 to 5.\n\nIt's been hard to pin down, but it can be hard to make sense of the order in which seeders are run. Remember also that the commands are separate for running migrations and seeders, which means you can't interleave them efficiently. You'll have to run all migrations first, then run all seeders. As the database changes over time, you'll run into the problem I describe next:\n\n- **Never use your sequelize models in your migrations**\n\nWhen you use a sequelize model to fetch records, it explicitly fetches every column it knows about. So, imagine a migration sequence like this:\n\n- M1: create tables Car & Driver\n\n- M2: use Car & Driver models to generate seed data\n\nThat will work. Fast-forward to a date when you add a new column to Car (say, `isElectric`). That involves: (1) creating a migraiton to add the column, and (2) declaring the new column on the sequelize model. Now your migration process looks like this:\n\n- M1: create tables Car & Driver\n\n- M2: use Car & Driver models to generate seed data\n\n- M3: add `isElectric` to Car\n\nThe problem is that your sequelize models always reflect the *final* schema, without acknowledging the fact that the actual database is built by ordered accretion of mutations. So, in our example, M2 will fail because any built-in selection method (e.g. `Car.findOne`) will execute a SQL query like:\n\n```\nSELECT\n \"Car\".\"make\" AS \"Car.make\",\n \"Car\".\"isElectric\" AS \"Car.isElectric\"\nFROM\n \"Car\"\n```\n\nYour DB will throw because Car doesn't have an `isElectric` column when M2 executes.\n\nThe problem won't occur in environments that are only one migration behind, but you're boned if you hire a new developer or nuke the database on your local workstation and build the app from scratch.\n\n========================================\n\nCode:\n```text\n// User seeds\n\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    /*\n      Add altering commands here.\n      Return a promise to correctly handle asynchronicity.\n\n      Example:\n      return queryInterface.bulkInsert('Person', [{\n        name: 'John Doe',\n        isBetaMember: false\n      }], {});\n    */\n\n    var users = [];\n    for (let i = 0; i < 10; i++) {\n      users.push({\n        fname: \"Foo\",\n        lname: \"Bar\",\n        username: `foobar${i}`,\n        email: `foobar${i}@gmail.com`,\n        profileId: i + 1\n      });\n    }\n    return queryInterface.bulkInsert('Users', users);\n  },\n\n  down: function (queryInterface, Sequelize) {\n    /*\n      Add reverting commands here.\n      Return a promise to correctly handle asynchronicity.\n\n      Example:\n      return queryInterface.bulkDelete('Person', null, {});\n    */\n    return queryInterface.bulkDelete('Users', null, {});\n  }\n};\n```\n\n```text\n// Profile seeds\n\n'use strict';\nvar models = require('./../models');\nvar User = models.User;\nvar Profile = models.Profile;\n\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    /*\n      Add altering commands here.\n      Return a promise to correctly handle asynchronicity.\n\n      Example:\n      return queryInterface.bulkInsert('Person', [{\n        name: 'John Doe',\n        isBetaMember: false\n      }], {});\n    */\n\n    var profiles = [];\n    var genders = ['m', 'f'];\n    for (let i = 0; i < 10; i++) {\n      profiles.push({\n        birthday: new Date(),\n        gender: genders[Math.round(Math.random())],\n        occupation: 'Dev',\n        description: 'Cool yo',\n        userId: i + 1\n      });\n    }\n    return queryInterface.bulkInsert('Profiles', profiles);\n  },\n\n  down: function (queryInterface, Sequelize) {\n    /*\n      Add reverting commands here.\n      Return a promise to correctly handle asynchronicity.\n\n      Example:\n      return queryInterface.bulkDelete('Person', null, {});\n    */\n    return queryInterface.bulkDelete('Profiles', null, {});\n  }\n};\n```\n\n```text\nprofileId\n```\n\n```text\nprofileId\n```\n\n```text\nfor\n```\n\n```text\nup: function (queryInterface, Sequelize) {\n  return Promise.all([\n    models.Profile.create({\n        data: 'profile stuff',\n        users: [{\n          name: \"name\",\n          ...\n        }, {\n          name: 'another user',\n          ...\n        }]}, {\n        include: [ model.users]\n      }\n    ),\n    models.Profile.create({\n      data: 'another profile',\n      users: [{\n        name: \"more users\",\n        ...\n      }, {\n        name: 'another user',\n        ...\n      }]}, {\n        include: [ model.users]\n      }\n    )\n  ])\n}\n```\n\n```text\ncreate()\n```\n\n```text\nPromise.all()\n```\n\n```text\nconst {\n    Driver,\n    Car\n} = require('models')\n\nmodule.exports = {\n\n    up: async (queryInterface, Sequelize) => {\n\n        // fetch base entities that were created by previous seeders\n        // these will be used to create seed relationships\n\n        const [ drivers , cars ] = await Promise.all([\n            Driver.findAll({ /* limit ? */ order: Sequelize.fn( 'RANDOM' ) }),\n            Car.findAll({ /* limit ? */ order: Sequelize.fn( 'RANDOM' ) })\n        ])\n\n        const fakeDriverCars = Array(30).fill().map((_, i) => {\n            // create new tuples that reference drivers & cars,\n            // and which reflect the schema of the DriverCar table\n        })\n\n        return queryInterface.bulkInsert( 'DriverCar', fakeDriverCars );\n    },\n\n    down: (queryInterface, Sequelize) => {\n        return queryInterface.bulkDelete('DriverCar');\n    }\n}\n```\n\n```text\nconst CONFIG = {\n    ownership: [\n        [ 'a', 'b', 'c', 'd' ], // driver 1 linked to cars a, b, c, and d\n        [ 'b' ],                // driver 2 linked to car b\n        [ 'b', 'b' ]            // driver 3 has two of the same kind of car\n    ]\n};\n```\n\n```text\nSELECT\n  \"Car\".\"make\" AS \"Car.make\",\n  \"Car\".\"isElectric\" AS \"Car.isElectric\"\nFROM\n  \"Car\"\n```\n\n```text\nbulkInsert\n```\n\n```text\nDriver\n```\n\n```text\nCar\n```\n\n```text\nmake\n```\n\n```text\nmodel\n```\n\n```text\nDriverCar\n```\n\n```text\nCar\n```\n\n```text\nDriver\n```\n\n```text\nDriverCar\n```\n\n```text\nCONFIG\n```\n\n```text\nlimit\n```\n\n```text\nfindAll\n```\n\n```text\nquantity: 30\n```\n\n```text\nDriver\n```\n\n```text\nCar\n```\n\n```text\nlimit: 3\n```\n\n```text\nDriver.findAll\n```\n\n```text\nlimit: 4\n```\n\n```text\nCar.findAll\n```\n\n```text\nCar\n```\n\n```text\nCar\n```\n\n```text\nisElectric\n```\n\n```text\nisElectric\n```\n\n```text\nCar.findOne\n```\n\n```text\nisElectric\n```\n\n========================================\n\nComments:\n- Thanks @simon.ro! This is a big help and nice to know I'm not the only one who struggled with this\n- Tom, your recommendation on using migrations to insert data such as Car, with make and model, makes a lot of sense to me, as it's likely this data would be required to make the application functional. You said \"Never use seeders\", but what about for test data such as the fake generated drivercars from your example above?\n- Never use seeders. There are no exceptions to that rule. If you need to automate the insertion of data, use a migration. They have identical capabilities. A \"seeder\" is just a migration that Sequelize handles poorly. You can even write a migration that performs a no-op when the app is running in production or CI (or vice versa), by examining environment variables. (Although, sqlz will interpret a \"no-op\" as \"migration completed successfully.\" And sqlz ships with no tech for this, so you must build your own solution. Maybe there's an npm package by now...)\n- I understand the issues you’ve faced with seeders, I believe they can still be useful, especially in development and testing environments. The key is to use them careful, like ensuring they’re idempotent and tracking which seeders have been run which sequelize did by itself. Using models in migrations can lead to problems with schema changes, so sticking to raw SQL there makes sense.","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":502,"estimatedTokens":3981}}435{"id":"stack-16356856","source":"stackoverflow","questionId":16356856,"title":"sequelize.js custom validator, check for unique username / password","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: sequelize.js custom validator, check for unique username / password\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nImagine I have defined the following custom validator function:\n\n```\nisUnique: function () { // This works as expected\n throw new Error({error:[{message:'Email address already in use!'}]});\n}\n```\n\nHowever, when I attempt to query the DB I run into problems:\n\n```\nisUnique: function (email) { // This doesn't work\n var User = seqeulize.import('/path/to/user/model');\n\n User.find({where:{email: email}})\n .success(function () { // This gets called\n throw new Error({error:[{message:'Email address already in use!'}]}); // But this isn't triggering a validation error.\n });\n}\n```\n\nHow can I query the ORM in a custom validator and trigger a validation error based on the response from the ORM?\n\n========================================\n\nTop Answer:\nHere's a simplified sample of a functioning `isUnique` validation callback (works as of SequelizeJS v2.0.0). I added comments to explain the important bits:\n\n```\nvar UserModel = sequelize.define('User', {\n\n id: {\n type: Sequelize.INTEGER(11).UNSIGNED,\n autoIncrement: true,\n primaryKey: true\n },\n email: {\n type: Sequelize.STRING,\n validate: {\n isUnique: function(value, next) {\n\n UserModel.find({\n where: {email: value},\n attributes: ['id']\n })\n .done(function(error, user) {\n\n if (error)\n // Some unexpected error occured with the find method.\n return next(error);\n\n if (user)\n // We found a user with this email address.\n // Pass the error to the next method.\n return next('Email address already in use!');\n\n // If we got this far, the email address hasn't been used yet.\n // Call next with no arguments when validation is successful.\n next();\n\n });\n\n }\n }\n }\n\n});\n\nmodule.exports = UserModel;\n```\n\n========================================\n\nCode:\n```text\nisUnique: function () { // This works as expected\n  throw new Error({error:[{message:'Email address already in use!'}]});\n}\n```\n\n```text\nisUnique: function (email) { // This doesn't work\n  var User = seqeulize.import('/path/to/user/model');\n\n  User.find({where:{email: email}})\n    .success(function () { // This gets called\n      throw new Error({error:[{message:'Email address already in use!'}]});  // But this isn't triggering a validation error.\n    });\n}\n```\n\n```text\nemail: {\n  type: Sequelize.STRING,\n  allowNull: false,\n  validate: {\n    isEmail:true\n  },\n  unique: {\n      args: true,\n      msg: 'Email address already in use!'\n  }\n}\n```\n\n```text\nisUnique: function (email) {\n  var User = seqeulize.import('/path/to/user/model');\n\n  User.find({where:{email: email}})\n    .success(function (u) { // This gets called\n      if(u){\n        throw new Error({error:[{message:'Email address already in use!'}]});  // But this isn't triggering a validation error.\n      }\n    });\n}\n```\n\n```text\nvar UserModel = sequelize.define('User', {\n\n    id: {\n        type: Sequelize.INTEGER(11).UNSIGNED,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    email: {\n        type: Sequelize.STRING,\n        validate: {\n            isUnique: function(value, next) {\n\n                UserModel.find({\n                    where: {email: value},\n                    attributes: ['id']\n                })\n                    .done(function(error, user) {\n\n                        if (error)\n                            // Some unexpected error occured with the find method.\n                            return next(error);\n\n                        if (user)\n                            // We found a user with this email address.\n                            // Pass the error to the next method.\n                            return next('Email address already in use!');\n\n                        // If we got this far, the email address hasn't been used yet.\n                        // Call next with no arguments when validation is successful.\n                        next();\n\n                    });\n\n            }\n        }\n    }\n\n});\n\nmodule.exports = UserModel;\n```\n\n```text\nisUnique\n```\n\n```text\nvar User = sequelize.define('User',\n    {\n        email: {\n            type: Sequelize.STRING,\n            allowNull: false,\n            unique: true,\n            validate: {\n                isUnique: function (value, next) {\n                    var self = this;\n                    User.find({where: {email: value}})\n                        .then(function (user) {\n                            // reject if a different user wants to use the same email\n                            if (user && self.id !== user.id) {\n                                return next('Email already in use!');\n                            }\n                            return next();\n                        })\n                        .catch(function (err) {\n                            return next(err);\n                        });\n                }\n            }\n        },\n        other_field: Sequelize.STRING\n    });\n\nmodule.exports = User;\n```\n\n```text\nvar Sequelize = require('sequelize'),\n    _ = require('lodash'),\n    User = require('./path/to/User.model');\n\nexports.create = function (req, res) {\n    var allowedKeys = ['email', 'other_field'];\n    var attributes = _.pick(req.body, allowedKeys);\n    User.create(attributes)\n        .then(function (user) {\n            res.json(user);\n        })\n        .catch(Sequelize.ValidationError, function (err) {\n            // respond with validation errors\n            return res.status(422).send(err.errors);\n        })\n        .catch(function (err) {\n            // every other error\n            return res.status(400).send({\n                message: err.message\n            });\n        });\n```\n\n```text\nconst { DataTypes } = require('sequelize');\nconst sequelize = require('../config/db');\n\nconst UserModel = sequelize.define('user', {\n  id: {\n    type: DataTypes.INTEGER(11).UNSIGNED,\n    autoIncrement: true,\n    primaryKey: true,\n  },\n  name: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  },\n  email: {\n    type: DataTypes.STRING,\n    allowNull: false,\n    validate: {\n      isUnique: (value, next) => {\n        UserModel.findAll({\n          where: { email: value },\n          attributes: ['id'],\n        })\n          .then((user) => {\n            if (user.length != 0)\n              next(new Error('Email address already in use!'));\n            next();\n          })\n          .catch((onError) => console.log(onError));\n      },\n    },\n  },\n  password: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  },\n  createdAt: {\n    type: DataTypes.DATE,\n    allowNull: false,\n  },\n  updatedAt: {\n    type: DataTypes.DATE,\n    allowNull: false,\n  },\n});\n\nmodule.exports = UserModel;\n```\n\n```js\nus_mail: {\n      type: DataTypes.STRING(150),\n      allowNull: false,\n      unique: 'us_mail_UNIQUE',\n      validate:{\n        notEmpty:{msg: 'Renseigner une adresse mail pour valider le compte'},\n        notNull: {msg: 'Renseigner une adresse mail pour valider le compte'},\n        isEmail:{msg: 'Renseigner une adresse mail valide !'},\n      }\n    },\n```\n\n```js\nus_mail: {\n      type: DataTypes.STRING(150),\n      allowNull: false,\n      unique: {name:'us_mail_UNIQUE',msg: 'Cette adresse mail est déjà utlisée'},\n      validate:{\n        notEmpty:{msg: 'Renseigner une adresse mail pour valider le compte'},\n        notNull: {msg: 'Renseigner une adresse mail pour valider le compte'},\n        isEmail:{msg: 'Renseigner une adresse mail valide !'},\n      }\n    },\n```\n\n========================================\n\nComments:\n- well that won't work, you can try to simple run `.find()` and in callback manipulate the result of query and call `response.render` or anything else to send a message to user.\n- Seriously!? I'm trying to program to the Sequelize interface rather than a solid implementation. Why doesn't the above work? I can only imagine that .find is catching the error somewhere?\n- Just to clarify, User.find({where:{email: email}}).success() works perfectly (as specified in the Sequelize docs). The problem is that Sequelize is not catching the Error, or the error is being caught else where.\n- as far as i know `User.find()` returns an event, it will throw an error when event is emitted, so calling the `isUnique(\"example@example.com\")`, and even try `try..catch` won't do it.\n- Ok, looks like I have a lot of work to do to get Sequelize into shape. It's nowhere near as robust as I had been led to believe...\n- The error is thrown in the callback, so it never will occur in the isUnique function. Solution would be to make validation asyncroniously. Sadly sequelize currently does not allow this.\n- I am troubled by the fact that the code in the accepted answer includes a comment that reads \"this doesn't work\". Especially since the code seems to rely on the thing that presumably doesn't work.\n- This is because I just copied the code in the question and added the if statement so it would work\n- I removed the misleading comment\n- thanks you for answer. I am using above approach for my query but I am unable to catch validation errors on my controller. As I am using await User.create() instead of User.create().then(). I have tried nesting User.create() in try block and catching errors in catch block but I am unable to get those validation errors inside catch block. Any suggestions?\n- This! I don't understand why the others need to run a `user.find` before insert.\n- @BaNz yes you can do this & obviously its better, but if you have auto increment value in the table then if your insert query fails because of unique violation then also your auto increment id will increase, yes its the way any SQL works.\n- I'm confused, you seem to use `unique` property of the column `email` (i.e. not as a property of your `validate` object.) The docs say that `attributes.column.unique` can have value of `String | Boolean` ; but your value is an *object* (not String or Boolean) whose value is : ` { args: true, msg : '...' }` . That value looks like how you would use `unique` if you added it to the `validate` object; but you have `unique` directly on the `email` (aka column) object...\n- The `unique` parameter accepts a object if it have `args` as a 'String' or a 'Boolean' value. The msg attribute is used as a validation message.\n- I've changed this to the accepted answer. It was answered almost 4 years after the original question and I only just noticed it.\n- 2021 and this is not working as mentionere here. Using Sequelize 6.3.3\n- @NeerajGulia Working just fine for me on 6.6.5","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":319,"estimatedTokens":2624}}436{"id":"stack-29866133","source":"stackoverflow","questionId":29866133,"title":"Can't connect to MySQL with Sequelize","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Can't connect to MySQL with Sequelize\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI consistently get a `SequelizeConnectionRefusedError` when trying to connect to a MySQL database on my server.\n\nThe login credentials are correct, the port is open, everything seems good (and works like a charm in the dev environment).\n\nSorry for the scarce background information, but I'm dumbfounded here - I really don't know what could be causing this problem.\n\nThis is my output from `mysql --version`\n\n```\nmysql Ver 14.14 Distrib 5.5.43, for debian-linux-gnu (x86_64) using readline 6.3\n```\n\nAnd this is the code I'm using to initialize Sequelize. The table I want it to use doesn't exist yet, but I'm fairly sure that hasn't got anything to do with this problem. I've tried logging in with the root user as well, but no dice - I still get the same error.\n\n```\nvar sequelize = new Sequelize(\"database\", username, password, {\n host: \"localhost\",\n dialect: \"mysql\",\n port: 3306,\n define: {\n paranoid: true\n }\n});\n\nvar Model = sequelize.define(\"Model\", {\n md5: {type: Sequelize.STRING(128)},\n ip: {type: Sequelize.STRING(256)},\n url: {type: Sequelize.STRING(1024)}\n});\n\nsequelize.sync();\n```\n\nThis is running on Ubuntu 14.04, where node is being run behind Passenger (although the error appears if I run the application with node directly as well). I'm running nginx and PHP on the same server, where another PHP application is connecting to the database, if that's of any relevance.\n\nWhat could be causing this problem?\n\n========================================\n\nCode:\n```text\nmysql  Ver 14.14 Distrib 5.5.43, for debian-linux-gnu (x86_64) using readline 6.3\n```\n\n```text\nvar sequelize = new Sequelize(\"database\", username, password, {\n    host: \"localhost\",\n    dialect: \"mysql\",\n    port: 3306,\n    define: {\n        paranoid: true\n    }\n});\n\nvar Model = sequelize.define(\"Model\", {\n    md5: {type: Sequelize.STRING(128)},\n    ip: {type: Sequelize.STRING(256)},\n    url: {type: Sequelize.STRING(1024)}\n});\n\nsequelize.sync();\n```\n\n```text\nSequelizeConnectionRefusedError\n```\n\n```text\nmysql --version\n```\n\n```text\nvar sequelize = new Sequelize(\"database\", username, password, {\n    host: \"localhost\",\n    dialect: \"mysql\",\n    logging: function () {},\n    pool: {\n        max: 5,\n        min: 0,\n        idle: 10000\n    },\n    dialectOptions: {\n        socketPath: \"/var/run/mysqld/mysqld.sock\"\n    },\n    define: {\n        paranoid: true\n    }\n});\n```\n\n```text\nmysql\n```\n\n```text\nsocketPath\n```\n\n========================================\n\nComments:\n- Is the database you want to connect to actually called 'database'?\n- No, it's called something else, that's just my somewhat clumsy masquerading of what application this actually concerns.\n- Adding the dialectOptions key also resolved a slightly different error that I encountered: \"SequelizeConnectionError: Connection lost: The server closed the connection.\". This error occurred with both Sequelize 3.3.2 and 3.13.0 and was fixed by dialectOptions in both cases.\n- Is there a scenario under which one would not use socketPath? Does this work equally well across the wire (remote DB server) as it would for a local DB server.\n- This doesn't solve the problem if you have a dedicated MySQL server host.","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":111,"estimatedTokens":822}}437{"id":"stack-49052296","source":"stackoverflow","questionId":49052296,"title":"Sequelize select only chosen attributes","tags":["mysql","express","select","model","sequelize.js"],"text":"Title: Sequelize select only chosen attributes\nTags: mysql, express, select, model, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using MySQL database, when I am doing: \n\n```\nmodels.modelA.findAll({\n attributes: [\n ['modelA.id','id']\n ],\n raw: true,\n include:\n [\n {\n model: models.modelB,\n required: true\n }\n ]\n\n }).then(function (tenants) {\n\n });\n```\n\nNevertheless that I've selected only `id`, Sequelize is retrieving all attributes, from related table as well so I'm getting {`id`, ... All attributes here}.\n\nHow I can prevent this? Sometimes I want to select only 2/3 columns and Sequelize is always selecting all of them what is not efficient.\n\n========================================\n\nTop Answer:\nYou can try sending empty array as attributes to exclude them:\n\n```\nmodels.modelA.findAll({\n attributes: [\n ['modelA.id','id']\n ],\n raw: true,\n include:\n [\n {\n model: models.modelB,\n attributes: [],\n required: true\n }\n ]\n\n }).then(function (tenants) {\n\n });\n```\n\n========================================\n\nCode:\n```text\nmodels.modelA.findAll({\n            attributes: [\n               ['modelA.id','id']\n            ],\n            raw: true,\n            include:\n                [\n                    {\n                        model: models.modelB,\n                        required: true\n                    }\n                ]\n\n        }).then(function (tenants) {\n\n        });\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nmodels.modelA.findAll({\n        attributes: [\n           'id'\n        ],\n        raw: true,\n        include:\n            [\n                {\n                    model: models.modelB,\n                    attributes: ['fieldName1', 'fieldName2'], // Add column names here inside attributes array.\n                    required: true\n                }\n            ]\n\n    }).then(function (tenants) {\n\n    });\n```\n\n```text\nmodels.modelA.findAll({\n            attributes: [\n               ['modelA.id','id']\n            ],\n            raw: true,\n            include:\n                [\n                    {\n                        model: models.modelB,\n                        attributes: [],\n                        required: true\n                    }\n                ]\n\n        }).then(function (tenants) {\n\n        });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":124,"estimatedTokens":564}}438{"id":"stack-42841810","source":"stackoverflow","questionId":42841810,"title":"Feathers.js / Sequelize -> Service with relations between two models","tags":["mysql","node.js","sequelize.js","feathersjs","feathers-sequelize"],"text":"Title: Feathers.js / Sequelize -> Service with relations between two models\nTags: mysql, node.js, sequelize.js, feathersjs, feathers-sequelize\nSource: Stack Overflow\n\nQuestion:\nI've got feathers.js functioning with mysql via sequelize. This is working, I can collect data from tables. Next step is to define 'joins' in the models.\n\nI have a table with a column 'status_id' and 'country_id'. These columns reference to an id in a metadata table. In SQL I would right:\n\n```\nSELECT status.description, country.description, detail \nFROM details \nINNER JOIN metadata status \n ON (details.status_id = status.id AND status.type = 'status' \nINNER JOIN metadata country \n ON (details.country_id =country.id AND country.type = 'country')\n```\n\nThis metadata table won't be big in this case so hence this approach. It does give flexibility I need.\n\nWhat do I need to do to make this in feathters.js?\n\n========================================\n\nTop Answer:\nHaving helped a lot of people with this same issue, I have learned that the solution comes in two parts:\n\n**#1 - embrace the ORM**\n\nMost of people's problems come from a lack of understanding of sequelize. In order to help you, you will first need to have an understanding how sequelize associations work and how to perform queries using the \"include\" option (aka \"eager loading\"). I recommend reading all of the contents of those links a couple times, and then one more time for good measure; this is the steepest part of the sequelize learning curve. If you have never used an ORM, let it do a lot of the heavy lifting for you!\n\n**#2 - setting sequelize options from a feathers hook**\n\nOnce you understand how the \"include\" option works with sequelize, you will want to set that option from a \"before\" hook in feathers. Feathers will pass the value of `hook.params.sequelize` as the options parameter for all sequelize method calls. This is what your hook might look like:\n\n```\n// GET /my-service?name=John&include=1\nfunction (hook) {\n if (hook.params.query.include) {\n const AssociatedModel = hook.app.services.fooservice.Model;\n hook.params.sequelize = {\n include: [{ model: AssociatedModel }]\n };\n // delete any special query params so they are not used\n // in the WHERE clause in the db query.\n delete hook.params.query.include;\n }\n return Promise.resolve(hook);\n}\n```\n\nUnderneath the hood, feathers will call your models `find` method sort of like this:\n\n```\n// YourModel is a sequelize model\nconst options = Object.assign({ where: { name: 'John' }}, hook.params.sequelize);\nYourModel.findAndCount(options);\n```\n\n**Noteworthy:**\n\nThe old v1.x feathers generators (before March 2017) do not generate code which is friendly for sequelize. This has been fixed in the new v2.x generators. If you are pretty far into your project from before March 2017, then **do not** use the new generators. Please join the Slack Channel and join the `sequelize` room for help. I keep an eye on things there and can help you. If you just started your project and haven't gotten very far, then I highly suggest starting fresh with the new generators. Run this command (and these instructions):\n\n```\n$ feathers --version # see what version you are using\n$ npm install -g @feathersjs/cli # install latest version of the CLI\n```\n\n========================================\n\nCode:\n```text\nSELECT status.description, country.description, detail \nFROM details \nINNER JOIN metadata status \n    ON (details.status_id = status.id AND status.type = 'status' \nINNER JOIN metadata country \n    ON (details.country_id =country.id AND country.type = 'country')\n```\n\n```text\nclassMethods: {\n    associate() {\n        category.hasOne(sequelize.models.sections, {\n            as: 'category',\n            foreignKey: 'category_id'\n        });\n    },\n},\n```\n\n```text\nclassMethods: {\n    associate() {\n        section.belongsTo(sequelize.models.categories, {\n            allowNull: true\n        });\n    },\n},\n```\n\n```text\n...\napp.set('models', sequelize.models);\n...\nObject.keys(sequelize.models).forEach(function(modelName) {\n    if (\"associate\" in sequelize.models[modelName]) {\n        sequelize.models[modelName].associate();\n    }\n});\n```\n\n```text\nserviceSections.find({\n    include: [{\n        model: serviceCategories.Model\n    }],\n    query: {\n        $sort: {\n            section_description_en: 1\n        }\n    }\n}).then(page => {\n    page.data.reverse();\n    this.listSections = page.data;\n})\n```\n\n```text\nexports.before = {\n    ...\n    find: [{\n        function (hook) {\n            if (hook.params.query.include) {\n                const AssociatedModel = hook.app.services.category.Model;\n                hook.params.sequelize = {\n                    include: [{ model: AssociatedModel }]\n                };\n            }\n            return Promise.resolve(hook);\n        }\n    }],\n    ...\n};\n```\n\n```text\n...\nexports.before = {\n    all: [],\n    find: [\n        getCategory()\n    ],\n    get: [\n        getCategory()\n    ],\n    create: [],\n    update: [],\n    patch: [],\n    remove: []\n};\n...\n\nfunction getCategory() {\n    return function (hook) {\n        const category = hook.app.services.categories.Model;\n        hook.params.sequelize = {\n            include: [{ model: category }]\n        };\n        return Promise.resolve(hook);\n    };\n}\n```\n\n```text\nclassMethods: {\n    associate() {\n        metadata.hasOne(sequelize.models.sections, {\n            as: 'satus',\n            foreignKey: 'status_id',\n            targetKey: 'status_id'\n        });\n    }, },\n```\n\n```text\nclassMethods: {\n    associate() {\n        section.belongsTo(sequelize.models.categories, {\n            allowNull: false,\n            as: 'category'\n        });\n        section.belongsTo(sequelize.models.metadata, {\n            allowNull: false,\n            as: 'status'\n        });\n    }, },\n```\n\n```text\nfunction getRelatedInfo() {\n    return function (hook) {\n        hook.params.sequelize = {\n            include: [\n                {\n                    model: hook.app.services.categories.Model,\n                    as: 'category'\n                },{\n                    model: hook.app.services.metadata.Model,\n                    as: 'status',\n                    where: {\n                        type: 'status'\n                    }\n                }\n            ]\n        };\n        return Promise.resolve(hook);\n    };\n}\n```\n\n```text\nconst socket = io();\nconst appFeathers = feathers()\n    .configure(feathers.socketio(socket))\n    .configure(feathers.hooks());\nconst serviceSections = appFeathers.service('sections');\nconst serviceArticles = appFeathers.service('articles');\nconst serviceMetadata = appFeathers.service('metadata');\n...\nmounted() {\n    serviceArticles.find({\n        include: [{\n            model: serviceMetadata.Model,\n            as: 'country',\n            query: {\n                $select: [\n                    'country_icon'\n                ]\n            }\n        }],\n        query: {\n            $sort: {\n                article_description_en: 1\n            },\n            $select: [\n                'id',\n                ['article_description_en', 'article_description'],\n                'article_length',\n                'article_ascend',\n                'article_code'\n            ]\n        }\n    }).then(page => {\n        this.listTrails = page.data;\n    })\n}\n```\n\n```text\n// GET /my-service?name=John&include=1\nfunction (hook) {\n   if (hook.params.query.include) {\n      const AssociatedModel = hook.app.services.fooservice.Model;\n      hook.params.sequelize = {\n         include: [{ model: AssociatedModel }]\n      };\n      // delete any special query params so they are not used\n      // in the WHERE clause in the db query.\n      delete hook.params.query.include;\n   }\n   return Promise.resolve(hook);\n}\n```\n\n```text\n// YourModel is a sequelize model\nconst options = Object.assign({ where: { name: 'John' }}, hook.params.sequelize);\nYourModel.findAndCount(options);\n```\n\n```text\n$ feathers --version              # see what version you are using\n$ npm install -g @feathersjs/cli    # install latest version of the CLI\n```\n\n```text\nhook.params.sequelize\n```\n\n```text\nfind\n```\n\n```text\nsequelize\n```\n\n```text\nconst Model = sequelize.define('Model', {\n    ...\n}, {\n    classMethods: {\n        associate: function (model) {...}\n    },\n    instanceMethods: {\n        someMethod: function () { ...}\n    }\n});\n```\n\n```text\nconst Model = sequelize.define('Model', {\n    ...\n});\n\n// Class Method\nModel.associate = function (models) {\n    ...associate the models\n};\n\n// Instance Method\nModel.prototype.someMethod = function () {..}\n```\n\n```text\nclassMethods\n```\n\n```text\nassociate\n```\n\n```text\nclassMethods\n```\n\n========================================\n\nComments:\n- Thanks for adjusting the code sections, I forgot them.\n- I'm working on these tips and have now associations in the models. I'm trying to get the last part running now, since I don't get compile errors any more. I got a bit confused with the plural and non-plural notations in my model file and which to use where but figured that out. I'll post when it's solved.\n- That's fantastic because your example also shows how it works on the client. In the client you can adjust what sort of info you want to get returned from the backend. Sort of like a simplified version of GraphQL ...","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":343,"estimatedTokens":2319}}439{"id":"stack-55191891","source":"stackoverflow","questionId":55191891,"title":"How to loop through result in sequelize","tags":["node.js","sequelize.js"],"text":"Title: How to loop through result in sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I get the `dataValues` out of the response. I have tried doing `console.log(result.dataValues)` but it returns undefined.\n\nResponse\n\n```\n[ User {\n dataValues: {\n id: 16,\n user_id: '140235016357535420',\n server_id: '535881918483398676',\n xp: 40995,\n coins: 0,\n createdAt: 2019-03-09T22\n :\n 59: 09.216Z,\n updatedAt: 2019-03-09T22\n :\n 59: 09.216Z\n },\n},\nUser {\n dataValues: {\n id: 16,\n user_id: '140235016357535420',\n server_id: '535881918483398676',\n xp: 40995,\n coins: 0,\n createdAt: 2019-03-09T22\n :\n 59: 09.216Z,\n updatedAt: 2019-03-09T22\n :\n 59: 09.216Z\n },\n},]\n```\n\nQuery\n\n```\nUser.findAll({\n where: {\n server_id: msg.guild.id,\n },\n limit: 2,\n order: [\n ['xp', 'DESC'],\n ],\n}).then(result => {\n console.log(result);\n});\n```\n\nModel \n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const User = sequelize.define('User', {\n user_id: DataTypes.STRING,\n server_id: DataTypes.STRING,\n xp: DataTypes.INTEGER,\n coins: DataTypes.INTEGER,\n }, {});\n /* User.associate = function(models) {\n // associations can be defined here\n };*/\n return User;\n};\n```\n\n========================================\n\nTop Answer:\n**Before render/print you need to transform the Models array into array**\n\n```\nconst records = results.map(result => result.dataValues)\n```\n\nDetails:\n\nOut of Model search you've got an array of models like:\n\n```\n[ User {\n dataValues: {\n id: 16,\n user_id: '140235016357535420',\n server_id: '535881918483398676',\n xp: 40995,\n coins: 0,\n createdAt: 2019-03-09T22,\n updatedAt: 2019-03-09T22\n },\n},\n...]\n```\n\nJust \"map\" it like this:\n\n```\nconst results = await User.findAll();\n\nconst records = results.map(function(result) {\n return result.dataValues\n })\n```\n\nand You'll get an array like this:\n\n```\n[\n{\n id: 16,\n user_id: '140235016357535420',\n server_id: '535881918483398676',\n xp: 40995,\n coins: 0,\n createdAt: 2019-03-09T22,\n updatedAt: 2019-03-09T22\n},...\n]\n```\n\n*compact version:\n\n```\nconst records = results.map(result => result.dataValues)\n```\n\n========================================\n\nCode:\n```text\n[ User {\n  dataValues: {\n    id: 16,\n    user_id: '140235016357535420',\n    server_id: '535881918483398676',\n    xp: 40995,\n    coins: 0,\n    createdAt: 2019-03-09T22\n    :\n    59: 09.216Z,\n    updatedAt: 2019-03-09T22\n    :\n    59: 09.216Z\n  },\n},\nUser {\n  dataValues: {\n    id: 16,\n    user_id: '140235016357535420',\n    server_id: '535881918483398676',\n    xp: 40995,\n    coins: 0,\n    createdAt: 2019-03-09T22\n    :\n    59: 09.216Z,\n    updatedAt: 2019-03-09T22\n    :\n    59: 09.216Z\n  },\n},]\n```\n\n```text\nUser.findAll({\n    where: {\n        server_id: msg.guild.id,\n    },\n    limit: 2,\n    order: [\n        ['xp', 'DESC'],\n    ],\n}).then(result => {\n    console.log(result);\n});\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n    const User = sequelize.define('User', {\n        user_id: DataTypes.STRING,\n        server_id: DataTypes.STRING,\n        xp: DataTypes.INTEGER,\n        coins: DataTypes.INTEGER,\n    }, {});\n    /*  User.associate = function(models) {\n        // associations can be defined here\n    };*/\n    return User;\n};\n```\n\n```text\ndataValues\n```\n\n```text\nconsole.log(result.dataValues)\n```\n\n```js\nfor (let i = 0; i < result.length; i++)  {\n  console.log(result[i].dataValues);\n}\n```\n\n```js\nresult.forEach( \n  (user) => { \n    console.log(user.dataValues);\n  }\n);\n```\n\n```text\ndataValues\n```\n\n```text\nforEach()\n```\n\n```text\nconst records = results.map(result => result.dataValues)\n```\n\n```text\n[ User {\n  dataValues: {\n    id: 16,\n    user_id: '140235016357535420',\n    server_id: '535881918483398676',\n    xp: 40995,\n    coins: 0,\n    createdAt: 2019-03-09T22,\n    updatedAt: 2019-03-09T22\n  },\n},\n...]\n```\n\n```text\nconst results = await User.findAll();\n\nconst records = results.map(function(result) {\n            return result.dataValues\n        })\n```\n\n```text\n[\n{\n    id: 16,\n    user_id: '140235016357535420',\n    server_id: '535881918483398676',\n    xp: 40995,\n    coins: 0,\n    createdAt: 2019-03-09T22,\n    updatedAt: 2019-03-09T22\n},...\n]\n```\n\n```text\nconst records = results.map(result => result.dataValues)\n```\n\n```text\nconst users = User.findAll({\n    raw: true,\n    //Other parameters\n});\n```\n\n```text\nraw: true\n```\n\n========================================\n\nComments:\n- Array.forEach isn't asynchronous. It might only seem that way, depending on what you do in the callback.\n- This converts my array to an object type in node","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":293,"estimatedTokens":1132}}440{"id":"stack-30699742","source":"stackoverflow","questionId":30699742,"title":"Unhandled rejection TypeError: Dependency name must be given as a not empty string","tags":["sequelize.js","hapi.js"],"text":"Title: Unhandled rejection TypeError: Dependency name must be given as a not empty string\nTags: sequelize.js, hapi.js\nSource: Stack Overflow\n\nQuestion:\nI got this error when codes hitting `require('./models').sequelize.sync()`. (`models` is a directory created by running command `sequelize init`) Could anyone give me some hints about what induces this error?\n\n```\n> node src/server.js\n\nUnhandled rejection TypeError: Dependency name must be given as a not empty string\n at /Users/syg/Repos/example/node_modules/sequelize/node_modules/toposort-class/toposort.js:37:31\n at Array.forEach (native)\n at Toposort.self.add (/Users/syg/Repos/example/node_modules/sequelize/node_modules/toposort-class/toposort.js:35:22)\n at /Users/syg/Repos/example/node_modules/sequelize/lib/model-manager.js:89:12\n at Array.forEach (native)\n at ModelManager.forEachModel (/Users/syg/Repos/example/node_modules/sequelize/lib/model-manager.js:58:15)\n at /Users/syg/Repos/example/node_modules/sequelize/lib/sequelize.js:862:23\n at tryCatcher (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/util.js:24:31)\n at Promise._settlePromiseFromHandler (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:454:31)\n at Promise._settlePromiseAt (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:530:18)\n at Promise._settlePromiseAtPostResolution (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:224:10)\n at Async._drainQueue (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/async.js:182:12)\n at Async._drainQueues (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/async.js:187:10)\n at Immediate.Async.drainQueues [as _onImmediate] (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n at processImmediate [as _immediateCallback] (timers.js:358:17)\n```\n\nI'm using `sequelize@3.2.0` with `HapiJS`. An similar repo can be found here. (This repo is indeed working, even with `sequelize` upgraded to latest version)\n\n========================================\n\nTop Answer:\nIt was due to declaring of foreign key according to previous version of sequelize.\n\nAs per latest version \"sequelize\": \"^4.31.2\", correct way to add foreign key is-\n\n```\naddressId: {\n type: DataTypes.INTEGER,\n references: {\n model: 'addresses',\n key: 'id'\n }\n}\n```\n\nI was declaring it as \n\n```\naddressId: {\n type: DataTypes.INTEGER,\n references: 'addresses',\n referencesKey: 'id'\n}\n```\n\n========================================\n\nCode:\n```text\n> node src/server.js\n\nUnhandled rejection TypeError: Dependency name must be given as a not empty string\n    at /Users/syg/Repos/example/node_modules/sequelize/node_modules/toposort-class/toposort.js:37:31\n    at Array.forEach (native)\n    at Toposort.self.add (/Users/syg/Repos/example/node_modules/sequelize/node_modules/toposort-class/toposort.js:35:22)\n    at /Users/syg/Repos/example/node_modules/sequelize/lib/model-manager.js:89:12\n    at Array.forEach (native)\n    at ModelManager.forEachModel (/Users/syg/Repos/example/node_modules/sequelize/lib/model-manager.js:58:15)\n    at /Users/syg/Repos/example/node_modules/sequelize/lib/sequelize.js:862:23\n    at tryCatcher (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/util.js:24:31)\n    at Promise._settlePromiseFromHandler (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:454:31)\n    at Promise._settlePromiseAt (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:530:18)\n    at Promise._settlePromiseAtPostResolution (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:224:10)\n    at Async._drainQueue (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/async.js:182:12)\n    at Async._drainQueues (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/async.js:187:10)\n    at Immediate.Async.drainQueues [as _onImmediate] (/Users/syg/Repos/example/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n    at processImmediate [as _immediateCallback] (timers.js:358:17)\n```\n\n```text\nrequire('./models').sequelize.sync()\n```\n\n```text\nmodels\n```\n\n```text\nsequelize init\n```\n\n```text\nsequelize@3.2.0\n```\n\n```text\nHapiJS\n```\n\n```text\nsequelize\n```\n\n```text\naddressId: {\n    type: DataTypes.INTEGER,\n    references: {\n        model: 'addresses',\n        key: 'id'\n    }\n}\n```\n\n```text\naddressId: {\n    type: DataTypes.INTEGER,\n    references: 'addresses',\n    referencesKey: 'id'\n}\n```\n\n```text\n// Collect all models in an object\nconst models = {\n    FModel,\n    SModel\n};\n\n// Sync associations by passing models as argument\nObject.values(models).forEach(model => {\n    if (model.associate) {\n        model.associate(models);\n    }\n});\n```\n\n========================================\n\nComments:\n- Do you have more precision?\n- @user1843507 I don't have codes with me now, but you might as well look at your codes that specify 1toN/MtoN relationships carefully, especially variable names.\n- E.g. I had old school DB, without real foreign keys, connections (foreign keys) were just plain Integers so registering them as FK-s in models threw error.","metadata":{"transformedAt":"2026-08-18T18:33:34.375Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":144,"estimatedTokens":1333}}441{"id":"stack-63856212","source":"stackoverflow","questionId":63856212,"title":"How to display Sequelize validation error messages in Express API","tags":["javascript","node.js","express","orm","sequelize.js"],"text":"Title: How to display Sequelize validation error messages in Express API\nTags: javascript, node.js, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have this Organization model used in a Node.js/Express API with Sequelize ORM running MySQL. When I violate the 2-100 character rule under `validation` in the first code example below I get the classic `err` item from the catch block in the second code example, which doesn't contain any information about the validation error.\n\nI would like instead to display the validation error message you can see under `validation { len: { msg: ...}}` in the model. At least console.log it, and then later display it to the end user.\n\nHowever, the Sequelize manual and any other information I can find don't explain how I make use of this custom error message. So my question is how can I make use of it and display it.\n\nModel:\n\n```\n'use strict'\n\nconst { Sequelize, DataTypes } = require('sequelize');\nconst db = require('./../config/db.js')\n\nconst Organization = db.define('organizations', {\n id: {\n type: DataTypes.UUID,\n defaultValue: Sequelize.UUIDV4,\n primaryKey: true,\n allowNull: false,\n unique: true,\n validate: {\n isUUID: {\n args: 4,\n msg: 'The ID must be a UUID4 string'\n }\n }\n },\n name: {\n type: DataTypes.STRING,\n required: true,\n allowNull: false,\n validate: {\n len: {\n args: [2, 100],\n msg: 'The name must contain between 2 and 100 characters.' // Error message I want to display\n }\n }\n },\n created_at: {\n type: DataTypes.DATE,\n required: true,\n allowNull: false\n },\n updated_at: {\n type: DataTypes.DATE,\n required: true,\n allowNull: false\n },\n deleted_at: {\n type: DataTypes.DATE\n }\n},\n{\n underscored: true,\n paranoid: true,\n tableName: 'organizations',\n updatedAt: 'updated_at',\n createdAt: 'created_at',\n deletedAt: 'deleted_at'\n})\n\nmodule.exports = Organization\n```\n\nController:\n\n```\n/**\n * @description Create new organization\n * @route POST /api/v1/organizations\n */\n\nexports.createOrganization = async (req, res, next) => {\n try {\n const org = await Organization.create(\n req.body,\n {\n fields: ['name', 'type']\n })\n return res.status(200).json({\n success: true,\n data: {\n id: org.id,\n name: org.name\n },\n msg: `${org.name} has been successfully created.`\n })\n } catch (err) {\n next(new ErrorResponse(`Sorry, could not save the new organization`, 404))\n\n// ^ This is the message I get if I violate the validation rule ^\n\n }\n}\n```\n\nThe Sequelize documentation for validation and constraints is found here: https://sequelize.org/master/manual/validations-and-constraints.html\n\nThe validation is built on Validatorjs (https://github.com/validatorjs/validator.js) which unfortunately also lacks practical info on the use of the validation object. I guess that means it must be self explanatory, but as I'm a noob I am lost.\n\n========================================\n\nTop Answer:\nAfter getting help from @Rohit Ambre my catch block is like this:\n\n```\n} catch (err) {\n if (err.name === 'SequelizeValidationError') {\n return res.status(400).json({\n success: false,\n msg: err.errors.map(e => e.message)\n })\n } else {\n next(new ErrorResponse(`Sorry, could not save ${req.body.name}`, 404))\n }\n }\n```\n\nAPI response:\n\n```\n{\n \"success\": false,\n \"msg\": [\n \"The name must contain between 2 and 100 characters.\",\n \"The organization type is not valid.\"\n ]\n}\n```\n\nIt would maybe helpful to add a key for each item, something like this, but whatever I do in the catch block it seems to give me an UnhandledPromiseRejectionWarning:\n\n```\ncatch (err) {\n if (err.name === 'SequelizeValidationError') {\n const errors = err.errors\n\n const errorList = errors.map(e => {\n let obj = {}\n obj[e] = e.message\n return obj;\n })\n \n return res.status(400).json({\n success: false,\n msg: errorList\n })\n } else {\n next(new ErrorResponse(`Sorry, could not save ${req.body.name}`, 404))\n }\n }\n```\n\nAny tips, por favor?\n\n========================================\n\nCode:\n```text\n'use strict'\n\nconst { Sequelize, DataTypes } = require('sequelize');\nconst db = require('./../config/db.js')\n\nconst Organization = db.define('organizations', {\n  id: {\n    type: DataTypes.UUID,\n    defaultValue: Sequelize.UUIDV4,\n    primaryKey: true,\n    allowNull: false,\n    unique: true,\n    validate: {\n      isUUID: {\n        args: 4,\n        msg: 'The ID must be a UUID4 string'\n      }\n    }\n  },\n  name: {\n    type: DataTypes.STRING,\n    required: true,\n    allowNull: false,\n    validate: {\n      len: {\n        args: [2, 100],\n        msg: 'The name must contain between 2 and 100 characters.' // Error message I want to display\n      }\n    }\n  },\n  created_at: {\n    type: DataTypes.DATE,\n    required: true,\n    allowNull: false\n  },\n  updated_at: {\n    type: DataTypes.DATE,\n    required: true,\n    allowNull: false\n  },\n  deleted_at: {\n    type: DataTypes.DATE\n  }\n},\n{\n  underscored: true,\n  paranoid: true,\n  tableName: 'organizations',\n  updatedAt: 'updated_at',\n  createdAt: 'created_at',\n  deletedAt: 'deleted_at'\n})\n\nmodule.exports = Organization\n```\n\n```text\n/**\n *  @description Create new organization\n *  @route POST /api/v1/organizations\n */\n\nexports.createOrganization = async (req, res, next) => {\n  try {\n    const org = await Organization.create(\n      req.body,\n      {\n        fields: ['name', 'type']\n      })\n    return res.status(200).json({\n      success: true,\n      data: {\n        id: org.id,\n        name: org.name\n      },\n      msg: `${org.name} has been successfully created.`\n    })\n  } catch (err) {\n    next(new ErrorResponse(`Sorry, could not save the new organization`, 404))\n\n// ^ This is the message I get if I violate the validation rule ^\n\n  }\n}\n```\n\n```text\nvalidation\n```\n\n```text\nerr\n```\n\n```text\nvalidation { len: { msg: ...}}\n```\n\n```js\nconsole.log('err.name', err.name);\nconsole.log('err.message', err.message);\nconsole.log('err.errors', err.errors);\nerr.errors.map(e => console.log(e.message)) // The name must contain between 2 and 100 characters.\n```\n\n```js\nconst errObj = {};\nerr.errors.map( er => {\n   errObj[er.path] = er.message;\n})\nconsole.log(errObj);\n```\n\n```js\n{ \n  firstName: 'The firstName must contain between 2 and 100 characters.',\n  lastName: 'The lastName must contain between 2 and 100 characters.' \n}\n```\n\n```text\nfirstName\n```\n\n```text\nerr.name\n```\n\n```text\nSequelizeValidationError\n```\n\n```text\nerr.errors\n```\n\n```text\nmessage\n```\n\n```text\npath\n```\n\n```text\n} catch (err) {\n    if (err.name === 'SequelizeValidationError') {\n      return res.status(400).json({\n        success: false,\n        msg: err.errors.map(e => e.message)\n      })\n    } else {\n      next(new ErrorResponse(`Sorry, could not save ${req.body.name}`, 404))\n    }\n  }\n```\n\n```text\n{\n    \"success\": false,\n    \"msg\": [\n        \"The name must contain between 2 and 100 characters.\",\n        \"The organization type is not valid.\"\n    ]\n}\n```\n\n```text\ncatch (err) {\n    if (err.name === 'SequelizeValidationError') {\n       const errors = err.errors\n\n      const errorList = errors.map(e => {\n        let obj = {}\n        obj[e] = e.message\n        return obj;\n      })\n      \n      return res.status(400).json({\n        success: false,\n        msg: errorList\n      })\n    } else {\n      next(new ErrorResponse(`Sorry, could not save ${req.body.name}`, 404))\n    }\n  }\n```\n\n```text\nresponse.err(res, err.errors[0].message ?? 'tidak berhasil menambahkan data', 500);\n```\n\n```text\n.catch(error => {\n....\n        this.fetchLoading = false\n        this.$swal({\n          title: 'Error!',\n          text: `${error.response.data.message ?? 'except your message'}`,\n```\n\n```text\n\"sequelize\": \"^6.6.5\",\n    \"sequelize-cli\": \"^6.2.0\",\n```\n\n========================================\n\nComments:\n- Awesome, thank you very much. So it is pushed on to the generic err object I see, and I can check first before throwing the generic error if there is an err.name property that matches SequelizeValidationError and if so display that error instead. Perfect!\n- Your error message is clean, when I try it, it's like `users.name must contain between 2 and 100 characters.` Where the `users` is the table name. Any idea how to change that ?\n- @ShashankAC Use the `msg` property. F.e. `isInt: { msg: \"Must be an integer number of pennies\" }`\n- I have updated my answer with error formatting, check if that helps","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":378,"estimatedTokens":2061}}442{"id":"stack-19583467","source":"stackoverflow","questionId":19583467,"title":"Sequelize connection over ssh","tags":["node.js","sequelize.js"],"text":"Title: Sequelize connection over ssh\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am not able to connect to a remote mysql server using sequelize but I am able to ssh into the machine and connect to mysql.\n\nHow do I make Sequelize connect to mysql server over ssh rather than directly in node?\n\n========================================\n\nCode:\n```text\nssh -NL 33060:localhost:3306 yourserver\n```\n\n```text\nmysql --port 33060 --host 127.0.0.1\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n  host: \"127.0.0.1\",\n  port: 33060\n});\n```\n\n========================================\n\nComments:\n- i think sequelize doesn't support mysql connection over ssh.","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":31,"estimatedTokens":175}}443{"id":"stack-52290123","source":"stackoverflow","questionId":52290123,"title":"Sequelize, MySQL - Filtering rows in table with JSON column values","tags":["javascript","mysql","json","sequelize.js"],"text":"Title: Sequelize, MySQL - Filtering rows in table with JSON column values\nTags: javascript, mysql, json, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nNeed help in figuring out how to filter rows in MySQL table's JSON column with nested values using Sequelize. Documentation doesn't have it (Only given for PostgreSQL & MSSQL - ref)\n\nTable definition -\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Comment = sequelize.define('Comment', {\n action: DataTypes.STRING,\n type: DataTypes.STRING,\n reason: DataTypes.STRING,\n reference: DataTypes.JSON,\n active: {\n type: DataTypes.INTEGER,\n defaultValue: 1,\n },\n }, {\n classMethods: {\n associate(models) {\n Comment.belongsTo(models.User, {\n foreignKey: 'userId',\n });\n },\n },\n });\n return Comment;\n};\n```\n\nValues of reference column in `Comments` table -\n\n```\n{\n \"orderItemId\": 2,\n \"xkey\": 3,\n \"ykey\": 4\n}\n{\n \"orderItemId\": 4,\n \"xkey\": 1,\n \"ykey\": 1\n}\n{\n \"orderItemId\": 3,\n \"xkey\": 1,\n \"ykey\": 6\n}\n{\n \"orderItemId\": 2,\n \"xkey\": 1,\n \"ykey\": 0\n}\n```\n\nHow do I filter all the rows where \"orderItemId\" is 2.\n\nExpected SQL query\n\n```\nselect * from Comments where reference->\"$.orderItemId\" = 2\n```\n\nFigured out a way using `sequelize.literal`, but is there a way of not using this function.\n\n```\nmodels.Comment.findAll({\n where: sequelize.literal(`reference->\"$.orderItemId\"=2`),\n})\n```\n\nHow to add multiple conditions in the above case like - \n\n`reference->\"$.orderItemId\" = 2 and action = 'xyz'`\n\n========================================\n\nTop Answer:\nYou can use with below.\n\n```\nComment.findAll({\n action:'xys',\n 'reference.orderItemid':2\n})\n\n// oR\n\nComment.findAll({\n action:'xys',\n reference:{\n orderItemId:2\n }\n})\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Comment = sequelize.define('Comment', {\n    action: DataTypes.STRING,\n    type: DataTypes.STRING,\n    reason: DataTypes.STRING,\n    reference: DataTypes.JSON,\n    active: {\n      type: DataTypes.INTEGER,\n      defaultValue: 1,\n    },\n  }, {\n    classMethods: {\n      associate(models) {\n        Comment.belongsTo(models.User, {\n          foreignKey: 'userId',\n        });\n      },\n    },\n  });\n  return Comment;\n};\n```\n\n```text\n{\n  \"orderItemId\": 2,\n  \"xkey\": 3,\n  \"ykey\": 4\n}\n{\n  \"orderItemId\": 4,\n  \"xkey\": 1,\n  \"ykey\": 1\n}\n{\n  \"orderItemId\": 3,\n  \"xkey\": 1,\n  \"ykey\": 6\n}\n{\n  \"orderItemId\": 2,\n  \"xkey\": 1,\n  \"ykey\": 0\n}\n```\n\n```text\nselect * from Comments where reference->\"$.orderItemId\" = 2\n```\n\n```text\nmodels.Comment.findAll({\n  where: sequelize.literal(`reference->\"$.orderItemId\"=2`),\n})\n```\n\n```text\nComments\n```\n\n```text\nsequelize.literal\n```\n\n```text\nreference->\"$.orderItemId\" = 2 and action = 'xyz'\n```\n\n```text\nmodels.Comment.findAll({\n    where: {\n        action: 'xyz',\n        [Op.and]: sequelize.literal(`reference->\"$.orderItemId\"=2`),\n    },\n});\n```\n\n```text\nSequelize.Op\n```\n\n```text\nreference: {\n              [Op.and]: [{orderItemId: {[Op.eq]: 2}}]\n           }\n```\n\n```js\nComment.findAll({\n  action:'xys',\n  'reference.orderItemid':2\n})\n\n// oR\n\nComment.findAll({\n  action:'xys',\n  reference:{\n  orderItemId:2\n  }\n})\n```\n\n```text\nconst orderItemIdsArray = [1, 2, 3, 4]\n\nmodels.Comment.findAll({\n    where: {\n        action: 'xyz',\n        [Op.and] = [\n            sequelize.literal(`reference->\"$.orderItemId\" IN (${orderItemIdsArray})`)\n        ]\n```\n\n```text\nconst orderItemIdsArray = [\n    \"3ad108a4-f68c-4aca-9967-072ce5ec21af\", \n    \"ef30f7ca-b1bb-4e94-a06f-b6c783f5dc1f\", \n    \"bb591f28-0df9-4254-aa9b-c162fb0ed154\"\n]\n\nconst idsWithQuotes = orderItemIdsArray.map((id) => '\"' + id + '\"')\n\nmodels.Comment.findAll({\n    where: {\n        action: 'xyz',\n        [Op.and] = [\n            sequelize.literal(`reference->\"$.orderItemId\" IN (${idsWithQuotes})`)\n        ]\n```\n\n========================================\n\nComments:\n- Thanks a lot! Worked perfectly. Also, anyway to remove the use of literal?\n- Can be used sequelize.col sequelize.where(sequelize.col('profile->user.first_name'), { [Op.like]: sequelizeFilters.search, }),\n- Did you like my answer? If so, rate it.\n- This worked perfectly for object, but how with array object? for example: [{\"status\": \"y\", \"user_id\": 6}, {\"status\": \"n\", \"user_id\": 3}] I've try with code above did't work.\n- It seems like this would open you up to injection attacks. Never directly insert a variable into a query clause.\n- @KimballRobinson this code isn't inserting anything. It's using an array to filter the data. It is assumed that your data (in this case, the array of ids) is already sanitized.","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":243,"estimatedTokens":1138}}444{"id":"stack-46758407","source":"stackoverflow","questionId":46758407,"title":"beforeUpdate doesn't seem to be called","tags":["javascript","node.js","passwords","hook","sequelize.js"],"text":"Title: beforeUpdate doesn't seem to be called\nTags: javascript, node.js, passwords, hook, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n*I have a simple user model as follows :*\n\n```\n'use strict';\n\nlet hashPassword = (user, options) => {\n if (!user.changed('password')) { return; }\n return require('bcrypt')\n .hash(user.getDataValue('password'), 10)\n .then(hash => user.setDataValue('password', hash));\n};\n\nmodule.exports = (sequelize, DataTypes) => {\n const User = sequelize.define('User', {\n username: {allowNull: false, type: DataTypes.STRING, unique: true},\n email: {allowNull: false, type: DataTypes.STRING, unique: true},\n password: {allowNull: false, type: DataTypes.STRING, unique: false},\n }, {\n hooks: {\n beforeCreate: hashPassword,\n beforeUpdate: hashPassword\n }\n });\n return User;\n};\n```\n\nIt works very well on user creation, but the `beforeUpdate` hook doesn't seem to work or be called, and the password is saved in plain text in the database.\n\n**Where does it come from and how can it be fixed ?**\n\n========================================\n\nTop Answer:\nTo offer an alternative to Unglückspilz answer. You can also add the option\n\n```\n{ individualHooks: true }\n```\n\n Note: methods like bulkCreate do not emit individual hooks by default - only the bulk hooks. However, if you want individual hooks to be emitted as well, you can pass the { individualHooks: true } option to the query call. However, this can drastically impact performance, depending on the number of records involved (since, among other things, all instances will be loaded into memory). \n\nhttps://sequelize.org/master/manual/hooks.html#model-hooks\n\n========================================\n\nCode:\n```text\n'use strict';\n\nlet hashPassword = (user, options) => {\n    if (!user.changed('password')) { return; }\n    return require('bcrypt')\n        .hash(user.getDataValue('password'), 10)\n        .then(hash => user.setDataValue('password', hash));\n};\n\nmodule.exports = (sequelize, DataTypes) => {\n    const User = sequelize.define('User', {\n        username: {allowNull: false, type: DataTypes.STRING, unique: true},\n        email: {allowNull: false, type: DataTypes.STRING, unique: true},\n        password: {allowNull: false, type: DataTypes.STRING, unique: false},\n    }, {\n        hooks: {\n            beforeCreate: hashPassword,\n            beforeUpdate: hashPassword\n        }\n    });\n    return User;\n};\n```\n\n```text\nbeforeUpdate\n```\n\n```text\nwhere\n```\n\n```text\nbeforeUpdate\n```\n\n```text\nbeforeBulkUpdate\n```\n\n```text\n{ individualHooks: true }\n```\n\n========================================\n\nComments:\n- It looks like you are right, I use `db.user.update(..., {where: {id: req.params.userId}});`. Thank you very much\n- can you post sample code, because i can't find what parameters actually are\n- const user = await User.update(req.body,{ where: { id }, individualHooks: true});","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":103,"estimatedTokens":716}}445{"id":"stack-43993725","source":"stackoverflow","questionId":43993725,"title":"syntax error at or near \"SERIAL\" with autoIncrement only","tags":["javascript","angularjs","postgresql","sequelize.js"],"text":"Title: syntax error at or near \"SERIAL\" with autoIncrement only\nTags: javascript, angularjs, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI get the error on build :\n\n Server failed to start due to error: SequelizeDatabaseError: syntax\n error at or near \"SERIAL\"\n\nThis error ONLY appears when the parameter autoIncrement=true is given to the primary key.\n\n```\n'use strict';\n\nexport default function(sequelize, DataTypes) {\n return sequelize.define('Ladder', {\n ladder_id: {\n type: DataTypes.UUID,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true //I have Sequelize 3.30.4 and postgreSQL 9.6.\n\nI want autoIncrement at true because I am generating the UUID with postgreSQL uuid_generate_v4().\n\n========================================\n\nTop Answer:\nMy guess is that `autoIncrement` for PostgreSQL is hardcoded to use SERIAL type for column and this conflicts with your choice of UUID.\n\nTry removing autoincrement parameter and instead use defaultvalue:\n\n```\nreturn sequelize.define('Ladder', {\n ladder_id: {\n type: DataTypes.UUID,\n allowNull: false,\n primaryKey: true,\n defaultValue: UUIDV4\n },\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nexport default function(sequelize, DataTypes) {\n  return sequelize.define('Ladder', {\n    ladder_id: {\n      type: DataTypes.UUID,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true //<------- If commented it works fine\n    },\n    ladder_name: {\n      type: DataTypes.STRING(50),\n      allowNull: false,\n      unique: true\n    },\n    ladder_description: {\n      type: DataTypes.TEXT,\n      allowNull: true\n    },\n    ladder_open: {\n      type: DataTypes.BOOLEAN,\n      allowNull: false\n    },\n    ladder_hidden: {\n      type: DataTypes.BOOLEAN,\n      allowNull: false\n    },\n    ladder_creation_date: {\n      type: DataTypes.DATE,\n      allowNull: false\n    },\n    ladder_fk_user: {\n      type: DataTypes.INTEGER,\n      allowNull: false\n    },\n    ladder_fk_game: {\n      type: DataTypes.UUID,\n      allowNull: false\n    },\n    ladder_fk_platforms: {\n      type: DataTypes.ARRAY(DataTypes.UUID),\n      allowNull: false\n    }\n\n  },\n    {\n      schema: 'ladder',\n      tableName: 'ladders'\n    });\n}\n```\n\n```text\nladder_id: {\n    type: DataTypes.UUID,\n    allowNull: false,\n    primaryKey: true,\n    default: sequelize.fn('uuid_generate_v4')\n}\n```\n\n```text\nreturn sequelize.define('Ladder', {\n    ladder_id: {\n      type: DataTypes.UUID,\n      allowNull: false,\n      primaryKey: true,\n      defaultValue: UUIDV4\n    },\n```\n\n```text\nautoIncrement\n```\n\n```js\nchild_id: {\n    primaryKey: true,\n    autoIncrement: true,\n    type: Sequelize.INTEGER\n},\nparent_id: {\n    references: {\n        model: 'parent',\n        key: 'parent_id'\n    },\n    type: Sequelize.INTEGER\n}\n```\n\n========================================\n\nComments:\n- But that would make Sequelize generate the UUID. The thing is that I want postgreSQL to take care of it.\n- So if I get that right you cannot tell Sequelize to let PostgreSQL generate the UUID through the default value configured when I created the table ?\n- no this is what it does. passes a call to the postgresql generator. That's what sequelize.fn does\n- Yes but sequelize passes himself the call. He doesn't use the default value configurated in PostgreSQL. But I know what to do now. Thank you.\n- glad it helped. all the best with your project\n- Just a tip: generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":145,"estimatedTokens":892}}446{"id":"stack-19003148","source":"stackoverflow","questionId":19003148,"title":"get .findOrCreate() error","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: get .findOrCreate() error\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using `Sequelize` as ORM. Here's my user model:\n\n```\n###\n User model\n###\nUser = exports.User = globals.sequelize.define \"User\",\n username: globals.Sequelize.STRING\n email:\n type: globals.Sequelize.STRING\n validate:\n isEmail: true\n hash: globals.Sequelize.STRING\n salt: globals.Sequelize.STRING(512)\n fname: globals.Sequelize.STRING\n lname: globals.Sequelize.STRING\n country: globals.Sequelize.STRING\n```\n\nI'm saving user:\n\n```\nglobals.models.User.findOrCreate\n username: \"johny\"\n password: \"pass\"\n email: \"johny93[###]example.com\"\n.success (user, created)->\n console.log user.values\n res.send 200\n.error ->\n console.log err # how to catch this?\n res.send 502\n```\n\nIf email is valid (email: \"johny93@example.com\"), everything works great. But if email fails validation (as in the example above), I get an insertion error. How to catch error type? `.error` method can't get any error parameters.\n\n========================================\n\nTop Answer:\n```\nUser.findOrCreate({\n where: {\n username: \"johny\",\n password: \"pass\",\n email: \"johny93[###]example.com\"\n },\n defaults: {\n //properties to be created \n }\n}).then(function(user){\n var created = user[1];\n user = user[0];\n console.log(user.values);\n}).fail(function(err){\n console.log('Error occured', err);\n});\n```\n\nhttps://github.com/sequelize/sequelize/wiki/Upgrading-to-2.0\n\nEDIT: as @Domi pointed out, better way is to use 'spread' instead of 'then' \n\n```\nUser.findOrCreate({\n where: {\n username: \"johny\",\n password: \"pass\",\n email: \"johny93[###]example.com\"\n },\n defaults: {\n //properties to be created \n }\n}).spread(function(user, created){\n console.log(user.values);\n}).fail(function(err){\n console.log('Error occured', err);\n});\n```\n\n========================================\n\nCode:\n```text\n###\n    User model\n###\nUser = exports.User =  globals.sequelize.define \"User\",\n    username: globals.Sequelize.STRING\n    email:\n        type: globals.Sequelize.STRING\n        validate:\n            isEmail: true\n    hash:     globals.Sequelize.STRING\n    salt:     globals.Sequelize.STRING(512)\n    fname:    globals.Sequelize.STRING\n    lname:    globals.Sequelize.STRING\n    country:  globals.Sequelize.STRING\n```\n\n```text\nglobals.models.User.findOrCreate\n    username: \"johny\"\n    password: \"pass\"\n    email: \"johny93[###]example.com\"\n.success (user, created)->\n    console.log user.values\n    res.send 200\n.error ->\n    console.log err # how to catch this?\n    res.send 502\n```\n\n```text\nSequelize\n```\n\n```text\n.error\n```\n\n```text\nUser.findOrCreate({username: \"johny\",password: \"pass\",email: \"johny93[###]example.com\"})\n.success(function(user, created){\n    console.log(user.values);\n    res.send(200);\n})\n.error(function(err){\n   console.log('Error occured' + err);\n})\n```\n\n```text\nglobals.models.User.findOrCreate\n    username: \"johny\"\n    password: \"pass\"\n    email: \"johny93[###]example.com\"\n.success (user, created)->\n    console.log user.values\n    res.send 200\n.error (error)->\n    console.log error # how to catch this?\n    res.send 502\n```\n\n```text\nUser.findOrCreate({\n  where: {\n    username: \"johny\",\n    password: \"pass\",\n    email: \"johny93[###]example.com\"\n  },\n  defaults: {\n    //properties to be created \n  }\n}).then(function(user){\n  var created = user[1];\n  user = user[0];\n  console.log(user.values);\n}).fail(function(err){\n   console.log('Error occured', err);\n});\n```\n\n```text\nUser.findOrCreate({\n  where: {\n    username: \"johny\",\n    password: \"pass\",\n    email: \"johny93[###]example.com\"\n  },\n  defaults: {\n    //properties to be created \n  }\n}).spread(function(user, created){\n  console.log(user.values);\n}).fail(function(err){\n   console.log('Error occured', err);\n});\n```\n\n```text\nUser.findOrCreate({\n  where: {\n    username: 'johny',\n    password: 'pass',\n    email: 'johny93[###]example.com'\n  }\n}).then(function (user) {\n  res.send(200);\n}).catch(function (err) {\n  console.log(err);\n  res.send(502);\n});\n```\n\n========================================\n\nComments:\n- Can you turn on SQL logs for sequelize. It will give you the query you're trying to run that's causing the error. also @Sriharsha is correct that you need to specifiy the args string in order to console.log the error\n- thank you, I can't explain why it had not worked for me before. For example as error I get a string `Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect integer value: '' for column 'coreNumber' at row 1`. How can I get smth like error code and row id? I need this to handle input errors automatically to show error for user. Or will it be better to validate input before insertion to DB manually?\n- Are you looking for a regex that will pull ER_TRUNCATED_WRONG_VALUE_FOR_FIELD and row 1 out of that error string?\n- According to the link you shared, this code works, but it's not the recommended way to work with methods that return multiple arguments. You can use `spread(user, created)` instead of `then(userAndCreatedInOneArray)` with `findOrCreate`, to save you working with the array you call `user` (but is really not the user).\n- In Sequelize 3.0, it is recommended to user .spread() docs.sequelizejs.com/en/latest/api/model/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":208,"estimatedTokens":1304}}447{"id":"stack-38650200","source":"stackoverflow","questionId":38650200,"title":"how to catch Sequelize connection error","tags":["node.js","sequelize.js"],"text":"Title: how to catch Sequelize connection error\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow to catch a sequelize connection error in case there is one?\n\nI tried to do\n\n```\nvar connection = new Sequelize(\"db://uri\");\nconnection.on(\"error\", function() { /* perhaps reconnect here */ });\n```\n\nbut apparently this is not supported.\n\nI wanted to do this because I think sequelize might be throwing an occasional unhandled ETIMEOUT and crashing my node process.\n\nCurrently I am using sequelize to connect a mysql instance. I only need it for like 2-3 hours and during that time I will be doing a many read queries. The mysql server will not be connected to anything else during that time.\n\n========================================\n\nTop Answer:\nUsing sequelize sync method provides an easy way to catch the error.\nThe then block handles a Successful connection and the catch handles the rejection.To get a detailed reason for a failure access the error object.\nexample: `error.message e.t.c`\nHope this helps.\n\n```\nsequelize.sync().\nthen(function() {\n console.log('DB connection sucessful.');\n}).catch(err=> console.log('error has occured'));\n```\n\n========================================\n\nCode:\n```text\nvar connection = new Sequelize(\"db://uri\");\nconnection.on(\"error\", function() { /* perhaps reconnect here */ });\n```\n\n```text\nsequelize\n  .authenticate()\n  .then(() => {\n    console.log('Connection has been established successfully.');\n  })\n  .catch(err => {\n    console.error('Unable to connect to the database:', err);\n  });\n```\n\n```text\nauthenticate()\n```\n\n```text\nvar Sequelize = require('sequelize');\n\nsequelize = new Sequelize(config.database, config.username, config.password, {\n    'host' : config.host,\n    'dialect' : config.dialect,\n    'port' : config.port,\n    'logging' : false\n  })\n\nsequelize.sync().then(function(){\n  console.log('DB connection sucessful.');\n}, function(err){\n  // catch error here\n  console.log(err);\n\n});\n```\n\n```text\nsequelize.sync().\nthen(function() {\n  console.log('DB connection sucessful.');\n}).catch(err=> console.log('error has occured'));\n```\n\n```text\nerror.message e.t.c\n```\n\n```text\ntry {\n  await sequelize.authenticate()\n} catch (err) {\n  console.error('Unable to connect to the database:', err)\n}\n```\n\n```text\nprocess.on('unhandledRejection', (err : any) => {\n    console.error('Unhandled Rejection — ', err);\n    core.log.error('unhandled_exception', err);        \n    core.handle(err);\n});\n\nprocess.on('uncaughtException', (err : any) => {\n    console.error('Uncaught Exception — ', err);\n    core.log.error('unhandled_exception', err);        \n    core.handle(err);\n});\n```\n\n========================================\n\nComments:\n- Cool thanks I will try it out. I did sequelize.authenticate().then(resolve, reject) before and the reject was never invoked.","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":705}}448{"id":"stack-6358989","source":"stackoverflow","questionId":6358989,"title":"Sequelize, problem getting associations to return","tags":["node.js","sequelize.js"],"text":"Title: Sequelize, problem getting associations to return\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently experimenting with Sequelize and have two objects, a `Person` and `Position`, When getting a list of persons I want to get their position. \n\nmodels:\n\n```\nvar User = sequelize.define('user', {\n first_name: Sequelize.STRING,\n last_name: Sequelize.STRING \n});\n\nvar Position = sequelize.define('position', {\n name: Sequelize.STRING,\n affiliation: Sequelize.STRING\n});\n\nPosition.hasMany(User, { foreignKey : 'position_id' });\nUser.belongsTo(Position, { foreignKey : 'position_id'});\n```\n\nMy query:\n\n```\nUser.findAll({ fetchAssociations: true }, function(results) {\n //I've tried doing some work in here, but haven't found the correct procedure. \n}).on('success', function(results) {\n res.render('users', {\n title: 'user page',\n users: results\n });\n});\n```\n\nWatching the log it never queries `Person` at all. Do I need to use queryChaining? From the documentation I was able to find it appeared it should auto fetch associations.\n\n========================================\n\nTop Answer:\nFrom April 2013 in v1.7.0 you need just to expand your **Associations** to:\n\n```\nPosition.hasMany(User, {foreignKey : 'position_id', as: 'User'});\nUser.belongsTo(Position, {foreignKey : 'position_id', as: 'Posit'});\n```\n\nand then find all Users with associated Positions\n\n```\nUser.findAll({\n include: [{\n model: Position, as: 'Posit'\n }]\n}).success(function(match) {\n // your logic\n});\n```\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('user', {\n    first_name: Sequelize.STRING,\n    last_name: Sequelize.STRING \n});\n\nvar Position = sequelize.define('position', {\n    name: Sequelize.STRING,\n    affiliation: Sequelize.STRING\n});\n\nPosition.hasMany(User, { foreignKey : 'position_id' });\nUser.belongsTo(Position, { foreignKey : 'position_id'});\n```\n\n```text\nUser.findAll({ fetchAssociations: true }, function(results) {\n    //I've tried doing some work in here, but haven't found the correct procedure. \n}).on('success', function(results) {\n    res.render('users', {\n        title: 'user page',\n        users: results\n    });\n});\n```\n\n```text\nPerson\n```\n\n```text\nPosition\n```\n\n```text\nPerson\n```\n\n```text\nUser.findAll().on('success', function(users) {\n  var chainer = new Sequelize.Utils.QueryChainer\n    , _users  = []\n\n  users.forEach(function(u) {\n    var emitter = new Sequelize.Utils.CustomEventEmitter(function() {\n      u.getPosition().on('success', function(pos) {\n        _users.push({user: u, position: pos})\n        emitter.emit('success')\n      })\n    })\n    chainer.add(emitter.run())\n  })\n  chainer.run().on('success', function() {\n    res.render('users', {\n      title: 'user page',\n      users: _users\n    })\n  })\n})\n```\n\n```text\nUser.findAll().on('success', function(users) {\n  // asd\n})\n```\n\n```text\nPosition.hasMany(User, {foreignKey : 'position_id', as: 'User'});\nUser.belongsTo(Position, {foreignKey : 'position_id', as: 'Posit'});\n```\n\n```text\nUser.findAll({\n      include: [{\n        model: Position, as: 'Posit'\n      }]\n}).success(function(match) {\n    // your logic\n});\n```\n\n```text\n// define models \nvar Person = sequelize.define('Person', { name: Sequelize.STRING });\nvar Task = sequelize.define('Task', {\nname: Sequelize.STRING,\nnameWithPerson: {\n    type: Sequelize.VIRTUAL,\n    get: function() { return this.name + ' (' + this.Person.name + ')' }\n    attributes: [ 'name' ],\n    include: [ { model: Person, attributes: [ 'name' ] } ],\n    order: [ ['name'], [ Person, 'name' ] ]\n}\n});\n\n// define associations \nTask.belongsTo(Person);\nPerson.hasMany(Task);\n\n// activate virtual fields functionality \nsequelize.initVirtualFields();\n```\n\n========================================\n\nComments:\n- thanks so much for your response. If I understand you correctly, in v1.0 of sequelize there is currently no functionality for getting associated objects? Thanks for the tip on the underscores, I'm currently \"proof of concepting\" against a simple, but pre-existing db, I'll take that into note.\n- Oh there is association support but not via fetchAssociation. You can do user.getPosition().on('success',... I will post a workaround for your problem later.\n- Hah, I have no idea, I must have misread something at some point, sorry about that.\n- Thanks for the snippet, I'll play around with this a bit.\n- Your code has helped me tremendously. Would you mind if I asked where exactly you got the idea to implement a CustomEventEmitter? Since that ain't even in the API.\n- Actually having trouble with that since it keeps on returning _users filled with the last entered user. :|\n- Fixed it by embedding the insides of the forloop inside another anonymous fx whew\n- This post has help me retrieve associated objects. I was about to give up but I was luckily to have found this post. @sdepold can you please write more examples on how to do this in your documentation. Thanks!\n- There is now an even better solution :) You can now (with the current alpha release of 1.6.0) do this: `User.findAll({ include: ['position']})`. Doing so will include an attribute positions for all resulting users :)","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":180,"estimatedTokens":1290}}449{"id":"stack-28895593","source":"stackoverflow","questionId":28895593,"title":"Sequelize grouping by hours of a date range","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize grouping by hours of a date range\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to sequelize (postgres) and I cannot fin in the documentation how to select the hours of the day (date range), group by them and perform a count.\n\nThe query looks like this:\n\n```\nSELECT\n COUNT (*),\n EXTRACT (HOUR FROM paid_at) AS HOUR\nFROM\n transactions\nWHERE paid_at >= '2015-01-01 00:00:00' AND paid_at Could someone send me in the right direction please? I find the sequelize documenation very very basic. Advanced examples are missing.\n\n========================================\n\nCode:\n```text\nSELECT\n    COUNT (*),\n    EXTRACT (HOUR FROM paid_at) AS HOUR\nFROM\n    transactions\nWHERE paid_at >= '2015-01-01 00:00:00' AND paid_at <= '2015-01-31 23:59:59'\nGROUP BY\n    HOUR\nORDER BY hour asc\n```\n\n```text\nvar payments_by_hour = await Payment.findAll({\n  where: { \n    paid_at: {\n      $lte: '2015-01-31 23:00:00',\n      $gte: '2015-01-01 00:00:00'\n    }\n  },\n  attributes: [\n    [ sequelize.fn('date_trunc', 'hour', sequelize.col('updated_at')), 'hour'],\n    [ sequelize.fn('count', '*'), 'count']\n  ],\n  group: 'hour'\n});\n```\n\n```text\n$lte: new Date(),\n$gte: new Date(new Date() - 24 * 3600 * 1000)\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":310}}450{"id":"stack-49837932","source":"stackoverflow","questionId":49837932,"title":"Sequelize query Or-ing where and include statements","tags":["javascript","sql","sequelize.js"],"text":"Title: Sequelize query Or-ing where and include statements\nTags: javascript, sql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying make a Sequelize query that returns only records that match a **where clause** or **include wheres**. For example I have a user model that belongs to a person model. The user model has one field called username and the person model has a first and last name. \n\nExample Query:\n\n```\n{\n \"where\": {\n \"username\": {\n \"$iLike\": \"%s%\"\n }\n },\n \"include\": [{\n \"model\": Person,\n \"where\": {\n \"$or\": [{\n \"firstName\": {\n \"$iLike\": \"%s%\"\n }\n }, {\n \"lastName\": {\n \"$iLike\": \"%s%\"\n }\n }]\n }\n }]\n}\n```\n\nThe query above matches records that have a username AND (firstname or lastname) matching \"ilike\" 's'. I am trying to achieve username OR (firstname or lastname).\n\nI know how do use Or operators when working inside of a where but I want to use an Or on where or include. Is this possible? Do I use required false?\n\n========================================\n\nCode:\n```text\n{\n    \"where\": {\n      \"username\": {\n        \"$iLike\": \"%s%\"\n      }\n    },\n    \"include\": [{\n        \"model\": Person,\n        \"where\": {\n            \"$or\": [{\n                \"firstName\": {\n                    \"$iLike\": \"%s%\"\n                }\n            }, {\n                \"lastName\": {\n                    \"$iLike\": \"%s%\"\n                }\n            }]\n        }\n    }]\n}\n```\n\n```text\n{\nwhere: {\n  $or: [\n    {\n      userName: {\n        $ilike: \"%s%\"\n      }\n    },\n    {\n      '$person.firstName$': {\n        $ilike: \"%s%\"\n      }\n    },\n    {\n      '$person.lastName$': {\n        $ilike: \"%s%\"\n      }\n    }\n  ]\n},\ninclude: [\n  {\n    model: Person,\n  }\n]\n}\n```\n\n========================================\n\nComments:\n- Any idea how to do this on a model with a `hasMany` relationship? If there were more than one person, for example, this code wouldn't work. This works because there is only one person associated with this user model.\n- Just replace \"person\" with \"persons\" or whatever alias your are using. See sequelize.org/v5/manual/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":98,"estimatedTokens":513}}451{"id":"stack-47563038","source":"stackoverflow","questionId":47563038,"title":"Sequelize: difference of DataTypes and Sequelize","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize: difference of DataTypes and Sequelize\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have seen the use of both classes for defining data types, including in the official documentation, both apparently serve the same purpose.\n\nOn a tutorial, I saw the application was using DataTypes for the Model and Sequelize for Migrations, you can exchange between them and they continue to work. Example codes:\n\nModel using DataTypes:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Driver = sequelize.define('Driver', {\n firstName: {\n type: DataTypes.STRING(50),\n allowNull: false\n },\n```\n\nMigration using Sequelize:\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Drivers', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n```\n\n========================================\n\nTop Answer:\nAs stated in the docs, DataTypes is:\n\n A convenience class holding commonly used data types.\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Driver = sequelize.define('Driver', {\n    firstName: {\n      type: DataTypes.STRING(50),\n      allowNull: false\n    },\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('Drivers', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n```\n\n```text\nconst Sequelize = require('sequelize');\n```\n\n```text\nconst model = require(path.join(__dirname, file))(sequelize, Sequelize);\n```\n\n```text\nmodule.exports = (sequelize, asd) => {\n    const Driver = sequelize.define('Driver', {\n    firstName: {\n      type: asd.STRING(50),\n      allowNull: false\n    },\n```\n\n========================================\n\nComments:\n- I wanna know if we need to write types exactly same in models and migration files, writing `DataTypes.INTEGER(50)` works fine in model, but throws syntax error when written in migration file.","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":86,"estimatedTokens":519}}452{"id":"stack-49529231","source":"stackoverflow","questionId":49529231,"title":"Transaction Management in nodejs with mysql","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: Transaction Management in nodejs with mysql\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am working on nodejs with **MySQL**. I need to implement **transaction management** while inserting data in to multiple tables. So that I can **rollback** all insertions if any error occur. \n\nAll DB related operations are declared in different classes of each entity in DB layer. In business logic layer on a single operation we may need to handle multiple db layer calls from different entity. In JAVA Spring We can simply *annotate* **@Transaction** on service layer. \n\nIs there anything like this in nodejs?\n\n========================================\n\nTop Answer:\nComing from a java background, you may want to take a look at `sequelize` and `zb-sequelize`.\n\n- Sequelize is a layer which acts like a driver to connect to many different SQL-based databases.\n\n- ZB-sequelize is an extension to sequelize which adds the `@Transactional` decorator.\n\nIt simplifies transaction management to a point where you don't have to create, commit or rollback transactions at all. All of that is taken care of by those 2 decorators.\n\n```\nimport { Transactional, Tx } from 'zb-sequelize';\n\n@Transactional\nfunction fooBar(@Tx transaction) {\n foo(transaction);\n bar(transaction);\n}\n```\n\nIf you've worked with Spring before, then this will certainly look familiar.\n\n========================================\n\nCode:\n```js\nconst mysql = require('mysql');\n \nconst connection = mysql.createConnection(\n    {\n      host     : 'YOUR_HOST',\n      user     : 'YOUR_USERNAME',\n      password : 'YOUR_PASSWORD',\n      database : 'YOUR_DB_NAME'\n    }\n);\n \nconnection.connect(function(err) {\n  if (err) {\n    console.error('error connecting: ' + err.stack);\n    return;\n  }\n  console.log('connected as id ' + connection.threadId);\n});\n \n/* Begin transaction */\nconnection.beginTransaction(function(err) {\n  if (err) { throw err; }\n  connection.query('YOUR QUERY', \"PLACE HOLDER VALUES\", function(err, result) {\n    if (err) { \n      connection.rollback(function() {\n        throw err;\n      });\n    }\n \n    const log = result.insertId;\n \n    connection.query('ANOTHER QUERY PART OF TRANSACTION', log, function(err, result) {\n      if (err) { \n        connection.rollback(function() {\n          throw err;\n        });\n      }  \n      connection.commit(function(err) {\n        if (err) { \n          connection.rollback(function() {\n            throw err;\n          });\n        }\n        console.log('Transaction Completed Successfully.');\n        connection.end();\n      });\n    });\n  });\n});\n/* End transaction */\n```\n\n```js\nfunction executeTransaction(queries) {\n    try {\n      const connection = yield getConnectionObj({/* your db params to get connection */)\n  \n      let results = []\n\n      return new Promise(function(resolve, reject) {\n        connection.beginTransaction(function (err) {\n          if (err) throw err\n\n          console.log(\"Starting transaction\")\n\n          queries\n            .reduce(function (sequence, queryToRun) {\n              return sequence.then(function () {\n                /* pass your query and connection to a helper function and execute query there */\n                return queryConnection(\n                  connection,\n                  query,\n                  queryParams,\n                ).then(function (res) {\n                  /* Accumulate resposes of all queries */\n                  results = results.concat(res)\n                })\n              }).catch(function (error) {\n                reject(error)\n              })\n            }, Promise.resolve())\n            .then(function () {\n              connection.commit(function (err) {\n                if (err) {\n                  connection.rollback(function () {\n                    throw err\n                  })\n                }\n                console.log('Transactions were completed!')\n                /* release connection */\n                connection.release()\n                /* resolve promise with all results */\n                resolve({ results })\n              })\n            })\n            .catch(function (err) {\n              console.log('Transaction failed!')\n              connection.rollback(function () {\n                console.log('Abort Transaction !!!')\n                throw err\n              })\n            })\n        })\n      })\n   /* End Transaction */\n\n    } catch (error) {\n      return Promise.reject(error)\n    }\n  }\n```\n\n```text\nconnect\n```\n\n```text\nbeginTransaction\n```\n\n```text\nrollback\n```\n\n```text\ncommit\n```\n\n```text\nend\n```\n\n```text\nimport { Transactional, Tx } from 'zb-sequelize';\n\n@Transactional\nfunction fooBar(@Tx transaction) {\n  foo(transaction);\n  bar(transaction);\n}\n```\n\n```text\nsequelize\n```\n\n```text\nzb-sequelize\n```\n\n```text\n@Transactional\n```\n\n========================================\n\nComments:\n- I implemented it the same way you provided in the example, but for a reason it doesn't `rollback` , The first query is executed even if the second query failed, might be something should be related to configuration in the `mysql database`? The database type i am using is `innoDB`. I have been stuck on this since days. I have already opened a question. I appreciate your help there. stackoverflow.com/questions/61593344/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":196,"estimatedTokens":1322}}453{"id":"stack-35346563","source":"stackoverflow","questionId":35346563,"title":"How can I trigger the beforeCreate hook when bulkCreating in Sequelize?","tags":["sequelize.js"],"text":"Title: How can I trigger the beforeCreate hook when bulkCreating in Sequelize?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a `beforeCreate` hook in a Sequelize model (runs bcrypt on the password in a `User` table), and would like to create a user in the seed file. Functions like bulkCreate simply insert into the database, and so don't call any hooks (including the `createdAt`/`updatedAt`). How do I create with the hooks called in a way that matches the format required by the seeder?\n\nIt seems like many are just using `sequelize-fixtures`? Is this the way to go? Or I could just ignore the seed format, and use the standard .create/.build and .save format?\n\nAlso, where is documentation related to seeding located? The Google searches were pretty light in terms of info.\n\n========================================\n\nCode:\n```text\nbeforeCreate\n```\n\n```text\nUser\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nsequelize-fixtures\n```\n\n```text\nUser.bulkCreate(users, {individualHooks: true}).then(function() {\n  console.log(\"Done!\");\n});\n```\n\n```text\nfunction hashPassword(user, options, fn) {\n  //Don't hash if password is already hashed\n  if (user.dataValues.password.indexOf('$2a$') === 0) {\n    fn(null, user);\n    return;\n  }\n\n  bcrypt.hash(user.password, 10, function(err, hash) {\n    if (err) {\n      console.log('Error while generating hash!');\n      fn(err, null);\n      return;\n    }\n    user.password = hash;\n    fn(null, user);\n  });\n}\n```\n\n```text\nindividualHooks\n```\n\n```text\nbeforeUpdate\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":67,"estimatedTokens":384}}454{"id":"stack-56213758","source":"stackoverflow","questionId":56213758,"title":"ON DELETE CASCADE for multiple foreign keys with Sequelize","tags":["sql","sqlite","foreign-keys","sequelize.js","cascade"],"text":"Title: ON DELETE CASCADE for multiple foreign keys with Sequelize\nTags: sql, sqlite, foreign-keys, sequelize.js, cascade\nSource: Stack Overflow\n\nQuestion:\nSuppose I have three models:\n\n- **Task:** A thing that needs done, like \"take out the recycling\". Can be done many times.\n\n- **TaskList:** An object that represents a list of tasks, and has its own metadata.\n\n- **TaskListEntry:** An association between Task and TaskList, that may have data such as the priority or who is assigned to it.\n\nI have my associations set up like this:\n\n```\nTask.hasMany(TaskListEntry, {onDelete: 'cascade', hooks: true}));\n\nTaskList.hasMany(TaskListEntry, {onDelete: 'cascade', hooks: true});\n\nTaskListEntry.belongsTo(TaskList);\nTaskListEntry.belongsTo(Task);\n```\n\nThis works fine, except for deleting. When I delete a Task, any associated TaskListEntries are deleted as expected. However, when I delete a TaskList, its associated TaskListEntries simply have their foreign key for the TaskList set to `null`.\n\nIt seems that Sequelize is generating the following table:\n\n```\nCREATE TABLE `TaskListEntries`(\n `id` UUID PRIMARY KEY, \n /* some other fields here */\n `createdAt` DATETIME NOT NULL, \n `updatedAt` DATETIME NOT NULL, \n `TaskId` UUID REFERENCES `Tasks`(`id`) ON DELETE CASCADE ON UPDATE CASCADE, \n `TaskListId` UUID REFERENCES `TaskLists`(`id`) ON DELETE SET NULL ON UPDATE CASCADE);\n```\n\nDespite the associations being configured the same, the foreign keys for Tasks and TaskLists have different `DELETE` behavior. If I remove one of the associations, the other works just fine.\n\nTherefore, I think the issue is multiple foreign keys with `ON DELETE CASCADE`, at least as far as Sequelize seeis it.\n\nAny thoughts on how to correct this?\n\n========================================\n\nTop Answer:\ncan you try \n\n```\nTaskListEntry.belongsTo(TaskList);\nTaskListEntry.belongsTo(Task);\n```\n\ninstead of \n\n```\nTaskListEntry.belongsToMany(TaskList);\nTaskListEntry.belongsToMany(Task);\n```\n\nBecause, from my understanding of this problem, a single TaskListEntry record can only belong to a single Task and a single TaskList. \n\nOr Are you trying to establish a Many-to-Many relationship here? In that case, I don't think this is the ideal way of implementation.\n\n========================================\n\nCode:\n```text\nTask.hasMany(TaskListEntry, {onDelete: 'cascade', hooks: true}));\n\nTaskList.hasMany(TaskListEntry, {onDelete: 'cascade', hooks: true});\n\nTaskListEntry.belongsTo(TaskList);\nTaskListEntry.belongsTo(Task);\n```\n\n```text\nCREATE TABLE `TaskListEntries`(\n  `id` UUID PRIMARY KEY, \n  /* some other fields here */\n  `createdAt` DATETIME NOT NULL, \n  `updatedAt` DATETIME NOT NULL, \n  `TaskId` UUID REFERENCES `Tasks`(`id`) ON DELETE CASCADE ON UPDATE CASCADE, \n  `TaskListId` UUID REFERENCES `TaskLists`(`id`) ON DELETE SET NULL ON UPDATE CASCADE);\n```\n\n```text\nnull\n```\n\n```text\nDELETE\n```\n\n```text\nON DELETE CASCADE\n```\n\n```text\nTaskListEntry.belongsTo(TaskList, {\n  onDelete: 'cascade', \n  foreignKey: { allowNull: false }    //   <-------------\n  hooks: true\n});\n```\n\n```text\nclass User extends Model {}\nUser.init({}, { sequelize, modelName: 'user' })\n\nclass Project extends Model {}\nProject.init({}, { sequelize, modelName: 'project' })\n\nclass UserProjects extends Model {}\nUserProjects.init({\n  status: DataTypes.STRING\n}, { sequelize, modelName: 'userProjects' })\n\nUser.belongsToMany(Project, { through: UserProjects })\nProject.belongsToMany(User, { through: UserProjects })\n```\n\n```text\nallowNull:false\n```\n\n```text\nforeignKey\n```\n\n```text\nTaskListEntry.belongsTo(TaskList);\nTaskListEntry.belongsTo(Task);\n```\n\n```text\nTaskListEntry.belongsToMany(TaskList);\nTaskListEntry.belongsToMany(Task);\n```\n\n========================================\n\nComments:\n- Please in code questions give a minimal reproducible example--cut & paste & runnable code; example input with desired & actual output (including verbatim error messages); clear specification & explanation. That includes the least code you can give that is code that you show is OK extended by code that you show is not OK. (Debugging fundamental.)\n- Ah, thank you! I am very sorry... I *am* using `.belongsTo` for both. I accidentally posted some experimentation in my question instead of the real code. Sorry about that, thank you for your reply in correcting me. I have corrected the code in my question. Yes, a single TaskListEntry is associated with only one Task and one TaskList. A Task can have multiple TaskListEntries associated with it, as can a TaskList.\n- Correct me if I am wrong. Do you need both belongsTo and hasMany relationship? Ideally you can remove the belongsTo associations on the last two lines. I feel it is worth giving a shot.\n- Thanks, the \"through\" example is what I needed. I didn't realize I was able to add additional properties there, and query directly. Thanks for the help!","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":148,"estimatedTokens":1214}}455{"id":"stack-20600483","source":"stackoverflow","questionId":20600483,"title":"Is there a way to change the default \"id\" column that is created automatically?","tags":["node.js","sequelize.js"],"text":"Title: Is there a way to change the default \"id\" column that is created automatically?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen Sequelize saves an instance to a database (eg. MySQL) it automatically adds an \"id\" field at the end (auto-incremented also). I've read the articles and the documentation but I couldn't find any way to disable it.\n\nThank you.\n\n========================================\n\nCode:\n```text\nvar addDefaultAttributes = function() {\n    var self              = this\n      , defaultAttributes = {\n        id: {\n          type: DataTypes.INTEGER,\n          allowNull: false,\n          primaryKey: true,\n          autoIncrement: true\n        }\n      }\n\n    if (this.hasPrimaryKeys) {\n      defaultAttributes = {}\n    }\n\n    ... etc. ...\n```\n\n========================================\n\nComments:\n- Any reason why you would want to remove it? Also, which MySQL client are you using?","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":35,"estimatedTokens":230}}456{"id":"stack-60778574","source":"stackoverflow","questionId":60778574,"title":"Sequelize Query Where not equal and Other Conditions","tags":["node.js","sequelize.js"],"text":"Title: Sequelize Query Where not equal and Other Conditions\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to make the query id not equal in Sequelize.\n\nHere is my current sequelize query:\n\n```\nreturn db.Area.findAll({\n where: { id: { $ne: Id },\n slug: conditions.slug }\n})\n```\n\nThe resulting SQL Query:\n\n```\n*SELECT `id`, `title`, `name`, `titleL1`, `nameL1`, `level`, `slug`, `createdAt`, `updatedAt`, `ParentId` FROM `Areas` AS `Area` \nWHERE `Area`.`id` = '[object Object]' AND `Area`.`slug` = 'Nakyal-1';*\n```\n\nThis part is not correct:\n\n```\nWHERE `Area`.`id` = '[object Object]'\n```\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```js\nreturn db.Area.findAll({\n    where: { id: { $ne: Id },\n    slug: conditions.slug }\n})\n```\n\n```sql\n*SELECT `id`, `title`, `name`, `titleL1`, `nameL1`, `level`, `slug`, `createdAt`, `updatedAt`, `ParentId` FROM `Areas` AS `Area` \nWHERE `Area`.`id` = '[object Object]' AND `Area`.`slug` = 'Nakyal-1';*\n```\n\n```sql\nWHERE `Area`.`id` = '[object Object]'\n```\n\n```text\nconst Op = require('sequelize').Op;\n***\nwhere: { id: { [Op.ne]: Id }... }\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":55,"estimatedTokens":282}}457{"id":"stack-30747132","source":"stackoverflow","questionId":30747132,"title":"How to add a case-insensitive unique constraint in a SequelizeJS Model when using Postgresql?","tags":["node.js","postgresql","sequelize.js"],"text":"Title: How to add a case-insensitive unique constraint in a SequelizeJS Model when using Postgresql?\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\nvar Model = sequelize.define('Company', {\n name: {\n type: DataTypes.STRING,\n unique: true\n }\n}\n```\n\nIn the above example, unique: true is case sensitive. It allows both \"sample\" and \"Sample\" to be saved in the db. Is there a built-in way to do this in sequelize without having to write a custom validator?\n\n========================================\n\nTop Answer:\n01AUG2022 update. I stumbled across this while trying to solve the same problem and I come with good news! As long as you're using Postgres or SQLite you can set your data type to `type: DataTypes.CITEXT` and your values will retain their case in the database while also giving a Validation error if you try to add another entry regardless of case.\n\nTLDR: `testuser` and `TestUser` will throw a validation error if the column type is `CITEXT`.\n\n========================================\n\nCode:\n```text\nvar Model = sequelize.define('Company', {\n  name: {\n    type: DataTypes.STRING,\n    unique: true\n  }\n}\n```\n\n```text\nvar Model = sequelize.define('Company', {\n  name: {\n    type: DataTypes.STRING\n  }\n}, \n{\n  indexes: [\n    { \n      unique: true,   \n      name: 'unique_name',  \n      fields: [sequelize.fn('lower', sequelize.col('name'))]   \n    }\n  ]\n});\n```\n\n```text\ntype: DataTypes.CITEXT\n```\n\n```text\ntestuser\n```\n\n```text\nTestUser\n```\n\n```text\nCITEXT\n```\n\n========================================\n\nComments:\n- Thanks! If that is violated, will sequelize throw a Sequelize.ValidationError like other sequelize validators?\n- @JohnKevinM.Basco Validation happens before the data is sent to the database, so I wouldn't expect so. Instead the save() function (or update() etc) will fail.\n- @curiousdannii Ah. Makes sense since this unique index will be done on the database level. So I guess if I add this unique index, I still need to write a custom case-insensitive unique validator. Thanks!\n- @Jan Aagaard Meier - I tried your suggestion above. But for some reason, it still allows both \"sample\" and \"Sample\" to be saved in the db. Any idea why? Hmm. Should I convert strings to lower case before I save them to db?\n- It should work out of the box - do you see a unique index `lower(name)` created in the log? Are you perhaps using an old version of sequelize, I believe `indexes` was introduced somewhere in 2.0\n- Woops, I forgot the most important part - that the index should actually be unique. Post updated\n- @JanAagaardMeier It works now after I added unique: true in the index. Thank you very much! :)\n- @JanAagaardMeier Is there supposed to be a `:` after `fields`?\n- @Noah Yes - Edited\n- I can't make a single character edit but there is a missing brace in the fields definition. `[sequelize.fn('lower', sequelize.col('name'))]`","metadata":{"transformedAt":"2026-08-18T18:33:34.376Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":81,"estimatedTokens":720}}458{"id":"stack-39834331","source":"stackoverflow","questionId":39834331,"title":"Sequelize: Including join table attributes in findAll include","tags":["sql","node.js","sql-server-2008","sequelize.js"],"text":"Title: Sequelize: Including join table attributes in findAll include\nTags: sql, node.js, sql-server-2008, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently working on an app for managing branches and employees in a company, using NodeJS, MSSQL, and Sequilize as the ORM. \n\nA requirement is to keep track of certain changes in a way that we can 'go back' to a date in the past and see the state of the company at that specific point in time. In order to do that, we are using time stamps (`initDate` and `endDate`) to track the changes we care about, i.e. changes to the branches, and movement of employees among the active branches. Every time a record is changed, we set its `endDate` to `now()` and create a new record with the change and `endDate = null`, so the 'current' version of every branch or branch-employee relation is the one with `endDate IS NULL`.\n\nThe problem we are facing right now with Sequelize is: How can we specify the `endDate` for the branch-employee relation when `findAll()`ing our employees, while eager-loading (i.e. `include`ing) their branches? In the example below I'm querying the 'current' state of the company, so i'm asking for `endDate: null`, but that's actually an argument saying the point in time we want.\n\nThanks a lot for your help. Any insight would be really appreciated!\n\n--- Here I include the model definitions and the query ---\n\nBranch model definition:\n\n```\nvar BranchModel = db.define('Branch', {\n IdBranch: {\n primaryKey: true,\n type: DataTypes.INTEGER\n },\n Name: DataTypes.STRING,\n // ... other fields ...\n initDate: DataTypes.DATE,\n endDate: DataTypes.DATE\n}, {\n timestamps: false,\n classMethods: {\n associate: function (models) {\n\n Branch.belongsToMany(models.model('Employee'), {\n through: {\n model: models.model('Branch_Employee')\n },\n as: 'Employees',\n foreignKey: 'branchId'\n });\n\n // ... other associations ..\n\n }\n }\n});\n```\n\nEmployee model definition:\n\n```\nvar EmployeeModel = db.define('Employee', {\n idEmployee: {\n primaryKey: true,\n type: DataTypes.INTEGER\n },\n Name: DataTypes.STRING,\n // ... other fields ...\n active: DataTypes.BOOLEAN\n}, {\n timestamps: false,\n defaultScope: {\n where: {\n active: true\n }\n },\n classMethods: {\n associate: function (models) {\n\n EmployeeModel.belongsToMany(models.model('Branch'), {\n through: {\n model: models.model('Branch_Employee')\n },\n foreignKey: 'employeeId'\n });\n\n // ... other associations ...\n }\n }\n});\n```\n\nJoin table definition:\n\n```\nvar Branch_Employee = db.define('Branch_Employee', {\n branchId: DataTypes.INTEGER,\n employeeId: DataTypes.INTEGER\n // ... some other attributes of the relation ...\n initDate: DataTypes.DATE,\n endDate: DataTypes.DATE,\n}, {\n timestamps: false,\n classMethods: {\n associate: function(models) {\n\n Branch_Employee.belongsTo(models.model('Employee'), {\n as: 'Employee',\n foreignKey: 'employeeId'\n });\n\n Branch_Employee.belongsTo(models.model('Branch'), {\n as: 'Branch',\n foreignKey: 'branchId'\n });\n }\n },\n instanceMethods: {\n // ... some instance methods ...\n }\n});\n```\n\nSequelize query to get every active employee, eager loading the branches to which they are related:\n\n```\nlet employees = await EmployeeModel.findAll({\n logging: true,\n include: [{\n model: Branch,\n as: 'Branches',\n where: {\n endDate: null, // this would be [Branches].[endDate] IS NULL\n\n // i also need the generated query to include:\n // [Branches.Branch_Employee].[endDate] IS NULL\n\n },\n required: false\n }]\n});\n```\n\nThe generated SQL for the above query, looks like this:\n\n```\nSELECT [Employee].[idEmployee]\n,[Employee].[Name]\n,[Employee].[active]\n,[Branches].[IdBranch] AS [Branches.IdBranch]\n,[Branches].[Name] AS [Branches.Name]\n,[Branches].[initDate] AS [Branches.initDate]\n,[Branches].[endDate] AS [Branches.endDate]\n,[Branches.Branch_Employee].[initDate] AS Branches.Branch_Employee.initDate]\n,[Branches.Branch_Employee].[endDate] AS [Branches.Branch_Employee.endDate]\n,[Branches.Branch_Employee].[branchId] AS Branches.Branch_Employee.branchId]\n,[Branches.Branch_Employee].[employeeId] AS [Branches.Branch_Employee.employeeId]\nFROM [Employee] AS [Employee]\nLEFT OUTER JOIN (\n [Branch_Employee] AS [Branches.Branch_Employee]\n INNER JOIN [Branch] AS [Branches] \n ON [Branches].[IdBranch] = [Branches.Branch_Employee].[branchId]\n) ON [Employee].[idEmployee] = [Branches.Branch_Employee].[employeeId]\nAND [Branches].[endDate] IS NULL\nWHERE [Employee].[active] = 1;\n```\n\nBut, I actually need to further restrict the result set to only include the 'current' Branch-Employee relations, i.e. something like:\n\n```\n[Branches.Branch_Employee].[endDate] IS NULL\n```\n\n========================================\n\nCode:\n```text\nvar BranchModel = db.define<BranchInstance, Branch>('Branch', {\n    IdBranch: {\n        primaryKey: true,\n        type: DataTypes.INTEGER\n    },\n    Name: DataTypes.STRING,\n    // ... other fields ...\n    initDate: DataTypes.DATE,\n    endDate: DataTypes.DATE\n}, {\n    timestamps: false,\n    classMethods: {\n        associate: function (models) {\n\n            Branch.belongsToMany(models.model('Employee'), {\n                through: {\n                    model: models.model('Branch_Employee')\n                },\n                as: 'Employees',\n                foreignKey: 'branchId'\n            });\n\n            // ... other associations ..\n\n        }\n    }\n});\n```\n\n```text\nvar EmployeeModel = db.define<EmployeeInstance, Employee>('Employee', {\n    idEmployee: {\n        primaryKey: true,\n        type: DataTypes.INTEGER\n    },\n    Name: DataTypes.STRING,\n    // ... other fields ...\n    active: DataTypes.BOOLEAN\n}, {\n    timestamps: false,\n    defaultScope: {\n        where: {\n            active: true\n        }\n    },\n    classMethods: {\n        associate: function (models) {\n\n            EmployeeModel.belongsToMany(models.model('Branch'), {\n                through: {\n                    model: models.model('Branch_Employee')\n                },\n                foreignKey: 'employeeId'\n            });\n\n            // ... other associations ...\n        }\n    }\n});\n```\n\n```text\nvar Branch_Employee = db.define<BranchEmployeeInstance, BranchEmployee>('Branch_Employee', {\n    branchId: DataTypes.INTEGER,\n    employeeId: DataTypes.INTEGER\n    // ... some other attributes of the relation ...\n    initDate: DataTypes.DATE,\n    endDate: DataTypes.DATE,\n}, {\n    timestamps: false,\n    classMethods: {\n        associate: function(models) {\n\n            Branch_Employee.belongsTo(models.model('Employee'), {\n                as: 'Employee',\n                foreignKey: 'employeeId'\n            });\n\n            Branch_Employee.belongsTo(models.model('Branch'), {\n                as: 'Branch',\n                foreignKey: 'branchId'\n            });\n        }\n    },\n    instanceMethods: {\n        // ... some instance methods ...\n    }\n});\n```\n\n```text\nlet employees = await EmployeeModel.findAll({\n    logging: true,\n    include: [{\n        model: Branch,\n        as: 'Branches',\n        where: {\n            endDate: null, // this would be [Branches].[endDate] IS NULL\n\n            // i also need the generated query to include:\n            // [Branches.Branch_Employee].[endDate] IS NULL\n\n        },\n        required: false\n    }]\n});\n```\n\n```text\nSELECT [Employee].[idEmployee]\n,[Employee].[Name]\n,[Employee].[active]\n,[Branches].[IdBranch] AS [Branches.IdBranch]\n,[Branches].[Name] AS [Branches.Name]\n,[Branches].[initDate] AS [Branches.initDate]\n,[Branches].[endDate] AS [Branches.endDate]\n,[Branches.Branch_Employee].[initDate] AS Branches.Branch_Employee.initDate]\n,[Branches.Branch_Employee].[endDate] AS [Branches.Branch_Employee.endDate]\n,[Branches.Branch_Employee].[branchId] AS Branches.Branch_Employee.branchId]\n,[Branches.Branch_Employee].[employeeId] AS [Branches.Branch_Employee.employeeId]\nFROM [Employee] AS [Employee]\nLEFT OUTER JOIN (\n    [Branch_Employee] AS [Branches.Branch_Employee]\n    INNER JOIN [Branch] AS [Branches] \n    ON [Branches].[IdBranch] = [Branches.Branch_Employee].[branchId]\n) ON [Employee].[idEmployee] = [Branches.Branch_Employee].[employeeId]\nAND [Branches].[endDate] IS NULL\nWHERE [Employee].[active] = 1;\n```\n\n```text\n[Branches.Branch_Employee].[endDate] IS NULL\n```\n\n```text\ninitDate\n```\n\n```text\nendDate\n```\n\n```text\nendDate\n```\n\n```text\nnow()\n```\n\n```text\nendDate = null\n```\n\n```text\nendDate IS NULL\n```\n\n```text\nendDate\n```\n\n```text\nfindAll()\n```\n\n```text\ninclude\n```\n\n```text\nendDate: null\n```\n\n```text\nfindAll(options)\n```\n\n```text\n[options.include[].through.where]\n```\n\n========================================\n\nComments:\n- Thanks for adding your findings, a great help!","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":352,"estimatedTokens":2142}}459{"id":"stack-60406603","source":"stackoverflow","questionId":60406603,"title":"How to order by many to many relationship in Sequelize?","tags":["javascript","sql","node.js","express","sequelize.js"],"text":"Title: How to order by many to many relationship in Sequelize?\nTags: javascript, sql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a many to many relationship between **User** and **Category** through **UserCategory** as below. \n\n```\nlet user = await User.findAll({\n where: {\n id: req.query.user\n },\n attributes: [\"id\", \"name\"],\n include: [\n {\n model: models.Category,\n as: \"interests\",\n attributes: [\"id\", \"name\", \"nameTH\", \"icon\"],\n through: {\n model: models.UserCategory,\n as: \"user_categories\",\n attributes: [\"id\", \"userId\", \"categoryId\", \"updatedAt\"]\n }\n }\n ],\n // Here, I want to order by updatedAt in user_categories\n order: [[\"user_categories\", \"updatedAt\", \"DESC\"]] \n});\n```\n\n How can I order the result by \"updatedAt\" inside **UserCategory** model?\n\n========================================\n\nTop Answer:\nFor **those** who have error like this: \n\n`ошибка синтаксиса (примерное положение: \\\".\\\")`\nor\n`syntax error (approximate position: \\ \". \\\")`\n\nGo to `Sequelize.literal()` function\n\nChange the argument string from **single quotes ('')** to **double quotes (\"\")**\n\nThen, just swap **backticks ( `` )** and **double quotes (\"\")**\n\n```\nlet user = await User.findAll({\n where: {\n id: req.query.user\n },\n attributes: [\"id\", \"name\"],\n include: [\n {\n model: models.Category,\n as: \"interests\",\n attributes: [\"id\", \"name\", \"nameTH\", \"icon\"],\n through: {\n model: models.UserCategory,\n as: \"user_categories\",\n attributes: [\"id\", \"userId\", \"categoryId\", \"updatedAt\"]\n }\n }\n ],\n // Your changes here\n order: [[Sequelize.literal(`\"interests->user_categories\".\"updatedAt\"`), 'DESC']] \n // order: [[Sequelize.literal('`interests->user_categories`.`updatedAt`'), 'DESC']] \n});\n```\n\nSpecial thanks to @SohamLawar\n\n========================================\n\nCode:\n```text\nlet user = await User.findAll({\n  where: {\n    id: req.query.user\n  },\n  attributes: [\"id\", \"name\"],\n  include: [\n    {\n      model: models.Category,\n      as: \"interests\",\n      attributes: [\"id\", \"name\", \"nameTH\", \"icon\"],\n      through: {\n        model: models.UserCategory,\n        as: \"user_categories\",\n        attributes: [\"id\", \"userId\", \"categoryId\", \"updatedAt\"]\n      }\n    }\n  ],\n  // Here, I want to order by updatedAt in user_categories\n  order: [[\"user_categories\", \"updatedAt\", \"DESC\"]] \n});\n```\n\n```text\nlet user = await User.findAll({\n  where: {\n    id: req.query.user\n  },\n  attributes: [\"id\", \"name\"],\n  include: [\n    {\n      model: models.Category,\n      as: \"interests\",\n      attributes: [\"id\", \"name\", \"nameTH\", \"icon\"],\n      through: {\n        model: models.UserCategory,\n        as: \"user_categories\",\n        attributes: [\"id\", \"userId\", \"categoryId\", \"updatedAt\"]\n      }\n    }\n  ],\n  // Here, I want to order by updatedAt in user_categories\n  order: [[Sequelize.literal('`interests->user_categories`.`updatedAt`'), 'DESC']] \n});\n```\n\n```text\nupdatedAt\n```\n\n```text\nUserCategory\n```\n\n```text\nlet user = await User.findAll({\n  where: {\n    id: req.query.user\n  },\n  attributes: [\"id\", \"name\"],\n  include: [\n    {\n      model: models.Category,\n      as: \"interests\",\n      attributes: [\"id\", \"name\", \"nameTH\", \"icon\"],\n      through: {\n        model: models.UserCategory,\n        as: \"user_categories\",\n        attributes: [\"id\", \"userId\", \"categoryId\", \"updatedAt\"]\n      }\n    }\n  ],\n  // Your changes here\n  order: [[Sequelize.literal(`\"interests->user_categories\".\"updatedAt\"`), 'DESC']] \n  // order: [[Sequelize.literal('`interests->user_categories`.`updatedAt`'), 'DESC']] \n});\n```\n\n```text\nошибка синтаксиса (примерное положение: \\\".\\\")\n```\n\n```text\nsyntax error (approximate position: \\ \". \\\")\n```\n\n```text\nSequelize.literal()\n```\n\n```js\nlet user = await User.findAll({\n  where: {\n    id: req.query.user\n  },\n  attributes: [\"id\", \"name\"],\n  include: [\n    {\n      model: models.Category,\n      as: \"interests\",\n      attributes: [\"id\", \"name\", \"nameTH\", \"icon\"],\n      through: {\n        model: models.UserCategory,\n        as: \"user_categories\",\n        attributes: [\"id\", \"userId\", \"categoryId\", \"updatedAt\"]\n      }\n    }\n  ],\n  // Your changes here\n  order: [[{model: models.Category, as: 'interests'}, {model: models.UserCategory, as: 'user_categories'}, 'updatedAt',  'DESC']] \n});\n```\n\n========================================\n\nComments:\n- What is your sequelize version?\n- \"sequelize\": \"^5.21.3\", \"sequelize-cli\": \"^5.5.1\"\n- You save my life again! Thanks for your time. @SohamLawar\n- Amazing! Good call.\n- I have this error: syntax error (approximate position: \\ \". \\\") (translated from google). Can you help me with this?\n- Solved, answer below :)\n- Thank you for this update. It might be a SQL syntax thing for postgresql.\n- This was the perfect one!","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":200,"estimatedTokens":1172}}460{"id":"stack-30681673","source":"stackoverflow","questionId":30681673,"title":"Multiple count query in sequelize ORM","tags":["node.js","postgresql","charts","sequelize.js","c3.js"],"text":"Title: Multiple count query in sequelize ORM\nTags: node.js, postgresql, charts, sequelize.js, c3.js\nSource: Stack Overflow\n\nQuestion:\nI'd like to create query which is able to count number of records for every day in month at once in sequelize.js\nNot like :\n\n```\nRecord.count({ where: { createdAt: { $like: '2015-04-14%' } } }).then(function(c) {\n console.log(\"2015-04-14 have been created\" + c + \"records\");\n});\n\nRecord.count({ where: { createdAt: { $like: '2015-04-15%' } } }).then(function(c) {\n console.log(\"2015-04-15 have been created\" + c + \"records\");\n});\n\nRecord.count({ where: { createdAt: { $like: '2015-04-16%' } } }).then(function(c) {\n console.log(\"2015-04-16 have been created\" + c + \"records\");\n});\n\n....\n....\n```\n\nI wanna make query which will returns number of rows at once, not like ask database for this data in 30 queries. It is possible make it with transactions?\n\nI'll use it for chart purposes, so best output from this is like:\n\n```\n[500, 300, 400, 550....]\n```\n\nThanks for any help!\n\n========================================\n\nTop Answer:\nMy solution with raw query for PostgreSQL:\n\n```\ndb.sequelize\n .query(\"SELECT count(*), date_trunc('month', \\\"createdAt\\\") AS date FROM tables WHERE active = true AND \\\"createdAt\\\" BETWEEN '\"+moment().startOf('year').format()+\"' AND '\"+moment().format()+\"' GROUP BY date\")\n .then(function(results){\n res.json(results[0]);\n});\n```\n\nI hope it helps to somebody.\n\n========================================\n\nCode:\n```text\nRecord.count({ where: { createdAt: { $like: '2015-04-14%' } } }).then(function(c) {\n  console.log(\"2015-04-14 have been created\" + c + \"records\");\n});\n\nRecord.count({ where: { createdAt: { $like: '2015-04-15%' } } }).then(function(c) {\n  console.log(\"2015-04-15 have been created\" + c + \"records\");\n});\n\n\nRecord.count({ where: { createdAt: { $like: '2015-04-16%' } } }).then(function(c) {\n  console.log(\"2015-04-16 have been created\" + c + \"records\");\n});\n\n....\n....\n```\n\n```text\n[500, 300, 400, 550....]\n```\n\n```text\ndb.record.findAll({\n  attributes: [\n    [\n      db.sequelize.fn('date_trunc', \n        'day', \n        db.sequelize.col('createdAt')\n      ), \n      'dateTrunc'\n    ],\n    [\n      db.sequelize.fn('count', \n        db.sequelize.col('id')\n      ), \n      'count'\n    ]\n  ],\n  group: '\"dateTrunc\"'\n}).then(function(rows) {\n  console.log(rows);\n});\n```\n\n```text\ndb.sequelize\n  .query(\"SELECT count(*), date_trunc('month', \\\"createdAt\\\") AS date FROM tables WHERE active = true AND \\\"createdAt\\\" BETWEEN '\"+moment().startOf('year').format()+\"' AND '\"+moment().format()+\"' GROUP BY date\")\n  .then(function(results){\n     res.json(results[0]);\n});\n```\n\n========================================\n\nComments:\n- Thanks a lot, I already created it with raw query. Basically your solution is same.\n- Are you Dj really? I have price columnt in this rows.. Do you know how can I sum all these prices in this case for all records in particular day?\n- Use the `sum` function instead of `count`. See this attribute definition: `[ db.sequelize.fn('sum', db.sequelize.col('price') ), 'priceSum' ]`","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":112,"estimatedTokens":769}}461{"id":"stack-49470508","source":"stackoverflow","questionId":49470508,"title":"Sequelize.define() is not a function?","tags":["node.js","sequelize.js"],"text":"Title: Sequelize.define() is not a function?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nTrying to play around with Sequelize in a node.js webserver.\n\nI have initialised the Sequelize connection pool in index.js like so\n\n**index.js**\n\n```\nconst config = require('./config/config');\nconst app = require('./config/express');\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize(config.mysql.database, config.mysql.user, config.mysql.pass, {\n host: config.mysql.host,\n dialect: 'mysql',\n operatorsAliases: false,\n\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000\n },\n});\n\nsequelize\n .authenticate()\n .then(() => {\n console.log('Connection has been established successfully.'); // eslint-disable-line no-console\n })\n .catch((err) => {\n console.error('Unable to connect to the database:', err); // eslint-disable-line no-console\n });\n\nmodule.exports = { app, sequelize };\n```\n\n**user.js model**\n\n```\nconst sequelize = require('sequelize');\nconst DataTypes = require('mysql');\n/**\n * User model\n */\nconst User = sequelize.define('user', {\n\n id: {\n type: DataTypes.INTEGER,\n },\n name: {\n type: DataTypes.STRING,\n },\n email: {\n type: DataTypes.STRING,\n },\n lastEmail: {\n type: DataTypes.TIME,\n }\n});\n```\n\nWhen trying to start the server I get the following error\n\n TypeError: sequelize.define is not a function ... user.js \n\nI am guessing the sequelize object is not being made global, however I tested the connection before creating the model and it was fine.\n\n========================================\n\nTop Answer:\nI was having the same problem..and It works for me..\n\n```\nmodule.exports = (DataTypes , sequelize) => {\nconst User = sequelize.define('user', {\n id: {\n type: DataTypes.INTEGER,\n },\n name: {\n type: DataTypes.STRING,\n },\n email: {\n type: DataTypes.STRING,\n },\n lastEmail: {\n type: DataTypes.TIME,\n }\n})\nreturn User;\n};\n```\n\n========================================\n\nCode:\n```text\nconst config = require('./config/config');\nconst app = require('./config/express');\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize(config.mysql.database, config.mysql.user, config.mysql.pass, {\n  host: config.mysql.host,\n  dialect: 'mysql',\n  operatorsAliases: false,\n\n  pool: {\n    max: 5,\n    min: 0,\n    acquire: 30000,\n    idle: 10000\n  },\n});\n\nsequelize\n  .authenticate()\n  .then(() => {\n    console.log('Connection has been established successfully.'); // eslint-disable-line no-console\n  })\n  .catch((err) => {\n    console.error('Unable to connect to the database:', err); // eslint-disable-line no-console\n  });\n\nmodule.exports = { app, sequelize };\n```\n\n```text\nconst sequelize = require('sequelize');\nconst DataTypes = require('mysql');\n/**\n * User model\n */\nconst User = sequelize.define('user', {\n\n  id: {\n    type: DataTypes.INTEGER,\n  },\n  name: {\n    type: DataTypes.STRING,\n  },\n  email: {\n    type: DataTypes.STRING,\n  },\n  lastEmail: {\n    type: DataTypes.TIME,\n  }\n});\n```\n\n```text\nconst sequelize = require('index.js').sequelize;\nconst DataTypes = require('mysql');\n\n/**\n * User model\n */\nconst User = sequelize.define('user', {\n\n  id: {\n    type: DataTypes.INTEGER,\n  },\n  name: {\n    type: DataTypes.STRING,\n  },\n  email: {\n    type: DataTypes.STRING,\n  },\n  lastEmail: {\n    type: DataTypes.TIME,\n  }\n});\n```\n\n```text\n.define()\n```\n\n```text\napp\n```\n\n```text\nsequelize\n```\n\n```text\nrequire\n```\n\n```text\nmodule.exports = (DataTypes , sequelize) => {\nconst User = sequelize.define('user', {\n  id: {\n    type: DataTypes.INTEGER,\n  },\n  name: {\n    type: DataTypes.STRING,\n  },\n  email: {\n    type: DataTypes.STRING,\n  },\n  lastEmail: {\n    type: DataTypes.TIME,\n  }\n})\nreturn User;\n};\n```\n\n========================================\n\nComments:\n- Thanks Mike. what would be the best way to do this then?\n- I guess the question is what is the \"this\" you are trying to do? For example, do you have a route handler defined somewhere that is using the user model. If so, can you that code? Also, it looks like there is a related stack overflow question on this topic here: stackoverflow.com/questions/12487416/&hellip;.\n- Yea I have a user route and user controller defined. The original example I copied from used mongodb, however I was hoping to swap it over to mysql","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":219,"estimatedTokens":1060}}462{"id":"stack-58883687","source":"stackoverflow","questionId":58883687,"title":"Sequelize - update query with returning: true succeeds but returns undefined","tags":["javascript","sql","node.js","express","sequelize.js"],"text":"Title: Sequelize - update query with returning: true succeeds but returns undefined\nTags: javascript, sql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following function which I use to update the URL to the user's profile pic - \n\n```\nconst updateProfilePic = async (req, res) => {\n const userId = req.param(\"id\");\n if (userId) {\n const targetPath = `...`;\n User.update(\n {\n profilePic: targetPath\n },\n { where: { id: userId }, returning: true }\n )\n .then(updatedUser => {\n console.log(updatedUser);\n res.json(updatedUser);\n })\n .catch(error => {\n console.log(error);\n res.status(400).send({ error: error });\n });\n }\n};\n```\n\nThis updates the DB successfully - however `then` obtains `[ undefined, 1 ]` as the `updatedUser` instead of the user data - if I remove the `returning : true` flag, it just returns `[ 1 ]`. I'm not sure what I'm doing wrong - I'm trying to obtain the user object so that I can pass it on to the client.\n\n========================================\n\nCode:\n```text\nconst updateProfilePic = async (req, res) => {\n  const userId = req.param(\"id\");\n  if (userId) {\n    const targetPath = `...`;\n    User.update(\n      {\n        profilePic: targetPath\n      },\n      { where: { id: userId }, returning: true }\n    )\n      .then(updatedUser => {\n        console.log(updatedUser);\n        res.json(updatedUser);\n      })\n      .catch(error => {\n        console.log(error);\n        res.status(400).send({ error: error });\n      });\n  }\n};\n```\n\n```text\nthen\n```\n\n```text\n[ undefined, 1 ]\n```\n\n```text\nupdatedUser\n```\n\n```text\nreturning : true\n```\n\n```text\n[ 1 ]\n```\n\n```text\nreturning\n```\n\n```text\nUpdate()\n```\n\n========================================\n\nComments:\n- what db are you using with sequelize?","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":90,"estimatedTokens":437}}463{"id":"stack-48254197","source":"stackoverflow","questionId":48254197,"title":"Do I need to sanitize user input when using Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: Do I need to sanitize user input when using Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn the past, I was under the impression that sequelize somehow automatically prevented SQL injection, but the current version of the manual implies that there are situations where sanitization is required (link)\n\nSorry if this is a silly question, but I haven't been able to find any definite answer as to whether or not sanitization is required when using sequelize.\n\nThanks\n\n========================================\n\nTop Answer:\nOther than agreeing with McCabe's answer, I want to add that sequelize at least takes care of unescaped strings, which one could argue is a big part of handling SQL Injection issues. Even if you want to write custom queries, this is also possible using replacements, as stated in the first sentence here: \"...**replacements are escaped** and inserted into the query by sequelize before the query is sent to the database...\".\n\n========================================\n\nCode:\n```text\nSequelize.Op\n```\n\n========================================\n\nComments:\n- If I use operators, then what part of the input do I need to sanitize?\n- That is more a general question about sanitisation. The docs, and my comment, are just warning that there are problems, and there is no such thing as a perfect non-penetrable system. Using things like Sequelize.Op helps mitigate risk. For example, if you let someone type in a phrase to search by. Someone could type `%' UNION SELECT password FROM Users where username LIKE '%`. If you didnt sanitise that and it went to a raw query like `sequelize.query(\"SELECT x FROM y WHERE x like '%\" + query + \"%'\", { type: models.sequelize.QueryTypes.SELECT} )` You may have issues","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":28,"estimatedTokens":439}}464{"id":"stack-43634819","source":"stackoverflow","questionId":43634819,"title":"How to use \"interval\" in SequelizeJS?","tags":["sequelize.js"],"text":"Title: How to use \"interval\" in SequelizeJS?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to convert MySQL query below to SequelizeJS query\n\n```\nWHERE createdAt < now() - interval 5 hour\n```\n\n========================================\n\nTop Answer:\nI got it working using `Sequelize.literal`:\n\n```\nModel.find({\n where: {\n [Sequelize.Op.and]: [\n Sequelize.literal(`created_at > NOW() - INTERVAL '5h'`),\n ],\n },\n logging: console.log,\n})\n```\n\nI would love if anybody could enrich this answer by mixing in `Sequelize.col()` so to automatically get the correct column name inside the literal.\n\n========================================\n\nCode:\n```text\nWHERE createdAt < now() - interval 5 hour\n```\n\n```text\nnew Date((new Date()).getTime() - 18000000)  //5*60*60*1000\n```\n\n```text\nModel.find({\n  where: {\n    [Sequelize.Op.and]: [\n      Sequelize.literal(`created_at > NOW() - INTERVAL '5h'`),\n    ],\n  },\n  logging: console.log,\n})\n```\n\n```text\nSequelize.literal\n```\n\n```text\nSequelize.col()\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":58,"estimatedTokens":251}}465{"id":"stack-61463636","source":"stackoverflow","questionId":61463636,"title":"Nest can't resolve dependencies of the ....Please make sure that the argument .. at index [0] is available in the","tags":["node.js","sequelize.js","nestjs"],"text":"Title: Nest can't resolve dependencies of the ....Please make sure that the argument .. at index [0] is available in the\nTags: node.js, sequelize.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/sequelize';\nimport { Conversation } from './conversation.model'\nimport { FindConversationsDto } from '../dto/conversations.find'\n\n@Injectable()\nexport class ConversationsService {\n constructor(\n @InjectModel(Conversation)\n private conversationModel: typeof Conversation\n ) { }\n\n async findConversations(queryParams: FindConversationsDto): Promise {\n return new Promise((resolve) => [])\n // return await this.conversationModel.findAll();\n\n }\n}\n```\n\nAnd I get this weird error:\n\n```\nNest can't resolve dependencies of the ConversationsService (?). Please make sure that the argument ConversationRepository at index [0] is available in the ConversationsModule context.\n\nPotential solutions:\n- If ConversationRepository is a provider, is it part of the current ConversationsModule?\n- If ConversationRepository is exported from a separate @Module, is that module imported within ConversationsModule?\n @Module({\n imports: [ /* the Module containing ConversationRepository */ ]\n })\n```\n\n`ConversationModule` is:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConversationsController } from './conversations.controller';\nimport { ConversationsService } from './conversations.service';\n\n@Module({\n controllers: [ConversationsController],\n providers: [ConversationsService]\n})\nexport class ConversationsModule {}\n```\n\nNot sure what `ConversationRepository` is referring to.\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/sequelize';\nimport { Conversation } from './conversation.model'\nimport { FindConversationsDto } from '../dto/conversations.find'\n\n@Injectable()\nexport class ConversationsService {\n    constructor(\n        @InjectModel(Conversation)\n        private conversationModel: typeof Conversation\n    ) { }\n\n    async findConversations(queryParams: FindConversationsDto): Promise<Conversation[]> {\n        return new Promise((resolve) => [])\n        // return await this.conversationModel.findAll();\n\n\n    }\n}\n```\n\n```text\nNest can't resolve dependencies of the ConversationsService (?). Please make sure that the argument ConversationRepository at index [0] is available in the ConversationsModule context.\n\nPotential solutions:\n- If ConversationRepository is a provider, is it part of the current ConversationsModule?\n- If ConversationRepository is exported from a separate @Module, is that module imported within ConversationsModule?\n  @Module({\n    imports: [ /* the Module containing ConversationRepository */ ]\n  })\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConversationsController } from './conversations.controller';\nimport { ConversationsService } from './conversations.service';\n\n@Module({\n  controllers: [ConversationsController],\n  providers: [ConversationsService]\n})\nexport class ConversationsModule {}\n```\n\n```text\nConversationModule\n```\n\n```text\nConversationRepository\n```\n\n```js\n@Module({\n  imports: [SequelizeModule.forFeature([Conversation])],\n  providers: [ConversationService],\n  controllers: [ConversationController]\n})\nexport class ConversationModule {}\n```\n\n```text\nSequelizeModule.forFeature()\n```\n\n```text\nConversationModule\n```\n\n```text\nimports\n```\n\n```text\nConversationRepository\n```\n\n```text\nConverstationModule\n```\n\n========================================\n\nComments:\n- Can you show your `ConversationModule` file well?\n- Updated with `ConversationModule`\n- I have `autoLoadModels: true` in my DB loader. Do I still need to import the models in each Module?\n- Yes, it is needed for nestjs.\n- Yes. Quote from the docs: \"Note that models that aren't registered through the forFeature() method, but are only referenced from the model (via an association), won't be included. \"","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":150,"estimatedTokens":1003}}466{"id":"stack-41528676","source":"stackoverflow","questionId":41528676,"title":"Sequelize BelongsToMany with custom join table primary key","tags":["sql","node.js","sequelize.js"],"text":"Title: Sequelize BelongsToMany with custom join table primary key\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a many-to-many-relationship with a join table in the middle. The tables are Cookoff, Participant, and CookoffParticipant. I should mention I am not allowing Sequelize to create or modify my tables, I am simply mapping my existing relationships. I need help understanding which relationship options tells sequelize what to call the foreign key that relates a join table to the main table.\n\nAs I understand it, Sequelize assumes that the CookoffID and ParticipantID are a composite primary key on CookoffParticipant. In my situation, I require the primary key to be an identity column I'm calling CookoffParticipantID and creating a unique index on the CookoffID, ParticipantID pair in the CookoffParticipant table.\n\nWhen I attempt to get the cookoff and participant data by querying through the cookoffParticipant table, Sequelize is using the wrong key to accomplish the join. There must be something simple that I am not doing. Below is my table structure and the query with results.\n\nCookoff Table\n\n```\nvar Cookoff = sequelize.define(\"Cookoff\", {\n\n // Table columns\n\n CookoffID: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n Title: {\n type: DataTypes.STRING,\n allowNull: false\n },\n EventDate: {\n type: DataTypes.DATE,\n allowNull: false\n }\n}, _.extend({},\n\n // Table settings\n defaultTableSettings,\n\n {\n classMethods: {\n associate: function(models) {\n Cookoff.belongsToMany(models.Participant, {\n through: {\n model: models.CookoffParticipant\n },\n as: \"Cookoffs\",\n foreignKey: \"CookoffID\",\n otherKey: \"ParticipantID\"\n });\n }\n }\n }\n));\n```\n\nParticipant table\n\n```\nvar Participant = sequelize.define(\"Participant\", {\n\n // Table columns\n ParticipantID: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n Name: {\n type: DataTypes.STRING(100),\n allowNull: false\n }\n\n}, _.extend({},\n\n defaultTableSettings,\n\n {\n classMethods: {\n associate: function(models) {\n Participant.belongsToMany(models.Cookoff, {\n through: {\n model: models.CookoffParticipant\n },\n as: \"Participants\",\n foreignKey: \"ParticipantID\",\n otherKey: \"CookoffID\"\n });\n }\n }\n }\n));\n```\n\nCookoffParticipant Table\n\n```\nvar CookoffParticipant = sequelize.define(\"CookoffParticipant\", {\n CookoffParticipantID: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n CookoffID: {\n type: DataTypes.INTEGER,\n allowNull: false,\n references: {\n model: cookoff,\n key: \"CookoffID\"\n }\n },\n ParticipantID: {\n type: DataTypes.INTEGER,\n allowNull: false,\n references: {\n model: participant,\n key: \"ParticipantID\"\n }\n }\n}, _.extend(\n { },\n defaultTableSettings,\n {\n classMethods: {\n associate: function (models) {\n CookoffParticipant.hasOne(models.Cookoff, { foreignKey: \"CookoffID\" });\n CookoffParticipant.hasOne(models.Participant, { foreignKey: \"ParticipantID\" });\n\n }\n }\n }\n));\n```\n\nMy Query\n\n```\nreturn cookoffParticpants.findOne({\n where: { CookoffID: cookoffID, ParticipantID: participantID },\n include: [\n { model: participants },\n { model: cookoffs }\n ]\n });\n```\n\nThe generated SQL\n\n```\nSELECT \n [CookoffParticipant].[CookoffParticipantID], \n [CookoffParticipant].[CookoffID], \n [CookoffParticipant].[ParticipantID], \n [Participant].[ParticipantID] AS [Participant.ParticipantID], \n [Participant].[Name] AS [Participant.Name], \n [Cookoff].[CookoffID] AS [Cookoff.CookoffID], \n [Cookoff].[Title] AS [Cookoff.Title], \n [Cookoff].[EventDate] AS [Cookoff.EventDate] \nFROM [CookoffParticipant] AS [CookoffParticipant] \nLEFT OUTER JOIN [Participant] AS [Participant] \n ON [CookoffParticipant].[CookoffParticipantID] = [Participant].[ParticipantID] -- This should be CookoffParticipant.ParticipantID\nLEFT OUTER JOIN [Cookoff] AS [Cookoff] \n ON [CookoffParticipant].[CookoffParticipantID] = [Cookoff].[CookoffID] -- This should be CookoffParticipant.CookoffID\nWHERE [CookoffParticipant].[CookoffID] = 1 \nAND [CookoffParticipant].[ParticipantID] = 6 \nORDER BY [CookoffParticipantID] \nOFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;\n```\n\nYou can see that Sequelize is trying to join CookoffParticipant.CookoffParticipantID ON Participant.ParticipantID, where it should be CookoffParticipant.ParticipantID = Participant.ParticipantID and similarly for CookoffID. What am I doing wrong here?\n\nThank you in advance for your help.\n\n========================================\n\nCode:\n```text\nvar Cookoff = sequelize.define(\"Cookoff\", {\n\n    // Table columns\n\n    CookoffID: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    Title: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    EventDate: {\n        type: DataTypes.DATE,\n        allowNull: false\n    }\n}, _.extend({},\n\n    // Table settings\n    defaultTableSettings,\n\n    {\n        classMethods: {\n            associate: function(models) {\n                Cookoff.belongsToMany(models.Participant, {\n                    through: {\n                        model: models.CookoffParticipant\n                    },\n                    as: \"Cookoffs\",\n                    foreignKey: \"CookoffID\",\n                    otherKey: \"ParticipantID\"\n                });\n            }\n        }\n    }\n));\n```\n\n```text\nvar Participant = sequelize.define(\"Participant\", {\n\n    // Table columns\n    ParticipantID: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    Name: {\n        type: DataTypes.STRING(100),\n        allowNull: false\n    }\n\n}, _.extend({},\n\n    defaultTableSettings,\n\n    {\n        classMethods: {\n            associate: function(models) {\n                Participant.belongsToMany(models.Cookoff, {\n                    through: {\n                        model: models.CookoffParticipant\n                    },\n                    as: \"Participants\",\n                    foreignKey: \"ParticipantID\",\n                    otherKey: \"CookoffID\"\n                });\n            }\n        }\n    }\n));\n```\n\n```text\nvar CookoffParticipant = sequelize.define(\"CookoffParticipant\", {\n    CookoffParticipantID: {\n        type: DataTypes.INTEGER,\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    CookoffID: {\n        type: DataTypes.INTEGER,\n        allowNull: false,\n        references: {\n            model: cookoff,\n            key: \"CookoffID\"\n        }\n    },\n    ParticipantID: {\n        type: DataTypes.INTEGER,\n        allowNull: false,\n        references: {\n            model: participant,\n            key: \"ParticipantID\"\n        }\n    }\n}, _.extend(\n    { },\n    defaultTableSettings,\n    {\n        classMethods: {\n          associate: function (models) {\n              CookoffParticipant.hasOne(models.Cookoff, { foreignKey: \"CookoffID\" });\n              CookoffParticipant.hasOne(models.Participant, { foreignKey: \"ParticipantID\" });\n\n            }\n        }\n    }\n));\n```\n\n```text\nreturn cookoffParticpants.findOne({\n        where: { CookoffID: cookoffID, ParticipantID: participantID },\n        include: [\n            { model: participants },\n            { model: cookoffs }\n        ]\n    });\n```\n\n```text\nSELECT \n    [CookoffParticipant].[CookoffParticipantID], \n    [CookoffParticipant].[CookoffID], \n    [CookoffParticipant].[ParticipantID], \n    [Participant].[ParticipantID] AS [Participant.ParticipantID], \n    [Participant].[Name] AS [Participant.Name], \n    [Cookoff].[CookoffID] AS [Cookoff.CookoffID], \n    [Cookoff].[Title] AS [Cookoff.Title], \n    [Cookoff].[EventDate] AS [Cookoff.EventDate] \nFROM [CookoffParticipant] AS [CookoffParticipant] \nLEFT OUTER JOIN [Participant] AS [Participant] \n    ON [CookoffParticipant].[CookoffParticipantID] = [Participant].[ParticipantID]  -- This should be CookoffParticipant.ParticipantID\nLEFT OUTER JOIN [Cookoff] AS [Cookoff] \n    ON [CookoffParticipant].[CookoffParticipantID] = [Cookoff].[CookoffID] -- This should be CookoffParticipant.CookoffID\nWHERE [CookoffParticipant].[CookoffID] = 1 \nAND [CookoffParticipant].[ParticipantID] = 6 \nORDER BY [CookoffParticipantID] \nOFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;\n```\n\n```text\nCookoff.hasMany(Book, { through: CookoffParticipant })\nParticipant.hasMany(User, { through: CookoffParticipant })\nCookoffParticipant.belongsTo(Cookoff)\nCookoffParticipant.belongsTo(Participant)\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    var Cookoff = sequelize.define(\"Cookoff\", {\n        CookoffID: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        }\n    }, _.extend(\n        {},\n        {\n            classMethods: {\n                associate: function(models) {\n                    Cookoff.belongsToMany(models.Participant, {\n                        through: models.CookoffParticipant,\n                        foreignKey: \"CookoffID\",\n                        otherKey: \"ParticipantID\"\n                    });\n                }\n            }\n        }\n    ));\n    return Cookoff;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    var Participant = sequelize.define(\"Participant\", {\n        ParticipantID: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        }\n    }, _.extend(\n        {},\n        {\n            classMethods: {\n                associate: function(models) {\n                    Participant.belongsToMany(models.Cookoff, {\n                        through: models.CookoffParticipant,\n                        foreignKey: \"ParticipantID\",\n                        otherKey: \"CookoffID\"\n                    });\n                }\n            }\n        }\n    ));\n    return Participant;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    var CookoffParticipant = sequelize.define(\"CookoffParticipant\", {\n        CookoffParticipantID: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true\n        }\n    }, _.extend(\n        {},\n        {\n            classMethods: {\n                associate: function(models) {\n                    CookoffParticipant.belongsTo(models.Cookoff, { foreignKey: \"CookoffID\" });\n                    CookoffParticipant.belongsTo(models.Participant, { foreignKey: \"ParticipantID\" });\n                }\n            }\n        }\n    ));\n    return CookoffParticipant;\n};\n```\n\n```text\nconst db = require('../db');\nconst Cookoff = db.Cookoff;\nconst Participant = db.Participant;\nconst CookoffParticipant = db.CookoffParticipant;\nlet cookoff,\n    participant;\n\nPromise.all([\n    Cookoff.create({}),\n    Participant.create({})\n]).then(([ _cookoff, _participant ]) => {\n    cookoff = _cookoff;\n    participant = _participant;\n\n    return cookoff.addParticipant(participant);\n}).then(() => {\n    return CookoffParticipant.findOne({\n        where: { CookoffID: cookoff.CookoffID, ParticipantID: participant.ParticipantID },\n        include: [ Cookoff, Participant ]\n    });\n}).then(cookoffParticipant => {\n    console.log(cookoffParticipant.toJSON());\n});\n```\n\n```text\nhasOne\n```\n\n```text\nbelongsTo\n```\n\n```text\nas\n```\n\n========================================\n\nComments:\n- Thank you. The key error was using hasOne instead of belongsTo. Making that switch fixed the problem immediately.","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":443,"estimatedTokens":2824}}467{"id":"stack-57057733","source":"stackoverflow","questionId":57057733,"title":"Sequelize logging questions marks instead of values after migrating to V5","tags":["javascript","node.js","typescript","sequelize.js"],"text":"Title: Sequelize logging questions marks instead of values after migrating to V5\nTags: javascript, node.js, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAfter migrating to v5 from v4, Sequelize logs question marks on the console instead of the values of the SQL queries.\n\nFor instance, this is what is shown on the console:\n\n```\nINSERT INTO `Product` (`uid`,`title`,`price`,`isPerishable`,`categoryId`) VALUES (?,?,?,?,?);\n```\n\nThis is my Sequelize instance:\n\n```\ndb = new Sequelize({\n dialect: 'mysql',\n database: process.env.DB_NAME,\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n host: process.env.DB_HOST,\n operatorsAliases: operatorsAliases,\n logging: console.log,\n });\n```\n\nWhether before, on version 4, the values were being displayed correctly.\n\nWhat I am expecting to be logged is somethings like:\n\n```\nINSERT INTO `Product` (`uid`,`title`,`price`,`isPerishable`,`categoryId`) VALUES (DEFAULT,'iPhone X',999.99,false,'1');\n```\n\n========================================\n\nCode:\n```sql\nINSERT INTO `Product` (`uid`,`title`,`price`,`isPerishable`,`categoryId`) VALUES (?,?,?,?,?);\n```\n\n```js\ndb = new Sequelize({\n      dialect: 'mysql',\n      database: process.env.DB_NAME,\n      username: process.env.DB_USER,\n      password: process.env.DB_PASS,\n      host: process.env.DB_HOST,\n      operatorsAliases: operatorsAliases,\n      logging: console.log,\n    });\n```\n\n```sql\nINSERT INTO `Product` (`uid`,`title`,`price`,`isPerishable`,`categoryId`) VALUES (DEFAULT,'iPhone X',999.99,false,'1');\n```\n\n========================================\n\nComments:\n- Already resolved in 5.19.0","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":62,"estimatedTokens":404}}468{"id":"stack-43073715","source":"stackoverflow","questionId":43073715,"title":"Max connection pool size and autoscaling group","tags":["amazon-ec2","sequelize.js","autoscaling","amazon-aurora","connection-pool"],"text":"Title: Max connection pool size and autoscaling group\nTags: amazon-ec2, sequelize.js, autoscaling, amazon-aurora, connection-pool\nSource: Stack Overflow\n\nQuestion:\nIn Sequelize.js you should configure the max connection pool size (default 5). I don't know how to deal with this configuration as I work on an autoscaling platform in AWS. \n\nThe Aurora DB cluster on r3.2xlarge allows 2000 max connections per read replica (you can get that by running SELECT @@MAX_CONNECTIONS;).\n\nThe problem is I don't know what should be the right configuration for each server hosted on our EC2s. What should be the right max connection pool size as I don't know how many servers will be launched by the autoscaling group? Normally, the DB MAX_CONNECTIONS value should be divided by the number of connection pools (one by server), but I don't know how many server will be instantiated at the end.\n\nOur concurrent users count is estimated to be between 50000 and 75000 concurrent users at our release date.\n\nDid someone get previous experience with this kind of situation?\n\n========================================\n\nComments:\n- Thank you for your answer and inputs. I did simulations like yours with Locust over the last weeks (different use case scenarios). Through those stress tests, I ran with 150K concurrent clients over a 10 to 12 minutes span to cover our \"worst\" case scenario. We conclude that, in the end, there is more than enough DB connections for everyone and we managed to find out the correct pool max size for each instance as you did. I think this a good way to resolve this problematic.\n- @NinjaFisherman I'm curious what you settled on for pool size?","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":20,"estimatedTokens":414}}469{"id":"stack-39384801","source":"stackoverflow","questionId":39384801,"title":"How to call a MSSQL Stored Procedure using Sequelize?","tags":["sql-server","node.js","sequelize.js"],"text":"Title: How to call a MSSQL Stored Procedure using Sequelize?\nTags: sql-server, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am struggling with calling a MS SQL Stored Proc using Sequelize. This is how i normally call the stored proc from SSMS\n\n```\nUSE [MYDB]\nGO\n\nDECLARE @return_value int\n\nEXEC @return_value = [dbo].[GetThings_ByLocation]\n @BeginDate = N'2016-06-23',\n @EndDate = N'2016-07-09',\n @LocationID = NULL\n\nSELECT 'Return Value' = @return_value\n\nGO\n```\n\nHow would i make this call using sequelize?\n\n========================================\n\nCode:\n```text\nUSE [MYDB]\nGO\n\nDECLARE    @return_value int\n\nEXEC    @return_value = [dbo].[GetThings_ByLocation]\n        @BeginDate = N'2016-06-23',\n        @EndDate = N'2016-07-09',\n        @LocationID = NULL\n\nSELECT    'Return Value' = @return_value\n\nGO\n```\n\n```text\nsequelize.query('GetThings_ByLocation @BeginDate=\\'2016-08-01\\', @EndDate=\\'2016-08-07\\', @LocationID=NULL;')\n  .then(function(result) {\n      console.log('RESULT', result);\n  })\n  .error(function(err) {\n      console.log(err);\n  });\n```\n\n========================================\n\nComments:\n- Please see my question and simplified answer on stackoverflow below. It is not necessary to format the parameters as you can use the replacements functionality. Sequelize Stored Procedure\n- Using .spread(function(result){.... instead of .then(function(result){...... would be a better option","metadata":{"transformedAt":"2026-08-18T18:33:34.379Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":59,"estimatedTokens":354}}470{"id":"stack-45941561","source":"stackoverflow","questionId":45941561,"title":"Cognito returns UnexpectedLambdaException timeout error while invoking Lambda function","tags":["amazon-web-services","lambda","sequelize.js","amazon-cognito"],"text":"Title: Cognito returns UnexpectedLambdaException timeout error while invoking Lambda function\nTags: amazon-web-services, lambda, sequelize.js, amazon-cognito\nSource: Stack Overflow\n\nQuestion:\nThe very first time I login to my application, first thing in the morning, AWS Cognito returns this error:\n\n```\n{\n \"message\": \"arn:aws:lambda:us-east-1:XXXXXXXXXX:function:main-devryan-users_onCognitoLogin failed with error Socket timeout while invoking Lambda function.\",\n \"code\": \"UnexpectedLambdaException\",\n \"time\": \"2017-08-29T13:30:01.351Z\",\n \"requestId\": \"1c04c982-8cbe-11e7-b9c9-a584e55a17f8\",\n \"statusCode\": 400,\n \"retryable\": false,\n \"retryDelay\": 96.636396268355\n}\n```\n\nThe second time, and every time afterwards for the rest of the day, everything is fine.\n\nWhen I check the logs in Cloudwatch for my main-devryan-users_onCognitoLogin function, it finished successfully in 2.3 seconds:\n\n```\nREPORT RequestId: 1f2d5a22-8cbe-11e7-ba74-5b21665a40c1 Duration: 2283.60 ms Billed Duration: 2300 ms Memory Size: 128 MB Max Memory Used: 51 MB\n```\n\nEvery time afterwards, for the rest of the day, I don't see this error. My Lambda is set to timeout after 30 seconds, but I know Cognito needs a response in 5 seconds. \n\nMy lambda function is just updating the last login time in the DB. It's slow the first time because it takes about 1.8 seconds to create a connection to my RDS DB. I'm using Node JS 6 with Sequelize 3 for that part.\n\nI'm guessing it took 2.7 seconds for Lambda to load my app into a container.\n\nDoes anybody have solution here? I'm stumped.\n\n========================================\n\nTop Answer:\nThis seems to be a lambda cold start time issue. There are various approaches you can try to optimize this such as: \n\nIncrease the memory allocated to your functions, which also increases CPU proportionally. Because your functions are called very infrequently, the added cost of increasing memory size will be balanced by faster cold start times and thus lower billed duration.\n\nReduce your code size: a smaller .zip, removing unnecessary require()'s in Node.js, etc. For example, if you are including the Async library just to remove a nested callback, consider forgoing that to improve performance.\n\n========================================\n\nCode:\n```text\n{\n  \"message\": \"arn:aws:lambda:us-east-1:XXXXXXXXXX:function:main-devryan-users_onCognitoLogin failed with error Socket timeout while invoking Lambda function.\",\n  \"code\": \"UnexpectedLambdaException\",\n  \"time\": \"2017-08-29T13:30:01.351Z\",\n  \"requestId\": \"1c04c982-8cbe-11e7-b9c9-a584e55a17f8\",\n  \"statusCode\": 400,\n  \"retryable\": false,\n  \"retryDelay\": 96.636396268355\n}\n```\n\n```text\nREPORT RequestId: 1f2d5a22-8cbe-11e7-ba74-5b21665a40c1  Duration: 2283.60 ms    Billed Duration: 2300 ms Memory Size: 128 MB    Max Memory Used: 51 MB\n```\n\n```text\nlet AWS = require(\"aws-sdk\");\nlet lambda = new AWS.Lambda();\n\nlet params = {\n    FunctionName: \"main-@deploy_env@-users_actualCognitoLogin\", // I'm using the Serverless framework\n    InvocationType: \"Event\", // Makes it async\n    LogType: \"None\",\n    Payload: JSON.stringify(event)\n};\n\nlambda.invoke(params, (err, data) => {\n    if (err) {\n        console.log(\"ERROR: \" + err, err.stack); // an error occurred\n        context.done(err, event);\n    } else {\n        console.log(data); // successful response\n        context.done(null, event);\n    }\n});\n```\n\n```text\nonLogin\n```\n\n```text\nactualOnLogin\n```\n\n```text\nonLogin\n```\n\n```text\nactualOnLogin\n```\n\n```text\nactualOnLogin\n```\n\n```text\nonLogin\n```\n\n========================================\n\nComments:\n- I couldn't get this to work; received an 'Unrecognizable lambda output' error. Any suggestions?\n- Did you receive that from Cognito or Lambda? What do the logs of your Lambda say? Maybe they couldn't find the `actualOnLogin` Lambda?\n- Thanks for up. I got it working. In Lambda function (JavaScript), I declared `callback` parameter in `exports.handler`, however I was not calling it at the end like `callback(null, event)`.","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":115,"estimatedTokens":999}}471{"id":"stack-40040412","source":"stackoverflow","questionId":40040412,"title":"Sequelize getter not called when I use find","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize getter not called when I use find\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have getters defined within the property definition of my model, they look like this:\n\n```\ntimeReported: {\n type: DataTypes.DATE,\n defaultValue: Sequelize.NOW,\n get() {\n const input = this.getDataValue('timeReported')\n const output = moment(input).valueOf()\n return output\n },\n set(input) {\n var output = moment(input).toDate()\n this.setDataValue('timeReported', output)\n },\n validate: {\n isBefore: moment().format('YYYY-MM-DD')\n }\n }\n```\n\nI have tried adding the getter to `getterMethods` in the `options` instead of within the `property`:\n\n```\ngetterMethods: {\n timeReported: function () {\n debugger\n const input = this.getDataValue('timeReported')\n const output = moment(input).valueOf()\n return output\n }\n}\n```\n\nI find that the setters are executed correctly when I save because I use timestamps as the request payload. I also find that validations work correctly.\nInterestingly the `afterFind` hook is called correctly and it does show that `customGetters` have been registered as existing on my model.\n\nHowever, when I call the `find` method on my model like this:\n\n```\nconst {dataValues} = yield models.Reporting.findOne({\n where: {\n reportNo: reportNo\n }\n})\n```\n\nMy `getter` methods are not invoked to transform my data for presentation. How do I invoke these methods on the data fetched from the db before I can access it.\n\nI have tried adding the `raw:false` property to the `queryOptions` along with `where`. That did not work.\n\n**NOTE**: I fetch my data using `co`, I have to retrieve the `dataValues` property from the model. None of the examples seem to be using the property.\n\n========================================\n\nCode:\n```text\ntimeReported: {\n      type: DataTypes.DATE,\n      defaultValue: Sequelize.NOW,\n      get() {\n        const input = this.getDataValue('timeReported')\n        const output = moment(input).valueOf()\n        return output\n      },\n      set(input) {\n        var output = moment(input).toDate()\n        this.setDataValue('timeReported', output)\n      },\n      validate: {\n        isBefore: moment().format('YYYY-MM-DD')\n      }\n    }\n```\n\n```text\ngetterMethods: {\n  timeReported: function () {\n    debugger\n    const input = this.getDataValue('timeReported')\n    const output = moment(input).valueOf()\n    return output\n  }\n}\n```\n\n```text\nconst {dataValues} = yield models.Reporting.findOne({\n  where: {\n    reportNo: reportNo\n  }\n})\n```\n\n```text\ngetterMethods\n```\n\n```text\noptions\n```\n\n```text\nproperty\n```\n\n```text\nafterFind\n```\n\n```text\ncustomGetters\n```\n\n```text\nfind\n```\n\n```text\ngetter\n```\n\n```text\nraw:false\n```\n\n```text\nqueryOptions\n```\n\n```text\nwhere\n```\n\n```text\nco\n```\n\n```text\ndataValues\n```\n\n```text\nconst data = instance.get()\n```\n\n```text\nconst propValue = instance.get('timeReported')\n```\n\n```text\ndataValues\n```\n\n```text\ngetters\n```\n\n```text\nvirtual\n```\n\n```text\ngetter\n```\n\n========================================\n\nComments:\n- As of Sequelize 5 it seems like calling the getter on the property itself is required. In Sequelize 4 calling `.get()` would invoke all getter functions. Now we must call `.get('timeReported')` (see github.com/sequelize/sequelize/pull/9568).","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":175,"estimatedTokens":816}}472{"id":"stack-59828195","source":"stackoverflow","questionId":59828195,"title":"Weird now() time difference with Postgres triggers","tags":["postgresql","transactions","timestamp","sequelize.js","plpgsql"],"text":"Title: Weird now() time difference with Postgres triggers\nTags: postgresql, transactions, timestamp, sequelize.js, plpgsql\nSource: Stack Overflow\n\nQuestion:\nIn a Postgres 10.10 database, I have a table `table1` , and an `AFTER INSERT` trigger on `table1` for `table2`:\n\n```\nCREATE TABLE table1 (\n id SERIAL PRIMARY KEY,\n -- other cols\n created_at timestamp with time zone NOT NULL,\n updated_at timestamp with time zone NOT NULL\n);\n\nCREATE UNIQUE INDEX table1_pkey ON table1(id int4_ops);\n\nCREATE TABLE table2 (\n id SERIAL PRIMARY KEY,\n table1_id integer NOT NULL REFERENCES table1(id) ON UPDATE CASCADE,\n -- other cols (not used in query)\n created_at timestamp with time zone NOT NULL,\n updated_at timestamp with time zone NOT NULL\n);\n\nCREATE UNIQUE INDEX table2_pkey ON table2(id int4_ops);\n```\n\nThis query is executed on application start:\n\n```\nCREATE OR REPLACE FUNCTION after_insert_table1()\nRETURNS trigger AS\n$$\nBEGIN\n INSERT INTO table2 (table1_id, ..., created_at, updated_at)\n VALUES (NEW.id, ..., 'now', 'now');\nRETURN NEW;\nEND;\n$$\nLANGUAGE 'plpgsql';\n\nDROP TRIGGER IF EXISTS after_insert_table1 ON \"table1\";\n\nCREATE TRIGGER after_insert_table1\nAFTER INSERT ON \"table1\"\nFOR EACH ROW \nEXECUTE PROCEDURE after_insert_table1();\n```\n\nI noticed some `created_at` and `updated_at` values on `table2` are different to `table1`. In fact, `table2` has mostly older values.\n\nHere are 10 sequential entries, which show the difference jumping around a huge amount within a few minutes:\n\n```\n|table1_id|table1_created |table2_created |diff |\n|---------|--------------------------|-----------------------------|----------------|\n|2000 |2019-11-07 22:29:47.245+00|2019-11-07 19:51:09.727021+00|-02:38:37.517979|\n|2001 |2019-11-07 22:30:02.256+00|2019-11-07 13:18:29.45962+00 |-09:11:32.79638 |\n|2002 |2019-11-07 22:30:43.021+00|2019-11-07 13:44:12.099577+00|-08:46:30.921423|\n|2003 |2019-11-07 22:31:00.794+00|2019-11-07 19:51:09.727021+00|-02:39:51.066979|\n|2004 |2019-11-07 22:31:11.315+00|2019-11-07 13:18:29.45962+00 |-09:12:41.85538 |\n|2005 |2019-11-07 22:31:27.234+00|2019-11-07 13:44:12.099577+00|-08:47:15.134423|\n|2006 |2019-11-07 22:31:47.436+00|2019-11-07 13:18:29.45962+00 |-09:13:17.97638 |\n|2007 |2019-11-07 22:33:19.484+00|2019-11-07 17:22:48.129063+00|-05:10:31.354937|\n|2008 |2019-11-07 22:33:51.607+00|2019-11-07 19:51:09.727021+00|-02:42:41.879979|\n|2009 |2019-11-07 22:34:28.786+00|2019-11-07 13:18:29.45962+00 |-09:15:59.32638 |\n|2010 |2019-11-07 22:36:50.242+00|2019-11-07 13:18:29.45962+00 |-09:18:20.78238 |\n```\n\nSequential entries have similar differences (mostly negative/mostly positive), and similar orders of magnitude (mostly minutes vs mostly hours) within the sequence, though there are exceptions\n\nHere are the top 5 largest positive differences:\n\n```\n|table1_id|table1_created |table2_created |diff |\n|---------|--------------------------|-----------------------------|----------------|\n|1630 |2019-10-25 21:12:14.971+00|2019-10-26 00:52:09.376+00 |03:39:54.405 |\n|950 |2019-09-16 12:36:07.185+00|2019-09-16 14:07:35.504+00 |01:31:28.319 |\n|1677 |2019-10-26 22:19:12.087+00|2019-10-26 23:38:34.102+00 |01:19:22.015 |\n|58 |2018-12-08 20:11:20.306+00|2018-12-08 21:06:42.246+00 |00:55:21.94 |\n|171 |2018-12-17 22:24:57.691+00|2018-12-17 23:16:05.992+00 |00:51:08.301 |\n```\n\nHere are the top 5 largest negative differences:\n\n```\n|table1_id|table1_created |table2_created |diff |\n|---------|--------------------------|-----------------------------|----------------|\n|1427 |2019-10-15 16:03:43.641+00|2019-10-14 17:59:41.57749+00 |-22:04:02.06351 |\n|1426 |2019-10-15 13:26:07.314+00|2019-10-14 18:00:50.930513+00|-19:25:16.383487|\n|1424 |2019-10-15 13:13:44.092+00|2019-10-14 18:00:50.930513+00|-19:12:53.161487|\n|4416 |2020-01-11 00:15:03.751+00|2020-01-10 08:43:19.668399+00|-15:31:44.082601|\n|4420 |2020-01-11 01:58:32.541+00|2020-01-10 11:04:19.288023+00|-14:54:13.252977|\n```\n\nNegative differences outnumber positive differences 10x. The database timezone is UTC. \n\n`table2.table1_id` is a foreign key, so it should be impossible to insert before insert on `table1` completes.\n\n`table1.created_at` is set by Sequelize, using option `timestamps: true` on the model.\n\nWhen a row is inserted into `table1`, it's done inside a transaction. From the documentation I can find, triggers are executed inside the same transaction, so I can't think of a reason for this.\n\nI can fix the issue by changing my trigger to use `NEW.created_at` instead of 'now', but I'm curious if anyone has any idea what the cause of this bug is?\n\nHere is the query used to produce the above difference tables:\n\n```\nSELECT\n table1.id AS table1_id,\n table1.created_at AS table1_created,\n table2.created_at AS table2_created,\n (table2.created_at - table1.created_at) AS diff\nFROM table1\nINNER JOIN table2 ON \n table2.table1_id = table1.id AND (\n (table2.created_at - table1.created_at) > '2 min' OR \n (table1.created_at - table2.created_at) > '2 min')\nORDER BY diff;\n```\n\n========================================\n\nCode:\n```text\nCREATE TABLE table1 (\n    id SERIAL PRIMARY KEY,\n    -- other cols\n    created_at timestamp with time zone NOT NULL,\n    updated_at timestamp with time zone NOT NULL\n);\n\nCREATE UNIQUE INDEX table1_pkey ON table1(id int4_ops);\n\nCREATE TABLE table2 (\n    id SERIAL PRIMARY KEY,\n    table1_id integer NOT NULL REFERENCES table1(id) ON UPDATE CASCADE,\n    -- other cols (not used in query)\n    created_at timestamp with time zone NOT NULL,\n    updated_at timestamp with time zone NOT NULL\n);\n\nCREATE UNIQUE INDEX table2_pkey ON table2(id int4_ops);\n```\n\n```text\nCREATE OR REPLACE FUNCTION after_insert_table1()\nRETURNS trigger AS\n$$\nBEGIN\n    INSERT INTO table2 (table1_id, ..., created_at, updated_at)\n    VALUES (NEW.id, ..., 'now', 'now');\nRETURN NEW;\nEND;\n$$\nLANGUAGE 'plpgsql';\n\nDROP TRIGGER IF EXISTS after_insert_table1 ON \"table1\";\n\nCREATE TRIGGER after_insert_table1\nAFTER INSERT ON \"table1\"\nFOR EACH ROW \nEXECUTE PROCEDURE after_insert_table1();\n```\n\n```text\n|table1_id|table1_created            |table2_created               |diff            |\n|---------|--------------------------|-----------------------------|----------------|\n|2000     |2019-11-07 22:29:47.245+00|2019-11-07 19:51:09.727021+00|-02:38:37.517979|\n|2001     |2019-11-07 22:30:02.256+00|2019-11-07 13:18:29.45962+00 |-09:11:32.79638 |\n|2002     |2019-11-07 22:30:43.021+00|2019-11-07 13:44:12.099577+00|-08:46:30.921423|\n|2003     |2019-11-07 22:31:00.794+00|2019-11-07 19:51:09.727021+00|-02:39:51.066979|\n|2004     |2019-11-07 22:31:11.315+00|2019-11-07 13:18:29.45962+00 |-09:12:41.85538 |\n|2005     |2019-11-07 22:31:27.234+00|2019-11-07 13:44:12.099577+00|-08:47:15.134423|\n|2006     |2019-11-07 22:31:47.436+00|2019-11-07 13:18:29.45962+00 |-09:13:17.97638 |\n|2007     |2019-11-07 22:33:19.484+00|2019-11-07 17:22:48.129063+00|-05:10:31.354937|\n|2008     |2019-11-07 22:33:51.607+00|2019-11-07 19:51:09.727021+00|-02:42:41.879979|\n|2009     |2019-11-07 22:34:28.786+00|2019-11-07 13:18:29.45962+00 |-09:15:59.32638 |\n|2010     |2019-11-07 22:36:50.242+00|2019-11-07 13:18:29.45962+00 |-09:18:20.78238 |\n```\n\n```text\n|table1_id|table1_created            |table2_created               |diff            |\n|---------|--------------------------|-----------------------------|----------------|\n|1630     |2019-10-25 21:12:14.971+00|2019-10-26 00:52:09.376+00   |03:39:54.405    |\n|950      |2019-09-16 12:36:07.185+00|2019-09-16 14:07:35.504+00   |01:31:28.319    |\n|1677     |2019-10-26 22:19:12.087+00|2019-10-26 23:38:34.102+00   |01:19:22.015    |\n|58       |2018-12-08 20:11:20.306+00|2018-12-08 21:06:42.246+00   |00:55:21.94     |\n|171      |2018-12-17 22:24:57.691+00|2018-12-17 23:16:05.992+00   |00:51:08.301    |\n```\n\n```text\n|table1_id|table1_created            |table2_created               |diff            |\n|---------|--------------------------|-----------------------------|----------------|\n|1427     |2019-10-15 16:03:43.641+00|2019-10-14 17:59:41.57749+00 |-22:04:02.06351 |\n|1426     |2019-10-15 13:26:07.314+00|2019-10-14 18:00:50.930513+00|-19:25:16.383487|\n|1424     |2019-10-15 13:13:44.092+00|2019-10-14 18:00:50.930513+00|-19:12:53.161487|\n|4416     |2020-01-11 00:15:03.751+00|2020-01-10 08:43:19.668399+00|-15:31:44.082601|\n|4420     |2020-01-11 01:58:32.541+00|2020-01-10 11:04:19.288023+00|-14:54:13.252977|\n```\n\n```text\nSELECT\n    table1.id AS table1_id,\n    table1.created_at AS table1_created,\n    table2.created_at AS table2_created,\n    (table2.created_at - table1.created_at) AS diff\nFROM table1\nINNER JOIN table2   ON \n    table2.table1_id = table1.id AND (\n        (table2.created_at - table1.created_at) > '2 min' OR \n        (table1.created_at - table2.created_at) > '2 min')\nORDER BY diff;\n```\n\n```text\ntable1\n```\n\n```text\nAFTER INSERT\n```\n\n```text\ntable1\n```\n\n```text\ntable2\n```\n\n```text\ncreated_at\n```\n\n```text\nupdated_at\n```\n\n```text\ntable2\n```\n\n```text\ntable1\n```\n\n```text\ntable2\n```\n\n```text\ntable2.table1_id\n```\n\n```text\ntable1\n```\n\n```text\ntable1.created_at\n```\n\n```text\ntimestamps: true\n```\n\n```text\ntable1\n```\n\n```text\nNEW.created_at\n```\n\n```text\nCREATE TABLE table1 (\n    id SERIAL PRIMARY KEY,\n    -- other cols\n    created_at timestamptz NOT NULL DEFAULT now(),\n    updated_at timestamptz NOT NULL DEFAULT now()   -- or leave this one NULL?\n);\n\nCREATE TABLE table2 (\n    id SERIAL PRIMARY KEY,\n    table1_id integer NOT NULL REFERENCES table1(id) ON UPDATE CASCADE,\n    -- other cols (not used in query)\n    created_at timestamptz NOT NULL DEFAULT now(),  -- not 'now'!\n    updated_at timestamptz NOT NULL DEFAULT now()   -- or leave this one NULL?\n);\n\nCREATE OR REPLACE FUNCTION after_insert_table1()\n  RETURNS trigger LANGUAGE plpgsql AS\n$$\nBEGIN\n   INSERT INTO table2 (table1_id)  -- more columns? but not: created_at, updated_at\n   VALUES (NEW.id);                -- more columns?\n\n   RETURN NULL;                     -- can be NULL for AFTER trigger\nEND\n$$;\n```\n\n```text\n'now'\n```\n\n```text\nnow\n```\n\n```text\nSPI_prepare\n```\n\n```text\n'now'\n```\n\n```text\ntransaction_timestamp()\n```\n\n```text\ntable2\n```\n\n```text\ntable1\n```\n\n```text\ntable1\n```\n\n```text\ntable2\n```\n\n```text\n'now'\n```\n\n```text\nnow()\n```\n\n```text\nCURRENT_TIMESTAMP\n```\n\n```text\ntransaction_timestamp()\n```\n\n```text\nnow()\n```\n\n```text\ntable1\n```\n\n```text\ntable2\n```\n\n```text\nINSERT\n```\n\n```text\ntable1\n```\n\n========================================\n\nComments:\n- 'now' is not a timestamp, it is a string. Try using the function now(). But to your direct question you you can new.created_at from the table1 row.\n- They're the same: `SELECT 'now'::timestamp = now();`. Aware I can use `NEW.created_at`, was asking about the root cause for this\n- 1. Are you sure, neither table receives **updates**? You can identify inserted rows by looking at `xmax`. See: stackoverflow.com/a/40880200/939860 2. Are there any other *triggers* on table `table1` that might interfere? 3. Does the target column list of your `INSERT`have the same number of elements as the `VALUES` list?\n- Generally, please show the verbatim, complete trigger and trigger function definitions and *always* your version of Postgres. Also, the error may be in the query used to join `table1` and `table2` to inspect the diff. We'd really need to see query and table definitions. All in all, this is a case for a crystal ball ...\n- @ErwinBrandstetter I've added the requested details above\n- @BenedictLewis: You delivered and provided everything to make this a useful and interesting question now.\n- @Belayer: You were on the right track. `SELECT 'now'::timestamp = now();` returns `true`. Both are still not \"the same\".","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":40,"totalLines":386,"estimatedTokens":2899}}473{"id":"stack-53042399","source":"stackoverflow","questionId":53042399,"title":"Why spread() method doesn't work in Sequelize?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Why spread() method doesn't work in Sequelize?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using a `Sequelize` for my `node.js` app. I use `findOrCreate()` method to create a new user if not exist. Accordingly to docs `findOrCreate` returns an array containing the object that was found or created and a boolean that will be true if a new object was created and false if not.\n\nThe sequelize recommend to use `spread()` method which divides the array into its 2 parts and passes them as arguments to the callback function. First part is a user object and second is boolean if new row was added.\n\nI work in `async/await` style. My code is:\n\n```\napp.post('/signup', async (req, res) => {\n try {\n let insertedUser = await User.findOrCreate({\n where: { email: req.body.userEmail },\n defaults: {\n pass: req.body.userPass\n }\n })\n insertedUser.spread((user, created) => {\n if(created) {\n res.json(user.email)\n }\n })\n } catch (err) {\n console.log(`ERROR! => ${err.name}: ${err.message}`)\n res.status(500).send(err.message)\n }\n }\n})\n```\n\nAfter post request I get an error:\n\n```\nERROR! => TypeError: insertedUser.spread is not a function\n```\n\nWhy is that, the doc says it must be a function?\n\n========================================\n\nCode:\n```text\napp.post('/signup', async (req, res) => {\n        try {\n            let insertedUser = await User.findOrCreate({\n                where: { email: req.body.userEmail },\n                defaults: {\n                    pass: req.body.userPass\n                }\n            })\n            insertedUser.spread((user, created) => {\n                if(created) {\n                    res.json(user.email)\n                }\n            })\n        } catch (err) {\n            console.log(`ERROR! => ${err.name}: ${err.message}`)\n            res.status(500).send(err.message)\n        }\n    }\n})\n```\n\n```text\nERROR! => TypeError: insertedUser.spread is not a function\n```\n\n```text\nSequelize\n```\n\n```text\nnode.js\n```\n\n```text\nfindOrCreate()\n```\n\n```text\nfindOrCreate\n```\n\n```text\nspread()\n```\n\n```text\nasync/await\n```\n\n```text\napp.post('/signup', async (req, res) => {\n        try {\n            let created = await User.findOrCreate({\n                where: { email: req.body.userEmail },\n                defaults: {\n                    pass: req.body.userPass\n                }\n            }).spread((user, created) => {\n                return created;\n            })\n            if(created) {\n                res.json(user.email)\n            }\n        } catch (err) {\n            console.log(`ERROR! => ${err.name}: ${err.message}`)\n            res.status(500).send(err.message)\n        }\n    }\n})\n```\n\n```text\nspread\n```\n\n```text\nfindOrCreate\n```\n\n```text\nspread\n```\n\n```text\nthen\n```\n\n```text\npromise\n```\n\n```text\nfindOrCreate\n```\n\n```text\nfindOrCreate\n```\n\n```text\nawait\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- Can you provide the second example with await also. Want to understand it with example. Thank you in advance\n- Here is a very insightful article: medium.com/front-end-hacking/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":157,"estimatedTokens":776}}474{"id":"stack-48587478","source":"stackoverflow","questionId":48587478,"title":"Sequelize transactions as Express middleware","tags":["node.js","express","transactions","sequelize.js"],"text":"Title: Sequelize transactions as Express middleware\nTags: node.js, express, transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add Sequelize transactions to my Express app, but I'm unsuccessful. I'm using async/await across the app, and I've created the namespace using the 'cls-hooked' package as instructed on the docs for Sequelize transactions.\n\n```\nSequelize.useCLS(require('cls-hooked').createNamespace('db'));\n```\n\nMy middleware is pretty simple and looks something like this\n\n```\nmodule.exports = () => (req, res, next) => sequelize.transaction(async () => next());\n```\n\nand in app.js\n\n```\napp.use(sequelizeTransaction());\napp.use('/api', apiRoutes);\n```\n\nI've also tried using the middleware directly on routes, but I get the same result as above\n\n```\nrouter.post('/', sequelizeTransaction(), async (req, res) => {\n await serviceThatDoesTwoDBOperations();\n});\n```\n\nThe result is that I get the transaction, but only around the first DB operation. Everything after that is ignored, and rollbacks aren't happening on errors. I'm probably doing something obviously wrong, but I can't put my finger on it.\n\n========================================\n\nCode:\n```text\nSequelize.useCLS(require('cls-hooked').createNamespace('db'));\n```\n\n```text\nmodule.exports = () => (req, res, next) => sequelize.transaction(async () => next());\n```\n\n```text\napp.use(sequelizeTransaction());\napp.use('/api', apiRoutes);\n```\n\n```text\nrouter.post('/', sequelizeTransaction(), async (req, res) => {\n    await serviceThatDoesTwoDBOperations();\n});\n```\n\n```text\nexport const transactionMiddleware = async (req, res, next) => {\n  namespace.bindEmitter(req);\n  namespace.bindEmitter(res);\n  namespace.bind(next);\n  namespace.run(async () => {\n    const transaction = await sequelize.transaction();\n    namespace.set('transaction', transaction);\n    onFinished(res, (err) => {\n      if (!err) {\n        transaction.commit();\n      } else {\n        transaction.rollback();\n      }\n    });\n    next();\n  });\n};\n```\n\n========================================\n\nComments:\n- Works great, but is there a way to check for sequelize errors instead of response errors?","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":80,"estimatedTokens":540}}475{"id":"stack-68494554","source":"stackoverflow","questionId":68494554,"title":"Sequelize table name updates","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize table name updates\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table in Postgres and for ORM I am using sequelize I need to update the table name so I've tried the below migration for this\n\n```\nqueryInterface.renameTable('table1', 'table2', { transaction }\n```\n\nbut for some reason, it's creating a new table with table2 with the same data as table 1 but table 1 still exits with blank data.is this correct behavior of this function so'll add a delete query.\n\n========================================\n\nTop Answer:\nFor that use case i normally rely on raw queries:\n\n```\nconst { sequelize } = queryInterface;\n\nawait sequelize.query(\n `ALTER TABLE table1\n RENAME TO table2`,\n {\n type: QueryTypes.RAW,\n raw: true,\n transaction,\n },\n);\n```\n\n========================================\n\nCode:\n```text\nqueryInterface.renameTable('table1', 'table2', { transaction }\n```\n\n```text\nconst { sequelize } = queryInterface;\n\nawait sequelize.query(\n  `ALTER TABLE table1\n   RENAME TO table2`,\n  {\n    type: QueryTypes.RAW,\n    raw: true,\n    transaction,\n  },\n);\n```\n\n========================================\n\nComments:\n- why raw query but? isn't sequelize is enough for this?\n- Sequelize supports this but i'm just used to do that way\n- not answer my question I need this working on sequelize\n- I think that Sequelize do create that extra table to allow `safe&#47;strong` migrations. github.com/ankane/strong_migrations#renaming-a-table So when you're renaming a table, that's a blocking operation, meaning that if you have a lot of requests being made to the database it will lock that table (which don't happens if it creates a newer one) so i think Sequelize behaviour implement that to allow strong migrations. If its not a problem for you, you can just perform the `raw` query i've showed, or you can do your way, it will create a new table, and you would need to drop that `table1`.\n- with raw query too same is happening. can you post full code I think I am making some mistake","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":61,"estimatedTokens":506}}476{"id":"stack-41924281","source":"stackoverflow","questionId":41924281,"title":"How to update an array in Sequelize Postgres","tags":["node.js","postgresql","sequelize.js"],"text":"Title: How to update an array in Sequelize Postgres\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a user model in Sequelize for a Postgres db: \n\n```\nvar User = sequelize.define('User', {\nfb_id: DataTypes.STRING,\naccess_token: DataTypes.TEXT,\nfirst_name: DataTypes.STRING,\nlast_name: DataTypes.STRING,\nemail: DataTypes.TEXT,\nprofilePictureURL: DataTypes.TEXT,\nlibrary: DataTypes.ARRAY(DataTypes.STRING)\n}, {\nunderscored: true,\nclassMethods: {\n associate: function(models) {\n\n }\n }\n });\n```\n\nI am trying to update the library field by adding ISBNs to the array. This is the code for my POST request: \n\n```\nreq.user.library.push(req.body._isbn); // adding the posted ISBN to the user object in my express-session\n\nUser.findOrCreate({where: {fb_id: req.user.fb_id}, \n defaults: {\n access_token : req.user.access_token, \n first_name : req.user.first_name,\n last_name : req.user.last_name,\n email : req.user.email, \n profilePictureURL : req.user.profilePictureURL,\n library: req.user.library // new library object\n }})\n .spread(function (updatedUser, created){\n res.status(200).json(updatedUser);\n }).error(function(err){\n res.status(500).json(err);\n });\n```\n\nThere is no error, but the library field is not updated after checking the updatedUser object. How do I correctly update an array field in Sequelize?\n\n========================================\n\nTop Answer:\nFor next visitors, I may have found a better way to solve this issue :\n\n```\nUser.update(\n {library: Sequelize.fn('array_append', Sequelize.col('library'), req.body._isbn)},\n {where: {fb_id: req.user.fb_id}}\n);\n```\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {\nfb_id: DataTypes.STRING,\naccess_token: DataTypes.TEXT,\nfirst_name: DataTypes.STRING,\nlast_name: DataTypes.STRING,\nemail: DataTypes.TEXT,\nprofilePictureURL: DataTypes.TEXT,\nlibrary: DataTypes.ARRAY(DataTypes.STRING)\n}, {\nunderscored: true,\nclassMethods: {\n  associate: function(models) {\n\n   }\n }\n  });\n```\n\n```text\nreq.user.library.push(req.body._isbn); // adding the posted ISBN to the user object in my express-session\n\nUser.findOrCreate({where: {fb_id: req.user.fb_id}, \n        defaults: {\n            access_token :      req.user.access_token,                 \n            first_name :        req.user.first_name,\n            last_name :         req.user.last_name,\n            email :             req.user.email, \n            profilePictureURL : req.user.profilePictureURL,\n            library: req.user.library // new library object\n        }})\n        .spread(function (updatedUser, created){\n            res.status(200).json(updatedUser);\n        }).error(function(err){\n            res.status(500).json(err);\n        });\n```\n\n```text\nUser.find({\n  where: {\n    fb_id: req.user.fb_id\n  }\n})\n.then((user) => {\n  user.library.push(req.body._isbn)\n  user.update({\n    library: user.library\n  },{\n    where: {\n      fb_id: req.user.fb_id\n    }\n  })\n  .then(user => res.json(user))\n})\n```\n\n```text\nUser.update(\n {library: Sequelize.fn('array_append', Sequelize.col('library'), req.body._isbn)},\n {where: {fb_id: req.user.fb_id}}\n);\n```\n\n```text\nlet newArray = Object.assign([], instance.arrayToUpdate);\n\nnewArray.push(myInterestingData)\nawait instance.update({\n  arrayToUpdate: newArray\n});\n```\n\n========================================\n\nComments:\n- Posting code is great, but please try to add some text to describe what you've done.","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":141,"estimatedTokens":861}}477{"id":"stack-53946898","source":"stackoverflow","questionId":53946898,"title":"How to obtain inheritance in sequelize models","tags":["mysql","node.js","sequelize.js"],"text":"Title: How to obtain inheritance in sequelize models\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am running a Node.js service with sequelize. I have 4 different types of users, all some of the same attributes like name, password etc. and all have user-role specific attributes. \n\nCurrently, I have all 4 models defined as separate models. This gives code duplication and multiple calls to the database if I want to retrieve all users.\n\nHow can I obtain a form of inheritance with sequelize? \nI would like to achieve something like this:\n\n========================================\n\nCode:\n```text\nInstructor\n```\n\n```text\nStudent\n```\n\n```text\nAdministrator\n```\n\n```text\nJanitor\n```\n\n```text\nUser\n```\n\n```text\nforeignKeys\n```\n\n```text\ntargetKeys\n```\n\n```text\nsourceKey\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsToMany\n```\n\n```text\nhasOne\n```\n\n========================================\n\nComments:\n- Thanks @Mohdule. I ended up doing as you suggested and defined my foregin keys like this \"db.admins.belongsTo(db.users, { foreignKey: \"id\", targetKey: \"id\" });\"\n- Hi @OhLongJohnJohnson, Can you please elaborate more on how you did solve this?\n- I think it does not really answer the question. In other ORMs there are inheritance mecanism where you can handle this either with a single table and a discriminator column or with multiple tables which gets automatically joined. At the end, you get a User which is either of type Instructor, Student, Administrator or Janitor and have the corresponding fields loaded in root object. You should also be able to know which Class it is instance of (by using instanceof). The question was is it possible with Sequelize or not (seems not ?)","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":65,"estimatedTokens":426}}478{"id":"stack-56061172","source":"stackoverflow","questionId":56061172,"title":"NodeJS sequelize auto generate models and run migrations SQL syntax error","tags":["mysql","node.js","model","migration","sequelize.js"],"text":"Title: NodeJS sequelize auto generate models and run migrations SQL syntax error\nTags: mysql, node.js, model, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am building a new NodeJS application with MySQL. I need to use the existing database schema. I have a mysql dump file that is loaded into the database (in a docker container). I am trying to generate models and migrations automatically and then run the migrations successfully. I am able to generate the models and migrations, however there is a SQL syntax error when running the generated migrations.\n\nHere are the relevant versions:\n\nNode10-alpine\n\n```\n\"mysql\": \"^2.17.1\",\n\"mysql2\": \"^1.6.5\",\n\"sequelize\": \"^5.8.5\",\n\"sequelize-auto\": \"^0.4.29\",\n\"sequelize-auto-migrations\": \"^1.0.3\"\n```\n\nI used the sequelize-auto module to generate the Models automatically. That works.\n\n```\nsequelize-auto -o \"./models\" -d sequelize_auto_test -h localhost -u username -p 5432 -x password -e mysql\n```\n\nI then attempted to use the sequelize-auto-migrations module to generate the Migrations and then run them automatically.\n\nGenerating the initial migration file works.\n\n```\nnode ./node_modules/sequelize-auto-migrations/bin/makemigration --name \n```\n\nHowever, when running the actual migration, there is a syntax error.\n\n```\nnode ./node_modules/sequelize-auto-migrations/bin/runmigration\n```\n\nThat works for many of the tables but then it runs into a syntax error.\n\n```\ncode: 'ER_PARSE_ERROR',\n errno: 1064,\n sqlState: '42000',\n sqlMessage:\n 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \\') ENGINE=InnoDB\\' at line 1',\n sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' },\n sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' }\n```\n\nHere is the relevant model osw.js (generated by the sequelize-auto module):\n\n```\n/* jshint indent: 2 */\n\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('osw', {\n OSWID: {\n type: DataTypes.INTEGER(10).UNSIGNED,\n allowNull: false,\n primaryKey: true\n },\n IdentificationID: {\n type: DataTypes.INTEGER(10).UNSIGNED,\n allowNull: true,\n references: {\n model: 'itemidentification',\n key: 'IdentificationID'\n }\n },\n ProposedHours: {\n type: DataTypes.DECIMAL,\n allowNull: true\n },\n WorkStartDate: {\n type: DataTypes.DATEONLY,\n allowNull: true\n },\n WorkEndDate: {\n type: DataTypes.DATEONLY,\n allowNull: true\n },\n FormatID: {\n type: DataTypes.INTEGER(10).UNSIGNED,\n allowNull: true,\n references: {\n model: 'formats',\n key: 'FormatID'\n }\n },\n WorkLocationID: {\n type: DataTypes.INTEGER(10).UNSIGNED,\n allowNull: true\n }\n }, {\n tableName: 'osw'\n });\n};\n```\n\nHere is the relevant part of the mysql dump file:\n\n```\nCREATE TABLE `OSW` (\n `OSWID` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `IdentificationID` int(10) unsigned DEFAULT NULL,\n `ProposedHours` decimal(10,2) DEFAULT NULL,\n `WorkStartDate` date DEFAULT NULL,\n `WorkEndDate` date DEFAULT NULL,\n `FormatID` int(10) unsigned DEFAULT NULL,\n `WorkLocationID` int(10) unsigned DEFAULT NULL,\n PRIMARY KEY (`OSWID`),\n KEY `OSW_FKIndex1` (`IdentificationID`),\n KEY `OSW_Format` (`FormatID`),\n CONSTRAINT `OSW_Format` FOREIGN KEY (`FormatID`) REFERENCES `formats` (`formatid`) ON DELETE SET NULL,\n CONSTRAINT `OSW_Ident` FOREIGN KEY (`IdentificationID`) REFERENCES `itemidentification` (`identificationid`) ON DELETE CASCADE\n) ENGINE=InnoDB AUTO_INCREMENT=1147 DEFAULT CHARSET=utf8 PACK_KEYS=0;\n```\n\nUPDATE: I think the issue might be related to the migration that was generated automatically. The migration file seems to be missing the column and field type definitions, so that might be why the SQL `CREATE table` command is missing the column names. Here is the relevant part of the migration file that was generated regarding the `osw` table:\n\n```\nvar migrationCommands = [{\n {\n fn: \"createTable\",\n params: [\n \"osw\",\n {\n\n },\n {}\n ]\n }\n];\n```\n\n========================================\n\nCode:\n```text\n\"mysql\": \"^2.17.1\",\n\"mysql2\": \"^1.6.5\",\n\"sequelize\": \"^5.8.5\",\n\"sequelize-auto\": \"^0.4.29\",\n\"sequelize-auto-migrations\": \"^1.0.3\"\n```\n\n```text\nsequelize-auto -o \"./models\" -d sequelize_auto_test -h localhost -u username -p 5432 -x password -e mysql\n```\n\n```text\nnode ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>\n```\n\n```text\nnode ./node_modules/sequelize-auto-migrations/bin/runmigration\n```\n\n```text\ncode: 'ER_PARSE_ERROR',\n     errno: 1064,\n     sqlState: '42000',\n     sqlMessage:\n      'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \\') ENGINE=InnoDB\\' at line 1',\n     sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' },\n  sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' }\n```\n\n```text\n/* jshint indent: 2 */\n\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('osw', {\n    OSWID: {\n      type: DataTypes.INTEGER(10).UNSIGNED,\n      allowNull: false,\n      primaryKey: true\n    },\n    IdentificationID: {\n      type: DataTypes.INTEGER(10).UNSIGNED,\n      allowNull: true,\n      references: {\n        model: 'itemidentification',\n        key: 'IdentificationID'\n      }\n    },\n    ProposedHours: {\n      type: DataTypes.DECIMAL,\n      allowNull: true\n    },\n    WorkStartDate: {\n      type: DataTypes.DATEONLY,\n      allowNull: true\n    },\n    WorkEndDate: {\n      type: DataTypes.DATEONLY,\n      allowNull: true\n    },\n    FormatID: {\n      type: DataTypes.INTEGER(10).UNSIGNED,\n      allowNull: true,\n      references: {\n        model: 'formats',\n        key: 'FormatID'\n      }\n    },\n    WorkLocationID: {\n      type: DataTypes.INTEGER(10).UNSIGNED,\n      allowNull: true\n    }\n  }, {\n    tableName: 'osw'\n  });\n};\n```\n\n```text\nCREATE TABLE `OSW` (\n  `OSWID` int(10) unsigned NOT NULL AUTO_INCREMENT,\n  `IdentificationID` int(10) unsigned DEFAULT NULL,\n  `ProposedHours` decimal(10,2) DEFAULT NULL,\n  `WorkStartDate` date DEFAULT NULL,\n  `WorkEndDate` date DEFAULT NULL,\n  `FormatID` int(10) unsigned DEFAULT NULL,\n  `WorkLocationID` int(10) unsigned DEFAULT NULL,\n  PRIMARY KEY (`OSWID`),\n  KEY `OSW_FKIndex1` (`IdentificationID`),\n  KEY `OSW_Format` (`FormatID`),\n  CONSTRAINT `OSW_Format` FOREIGN KEY (`FormatID`) REFERENCES `formats` (`formatid`) ON DELETE SET NULL,\n  CONSTRAINT `OSW_Ident` FOREIGN KEY (`IdentificationID`) REFERENCES `itemidentification` (`identificationid`) ON DELETE CASCADE\n) ENGINE=InnoDB AUTO_INCREMENT=1147 DEFAULT CHARSET=utf8 PACK_KEYS=0;\n```\n\n```text\nvar migrationCommands = [{\n    {\n        fn: \"createTable\",\n        params: [\n            \"osw\",\n            {\n\n            },\n            {}\n        ]\n    }\n];\n```\n\n```text\nCREATE table\n```\n\n```text\nosw\n```\n\n```text\n'use strict';\n\nvar Sequelize = require('sequelize');\n\n/**\n * Actions summary:\n *\n * createTable \"osw\", deps: [itemidentification, formats]\n *\n **/\n\nvar info = {\n    \"revision\": 1,\n    \"name\": \"osw\",\n    \"created\": \"2019-05-30T03:54:19.054Z\",\n    \"comment\": \"\"\n};\n\nvar migrationCommands = [{\n    fn: \"createTable\",\n    params: [\n        \"osw\",\n        {\n            \"OSWID\": {\n                \"type\": Sequelize.INTEGER(10).UNSIGNED,\n                \"field\": \"OSWID\",\n                \"primaryKey\": true,\n                \"allowNull\": false\n            },\n            \"IdentificationID\": {\n                \"type\": Sequelize.INTEGER(10).UNSIGNED,\n                \"field\": \"IdentificationID\",\n                \"references\": {\n                    \"model\": \"itemidentification\",\n                    \"key\": \"IdentificationID\"\n                },\n                \"allowNull\": true\n            },\n            \"ProposedHours\": {\n                \"type\": Sequelize.DECIMAL,\n                \"field\": \"ProposedHours\",\n                \"allowNull\": true\n            },\n            \"WorkStartDate\": {\n                \"type\": Sequelize.DATEONLY,\n                \"field\": \"WorkStartDate\",\n                \"allowNull\": true\n            },\n            \"WorkEndDate\": {\n                \"type\": Sequelize.DATEONLY,\n                \"field\": \"WorkEndDate\",\n                \"allowNull\": true\n            },\n            \"FormatID\": {\n                \"type\": Sequelize.INTEGER(10).UNSIGNED,\n                \"field\": \"FormatID\",\n                \"references\": {\n                    \"model\": \"formats\",\n                    \"key\": \"FormatID\"\n                },\n                \"allowNull\": true\n            },\n            \"WorkLocationID\": {\n                \"type\": Sequelize.INTEGER(10).UNSIGNED,\n                \"field\": \"WorkLocationID\",\n                \"allowNull\": true\n            },\n            \"createdAt\": {\n                \"type\": Sequelize.DATE,\n                \"field\": \"createdAt\",\n                \"allowNull\": false\n            },\n            \"updatedAt\": {\n                \"type\": Sequelize.DATE,\n                \"field\": \"updatedAt\",\n                \"allowNull\": false\n            }\n        },\n        {}\n    ]\n}];\n\nmodule.exports = {\n    pos: 0,\n    up: function(queryInterface, Sequelize)\n    {\n        var index = this.pos;\n        return new Promise(function(resolve, reject) {\n            function next() {\n                if (index < migrationCommands.length)\n                {\n                    let command = migrationCommands[index];\n                    console.log(\"[#\"+index+\"] execute: \" + command.fn);\n                    index++;\n                    queryInterface[command.fn].apply(queryInterface, command.params).then(next, reject);\n                }\n                else\n                    resolve();\n            }\n            next();\n        });\n    },\n    info: info\n};\n```\n\n```text\nsequelize init\n```\n\n```text\nnode ./node_modules/sequelize-auto-migrations/bin/makemigration --name osw\n```\n\n```text\nmigrationCommands\n```\n\n```text\nnpm i -s mysql2 sequelize-auto-migrations; sequelize init\n```\n\n```text\nnpm i sequelize\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":384,"estimatedTokens":2467}}479{"id":"stack-16865190","source":"stackoverflow","questionId":16865190,"title":"node.js sequelize associations, include on condition","tags":["node.js","orm","sequelize.js"],"text":"Title: node.js sequelize associations, include on condition\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to pass a condition in the include array of a findAll query?\n\nFor example I have UsersModel, PostsModel and UserVotesModel.\n\nUsers can vote on posts.\n\nFor the logged in user I want to query posts and include only the vote for the current user. I am not able to do this using Sequelize's include param. Sequelize joins posts and UserVotes on postId, but for this specific query I want to join on both postId and UserId.\n\nAny ideas how to solve this problem?\n\n========================================\n\nTop Answer:\nIf you include a model with a where condition ( that will default require to true) but if you mark it as false to LEFT OUTER JOIN the association\n\n```\nPost.findAll({\n where: {\n user_id: current_user_id\n },\n include: [\n {\n model: UserVote,\n where: {\n 'user_id': current_user_id\n },\n required: false\n }]\n})\n```\n\n========================================\n\nCode:\n```text\nPost.findAll({\n  where: {\n    user_id: current_user_id\n  },\n  include: [\n  {\n    model: UserVote,\n    where: {\n      'user_id':  current_user_id\n    },\n    required: false\n  }]\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":54,"estimatedTokens":301}}480{"id":"stack-44436233","source":"stackoverflow","questionId":44436233,"title":"How in graphql get last 3 element","tags":["express","sequelize.js","graphql","graphql-js"],"text":"Title: How in graphql get last 3 element\nTags: express, sequelize.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHow in graphql.js get last 3 created_at element from mysql db table?\nI use sequelize.js\n\nLike this:\n\n```\nquery: '{\n elements(last:3){ \n id\n }\n}'\n```\n\nThis is my file db.js\n\n```\nconst Conn = new Sequelize(/*connection config*/);\nConn.define('elements', {\n id: {\n type: Sequelize.STRING(36),\n primaryKey: true,\n allowNull: false\n }\n});\nexport default Conn;\n```\n\nThis is my file schema.js\n\n```\nconst Query = new GraphQLObjectType({\n name: 'Query',\n description: 'Root query object',\n fields() {\n return {\n elements: {\n type: new GraphQLList(Element),\n args: {\n id: {\n type: GraphQLString\n }\n },\n resolve (root, args) {\n return Db.models.elements.findAll({ where: args });\n }\n }\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nquery: '{\n    elements(last:3){ \n        id\n    }\n}'\n```\n\n```text\nconst Conn = new Sequelize(/*connection config*/);\nConn.define('elements', {\n    id: {\n        type: Sequelize.STRING(36),\n        primaryKey: true,\n        allowNull: false\n    }\n});\nexport default Conn;\n```\n\n```text\nconst Query = new GraphQLObjectType({\n    name: 'Query',\n    description: 'Root query object',\n    fields() {\n        return {\n            elements: {\n                type: new GraphQLList(Element),\n                args: {\n                    id: {\n                        type: GraphQLString\n                    }\n                },\n                resolve (root, args) {\n                    return Db.models.elements.findAll({ where: args });\n                }\n            }\n        }\n    }\n});\n```\n\n```text\n...\nreturn Db.models.elements.findAll({ \n  limit: 3, \n  where: args, \n  order: [['created_at', 'DESC']] \n});\n```\n\n========================================\n\nComments:\n- Thanks for answer. But how i can change my scheme.js? Like this? `lastThreeElements: { type: new GraphQLList(Element), args: { id: { type: GraphQLString } }, resolve (root, args) { return Db.models.elements.findAll({ limit: 3, where: args, order: [['created_at', 'DESC']] }); } }`\n- @pmnazar put it into a new question not a comment ... enjoy","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":115,"estimatedTokens":544}}481{"id":"stack-38421078","source":"stackoverflow","questionId":38421078,"title":"Sequelize create with existing association","tags":["sequelize.js"],"text":"Title: Sequelize create with existing association\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow to create entry with existing association by using object?\n\nFor example,\n\n```\nUser.create({\n socialMedia: [{\n socialId: 1, //should reference existing social media\n userSocialMedia: {\n name: 'foo' //should create new \"through\" entry\n }\n }],\n bank: {\n bankId: 1 //should reference existing bank\n });\n```\n\nI can do `User.create({ bankId: 1 })`, but since the data sent from client is in this form, is there a way to tell sequelize whether to add new or use existing for each included models?\n\n========================================\n\nCode:\n```text\nUser.create({\n  socialMedia: [{\n    socialId: 1, //should reference existing social media\n    userSocialMedia: {\n      name: 'foo' //should create new \"through\" entry\n    }\n  }],\n  bank: {\n    bankId: 1 //should reference existing bank\n  });\n```\n\n```text\nUser.create({ bankId: 1 })\n```\n\n```text\n{\n  socialMedia: [{\n    socialId: 1, //should reference existing social media\n    userSocialMedia: {\n      name: 'foo' //should create new \"through\" entry\n    }\n  }],\n  bankId: 1 //should reference existing bank\n}\n```\n\n========================================\n\nComments:\n- This issue on github lead me to this solution: github.com/sequelize/sequelize/issues/5583","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":60,"estimatedTokens":328}}482{"id":"stack-47367586","source":"stackoverflow","questionId":47367586,"title":"How to insert a row with association through sequelize queryInterface","tags":["node.js","postgresql","sequelize.js","sequelize-cli"],"text":"Title: How to insert a row with association through sequelize queryInterface\nTags: node.js, postgresql, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize cli with sequelize to generate a seeder file for a many to many join table\n\nHere I have Users and Collections and User_Collections as the join table\nI have already created seeder files for Users and Collections but I want to create a seeder file for the join table . How do I dynamically access the id of the row in User or Collection so that I can insert that value in the join table bulkinsert\n\nUsers:\n\n`module.exports = {\n up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Users', [ {\n first_name: 'John',\n last_name: 'Doe',\n email: 'john.doe@gmail.com',\n password: 'testme',\n createdAt: new Date(),\n updatedAt: new Date(),\n }], {}),\n down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Users', null, {}),\n };`\n\nCollection\n\n`module.exports = {\n up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Collections', [{\n collection_name: 'Test Collection1',\n createdAt: new Date(),\n updatedAt: new Date(),\n }, {\n collection_name: 'Test Collection2',\n createdAt: new Date(),\n updatedAt: new Date(),\n }, {\n collection_name: 'Test Collection3',\n createdAt: new Date(),\n updatedAt: new Date(),\n }]),\n\n down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Collections', null, {}),\n };`\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n      up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Users', [ {\n        first_name: 'John',\n        last_name: 'Doe',\n        email: 'john.doe@gmail.com',\n        password: 'testme',\n        createdAt: new Date(),\n        updatedAt: new Date(),\n      }], {}),\n      down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Users', null, {}),\n    };\n```\n\n```text\nmodule.exports = {\n      up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Collections', [{\n        collection_name: 'Test Collection1',\n        createdAt: new Date(),\n        updatedAt: new Date(),\n      }, {\n        collection_name: 'Test Collection2',\n        createdAt: new Date(),\n        updatedAt: new Date(),\n      }, {\n        collection_name: 'Test Collection3',\n        createdAt: new Date(),\n        updatedAt: new Date(),\n      }]),\n\n      down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Collections', null, {}),\n    };\n```\n\n```text\n'use strict';\nvar Promise = require(\"bluebird\");\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    var sequelize = queryInterface.sequelize;\n    return Promise.all([\n    sequelize.query('SELECT id FROM users', { type: sequelize.QueryTypes.SELECT}),\n    sequelize.query('SELECT id FROM collections', { type: sequelize.QueryTypes.SELECT}),\n    ]).spread((userids, collectionsids)=>{\n      var user_collections = [];\n      userids.forEach(userId=> {\n        collectionsids.forEach(collectionId =>{\n              user_collections.push({\n                user_id: userId.id,\n                collection_id: collectionId.id,\n                createdAt: new Date(),\n                updatedAt: new Date(),\n              })\n        });\n      });\n      return queryInterface.bulkInsert('User_Collections', user_collections, {});\n    })\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.bulkDelete('User_Collections', null, {});\n  }\n};\n```\n\n```text\nqueryInterface.sequelize\n```\n\n```text\nsequelize\n```\n\n```text\nid\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.380Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":123,"estimatedTokens":871}}483{"id":"stack-42121521","source":"stackoverflow","questionId":42121521,"title":"Sequelize model case insensitive","tags":["postgresql","sequelize.js","amazon-redshift"],"text":"Title: Sequelize model case insensitive\nTags: postgresql, sequelize.js, amazon-redshift\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize to make query in Redshift.\n\nHowever Redshift is case-insensitive for Table Column Names, so all table names are lowercase.\nAnd sequelize model isnt case-insensitive. So when I do a query findById, it execute this query:\n\n```\nSELECT \"id\", \"userId\", \"summonerId\", \"name\", \"profileIconId\", \"summonerLevel\", \"revisionDate\", \"createdAt\", \"updatedAt\" FROM \"Lol\" AS \"Lol\" WHERE \"Lol\".\"id\" = '463d118c-2139-4679-8cdb-d07249bd7777222';\n```\n\nIt works if I execute the query inside Redshift, but sequelize just bring me back id and name column names, because only that have the name lowercase in model.\n\nSo how I can make sequelize case-insensitive? I tried the `field` option, but doesnt work.\n\nSo my model is: \n\n```\nlol = sequelize.define('Lol', {\n id: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n field: 'id'\n },\n userId: {\n type: Sequelize.STRING,\n allowNull: false,\n field: 'userid'\n },\n summonerId: {\n type: Sequelize.INTEGER,\n allowNull: false,\n field: 'summonerid'\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false,\n field: 'name'\n },\n profileIconId: {\n type: Sequelize.INTEGER,\n allowNull: false,\n field: 'profileiconid'\n },\n summonerLevel: {\n type: Sequelize.INTEGER,\n allowNull: false,\n field: 'summonerlevel'\n },\n revisionDate: {\n type: Sequelize.BIGINT,\n allowNull: false,\n field: 'revisiondate'\n },\n createdAt: {\n type: Sequelize.DATE,\n allowNull: false,\n field: 'createdat'\n },\n updatedAt: {\n type: Sequelize.DATE,\n allowNull: false,\n field: 'updatedat'\n }\n }, {\n freezeTableName: true,\n tableName: 'Lol'\n })\n```\n\n========================================\n\nCode:\n```text\nSELECT \"id\", \"userId\", \"summonerId\", \"name\", \"profileIconId\", \"summonerLevel\", \"revisionDate\", \"createdAt\", \"updatedAt\" FROM \"Lol\" AS \"Lol\" WHERE \"Lol\".\"id\" = '463d118c-2139-4679-8cdb-d07249bd7777222';\n```\n\n```text\nlol = sequelize.define('Lol', {\n                id: {\n                    type: Sequelize.STRING,\n                    allowNull: false,\n                    unique: true,\n                    primaryKey: true,\n                    field: 'id'\n                },\n                userId: {\n                    type: Sequelize.STRING,\n                    allowNull: false,\n                    field: 'userid'\n                },\n                summonerId: {\n                    type: Sequelize.INTEGER,\n                    allowNull: false,\n                    field: 'summonerid'\n                },\n                name: {\n                    type: Sequelize.STRING,\n                    allowNull: false,\n                    field: 'name'\n                },\n                profileIconId: {\n                    type: Sequelize.INTEGER,\n                    allowNull: false,\n                    field: 'profileiconid'\n                },\n                summonerLevel: {\n                    type: Sequelize.INTEGER,\n                    allowNull: false,\n                    field: 'summonerlevel'\n                },\n                revisionDate: {\n                    type: Sequelize.BIGINT,\n                    allowNull: false,\n                    field: 'revisiondate'\n                },\n                createdAt: {\n                    type: Sequelize.DATE,\n                    allowNull: false,\n                    field: 'createdat'\n                },\n                updatedAt: {\n                    type: Sequelize.DATE,\n                    allowNull: false,\n                    field: 'updatedat'\n                }\n            }, {\n                freezeTableName: true,\n                tableName: 'Lol'\n            })\n```\n\n```text\nfield\n```\n\n```text\nvar Sequelize = require('sequelize');\nSequelize.HSTORE.types.postgres.oids.push('dummy'); // avoid auto-detection and typarray/pg_type error\nAWS.config.update({accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey', region: \"xxxxxx\"});\nvar sequelize = new Sequelize('database', 'username', 'password', {\n    host: 'hostname',\n    dialect: 'postgres',\n    port: '5439',\n    pool: {\n        max: 10,\n        min: 0,\n        idle: 20000\n    },\n    returning: false, // cause sql error\n    quoteIdentifiers: false, // set case-insensitive\n    keepDefaultTimezone: true, // avoid SET TIMEZONE\n    databaseVersion: '8.0.2' // avoid SHOW SERVER_VERSION\n\n});\n```\n\n========================================\n\nComments:\n- Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!\n- can i do {quoteIdentifiers: false} for particular model.","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":167,"estimatedTokens":1174}}484{"id":"stack-32808702","source":"stackoverflow","questionId":32808702,"title":"Do I need to validate, sanitise or escape data when using the build method in sequelize.js","tags":["javascript","node.js","security","express","sequelize.js"],"text":"Title: Do I need to validate, sanitise or escape data when using the build method in sequelize.js\nTags: javascript, node.js, security, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a node / express / sequelize app. I am using the build method in sequelize to create an instances of my foo model.\n\nFoo Controller\n\n```\nexports.create = function(req, res) {\n var foo = db.Foo.build(req.body);\n foo.save().then(function(){\n // do stuff\n });\n }\n```\n\nFoo Model\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\nvar Foo = sequelize.define('Foo', \n{\n bar: DataTypes.STRING,\n baz: DataTypes.STRING\n}\n```\n\nDoes the build method check that the data I am saving is clean or do I need to take some extra precautions here?\n\n========================================\n\nCode:\n```text\nexports.create = function(req, res) {\n     var foo = db.Foo.build(req.body);\n     foo.save().then(function(){\n         // do stuff\n     });\n }\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\nvar Foo = sequelize.define('Foo', \n{\n  bar: DataTypes.STRING,\n  baz: DataTypes.STRING\n}\n```\n\n========================================\n\nComments:\n- Data only needs \"cleaning\" (\"escaping\" is a better word) if it has special meaning to the underlying technology. In this case, the database is queried with the same code syntax as the utilising language, unlike SQL that takes a string parameter as a query - therefore your data does not need escaping before usage.\n- You mention that you set the validation in sequelize models. How do you do that? Could you provide a link or example? Thanks in advance.","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":59,"estimatedTokens":399}}485{"id":"stack-37141059","source":"stackoverflow","questionId":37141059,"title":"Sequelize-CLI Seeders - Cannot read property of undefined","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: Sequelize-CLI Seeders - Cannot read property of undefined\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI have been struggling with the `db:seed:all` for over an hour now and slowly I am losing my mind about this.\n\nI have a simple model:\n\n```\n'use strict';\nmodule.exports = function (sequelize, DataTypes) {\n var Car = sequelize.define('Cars', {\n name: DataTypes.STRING,\n type: DataTypes.INTEGER,\n models: DataTypes.INTEGER\n }, {\n classMethods: {\n associate: function (models) {\n // associations can be defined here\n }\n }\n });\n return Car;\n};\n```\n\nthis is in a migration and goes to the database using `sequelize db:migrate` which works fine.\n\nNext I wanted to insert - through a seed file - 2 cars.\nSo I ran the command `sequelize seed:create --name insertCars`\nand added the `bulkInsert`:\n\n```\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert(\n 'Cars',\n [\n {\n name: \"Auris\",\n type: 1,\n models: 500,\n createdAt: Date.now(), updatedAt: Date.now()\n },\n {\n name: \"Yaris\",\n type: 1,\n models: 500,\n createdAt: Date.now(), updatedAt: Date.now()\n }\n ]\n );\n },\n\n down: function (queryInterface, Sequelize) {\n }\n};\n```\n\nNow when I run `sequelize db:seed:all` I get following error:\n\n```\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\n== 20160510132128-insertCars: migrating =======\nSeed file failed with error: Cannot read property 'name' of undefined\n```\n\nHas anyone got any experience with running these seeders?\nFor your information here is my config file:\n\n```\n{\n \"development\": {\n \"username\": \"mydbdude\",\n \"password\": \"mydbdude\",\n \"database\": \"Cars\",\n \"host\": \"127.0.0.1\",\n \"dialect\": \"mssql\",\n \"development\": {\n \"autoMigrateOldSchema\": true\n }\n },\n ....other configs\n}\n```\n\n**EDIT: Output from db:migrate**\n\n```\nSequelize [Node: 5.9.1, CLI: 2.4.0, ORM: 3.23.0]\n\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\nNo migrations were executed, database schema was already up to date.\n```\n\n========================================\n\nTop Answer:\nI had same issue the problem was that I added extra commas in between objects check for any syntax error that might work\n\n```\ndataSources: [\n {\n name: 'Pattern'\n },\n ,// this comma was added by mistake for me\n {\n name: 'Upload'\n }\n ]\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = function (sequelize, DataTypes) {\n  var Car = sequelize.define('Cars', {\n    name: DataTypes.STRING,\n    type: DataTypes.INTEGER,\n    models: DataTypes.INTEGER\n  }, {\n      classMethods: {\n        associate: function (models) {\n          // associations can be defined here\n        }\n      }\n    });\n  return Car;\n};\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.bulkInsert(\n      'Cars',\n      [\n        {\n          name: \"Auris\",\n          type: 1,\n          models: 500,\n          createdAt: Date.now(), updatedAt: Date.now()\n        },\n        {\n          name: \"Yaris\",\n          type: 1,\n          models: 500,\n          createdAt: Date.now(), updatedAt: Date.now()\n        }\n      ]\n    );\n  },\n\n  down: function (queryInterface, Sequelize) {\n  }\n};\n```\n\n```text\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\n== 20160510132128-insertCars: migrating =======\nSeed file failed with error: Cannot read property 'name' of undefined\n```\n\n```text\n{\n  \"development\": {\n    \"username\": \"mydbdude\",\n    \"password\": \"mydbdude\",\n    \"database\": \"Cars\",\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mssql\",\n    \"development\": {\n      \"autoMigrateOldSchema\": true\n    }\n  },\n  ....other configs\n}\n```\n\n```text\nSequelize [Node: 5.9.1, CLI: 2.4.0, ORM: 3.23.0]\n\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\nNo migrations were executed, database schema was already up to date.\n```\n\n```text\ndb:seed:all\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nsequelize seed:create --name insertCars\n```\n\n```text\nbulkInsert\n```\n\n```text\nsequelize db:seed:all\n```\n\n```text\ndataSources: [\n    {\n        name: 'Pattern'\n    },\n    {\n        name: 'Upload'\n    }\n]\n```\n\n```text\nvar models = require('./../models'),\nsql = models.sequelize,\nPromise = models.Sequelize.Promise;\n\nvar objects = require('./seed/objects'), //this is where my object file is\ndataSources = objects.dataSources;\n\n\nvar express = require('express');\n\nvar seedDatabase = function () {\n    var promises = [];\n    promises.push(createDataSources());\n    //more can be added to the promises\n\n    return Promise.all(promises);\n};\n\nfunction createDataSources() {\n    return models.sequelize\n        .transaction(\n            {\n                isolationLevel: models.sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED\n            },\n            function (t) {\n                return models.DataSource\n                    .findAll({\n                        attributes: [\n                            'id'\n                        ]\n                    })\n                    .then(function (result) {\n                        if (!result || result.length == 0) {\n                            return models.DataSource\n                                .bulkCreate(dataSources, { transaction: t })\n                                .then(function () {\n                                    console.log(\"DataSources created\");\n                                })\n                        }\n                        else {\n                            console.log(\"DataSources seeder skipped, already objects in the database...\");\n                            return;\n                        }\n                    });\n            })\n        .then(function (result) {\n            console.log(\"DataSources seeder finished...\");\n            return;\n        })\n        .catch(function (error) {\n            console.log(\"DataSources seeder exited with error: \" + error.message);\n            return;\n        });\n};\n\nmodule.exports = {\n    seedDatabase: seedDatabase\n}\n```\n\n```text\n//includes and routes above, not interesting for this answer\ntry {\n    umzug.up().then(function (migrations) {\n        for (var i = 0; i < migrations.length; i++) {\n            console.log(\"Migration executed: \" + migrations[i].file);\n        }\n\n        console.log(\"Running seeder\");\n        seeder.seedDatabase().then(function () { //here I run my seeders\n            app.listen(app.get('port'), function () {\n                console.log('Express server listening on port ' + app.get('port'));\n            });\n        });\n    });\n}\ncatch (e) {\n    console.error(e);\n}\n```\n\n```text\nseeder.js\n```\n\n```text\nseedDatabase\n```\n\n```text\ndataSources: [\n    {\n        name: 'Pattern'\n    },\n    ,// this comma was added by mistake for me\n    {\n        name: 'Upload'\n    }\n ]\n```\n\n```js\nqueryInterface.bulkInsert(\n  \"table_name\",\n  mapDataAndAddCreatedAndUpdatedAtField(array_of_db_entries),\n  {\n    transaction,\n    ignoreDuplicates: false,\n    updateOnDuplicate: [\"col1\", \"col2\", ..., \"coln\"],\n    upsertKeys: [\"unique_col1\", ..., \"unique_coln\"],\n  }\n);\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\nbulkInsert\n```\n\n========================================\n\nComments:\n- Hi, can you show the terminal output of `sequelize db:migrate`?\n- @paolord I editted my original question and added the output from db:migrate at the bottom\n- what DB dialect are you using? I've had issues with Postgres and case sensitive names (ie. `Cars` vs. the `cars` table postgres creates)\n- Mssql, normally that should nog be case sensitive right? and even if, I have my model and table cased the same `Cars`","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":359,"estimatedTokens":1912}}486{"id":"stack-56920376","source":"stackoverflow","questionId":56920376,"title":"using replacements with sequelize.literal()","tags":["mysql","sql","node.js","express","sequelize.js"],"text":"Title: using replacements with sequelize.literal()\nTags: mysql, sql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use replacements with sequelize.literal() query.\n\n```\nrouter.get('/posts/testapik', function(req, res)\n{\n\n const user_id = req.session.user_id;\n\n const status =\"accept\"\n Posts.findAll({include:[{ model: Likes},{ model: Comments},{ model: Users}],\n where:{user_id:{[Op.in]:[sequelize.literal('SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=? and `Follows`.status=?',{ replacements: [user_id,status], type: sequelize.QueryTypes.SELECT })]}}\n\n })\n .then(users => \n {\n\n res.send(users);\n })\n\n});\n```\n\nBut it returns following error\n\n```\noriginal:\n { Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? and `Follows`.status=?)' at line 1\n```\n\n========================================\n\nTop Answer:\nFor replacements, you have to set the replacements property inside the query object.\n\n```\nrouter.get(\"/posts/testapik\", function (req, res) {\n const user_id = req.session.user_id;\n const status = \"accept\";\n\n Posts.findAll({\n include: [{ model: Likes }, { model: Comments }, { model: Users }],\n replacements: [user_id, status],\n where: {\n user_id: {\n [Op.in]: [\n sequelize.literal(\n \"SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=? and `Follows`.status=?\"\n ),\n ],\n },\n },\n }).then((users) => {\n res.send(users);\n });\n});\n```\n\n========================================\n\nCode:\n```text\nrouter.get('/posts/testapik', function(req, res)\n{\n\n    const user_id = req.session.user_id;\n\n    const status =\"accept\"\n  Posts.findAll({include:[{ model: Likes},{ model: Comments},{ model: Users}],\n                where:{user_id:{[Op.in]:[sequelize.literal('SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=? and `Follows`.status=?',{ replacements: [user_id,status], type: sequelize.QueryTypes.SELECT })]}}\n\n                })\n  .then(users => \n    {\n\n        res.send(users);\n  })\n\n});\n```\n\n```text\noriginal:\n   { Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? and `Follows`.status=?)' at line 1\n```\n\n```text\nrouter.get('/posts/testapik', function(req, res)\n{\n\n    const user_id = req.session.user_id;\n\n    const status =\"accept\"\n  Posts.findAll({include:[{ model: Likes},{ model: Comments},{ model: Users}],\n                where:{user_id:{[Op.in]:[sequelize.literal('(SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id='+user_id+' and `Follows`.status=\"accept\")')]}}\n\n                })\n  .then(users => \n    {\n        console.log(\"Posts data Testing =>\",users);\n        res.send(users);\n  })\n    .catch((err)=>\n    {\n        console.error(err)\n        res.status(501)\n        .send({\n                error : \"error..... check console log\"\n              })\n    })\n\n\n});\n```\n\n```text\nconst query = '(SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id= :userIdReplacement and `Follows`.status=\"accept\")';\n\ndb.sequelize.query(query, { replacements: { userIdReplacement : user_id }});\n```\n\n```text\n:userIdReplacement\n```\n\n```js\nrouter.get(\"/posts/testapik\", function (req, res) {\n  const user_id = req.session.user_id;\n  const status = \"accept\";\n\n  Posts.findAll({\n    include: [{ model: Likes }, { model: Comments }, { model: Users }],\n    replacements: [user_id, status],\n    where: {\n      user_id: {\n        [Op.in]: [\n          sequelize.literal(\n            \"SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=? and `Follows`.status=?\"\n          ),\n        ],\n      },\n    },\n  }).then((users) => {\n    res.send(users);\n  });\n});\n```\n\n========================================\n\nComments:\n- This can be dangerous because user_id is unprotected and can lead to SQL injections.","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":156,"estimatedTokens":997}}487{"id":"stack-42286611","source":"stackoverflow","questionId":42286611,"title":"How to handle Persistence with Rich Domain Model","tags":["node.js","architecture","domain-driven-design","sequelize.js","rich-domain-model"],"text":"Title: How to handle Persistence with Rich Domain Model\nTags: node.js, architecture, domain-driven-design, sequelize.js, rich-domain-model\nSource: Stack Overflow\n\nQuestion:\nI am redesigning my NodeJS application because I want to use the Rich Domain Model concept. Currently I am using Anemic Domain Model and this is not scaling well, I just see 'ifs' everywhere.\n\nI have read a bunch of blog posts and DDD related blogs, but there is something that I simply cannot understand... How do we handle Persistence properly.\n\nTo start, I would like to describe the layers that I have defined and their purpose:\n\nPersistence Model\n\n- Defines the Table Models. Defines the Table name, Columns, Keys and Relations\n\n- I am using Sequelize as ORM, so the Models defined with Sequelize are considered my Persistence Model\n\nDomain Model\n\n- Entities and Behaviors. Objects that correspond to the abstractions created as part of the Business Domain\n\n- I have created several classes and the best thing here is that I can benefit from hierarchy to solve all problems (without loads of ifs yay).\n\nData Access Object (DAO)\n\n- Responsible for the Data management and conversion of entries of the Persistence Model to entities of the Domain Model. All persistence related activities belong to this layer\n\n- In my case DAOs work on top of the Sequelize models created on the Persistence Model, however, I am serializing the records returned on Database Interactions in different objects based on their properties. Eg.: If I have a Table with a column called 'UserType' that contains two values [ADMIN,USER], when I select entries on this table, I would serialize the return according to the User Type, so a User with Type: ADMIN would be an instance of the AdminUser class where a User with type: USER would simply be a DefaultUser...\n\nService Layer\n\n- Responsible for all Generic Business Logic, such as Utilities and other Services that are not part of the behavior of any of the Domain Objects\n\nClient Layer\n\n- Any Consumer class that plays around with the Objects and is responsible in triggering the Persistence\n\nNow the confusion starts when I implement the Client Layer...\n\nLet's say I am implementing a new REST API:\n\n```\nPOST: .../api/CreateOrderForUser/\n{\n items: [{\n productId: 1,\n quantity: 4\n },{\n productId: 3,\n quantity: 2\n }]\n}\n```\n\nOn my handler function I would have something like:\n\n```\nfunction(oReq){\n var oRequestBody = oReq.body;\n var oCurrentUser = oReq.user; //This is already a Domain Object\n var aOrderItems = oRequestBody.map(function(mOrderData){\n return new OrderItem(mOrderData); //Constructor sets the properties internally\n });\n var oOrder = new Order({\n items: aOrderItems\n });\n\n oCurrentUser.addOrder(oOrder);\n\n // So far so good... But how do I persist whatever \n // happened above? Should I call each DAO for each entity \n // created? Like, first create the Order, then create the \n // Items, then update the User?\n\n}\n```\n\nOne way I found to make it work is to merge the Persistence Model and the Domain Model, which means that `oCurrentUser.addOrder(...)` would execute the business logic required and would call the OrderDAO to persist the Order along with the Items in the end. The bad thing about this is that now the `addOrder` also have to handle transactions, because I don't want to add the order without the items, or update the User without the Order.\n\nSo, what I am missing here?\n\n========================================\n\nCode:\n```text\nPOST: .../api/CreateOrderForUser/\n{\n  items: [{\n    productId: 1,\n    quantity: 4\n  },{\n    productId: 3,\n    quantity: 2\n  }]\n}\n```\n\n```text\nfunction(oReq){\n  var oRequestBody = oReq.body;\n  var oCurrentUser = oReq.user; //This is already a Domain Object\n  var aOrderItems = oRequestBody.map(function(mOrderData){\n    return new OrderItem(mOrderData); //Constructor sets the properties internally\n  });\n  var oOrder = new Order({\n    items: aOrderItems\n  });\n\n  oCurrentUser.addOrder(oOrder);\n\n  // So far so good... But how do I persist whatever \n  // happened above? Should I call each DAO for each entity \n  // created? Like, first create the Order, then create the \n  // Items, then update the User?\n\n}\n```\n\n```text\noCurrentUser.addOrder(...)\n```\n\n```text\naddOrder\n```\n\n```text\norderRepository.save(oOrder);\n```\n\n```text\noCurrentUser.addOrder(oOrder);\n```\n\n========================================\n\nComments:\n- You probably need to read up more about Repositories, Aggregates, Aggregate Roots and Application Services if you want to go full DDD. Also have a look at the concept of Unit of Work. And I'm afraid you have to dig into non-Node code samples if you need concrete examples of how an Application Service is typically implemented.","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":138,"estimatedTokens":1177}}488{"id":"stack-38224709","source":"stackoverflow","questionId":38224709,"title":"Sequelize group by with association includes id","tags":["group-by","sequelize.js"],"text":"Title: Sequelize group by with association includes id\nTags: group-by, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo when requesting a group by from sequelize as follows:\n\n```\nreturn models.WorkingCalendar\n .findAll({\n attributes: [\n 'WorkingCalendar.PeriodId',\n 'WorkingCalendar.date',\n 'Period.name'\n ],\n include: [\n {\n model: models.Period,\n attributes: []\n }\n ],\n where: {\n GetSudoId: currentGetsudo.id,\n UnitPlantId: unitPlantId\n },\n group: ['WorkingCalendar.PeriodId',\n 'WorkingCalendar.date',\n 'Period.name'],\n });\n```\n\nSequelize will run this query:\n\n```\nSELECT \n[WorkingCalendar].[id],\n[WorkingCalendar].[PeriodId], \n[WorkingCalendar].[date], \n[Period].[name] \nFROM [WorkingCalendars] AS [WorkingCalendar] \nLEFT OUTER JOIN [Periods] AS [Period] ON [WorkingCalendar].[PeriodId] = [Period].[id] \nWHERE [WorkingCalendar].[GetSudoId] = 1 AND [WorkingCalendar].[UnitPlantId] = N'1' \nGROUP BY [WorkingCalendar].[PeriodId], [WorkingCalendar].[date], [Period].[name];\n```\n\nYet I never asked for the `WorkingCalender.id` and I cannot seem to get rid of that.\nHow do I make sure sequelize is not getting me this `id` from the `workingCalendar`?\n\nI've already found that for associations the attributes should be an empty array and that works but not for the main object since I need only 3 columns.\n\n========================================\n\nTop Answer:\nJust pass `raw` flag to sequelize and it stops adding id field to attributes at least with sequelize 6:\n\n```\nconst groups = ['WorkingCalendar.PeriodId', 'WorkingCalendar.date', 'Period.name']\n\nreturn models.WorkingCalendar.findAll({\n attributes: groups,\n where: { GetSudoId: currentGetsudo.id, UnitPlantId: unitPlantId },\n include: [{ model: models.Period, attributes: [] }],\n group,\n raw: true,\n})\n```\n\n========================================\n\nCode:\n```text\nreturn models.WorkingCalendar\n            .findAll({\n                attributes: [\n                    'WorkingCalendar.PeriodId',\n                    'WorkingCalendar.date',\n                    'Period.name'\n                ],\n                include: [\n                    {\n                        model: models.Period,\n                        attributes: []\n                    }\n                ],\n                where: {\n                    GetSudoId: currentGetsudo.id,\n                    UnitPlantId: unitPlantId\n                },\n                group: ['WorkingCalendar.PeriodId',\n                    'WorkingCalendar.date',\n                    'Period.name'],\n            });\n```\n\n```text\nSELECT \n[WorkingCalendar].[id],\n[WorkingCalendar].[PeriodId], \n[WorkingCalendar].[date], \n[Period].[name] \nFROM [WorkingCalendars] AS [WorkingCalendar] \nLEFT OUTER JOIN [Periods] AS [Period] ON [WorkingCalendar].[PeriodId] = [Period].[id] \nWHERE [WorkingCalendar].[GetSudoId] = 1 AND [WorkingCalendar].[UnitPlantId] = N'1' \nGROUP BY [WorkingCalendar].[PeriodId], [WorkingCalendar].[date], [Period].[name];\n```\n\n```text\nWorkingCalender.id\n```\n\n```text\nid\n```\n\n```text\nworkingCalendar\n```\n\n```text\nreturn models.sequelize.query(\n    `SELECT \n    [WorkingCalendar].[id],\n    [WorkingCalendar].[PeriodId], \n    [WorkingCalendar].[date], \n    [Period].[name] \n    FROM [WorkingCalendars] AS [WorkingCalendar] \n    LEFT OUTER JOIN [Periods] AS [Period] ON [WorkingCalendar].[PeriodId] = [Period].[id] \n    WHERE [WorkingCalendar].[GetSudoId] = :getsudoId AND [WorkingCalendar].[UnitPlantId] = N'1' \n    GROUP BY [WorkingCalendar].[PeriodId], [WorkingCalendar].[date], [Period].[name]`,\n    {\n        replacements: { getsudoId: getsudoId },\n        type: models.Sequelize.QueryTypes.SELECT\n    }\n)\n```\n\n```text\nconst groups = ['WorkingCalendar.PeriodId', 'WorkingCalendar.date', 'Period.name']\n\nreturn models.WorkingCalendar.findAll({\n  attributes: groups,\n  where: { GetSudoId: currentGetsudo.id, UnitPlantId: unitPlantId },\n  include: [{ model: models.Period, attributes: [] }],\n  group,\n  raw: true,\n})\n```\n\n```text\nraw\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":151,"estimatedTokens":985}}489{"id":"stack-53822370","source":"stackoverflow","questionId":53822370,"title":"Sequelize: How to insert data into newly created table after sync","tags":["javascript","sequelize.js"],"text":"Title: Sequelize: How to insert data into newly created table after sync\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI basically want default settings populated in a table for my server to use on initial boot, or if the table were to be deleted. \n\nHow can I populate a table in sequelize after the sync method runs and only add the data once?\n\n========================================\n\nComments:\n- Do you mean after migrations?\n- @Moa OP is last active a year ago; so, I think you can try to give a generic answer with both case1. after migration / case2. no migration.","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":14,"estimatedTokens":148}}490{"id":"stack-43419514","source":"stackoverflow","questionId":43419514,"title":"Sequelize Join Models Include many to many","tags":["node.js","sequelize.js"],"text":"Title: Sequelize Join Models Include many to many\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSay I have three models like this\n\n```\nvar User = _define('user', {\n username: Sequelize.INTEGER\n});\nvar UserPubCrawl = _define('userpubcrawl', {\n user_id: Sequelize.STRING(64), // the user\n bar_id: Sequelize.INTEGER // 1 to many\n});\n\nvar Bars = _define('bar', {\n name: type: Sequelize.STRING,\n}\n```\n\nThe relationships are one meal\n\nUser(one) --> UserPubCrawl (to many) --> Bars(to many)\n\nSo 1 user can have multiple pubcrawls to many bars for a particular pub crawl \nI want to find all the bars that \"Simpson\" went to.\n\nDo i need to change the model definitions, if so please show me?\nWhat would the findAll Query look like?\n\n========================================\n\nCode:\n```text\nvar User = _define('user', {\n  username: Sequelize.INTEGER\n});\nvar UserPubCrawl = _define('userpubcrawl', {\n  user_id: Sequelize.STRING(64), // the user\n  bar_id: Sequelize.INTEGER // 1 to many\n});\n\nvar Bars = _define('bar', {\n  name:  type: Sequelize.STRING,\n}\n```\n\n```text\nUser.belongsToMany(Bar, { through: UserPubCrawl });\nBar.belongsToMany(User, { through: UserPubCrawl });\n```\n\n```text\nUser.findAll({\n  where: { user_id: '123' },\n  include: {\n    model: Bars,\n    through: { attributes: [] } // this will remove the rows from the join table (i.e. 'UserPubCrawl table') in the result set\n  }\n});\n```\n\n========================================\n\nComments:\n- Fantastic. This was exactly what I needed. Thank you @Adhyatmik\n- What if you want to find all of the users that visited bars X and Y?\n- @FelaMaslen User.findAll({ where: { user_id: '123' }, include: { model: Bars, where: {bar: X}, through: { attributes: [] } } });","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":69,"estimatedTokens":430}}491{"id":"stack-47367893","source":"stackoverflow","questionId":47367893,"title":"Sequelize reads datetime in UTC only","tags":["mysql","datetime","timezone","sequelize.js","utc"],"text":"Title: Sequelize reads datetime in UTC only\nTags: mysql, datetime, timezone, sequelize.js, utc\nSource: Stack Overflow\n\nQuestion:\nI have set the `timezone` option to my timezone (`Europe/Zagreb` and I've tried with `+02:00` too), and the time is saved as it should be, however, when reading the time from the database, Sequelize converts it to UTC. I have tried different timezones too, each is saved correctly, but always converted to UTC when read from database.\n\nAm I doing something wrong or is this a known issue and are there any workarounds?\n\nI create a new connection with:\n\n```\nsequelize = new Sequelize(config.database, config.username, config.password, config);\n```\n\nand my configuration looks something like this:\n\n```\n\"development\": {\n \"username\": \"root\",\n \"password\": \"root\",\n \"database\": \"db\",\n \"host\": \"localhost\",\n \"dialect\": \"mysql\",\n \"timezone\": \"Europe/Zagreb\"\n}\n```\n\n========================================\n\nTop Answer:\nMaybe timezone is not needed if you use UTC.\n\nFor example, my mysql server is timezone '+08:00',\n\n\"mysql2\": \"^1.6.4\",\n\"sequelize\": \"^4.41.2\"\n\n```\nconst sequelize = new Sequelize(database, username, password, {\n host: hostname,\n port: port,\n dialect: 'mysql',\n dialectOptions: {\n typeCast: function (field, next) {\n if (field.type == 'DATETIME' || field.type == 'TIMESTAMP') {\n return new Date(field.string() + 'Z');\n }\n return next();\n }\n },\n operatorsAliases: false,\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000\n }\n});\n```\n\n========================================\n\nCode:\n```text\nsequelize = new Sequelize(config.database, config.username, config.password, config);\n```\n\n```text\n\"development\": {\n    \"username\": \"root\",\n    \"password\": \"root\",\n    \"database\": \"db\",\n    \"host\": \"localhost\",\n    \"dialect\": \"mysql\",\n    \"timezone\": \"Europe/Zagreb\"\n}\n```\n\n```text\ntimezone\n```\n\n```text\nEurope/Zagreb\n```\n\n```text\n+02:00\n```\n\n```js\nconst sequelize = new Sequelize(mysql.database, mysql.user, mysql.password, {\n    host: mysql.host,\n    port:3306,\n    dialect:'mysql',\n    define: {\n      underscored: true,\n      freezeTableName: true, //use singular table name\n      timestamps: false,  // I do not want timestamp fields by default\n    },\n    dialectOptions: {\n      useUTC: false, //for reading from database\n      dateStrings: true,\n      typeCast: function (field, next) { // for reading from database\n        if (field.type === 'DATETIME') {\n          return field.string()\n        }\n          return next()\n        },\n    },\n    timezone: '+01:00'\n});\n```\n\n```text\nconst sequelize = new Sequelize(database, username, password, {\n    host: hostname,\n    port: port,\n    dialect: 'mysql',\n    dialectOptions: {\n        typeCast: function (field, next) {\n            if (field.type == 'DATETIME' || field.type == 'TIMESTAMP') {\n                return new Date(field.string() + 'Z');\n            }\n            return next();\n        }\n    },\n    operatorsAliases: false,\n    pool: {\n        max: 5,\n        min: 0,\n        acquire: 30000,\n        idle: 10000\n    }\n});\n```\n\n```js\nconst sequelize = new Sequelize(database, username, password, {\n  host: hostname,\n  port: port,\n  dialect: 'mysql',\n  dialectOptions: {\n    encrypt: false,\n    options: {\n      useUTC: false, // for reading from database\n    },\n  },\n  operatorsAliases: false,\n  pool: {\n    max: 5,\n    min: 0,\n    acquire: 30000,\n    idle: 10000\n  }\n});\n```\n\n```text\nvar con = mysql.createConnection({\n    host: \"localhost\",\n    port: \"3306\",\n    user: \"root\",\n    password: \"123456\",\n    insecureAuth : true,\n    database: \"devices\",\n    timezone: \".007Z\"//change utc to +7\n});\n```\n\n========================================\n\nComments:\n- Thanks, just the `typeCast` function in `dialectOptions` did the trick in my case.\n- I cannot get this method to work. Sequelize is still using UTC when inserting and reading the data. It will only work locally but not when I upload my app to my server. My server is set to use my timezone and the MySQL server is set to use the system timezone. Any thoughts as to why this will not work?\n- @user3183411 the `timezone : '+01:00' &#47;&#47; use your timezone here` is used for writing to the database, check if it is writing correct value in the dateTime field, and if it is writing correct value then just use the `typeCast` function in `dialectOptions`.\n- What if it is not writing the correct value? I've set the timezone to use timezone: '-07:00' and even America/Boise. Neither of those work.\n- @user3183411 `typecast` function just return the written value in the table as a string , so if the written value is incorrect then `typecast` function will just return that same value, it will not convert it into your timezone. So to make it work correctly you have to make sure that you are writing the correct time (as per your timezone) in the table.\n- I understand the concept, which is why I am trying to solve the problem as to why the incorrect time zone is being written to the database. It seems as though my configuration is being ignore by sequelize. At this point I'm just going to leave it as is and not use sequelize in the future.\n- @ArpitPandey Can you documentation link for `dialectOptions`. I am not able to find all options in Sequelize Usage guide\n- @M.AtifRiaz dialectOtions are part of mysql (or xyz DB), here you go github.com/mysqljs/mysql","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":182,"estimatedTokens":1330}}492{"id":"stack-26817057","source":"stackoverflow","questionId":26817057,"title":"Sequelize associations - please use promise-style instead","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize associations - please use promise-style instead\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to join 3 tables together `Products`, `Suppliers` and `Categories` and then get row with `SupplierID = 13`. I have read How to implement many to many association in sequelize, there is explained how to associate `0:M`.\n\n**DB model:**\n\n**Code:**\n\n```\nvar Sequelize = require('sequelize')\nvar sequelize = new Sequelize('northwind', 'nodejs', 'nodejs', {dialect: 'mysql',})\nvar Project = require('sequelize-import')(__dirname + '/models', sequelize, { exclude: ['index.js'] });\n\nProject.Suppliers.hasMany(Project.Products, {foreignKey: 'SupplierID'});\nProject.Products.belongsTo(Project.Suppliers, {foreignKey: 'SupplierID'});\nProject.Categories.hasMany(Project.Products, {foreignKey: 'CategoryID'});\nProject.Products.belongsTo(Project.Categories, {foreignKey: 'CategoryID'});\n\nProject.Products\n .find({\n where: {\n SupplierID: 13\n },\n include: [\n Project.Suppliers,\n Project.Category,\n ]\n })\n .success(function(qr){\n if (qr == null) throw \"Err\";\n\n console.log(\"---\");\n console.log(qr);\n })\n .error(function(err){\n console.log(\"Err\");\n });\n```\n\n**Log:**\n\n```\nEventEmitter#success|ok is deprecated, please use promise-style instead.\n EventEmitter#failure|fail|error is deprecated, please use promise-style instead.\n Err\n```\n\n========================================\n\nTop Answer:\ni had the same issue with you, you can change `.success` and `.error` with single `.done(function(err, result))` to do both operation and the warning message disappear too.\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize')\nvar sequelize = new Sequelize('northwind', 'nodejs', 'nodejs', {dialect: 'mysql',})\nvar Project = require('sequelize-import')(__dirname + '/models', sequelize, { exclude: ['index.js'] });\n\nProject.Suppliers.hasMany(Project.Products, {foreignKey: 'SupplierID'});\nProject.Products.belongsTo(Project.Suppliers, {foreignKey: 'SupplierID'});\nProject.Categories.hasMany(Project.Products, {foreignKey: 'CategoryID'});\nProject.Products.belongsTo(Project.Categories, {foreignKey: 'CategoryID'});\n\nProject.Products\n    .find({\n        where: {\n            SupplierID: 13\n        },\n        include: [\n            Project.Suppliers,\n            Project.Category,\n        ]\n    })\n    .success(function(qr){\n        if (qr == null) throw \"Err\";\n\n        console.log(\"---\");\n        console.log(qr);\n    })\n    .error(function(err){\n        console.log(\"Err\");\n    });\n```\n\n```text\nEventEmitter#success|ok is deprecated, please use promise-style instead.\n    EventEmitter#failure|fail|error is deprecated, please use promise-style instead.\n    Err\n```\n\n```text\nProducts\n```\n\n```text\nSuppliers\n```\n\n```text\nCategories\n```\n\n```text\nSupplierID = 13\n```\n\n```text\n0:M\n```\n\n```text\ndb.Model.find(something)\n  .then(function(results) {\n      //do something with results\n      //you can also take the results to make another query and return the promise.\n      return db.anotherModel.find(results[0].anotherModelId);          \n  }).then(function(results) {\n      //do something else\n  }).catch(function(err) {\n      console.log(err);\n  }).finally(function() {\n        // finally gets called always regardless of \n        // whether the promises resolved with or without errors.\n        // however this finally handler does not receive any arguments.\n  });\n```\n\n```text\n.finally()\n```\n\n```text\n.then()\n```\n\n```text\n.success\n```\n\n```text\n.error\n```\n\n```text\n.done\n```\n\n```text\n.then\n```\n\n```text\n.success\n```\n\n```text\n.catch\n```\n\n```text\n.error\n```\n\n```text\n.finally\n```\n\n```text\n.done\n```\n\n```text\n.finally\n```\n\n```text\n.success\n```\n\n```text\n.error\n```\n\n```text\n.done(function(err, result))\n```\n\n========================================\n\nComments:\n- `done` is also deprecated\n- Also this is a classic promise anti-pattern: github.com/petkaantonov/bluebird/wiki/&hellip;\n- Actually, `finally` would be a better replacement for `done`, since it is called regardless of the success or not. But it does not have access to neither err nor the result\n- That looks cool, but I am using Eclipse(nodeclipse) and it displays me compilation error when using .catch (The error says: \"Syntax error on token \"catch\", Identifier expected\"). How to avoid this error?\n- most probably some code error like missing quotations or brackets.\n- Actually syntax is not problem, for example, this code causes error: doSomethingAsync().then().catch()","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":201,"estimatedTokens":1125}}493{"id":"stack-53612103","source":"stackoverflow","questionId":53612103,"title":"How to get simple array in sequelize findAll()?","tags":["javascript","async-await","sequelize.js"],"text":"Title: How to get simple array in sequelize findAll()?\nTags: javascript, async-await, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get all rows with specific ID in `async/await` style using `sequelize`. My code looks like:\n\n**UPDATED:**\n\n```\nrouter.get('/', errorHandler(async (req, res, next) => {\n\n let domainsDB = await Domain.findAll({\n where: { accID: accID },\n attributes: [`adID`, `domain`, `status`]\n })\n\n}\n```\n\nWhen I `console.log(domainsDB)` I see this:\n\n```\n[ \n domains {\n dataValues: [Object],\n _previousDataValues: [Object],\n _changed: {},\n _modelOptions: [Object],\n _options: [Object],\n __eagerlyLoadedAssociations: [],\n isNewRecord: false },\n domains {\n...\n...\n...\n]\n```\n\nThe docs says it has to be an array in return. But console log shows this is an object. The data in this object in `dataValues` is correct. There are my domains. But I expect to get an array to work with.\n\nHow to get an array in return with `async/await?` Thank you for any help.\n\n========================================\n\nTop Answer:\nawait should be wrapped in a function with async key in it.\n\nA correct code snippet would look like this: \n\n```\nasync fetchData(accID) {\n return await Domain.findAll({\n where: { accID: accID },\n attributes: [`adID`, `domain`, `status`]\n })\n}\n\nlet data = fetchData(1);\nconsole.log(data);\n```\n\nAlternative approaches are: 1) using generator functions 2) promises.\n\nThey're basically the same thing in a manner that it makes your synchronous code act as asynchronous.\n\n========================================\n\nCode:\n```text\nrouter.get('/', errorHandler(async (req, res, next) => {\n\n    let domainsDB = await Domain.findAll({\n            where: { accID: accID },\n            attributes: [`adID`, `domain`, `status`]\n    })\n\n}\n```\n\n```text\n[ \n     domains {\n       dataValues: [Object],\n       _previousDataValues: [Object],\n       _changed: {},\n       _modelOptions: [Object],\n       _options: [Object],\n       __eagerlyLoadedAssociations: [],\n       isNewRecord: false },\n     domains {\n...\n...\n...\n]\n```\n\n```text\nasync/await\n```\n\n```text\nsequelize\n```\n\n```text\nconsole.log(domainsDB)\n```\n\n```text\ndataValues\n```\n\n```text\nasync/await?\n```\n\n```text\nlet domainsDB = await Domain.findAll({\n    where: { accID: accID },\n    attributes: [`adID`, `domain`, `status`],\n    raw : true // <--- HERE\n})\n```\n\n```text\nraw : true\n```\n\n```text\nsequelize\n```\n\n```text\nraw : true\n```\n\n```text\nasync fetchData(accID) {\n  return await Domain.findAll({\n      where: { accID: accID },\n      attributes: [`adID`, `domain`, `status`]\n  })\n}\n\nlet data = fetchData(1);\nconsole.log(data);\n```\n\n========================================\n\nComments:\n- Where do you console.log ? is it immediate call after `let domainsDB`?\n- @MehiShokri Yes, it's\n- It's because you're getting the created json object. not the answer.\n- Are you sure you're not getting an array? Your return result starts with `[` and ends with `]`\n- @KhauriMcClain Yes, it's an array. I expected more convenient array I think. But now I see promise returns the same array as async/await. Probably it's the expected behavior of sequelize\n- According to the reference it returns an array of Models, not plain objects. And that's what you have. NodeJS or whatever console you're using is unpacking the `Model's` methods and fields, so maybe it's sort of deceptive looking. I believe the question has been answered already, but I'd say in general the models themselve have a lot of useful features to consider as well.\n- But I wrapped it already in `router.get()` method. See my updated code in question.\n- Alright, you were getting it inside the async function.(Didn't mention it though). probably your solution is passing `raw:true` option.\n- @Nastro , Glad to know :) , Happy Coding BTW.\n- why it will return non array when including hasmany assosiation?\n- @MuhammadDyasYaskur you may have had to use a \"nested: true\" in the options for a non-flat object\n- raw is not a good option if you use association.","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":164,"estimatedTokens":995}}494{"id":"stack-35570410","source":"stackoverflow","questionId":35570410,"title":"Issues connecting to Amazon RDS Postgres database on node.js using sequelize ORM","tags":["javascript","node.js","postgresql","amazon-web-services","sequelize.js"],"text":"Title: Issues connecting to Amazon RDS Postgres database on node.js using sequelize ORM\nTags: javascript, node.js, postgresql, amazon-web-services, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently working on migrating an environment set up in Heroku over to the Amazon Web Services stack (RDS PostgreSQL, Elastic Beanstalk).\n\nI'm facing some issues when trying to connect to PostgreSQL through the sequelize.js ORM. Error message below:\n\n Unhandled rejection SequelizeHostNotFoundError: getaddrinfo ENOTFOUND\n [host].\n\nI can connect to the database through pgAdmin so I know the service is working, and the following configuration has worked on Heroku:\n\n```\nsequelize = new Sequelize(process.env.DATABASE_URI, {\n dialect: 'postgres',\n protocol: 'postgres',\n logging: true,\n timestamps: false\n })\n```\n\nDATABASE_URI is formatted in the following way: \n\n```\npostgres://[db_username]:[db_password]@[hostname]:[port]/[db_name]\n```\n\nAny help would be greatly appreciated. Thanks in advance!\n\n========================================\n\nTop Answer:\nI had a very similar problem, and it turned out I had a question mark in my password — causing half the password and the remainder of the connection URL to be ignored (as apparently part of the URL search portion).\n\nSomething like:\n\n```\nnew Sequelize(\"postgres://fred:xj78?23@example.com/db\");\n```\n\nWhere we end up with username: fred, password: xj78, and everything else blank.\n\nEscaping the question mark as %3F fixes the issue.\n\n========================================\n\nCode:\n```text\nsequelize = new Sequelize(process.env.DATABASE_URI, {\n        dialect: 'postgres',\n        protocol: 'postgres',\n        logging: true,\n        timestamps: false\n    })\n```\n\n```text\npostgres://[db_username]:[db_password]@[hostname]:[port]/[db_name]\n```\n\n```text\nnew Sequelize(\"postgres://fred:xj78?23@example.com/db\");\n```\n\n========================================\n\nComments:\n- i am still battling with this. Getting the connection timeout error. Can you elaborate more on your solution pls ?\n- Hi Nuru, were you able to connect to your database locally through curl or a tool like pgAdmin? If so, afterwards you will want to make sure you check the security group between your RDS and Elastic Beanstalk instance and make sure that the \"Inbound\" settings are configured correctly.\n- Ran into the same problem. Changing the password resolved the issue.","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":72,"estimatedTokens":598}}495{"id":"stack-29828676","source":"stackoverflow","questionId":29828676,"title":"Change default column name sequelize","tags":["node.js","sequelize.js"],"text":"Title: Change default column name sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am working with Nodejs, Sequelize. This is following structure of my user model:\n\n```\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define('user', { \n first_name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n last_name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n validate: {\n isUnique: function (email, done) {\n User.find({ where: { email: email }})\n .done(function (err, user) {\n if (err) {\n done(err);\n }\n if (user) {\n done(new Error('Email already registered'));\n }\n done();\n });\n }\n }\n },\n profile_image_path: {\n type: DataTypes.STRING,\n allowNull: true,\n },\n active_flag: {\n type: DataTypes.BOOLEAN,\n allowNull: true,\n defaultValue: true\n },\n delete_flag: {\n type: DataTypes.BOOLEAN,\n allowNull: true,\n defaultValue: false\n }\n }, {\n classMethods: {\n associate: function(models) {\n User.hasMany(models.account),\n User.hasMany(models.user_has_contact)\n }\n }\n });\n return User;\n};\n```\n\nBy default 3 columns are created:\n\n- id\n\n- createdAt\n\n- updatedAt\n\nI don't want `createdAt` & `updatedAt` in this format, what i want is `created_at` and `updated_at`. How to change these default column name??? \n\nI have another table `user_has_contact` with following relationship:\n\n```\n{\n classMethods: {\n associate: function(models) {\n UserHasContact.belongsTo(models.user)\n }\n }\n }\n```\n\nIts creating `userId` field automatically but again i want it as `user_id`. Any suggestion would be appreciated!\n\n========================================\n\nTop Answer:\nyou can do it globally by adding this setting in your configuration as below\n\n```\nvar config= {\n \"define\": {\n \"underscored\": true\n }\n }\n\n var Sequelize = require(\"sequelize\");\n var sequelize = new Sequelize(database, username, password, config);\n```\n\n========================================\n\nCode:\n```text\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define('user', { \n    first_name: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n    last_name: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n    email: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true,\n      validate: {\n        isUnique: function (email, done) {\n            User.find({ where: { email: email }})\n                .done(function (err, user) {\n                    if (err) {\n                        done(err);\n                    }\n                    if (user) {\n                        done(new Error('Email already registered'));\n                    }\n                    done();\n                });\n        }\n    }\n    },\n    profile_image_path: {\n      type: DataTypes.STRING,\n      allowNull: true,\n    },\n    active_flag: {\n      type: DataTypes.BOOLEAN,\n      allowNull: true,\n      defaultValue: true\n    },\n    delete_flag: {\n      type: DataTypes.BOOLEAN,\n      allowNull: true,\n      defaultValue: false\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        User.hasMany(models.account),\n        User.hasMany(models.user_has_contact)\n      }\n    }\n  });\n  return User;\n};\n```\n\n```text\n{\n    classMethods: {\n      associate: function(models) {\n        UserHasContact.belongsTo(models.user)\n      }\n    }\n  }\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\ncreated_at\n```\n\n```text\nupdated_at\n```\n\n```text\nuser_has_contact\n```\n\n```text\nuserId\n```\n\n```text\nuser_id\n```\n\n```text\nsequelize.define('user', ..., {\n  createdAt: 'created_at',\n  updatedAt: 'updated_at',\n});\n```\n\n```text\nUserHasContact.belongsTo(models.user, { foreignKey: 'user_id' })\n```\n\n```text\nvar config=  {\n     \"define\": {\n          \"underscored\": true\n        }\n    }\n\n  var Sequelize = require(\"sequelize\");\n  var sequelize = new Sequelize(database, username, password, config);\n```\n\n```text\nvar config=  {\n     \"define\": {\n          \"underscored\": true\n        }\n    }\nvar Sequelize = require(\"sequelize\");\nvar sequelize = new Sequelize(database, username, password, config);\n```\n\n========================================\n\nComments:\n- If i'll use `foreignKey: 'user_id'` do i have to create `user_id` column also.\n- Not if you let sequelize create the tables (`sequelize.sync`)","metadata":{"transformedAt":"2026-08-18T18:33:34.381Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":241,"estimatedTokens":1084}}496{"id":"stack-37136986","source":"stackoverflow","questionId":37136986,"title":"Get Resultset From Query without Meta Information Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Get Resultset From Query without Meta Information Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to Node.js/Sequelize.js. I have following piece of code for query:\n\n```\nvar agent_list = models.agent.findAll({\n subQuery: false,\n where: qry_filter,\n attributes: select_attributes,\n include:include_models,\n group: ['agent_id'],\n order: agent_data.sort || appConfig.DEFAULT_AGENT_SORT,\n limit: agent_data.num_results || appConfig.DEFAULT_RESPONSE_SIZE\n\n })\n\n .then(function(agent_list){\n\n console.log(agent_list);\n\n });\n```\n\nThe statement \"console.log(agent_list)\" prints the data retrieved from db plus the meta information like options:{...} , modelOptions: {...} etc. dataValues object contains data that i want. The resultset is nested js objects, each has the same structure so it would be very difficult to loop through the resultset and get only the dataValues.\n\nI have experience working with PHP where something like this \n**$db -> Execute(\"$qry\")** would return resultset with meta and to get rows \n**$db -> Execute(\"$qry\")->getRows()** can be used. How to achieve this in sequelize?\n\n========================================\n\nTop Answer:\nSequelize does not use concepts like resultsets or rows. It's an ORM, so rows (including nested associations) are treated as objects with nested objects as appropriate. It also applies an \"Active Record\" pattern, so each returned object has additional method added to it, like \"save\", \"update\", \"delete\" and more.\n\nWhen Sequelize instances are serialized to JSON, they strip all the Sequelize \"metadata\" properties and just return simple objects, as you would expect.\n\nAlso, Sequelize instances make use of property getters and setters to transparently behave like simple JS objects. This means you can do something like `agent_list[0].myProperty = 1; console.log(agent_list[0].myProperty);` and it will behave like you expect. The reason it does this is so it can keep track of updated values, so later \"update\" calls will only update the columns that have changed.\n\nYou should have no need to manually get the \"rows\" from the query result.\n\n========================================\n\nCode:\n```text\nvar agent_list =  models.agent.findAll({\n                                      subQuery: false,\n                                      where:   qry_filter,\n                                      attributes: select_attributes,\n                                      include:include_models,\n                                      group: ['agent_id'],\n                                      order: agent_data.sort || appConfig.DEFAULT_AGENT_SORT,\n                                      limit: agent_data.num_results || appConfig.DEFAULT_RESPONSE_SIZE\n\n                                    })\n\n                                   .then(function(agent_list){\n\n                                      console.log(agent_list);\n\n                                   });\n```\n\n```text\nmodels.agent.findAll({\n    subQuery: false,\n    where: qry_filter,\n    attributes: select_attributes,\n    include: include_models,\n    group: ['agent_id'],\n    order: agent_data.sort || appConfig.DEFAULT_AGENT_SORT,\n    limit: agent_data.num_results || appConfig.DEFAULT_RESPONSE_SIZE\n}).then(function(agent_list) {\n    return agent_list.map(function(agent) {\n        return agent.getValues();\n    });\n}).then(function(agent_list) {\n    console.log(agent_list);\n});\n```\n\n```text\nagent_list[0].myProperty = 1; console.log(agent_list[0].myProperty);\n```\n\n```text\nvar agent_list =  models.agent.findAll({\n                                      raw: true,\n                                      subQuery: false,\n                                      where:   qry_filter,\n                                      attributes: select_attributes,\n                                      include:include_models,\n                                      group: ['agent_id'],\n                                      order: agent_data.sort || appConfig.DEFAULT_AGENT_SORT,\n                                      limit: agent_data.num_results || appConfig.DEFAULT_RESPONSE_SIZE\n\n                                    })\n\n                                   .then(function(agent_list){\n\n                                      console.log(agent_list);\n\n                                   });\n```\n\n========================================\n\nComments:\n- I have implemented your solution with a bit modification. `then(function(agent_list){ agent_list.map(function(agent) { console.log(agent.getValues()); }); });` It is working great. Exactly what i needed.\n- Well, if you only want to log them maybe you should consider using forEach instead. Map function actually expects you to return something as the result of the map operation\n- I've found stringifying then parsing the JSON results from sequelize has the same effect as sequelize-values module. `JSON.parse(JSON.stringify(results))`\n- Yes toJSON strips all the meta information, but i need to do further processing on result before converting to JSON. I have 95 columns in table. Calling get method for each attribute would be too cumbersome.\n- My point is that you don't need to explicitly call .get() or .toJSON() in order to process anything. You can just map properties (columns) of each object (row) to properties of your desired output object. E.g. `var output = { outProp: input.columnA + input.columnB);`, where \"input\" is an instance of a Sequelize model (row).\n- What i am currently doing is findAll returns all data rows + meta data. I am using _.omit() inside toJSON method to omit columns that i don't need in response. Then as above answer suggest i am using sequelize-values to map the output. is this a bad practice? I am still learning node.js/sequelize.js","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":1436}}497{"id":"stack-32102725","source":"stackoverflow","questionId":32102725,"title":"How to set association at the time of save/create in sequelizejs?","tags":["sequelize.js"],"text":"Title: How to set association at the time of save/create in sequelizejs?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nFor a simple model like this:\n\n```\nvar User = sequelize.define('User', { email: Sequelize.STRING });\nvar Team = sequelize.define('Team', { name: Sequelize.STRING });\nUser.belongsTo(Team);\n\nTeam.create({name:'blah'});\n```\n\nHow do you store a new User and set its TeamId at the same time (same time here means in one INSERT)\n\nThis is important for cases where REFERENCE is mandatory (NOT NULL) and usual `user.setTeam(team)` which generates an UPDATE after an INSERT is not going to work.\n\nObviously extra team as an property in `User.create({ email: 'x', team: team })` will be ignored and the following:\n\n```\nvar user = User.build({email:'x'});\nuser.setTeam(team);\nuser.save();\n```\n\ngenerates one extra and completely wrong INSERT:\n\n```\nINSERT INTO `Users` (`TeamId`,`updatedAt`,`createdAt`) \nVALUES (4,'2015-08-19 18:10:36','2015-08-19 18:10:36'); \n-- has no id or email\n```\n\n========================================\n\nCode:\n```js\nvar User = sequelize.define('User', { email: Sequelize.STRING });\nvar Team = sequelize.define('Team', { name: Sequelize.STRING });\nUser.belongsTo(Team);\n\nTeam.create({name:'blah'});\n```\n\n```js\nvar user = User.build({email:'x'});\nuser.setTeam(team);\nuser.save();\n```\n\n```sql\nINSERT INTO `Users` (`TeamId`,`updatedAt`,`createdAt`) \nVALUES (4,'2015-08-19 18:10:36','2015-08-19 18:10:36');  \n-- has no id or email\n```\n\n```text\nuser.setTeam(team)\n```\n\n```text\nUser.create({ email: 'x', team: team })\n```\n\n```text\nvar user = User.build({email:'x'});\nuser.setTeam(team, {save: false});\nuser.save();\n```\n\n```text\nteam\n```\n\n```text\nsave\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- Did you find any solution? I have the exact same problem\n- No unfortunately\n- xersiee life saver","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":90,"estimatedTokens":465}}498{"id":"stack-38217802","source":"stackoverflow","questionId":38217802,"title":"Sequelize error: defineCall not defined in Index.js","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: Sequelize error: defineCall not defined in Index.js\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've been receiving this sequelize error\n\n```\n/node_modules/sequelize/lib/sequelize.js:508\n this.importCache[path] = defineCall(this, DataTypes);\n ^\n TypeError: defineCall is not a function\n at module.exports.Sequelize.import (/node_modules/sequelize/lib/sequelize.js:508:32)\nat /models/Index.js:16:33\nat Array.forEach (native)\nat Object. (/Users/vincentporta/Desktop/RCB_Classwork/cesarcell/models/Index.js:15:4)\nat Module._compile (module.js:409:26)\nat Object.Module._extensions..js (module.js:416:10)\nat Module.load (module.js:343:32)\nat Function.Module._load (module.js:300:12)\nat Module.require (module.js:353:17)\nat require (internal/module.js:12:17)\n```\n\nI've narrowed it down to the commented code in my `Index.js` file below\n\n`\"use strict\";`\n\n```\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar Sequelize = require(\"sequelize\");\nvar config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\nvar db = {};\n\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n })\n```\n\nThis commented code below breaks it \n `//.forEach(function(file) {\n // var model = sequelize.import(path.join(__dirname, file));\n // db[model.name] = model;\n // });`\n\n```\nObject.keys(db).forEach(function(modelName) {\n if (\"associate\" in db[modelName]) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nDoes anyone know why this error is occuring?\n\n========================================\n\nTop Answer:\nI saw a similar problem just now and the problem was a file that was in the models folder that was not actually a database model. Ensure that your models folder only contains models for your database. Hopefully this helps!\n\n========================================\n\nCode:\n```text\n/node_modules/sequelize/lib/sequelize.js:508\n      this.importCache[path] = defineCall(this, DataTypes);\n                           ^\n    TypeError: defineCall is not a function\n    at module.exports.Sequelize.import             (/node_modules/sequelize/lib/sequelize.js:508:32)\nat   /models/Index.js:16:33\nat Array.forEach (native)\nat Object.<anonymous> (/Users/vincentporta/Desktop/RCB_Classwork/cesarcell/models/Index.js:15:4)\nat Module._compile (module.js:409:26)\nat Object.Module._extensions..js (module.js:416:10)\nat Module.load (module.js:343:32)\nat Function.Module._load (module.js:300:12)\nat Module.require (module.js:353:17)\nat require (internal/module.js:12:17)\n```\n\n```text\nvar fs        = require(\"fs\");\nvar path      = require(\"path\");\nvar Sequelize = require(\"sequelize\");\nvar config    = require(path.join(__dirname, '..', 'config',    'config.json'))[env];\nvar sequelize = new Sequelize(config.database, config.username,  config.password, config);\nvar db        = {};\n\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n  })\n```\n\n```text\nObject.keys(db).forEach(function(modelName) {\n  if (\"associate\" in db[modelName]) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nIndex.js\n```\n\n```text\n\"use strict\";\n```\n\n```text\n//.forEach(function(file) {\n    //   var model = sequelize.import(path.join(__dirname, file));\n    //   db[model.name] = model;\n    // });\n```\n\n```text\nreturn (file.indexOf(\".\") !== 0) && (file !== \"Index.js\");\n```\n\n```text\nIndex.js\n```\n\n```text\n@Table\nexport class User extends Model<User> {\n  @Column\n  userId!: number;\n\n  @Column\n  tenantId!: number;\n}\n```\n\n```text\n@Table\nexport default class User extends Model<User> {\n  @Column\n  userId!: number;\n\n  @Column\n  tenantId!: number;\n}\n```\n\n```text\ndefault\n```\n\n```text\ndefault\n```\n\n========================================\n\nComments:\n- Which version of Sequelize are you using?\n- @rels Sequelize [Node: 4.4.2, CLI: 2.4.0, ORM: 2.0.0-rc1, mysql: ^2.10.2]","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":175,"estimatedTokens":1033}}499{"id":"stack-40808686","source":"stackoverflow","questionId":40808686,"title":"Sequelize CLI Not Finding Env Variables","tags":["sequelize.js","sequelize-cli"],"text":"Title: Sequelize CLI Not Finding Env Variables\nTags: sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am trying to run a db migration with the Sequelize CLI tool, but I'm running into an issue where my ENV variables are not being processed by the tool. In the github repo, it says in version 2.0.0 (I'm on 2.4.0) you can directly access ENV variables in `config/config.js` like so, process.env.DB_HOSTNAME, but I get an error that indicates that no values are being passed in from the variables\n\n**Error:**\n\n```\nUnable to connect to database: SequelizeAccessDeniedError: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'localhost' (using password: NO)\n```\n\n**config.js:**\n\n```\nmodule.exports = {\n \"development\": {\n \"username\": process.env.LOCAL_USERNAME,\n \"password\": process.env.LOCAL_PASSWORD,\n \"database\": process.env.LOCAL_DATABASE,\n \"host\": \"127.0.0.1\",\n \"dialect\": \"mysql\",\n \"migrationStorageTableName\": \"sequelize_meta\"\n },\n}\n```\n\n**.env:**\n\n```\nLOCAL_DATABASE=\"db_name\"\nLOCAL_USERNAME=\"root\"\nLOCAL_PASSWORD=\"test\"\n```\n\n========================================\n\nCode:\n```text\nUnable to connect to database: SequelizeAccessDeniedError: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'localhost' (using password: NO)\n```\n\n```text\nmodule.exports = {\n    \"development\": {\n        \"username\": process.env.LOCAL_USERNAME,\n        \"password\": process.env.LOCAL_PASSWORD,\n        \"database\": process.env.LOCAL_DATABASE,\n        \"host\": \"127.0.0.1\",\n        \"dialect\": \"mysql\",\n        \"migrationStorageTableName\": \"sequelize_meta\"\n    },\n}\n```\n\n```text\nLOCAL_DATABASE=\"db_name\"\nLOCAL_USERNAME=\"root\"\nLOCAL_PASSWORD=\"test\"\n```\n\n```text\nconfig/config.js\n```\n\n```text\nrequire('dotenv').config();  // this line is important!\nmodule.exports = {\n\"development\": {\n    \"username\": process.env.LOCAL_USERNAME,\n    \"password\": process.env.LOCAL_PASSWORD,\n    \"database\": process.env.LOCAL_DATABASE,\n    \"host\": \"127.0.0.1\",\n    \"dialect\": \"mysql\",\n    \"migrationStorageTableName\": \"sequelize_meta\"\n},\n}\n```\n\n```text\ndotenv\n```\n\n========================================\n\nComments:\n- Are you using dotenv(github.com/motdotla/dotenv) node module? Are you able to connect db through username root and password test?\n- how did you solve the problem?","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":89,"estimatedTokens":564}}500{"id":"stack-35796963","source":"stackoverflow","questionId":35796963,"title":"Sequelize error with MariaDB","tags":["node.js","sequelize.js","mariadb","mariasql"],"text":"Title: Sequelize error with MariaDB\nTags: node.js, sequelize.js, mariadb, mariasql\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup `sequelize` as ORM for my `MariaDB`.\n\nHere is my setup:\n\n```\nvar sequelize = require('sequelize');\n\nvar db= new sequelize('dbname', 'user', 'pass', {\n dialect: 'mariadb'\n});\n```\n\nWhen I run my app I get the following error :\n\n```\n/my/path/to/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:23\n throw new Error('Please install mysql package manually');\n ^\n\nError: Please install mysql package manually\n```\n\nWhy is sequelize trying to connect to mysql rather than mariadb as I specified in the `dialect` directive? Am I missing something?\n\n========================================\n\nTop Answer:\nSequelize now has the dialect `mariadb`, do not use `mysql`\n\n```\nnpm install --save mariadb\nnpm install --save sequelize\n```\n\nSequelize connection code...\n\n```\nvar sequelize = new Sequelize('database', 'username', 'password', {\n dialect: 'mariadb'\n})\n```\n\n========================================\n\nCode:\n```text\nvar sequelize = require('sequelize');\n\nvar db= new sequelize('dbname', 'user', 'pass', {\n  dialect: 'mariadb'\n});\n```\n\n```text\n/my/path/to/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:23\n    throw new Error('Please install mysql package manually');\n    ^\n\nError: Please install mysql package manually\n```\n\n```text\nsequelize\n```\n\n```text\nMariaDB\n```\n\n```text\ndialect\n```\n\n```text\n$ npm install --save mysql2\n```\n\n```text\ndialect: mysql\n```\n\n```text\ndialect: mariadb\n```\n\n```text\nnpm install --save mariadb\nnpm install --save sequelize\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n  dialect: 'mariadb'\n})\n```\n\n```text\nmariadb\n```\n\n```text\nmysql\n```\n\n```text\nnpm i -g mysql\n```\n\n```text\nyarn add mariadb\n```\n\n```text\nyarn\n```\n\n```text\nexport const sequelize = new Sequelize({\n  dialect: 'mariadb',\n  **dialectModule: _mariadb, // Here**\n  database: 'xx',\n  username: 'root',\n  password: 'xx',\n  models: [Person]\n});\n```\n\n```text\nimport * as _mariadb from 'mariadb';\n```\n\n========================================\n\nComments:\n- I went through the docs a bazillion times...don't know how I didn't see that...thank you!!\n- `mysql2` required for current versions\n- @indospace.io If the answer is incorrect in your opinion either say so in the comments or post your own answer, but do not edit somebody else's answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":142,"estimatedTokens":605}}501{"id":"stack-44211762","source":"stackoverflow","questionId":44211762,"title":"sequelize (js) association for multiple columns with one table","tags":["sql","node.js","sequelize.js"],"text":"Title: sequelize (js) association for multiple columns with one table\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nhope you're doing great.\n\nI have an issue with sequelizejs I cannot get to work for some reason, no matter how I set up the associations in between tables. My problem is, I have a table, called **Results**, this table has a structure of:\n\n```\n| id (primary) | first_guy_id | second_guy_id | third_guy_id | notes |\n|--------------|--------------|---------------|--------------|-------|\n| | | | | |\n```\n\nThis table connects to **Users**, and here comes the fun part, the table **Users** has a simple structure, like so \n\n```\n| id (primary) | first | last |\n|--------------|-------|------|\n| | | |\n```\n\nWhat I would like to do with sequelize is, to get a result (in json afterwards) that looks similar to this, nested with connections:\n\n```\n{\n \"id\": 17,\n \"first_guy_id\": { \"id\": 12, \"first\": \"First .... },\n \"second_guy_id\": { \"id\": 14, \"first\": \"First .... },\n \"third_guy_id\": { \"id\": 19, \"first\": \"First .... },\n \"notes\": \"notes\",\n}\n```\n\nDoing the SQL JOIN in regular SQL is easy even if all the id's for each column (first_guy, second ...) are different but reach such a goal in sequelize rendered myself completely hopeless.\n\nWhen I associate the two tables this way:\n\n```\nResults.hasOne(User, { as:'first_guy', foreignKey: 'first_guy' });\nUser.belongsTo(Results, { as: 'first_guy' });\n```\n\nWhen doing the actual call using\n\n```\nfindOne ...\n include: [\n { model: User,\n include: [\n {\n model: User,\n as: 'first_ugy',\n where: {\n 'id': sequelize.col('Results.first_guy_id')\n },\n }\n ],\n },\n```\n\nI get an error of:\n\n```\nER_BAD_FIELD_ERROR: Unknown column 'Results.user_id' in 'field list'\n```\n\nThis is of course because it looks for user_id as foreign key, connecting to table \"User\" it thinks the key should be user_id. \n\nTwo problems I have finding this solution are: \n\nHow do I join the result on any field with sequelize same way I would do with regular SQL (pseudo code here) \"**INNER JOIN User.id on Results.first_guy_id as MY_FIELD_NAME**\" \n\nHow do I join all of those fields to the same model but with different results for each column? So the get result from **Results** would return nested 3 different users by their ID listed in the **Results** table in that specific row. Using same model?\n\nI went through the docs of sequelize, tried many combinations but never achieving the result. It almost feels like i would have to end up writing models, that are named like those fields \"First_gu\", \"second_guy\", \"third_guy\" for Sequalize to work and auto append the \"_id\" there like it does with the **User** model now. But it feels like too much of an effort for something that should be solved by the \"foreignKey\" attribute in the belongsTo / hasOne?\n\n========================================\n\nCode:\n```text\n| id (primary) | first_guy_id | second_guy_id | third_guy_id | notes |\n|--------------|--------------|---------------|--------------|-------|\n|              |              |               |              |       |\n```\n\n```text\n| id (primary) | first | last |\n|--------------|-------|------|\n|              |       |      |\n```\n\n```text\n{\n  \"id\": 17,\n  \"first_guy_id\": { \"id\": 12, \"first\": \"First .... },\n  \"second_guy_id\": { \"id\": 14, \"first\": \"First .... },\n  \"third_guy_id\": { \"id\": 19, \"first\": \"First .... },\n  \"notes\": \"notes\",\n}\n```\n\n```text\nResults.hasOne(User, { as:'first_guy', foreignKey: 'first_guy' });\nUser.belongsTo(Results, { as: 'first_guy' });\n```\n\n```text\nfindOne ...\n   include: [\n        { model: User,\n          include: [\n            {\n              model: User,\n              as: 'first_ugy',\n              where: {\n                    'id': sequelize.col('Results.first_guy_id')\n              },\n            }\n          ],\n        },\n```\n\n```text\nER_BAD_FIELD_ERROR: Unknown column 'Results.user_id' in 'field list'\n```\n\n```text\nResults.belongsTo(User, { as:'firstGuy', foreignKey: 'first_guy_id'});\nResults.belongsTo(User, { as:'secondGuy', foreignKey: 'second_guy_id'});\n...\n```\n\n```text\nResults.findById(resultId, {\n   include: [{\n      model: User,\n      as: 'firstGuy'\n   }, {\n      model: User,\n      as: 'secondGuy'\n   },\n   ...\n   ]\n}).then(function(result){\n   var firstGuyUser = result.firstGuy;\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":149,"estimatedTokens":1071}}502{"id":"stack-40517942","source":"stackoverflow","questionId":40517942,"title":"unrecognized configuration parameter \"autocommit\" in PostgreSQL NodeJS","tags":["node.js","postgresql","sequelize.js"],"text":"Title: unrecognized configuration parameter \"autocommit\" in PostgreSQL NodeJS\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n{\"message\":\"Err on translation create, for key blah blah blah\n \",\"name\":\"SequelizeDatabaseError\",\"stack\":\"SequelizeDatabaseError:\n unrecognized configuration parameter \\\"autocommit\\\"\\n at\n Query.module.exports.Query.formatError\n (/var/www/courses/courses.com.mm/dist/node_modules/sequelize/lib/dialects/postgres/query.js:361:16)\\n\n at Query.\n (/var/www/courses/courses.com.mm/dist/node_modules/sequelize/lib/dialects/postgres/query.js:79:21)\\n\n at emitOne (events.js:96:13)\\n at Query.emit (events.js:188:7)\\n\n\n at Query.handleError\n (/var/www/courses/courses.com.mm/dist/node_modules/pg/lib/query.js:108:8)\\n\n at Connection.\n (/var/www/courses/courses.com.mm/dist/node_modules/pg/lib/client.js:171:26)\\n\n at emitOne (events.js:96:13)\\n at Connection.emit\n (events.js:188:7)\\n at Socket.\n (/var/www/courses/courses.com.mm/dist/node_modules/pg/lib/connection.js:109:12)\\n\n at emitOne (events.js:96:13)\\n at Socket.emit (events.js:188:7)\\n\n\n at readableAddChunk (_stream_readable.js:176:18)\\n at\n Socket.Readable.push (_stream_readable.js:134:10)\\n at TCP.onread\n (net.js:543:20)\",\"parent\":{\"name\":\"error\",\"length\":102,\"severity\":\"ERROR\",\"code\":\"42704\",\"file\":\"guc.c\",\"line\":\"5692\",\"routine\":\"set_config_option\",\"sql\":\"SET\n autocommit =\n 1;\"},\"original\":{\"name\":\"error\",\"length\":102,\"severity\":\"ERROR\",\"code\":\"42704\",\"file\":\"guc.c\",\"line\":\"5692\",\"routine\":\"set_config_option\",\"sql\":\"SET\n autocommit = 1;\"},\"sql\":\"SET autocommit =\n 1;\",\"isOperational\":true,\"level\":\"info\",\"timestamp\":\"2016-11-09T16:56:44.885Z\"}\n\nI've encountered above error when I checked log file by terminal. I'm not sure it's postgresql error or something else. Please help me how to solve it. And here is my postgresql version:\n\n PostgreSQL 9.5.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.2\n 20140120 (Red Hat 4.8.2-16), 64-bit (1 row)\n\n========================================\n\nCode:\n```text\nautocommit\n```\n\n========================================\n\nComments:\n- OK, then how *do* I disable autocommit? Because it needs to be disabled to properly use a fetch size: jdbc.postgresql.org/documentation/head/&hellip;\n- It is no problem to disable autocommit *on the client*.\n- Right, I see. Back to getting jOOQ/JDBC in line then. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":49,"estimatedTokens":591}}503{"id":"stack-42345650","source":"stackoverflow","questionId":42345650,"title":"Sequelize, set column as foreign key to a table from another schema","tags":["foreign-keys","schema","sequelize.js"],"text":"Title: Sequelize, set column as foreign key to a table from another schema\nTags: foreign-keys, schema, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a table:\n\n```\nqueryInterface.createTable('MyTable', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n SomeTableId: {\n type: Sequelize.INTEGER,\n references: { model: 'static.SomeTable', key: 'id'},\n allowNull: false\n },\n\n }, t);\n```\n\nThe problem is that this error is thrown, when I run the migration : \n\n```\n'Unhandled rejection SequelizeDatabaseError: relation \"static.SomeTable\" does not exist'\n```\n\nSo, basically, the question is:\n\n*When I am creating a table in the **'public'** schema, how can I specify a foreign key column in that table, that references a table in the **'static'** schema.*\n\n========================================\n\nCode:\n```text\nqueryInterface.createTable('MyTable', {\n                id: {\n                    type: Sequelize.INTEGER,\n                    primaryKey: true,\n                    autoIncrement: true\n                },\n               SomeTableId: {\n                    type: Sequelize.INTEGER,\n                    references: { model: 'static.SomeTable', key: 'id'},\n                    allowNull: false\n                },\n\n            }, t);\n```\n\n```text\n'Unhandled rejection SequelizeDatabaseError: relation \"static.SomeTable\" does not exist'\n```\n\n```text\nqueryInterface.createTable('MyTable', {\n                id: {\n                    type: Sequelize.INTEGER,\n                    primaryKey: true,\n                    autoIncrement: true\n                },\n               SomeTableId: {\n                    type: Sequelize.INTEGER,\n                    references: { \n                        model: {\n                            tableName: 'SomeTable', \n                            schema: 'static'\n                        }\n                        key: 'id'\n                    },\n                    allowNull: false\n                },\n\n            }, t);\n```\n\n========================================\n\nComments:\n- Great one, good to know about that feature! Tried to find an answer for couple of minutes but glad you made it :)\n- I got `ERROR: Failed to open the referenced table 'schema.table`. Do you know if there's any other setup required for this to work? Both schema and table exist","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":83,"estimatedTokens":585}}504{"id":"stack-49818406","source":"stackoverflow","questionId":49818406,"title":"Sequelize targetKey not working","tags":["node.js","associations","sequelize.js"],"text":"Title: Sequelize targetKey not working\nTags: node.js, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to associate two models \"Note\" and \"Resource\" using sequelize. However, targetKey is not working as expected.\n\n**Note modal** :\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('note', {\n NoteID: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n Title: {\n type: DataTypes.STRING(50),\n allowNull: true\n },\n Note: {\n type: DataTypes.STRING(500),\n allowNull: false\n },\n CreatedBy: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'resource',\n key: 'ResourceID'\n }\n },\n UpdatedBy: {\n type: DataTypes.INTEGER(11),\n allowNull: true,\n references: {\n model: 'resource',\n key: 'ResourceID'\n }\n }\n }, {\n tableName: 'note'\n });\n};\n```\n\n**Resource modal** :\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('resource', {\n ResourceID: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n FirstName: {\n type: DataTypes.STRING(250),\n allowNull: false\n },\n LastName: {\n type: DataTypes.STRING(250),\n allowNull: false\n }\n }, {\n tableName: 'resource'\n });\n};\n```\n\n**Association**:\n\n```\nResource.belongsTo(Note,{\n foreignKey: 'UpdatedBy',\n as: 'Resource_Updated_Note'\n});\n\nNote.hasOne(Resource,{\n foreignKey: 'ResourceID',\n targetKey: 'UpdatedBy',\n as: 'Note_Updated_By'\n});\n\nResource.belongsTo(Note,{\n foreignKey: 'CreatedBy',\n as: 'Resource_Created_Note'\n});\n\nNote.hasOne(Resource,{\n foreignKey: 'ResourceID',\n targetKey: 'CreatedBy',\n as: 'Note_Created_By'\n});\n```\n\nAlthough I have mentioned the targetKey while association, it is taking PrimaryKey while joining the tables.\n\n**Execution**.\n\n```\nNote.findAll({\n include: [{\n model: Resource,\n as: 'Note_Updated_By'\n }],\n where: {\n Status: {\n [SQLOP.or]: ['Active', 'ACTIVE']\n }\n }\n }).then(function (response) {\n callback(response);\n });\n```\n\nOn basis of the execution, this select query is generated.\n\n```\nSELECT * FROM `note` LEFT OUTER JOIN `resource` AS `Note_Updated_By` ON `note`.`NoteID` = `Note_Updated_By`.`ResourceID`;\n```\n\nInstead of `note`.`NoteID`, it should be `note`.`UpdatedBy`\n\n========================================\n\nTop Answer:\n**You have to set both `hasMany({ sourceKey` and `belongsTo({ targetKey`**\n\nThis is sequelize docs failing us again, each side has a different name, and we have to set both e.g.:\n\n```\nconst Country = sequelize.define('Country', {\n country_name: { type: DataTypes.STRING, unique: true },\n});\nconst City = sequelize.define('City', {\n parent_country: { type: DataTypes.STRING },\n city_name: { type: DataTypes.STRING },\n});\nCountry.hasMany(City, { foreignKey: 'parent_country', sourceKey: 'country_name' } )\nCity.belongsTo(Country, { foreignKey: 'parent_country', targetKey: 'country_name' } )\n```\n\nIf you set just the `sourceKey`, then the query will be wrong, both are needed.\n\nMinimal runnable example:\n\nmain.js\n\n```\n#!/usr/bin/env node\nconst assert = require('assert')\nconst path = require('path')\nconst { DataTypes, Sequelize } = require('sequelize')\nlet sequelize\nif (process.argv[2] === 'p') {\n sequelize = new Sequelize('tmp', undefined, undefined, {\n dialect: 'postgres',\n host: '/var/run/postgresql',\n })\n} else {\n sequelize = new Sequelize({\n dialect: 'sqlite',\n storage: 'tmp.sqlite'\n })\n}\n;(async () => {\nconst Country = sequelize.define('Country', {\n country_name: { type: DataTypes.STRING, unique: true },\n});\nconst City = sequelize.define('City', {\n parent_country: { type: DataTypes.STRING },\n city_name: { type: DataTypes.STRING },\n});\nCountry.hasMany(City, { foreignKey: 'parent_country', sourceKey: 'country_name' } )\nCity.belongsTo(Country, { foreignKey: 'parent_country', targetKey: 'country_name' } )\nawait sequelize.sync({force: true});\nawait Country.create({country_name: 'germany'})\nawait Country.create({country_name: 'france'})\nawait City.create({parent_country: 'germany', city_name: 'berlin'});\nawait City.create({parent_country: 'germany', city_name: 'munich'});\nawait City.create({parent_country: 'france', city_name: 'paris'});\nconst rows = await City.findAll({\n where: { parent_country: 'germany' },\n include: {\n model: Country,\n }\n});\nassert.strictEqual(rows[0].Country.country_name, 'germany')\nassert.strictEqual(rows[1].Country.country_name, 'germany')\nassert.strictEqual(rows.length, 2)\n})().finally(() => { return sequelize.close() })\n```\n\npackage.json\n\n```\n{\n \"name\": \"tmp\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"dependencies\": {\n \"pg\": \"8.5.1\",\n \"pg-hstore\": \"2.3.3\",\n \"sequelize\": \"6.14.0\",\n \"sqlite3\": \"5.0.2\"\n }\n}\n```\n\nProduced queries as desired:\n\n```\nExecuting (default): DROP TABLE IF EXISTS `Cities`;\nExecuting (default): DROP TABLE IF EXISTS `Countries`;\nExecuting (default): DROP TABLE IF EXISTS `Countries`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `Countries` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `country_name` VARCHAR(255) UNIQUE);\nExecuting (default): PRAGMA INDEX_LIST(`Countries`)\nExecuting (default): PRAGMA INDEX_INFO(`sqlite_autoindex_Countries_1`)\nExecuting (default): DROP TABLE IF EXISTS `Cities`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `Cities` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `parent_country` VARCHAR(255) REFERENCES `Countries` (`country_name`) ON DELETE CASCADE ON UPDATE CASCADE, `city_name` VARCHAR(255));\nExecuting (default): PRAGMA INDEX_LIST(`Cities`)\nExecuting (default): INSERT INTO `Countries` (`id`,`country_name`) VALUES (NULL,$1);\nExecuting (default): INSERT INTO `Countries` (`id`,`country_name`) VALUES (NULL,$1);\nExecuting (default): INSERT INTO `Cities` (`id`,`parent_country`,`city_name`) VALUES (NULL,$1,$2);\nExecuting (default): INSERT INTO `Cities` (`id`,`parent_country`,`city_name`) VALUES (NULL,$1,$2);\nExecuting (default): INSERT INTO `Cities` (`id`,`parent_country`,`city_name`) VALUES (NULL,$1,$2);\nExecuting (default): SELECT `City`.`id`, `City`.`parent_country`, `City`.`city_name`, `Country`.`id` AS `Country.id`, `Country`.`country_name` AS `Country.country_name` FROM `Cities` AS `City` LEFT OUTER JOIN `Countries` AS `Country` ON `City`.`parent_country` = `Country`.`country_name` WHERE `City`.`parent_country` = 'germany';\n```\n\nnotably we have the desired `REFERENES`:\n\n```\nCREATE TABLE IF NOT EXISTS `Cities` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `parent_country` VARCHAR(255) REFERENCES `Countries` (`country_name`) ON DELETE CASCADE ON UPDATE CASCADE,\n `city_name` VARCHAR(255));\n```\n\nand he desired JOIN ON:\n\n```\nON `City`.`parent_country` = `Country`.`country_name`\n```\n\nwith the custom columns.\n\nTested on SQLite and PostgreSQL 13.5.\n\nRelated:\n\n- sequelize: association is referencing to wrong foreignKey column name\n\n- Association is using wrong column\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('note', {\n    NoteID: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    Title: {\n      type: DataTypes.STRING(50),\n      allowNull: true\n    },\n    Note: {\n      type: DataTypes.STRING(500),\n      allowNull: false\n    },\n    CreatedBy: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      references: {\n        model: 'resource',\n        key: 'ResourceID'\n      }\n    },\n    UpdatedBy: {\n      type: DataTypes.INTEGER(11),\n      allowNull: true,\n      references: {\n        model: 'resource',\n        key: 'ResourceID'\n      }\n    }\n  }, {\n    tableName: 'note'\n  });\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('resource', {\n    ResourceID: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    FirstName: {\n      type: DataTypes.STRING(250),\n      allowNull: false\n    },\n    LastName: {\n      type: DataTypes.STRING(250),\n      allowNull: false\n    }\n  }, {\n    tableName: 'resource'\n  });\n};\n```\n\n```text\nResource.belongsTo(Note,{\n    foreignKey: 'UpdatedBy',\n    as: 'Resource_Updated_Note'\n});\n\nNote.hasOne(Resource,{\n    foreignKey: 'ResourceID',\n    targetKey: 'UpdatedBy',\n    as: 'Note_Updated_By'\n});\n\nResource.belongsTo(Note,{\n    foreignKey: 'CreatedBy',\n    as: 'Resource_Created_Note'\n});\n\nNote.hasOne(Resource,{\n    foreignKey: 'ResourceID',\n    targetKey: 'CreatedBy',\n    as: 'Note_Created_By'\n});\n```\n\n```text\nNote.findAll({\n        include: [{\n            model: Resource,\n            as: 'Note_Updated_By'\n        }],\n        where: {\n            Status: {\n                [SQLOP.or]: ['Active', 'ACTIVE']\n            }\n        }\n    }).then(function (response) {\n        callback(response);\n    });\n```\n\n```text\nSELECT * FROM `note` LEFT OUTER JOIN `resource` AS `Note_Updated_By` ON `note`.`NoteID` = `Note_Updated_By`.`ResourceID`;\n```\n\n```text\nnote\n```\n\n```text\nNoteID\n```\n\n```text\nnote\n```\n\n```text\nUpdatedBy\n```\n\n```text\nModelName.hasOne(ModelName1, {\n  as: 'SomeAlias',\n  foreignKey: 'foreign_key',\n  onDelete: 'NO ACTION',\n  onUpdate: 'NO ACTION',\n  sourceKey: 'YOUR_CUSTOM_ASSOCIATION_KEY'\n});\n```\n\n```text\n\"sequelize\": \"^5.8.12\"\n```\n\n```text\nsourceKey\n```\n\n```text\ntargetKey\n```\n\n```text\nhasOne\n```\n\n```text\nhasMany\n```\n\n```text\nconst Country = sequelize.define('Country', {\n  country_name: { type: DataTypes.STRING, unique: true },\n});\nconst City = sequelize.define('City', {\n  parent_country: { type: DataTypes.STRING },\n  city_name: { type: DataTypes.STRING },\n});\nCountry.hasMany(City, { foreignKey: 'parent_country', sourceKey: 'country_name' } )\nCity.belongsTo(Country, { foreignKey: 'parent_country', targetKey: 'country_name' } )\n```\n\n```text\n#!/usr/bin/env node\nconst assert = require('assert')\nconst path = require('path')\nconst { DataTypes, Sequelize } = require('sequelize')\nlet sequelize\nif (process.argv[2] === 'p') {\n  sequelize = new Sequelize('tmp', undefined, undefined, {\n    dialect: 'postgres',\n    host: '/var/run/postgresql',\n  })\n} else {\n  sequelize = new Sequelize({\n    dialect: 'sqlite',\n    storage: 'tmp.sqlite'\n  })\n}\n;(async () => {\nconst Country = sequelize.define('Country', {\n  country_name: { type: DataTypes.STRING, unique: true },\n});\nconst City = sequelize.define('City', {\n  parent_country: { type: DataTypes.STRING },\n  city_name: { type: DataTypes.STRING },\n});\nCountry.hasMany(City, { foreignKey: 'parent_country', sourceKey: 'country_name' } )\nCity.belongsTo(Country, { foreignKey: 'parent_country', targetKey: 'country_name' } )\nawait sequelize.sync({force: true});\nawait Country.create({country_name: 'germany'})\nawait Country.create({country_name: 'france'})\nawait City.create({parent_country: 'germany', city_name: 'berlin'});\nawait City.create({parent_country: 'germany', city_name: 'munich'});\nawait City.create({parent_country: 'france', city_name: 'paris'});\nconst rows = await City.findAll({\n  where: { parent_country: 'germany' },\n  include: {\n    model: Country,\n  }\n});\nassert.strictEqual(rows[0].Country.country_name, 'germany')\nassert.strictEqual(rows[1].Country.country_name, 'germany')\nassert.strictEqual(rows.length, 2)\n})().finally(() => { return sequelize.close() })\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.14.0\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS `Cities`;\nExecuting (default): DROP TABLE IF EXISTS `Countries`;\nExecuting (default): DROP TABLE IF EXISTS `Countries`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `Countries` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `country_name` VARCHAR(255) UNIQUE);\nExecuting (default): PRAGMA INDEX_LIST(`Countries`)\nExecuting (default): PRAGMA INDEX_INFO(`sqlite_autoindex_Countries_1`)\nExecuting (default): DROP TABLE IF EXISTS `Cities`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `Cities` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `parent_country` VARCHAR(255) REFERENCES `Countries` (`country_name`) ON DELETE CASCADE ON UPDATE CASCADE, `city_name` VARCHAR(255));\nExecuting (default): PRAGMA INDEX_LIST(`Cities`)\nExecuting (default): INSERT INTO `Countries` (`id`,`country_name`) VALUES (NULL,$1);\nExecuting (default): INSERT INTO `Countries` (`id`,`country_name`) VALUES (NULL,$1);\nExecuting (default): INSERT INTO `Cities` (`id`,`parent_country`,`city_name`) VALUES (NULL,$1,$2);\nExecuting (default): INSERT INTO `Cities` (`id`,`parent_country`,`city_name`) VALUES (NULL,$1,$2);\nExecuting (default): INSERT INTO `Cities` (`id`,`parent_country`,`city_name`) VALUES (NULL,$1,$2);\nExecuting (default): SELECT `City`.`id`, `City`.`parent_country`, `City`.`city_name`, `Country`.`id` AS `Country.id`, `Country`.`country_name` AS `Country.country_name` FROM `Cities` AS `City` LEFT OUTER JOIN `Countries` AS `Country` ON `City`.`parent_country` = `Country`.`country_name` WHERE `City`.`parent_country` = 'germany';\n```\n\n```text\nCREATE TABLE IF NOT EXISTS `Cities` (\n  `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n  `parent_country` VARCHAR(255) REFERENCES `Countries` (`country_name`) ON DELETE CASCADE ON UPDATE CASCADE,\n  `city_name` VARCHAR(255));\n```\n\n```text\nON `City`.`parent_country` = `Country`.`country_name`\n```\n\n```text\nhasMany({ sourceKey\n```\n\n```text\nbelongsTo({ targetKey\n```\n\n```text\nsourceKey\n```\n\n```text\nREFERENES\n```\n\n========================================\n\nComments:\n- confirm `sourceKey` works. the `targetKey` does not work, it returns wrong result","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":533,"estimatedTokens":3372}}505{"id":"stack-22002698","source":"stackoverflow","questionId":22002698,"title":"Sequelize, custom setter, doesn't set","tags":["node.js","sequelize.js"],"text":"Title: Sequelize, custom setter, doesn't set\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUnfortunatly the documentation for model property setters and getters is somewhat deficient and I'm having trouble getting my little setter to work.\n\n```\nvar bcrypt = require('bcrypt');\n\nmodule.exports = function( sequelize, DataTypes )\n{\n var User = sequelize.define('User', {\n username: { type:DataTypes.STRING, unique: true, allowNull: false },\n email: { type:DataTypes.STRING, allowNull: false, unique: true },\n userlevel: { type:DataTypes.INTEGER, allowNull:false, defaultValue:0 },\n password: { type:DataTypes.STRING, \n set: function(v) {\n var pw = this;\n var r;\n bcrypt.genSalt(10, function(err,salt) {\n bcrypt.hash(v, salt, function(err,hash) {\n pw.setDataValue('password', hash);\n });\n });\n } }\n });\n\n return User;\n}\n```\n\nNow from what I can tell based on github issues custom setters on properties are not called on create() so calling\n\n```\ndb.User.create( { username:'guest', email:'guest@guest', userlevel:1, password:'guest' } ).success( function(record) { console.log(record) });\n```\n\nresults in the following insert:\n\n```\nExecuting (default): INSERT INTO `Users` (`id`,`username`,`email`,`userlevel`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'guest','guest@guest',100,'2014-02-25 01:05:17','2014-02-25 01:05:17');\n```\n\nso I went ahead and added the following in the success clause:\n\n```\nu.set('password', 'stupid');\nu.save();\n```\n\nI can see that my setter is getting properly called and that the hash is getting set on the password property. However once the setter ends and I return back to my u.save() line the u object is back to it's previous state with no password set.\n\nAny ideas?\n\n========================================\n\nCode:\n```text\nvar bcrypt = require('bcrypt');\n\nmodule.exports = function( sequelize, DataTypes )\n{\n    var User = sequelize.define('User', {\n        username:       { type:DataTypes.STRING, unique: true, allowNull: false },\n        email:          { type:DataTypes.STRING, allowNull: false, unique: true },\n        userlevel:      { type:DataTypes.INTEGER, allowNull:false, defaultValue:0 },\n        password:       { type:DataTypes.STRING, \n            set: function(v) {\n                var pw = this;\n                var r;\n                bcrypt.genSalt(10, function(err,salt) {\n                    bcrypt.hash(v, salt, function(err,hash) {\n                        pw.setDataValue('password', hash);\n                    });\n                });\n            } }\n    });\n\n\n\n    return User;\n}\n```\n\n```text\ndb.User.create( { username:'guest', email:'guest@guest', userlevel:1, password:'guest' } ).success( function(record) { console.log(record) });\n```\n\n```text\nExecuting (default): INSERT INTO `Users` (`id`,`username`,`email`,`userlevel`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'guest','guest@guest',100,'2014-02-25 01:05:17','2014-02-25 01:05:17');\n```\n\n```text\nu.set('password', 'stupid');\nu.save();\n```\n\n```text\nvar User = sequelize.define('User', {\n    username:       { type: DataTypes.STRING,  allowNull: false, unique: true   },\n    email:          { type: DataTypes.STRING,  allowNull: false, unique: true   },\n    userlevel:      { type: DataTypes.INTEGER, allowNull:false,  defaultValue:0 },\n    password:       {\n        type: Sequelize.STRING,\n        set:  function(v) {\n            var salt = bcrypt.genSaltSync(10);\n            var hash = bcrypt.hashSync(v, salt);\n\n            this.setDataValue('password', hash);\n        }\n    }\n})\n```\n\n========================================\n\nComments:\n- Hooks/life cycle events for Sequelize are async, together with .changed() once could implement hashing in a hook if the password field has changed.\n- Does it say somehwere in the docs that getters and setters are sync only? I would love to be able to blame myself for just speed reading past it instead of wasting a good hour poking and prodding at this issue.\n- Actually the docs are super ugly at the moment when it comes to getters/setters. We will work on that.\n- Please not if you use this, validations will fail to work\n- The setter is not invoked when you use the findOrCreate method. The password is stored as-is and not as its hash. Why is that? Checked back. If raw is true for above method, it will not invoke the setters.","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":123,"estimatedTokens":1074}}506{"id":"stack-66487330","source":"stackoverflow","questionId":66487330,"title":"Cannot find module 'sequelize/types'","tags":["mysql","node.js","sequelize.js","sequelize-cli"],"text":"Title: Cannot find module 'sequelize/types'\nTags: mysql, node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nanyone knows why i am getting this error\nthis is my code\n\n```\n\"use strict\";\nconst { DataTypes } = require(\"sequelize/types\");\n\nmodule.exports = {\n up: async (queryInterface, DataTypes) => {\n await queryInterface.createTable(\"dummytables\", {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: DataTypes.INTEGER,\n },\n id: {\n type: DataTypes.NUMBER,\n },\n first_name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n last_name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n });\n },\n down: async (queryInterface, DataTypes) => {\n await queryInterface.dropTable(\"dummytables\");\n },\n};\n```\n\nwhen am trying to run this command `sequelize db:migrate`\nand its showing me `ERROR: Cannot find module 'sequelize/types'`\n\nmy dependencies file\n\n```\n\"dependencies\": {\n\"@types/sequelize\": \"^4.28.9\",\n \"express\": \"^4.17.1\",\n \"mysql2\": \"^2.2.5\",\n \"sequelize\": \"^6.5.0\",\n \"sequelize-cli\": \"^6.2.0\" }\n```\n\nany solution need help\n\n========================================\n\nTop Answer:\nIf you change the second line to;\n\n```\nconst { DataTypes } = require(\"sequelize\");\n```\n\nIt should work fine.\n\n========================================\n\nCode:\n```text\n\"use strict\";\nconst { DataTypes } = require(\"sequelize/types\");\n\nmodule.exports = {\n  up: async (queryInterface, DataTypes) => {\n    await queryInterface.createTable(\"dummytables\", {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: DataTypes.INTEGER,\n      },\n      id: {\n        type: DataTypes.NUMBER,\n      },\n      first_name: {\n        type: DataTypes.STRING,\n        allowNull: false,\n      },\n      last_name: {\n        type: DataTypes.STRING,\n        allowNull: false,\n      },\n    });\n  },\n  down: async (queryInterface, DataTypes) => {\n    await queryInterface.dropTable(\"dummytables\");\n  },\n};\n```\n\n```text\n\"dependencies\": {\n\"@types/sequelize\": \"^4.28.9\",\n    \"express\": \"^4.17.1\",\n    \"mysql2\": \"^2.2.5\",\n    \"sequelize\": \"^6.5.0\",\n    \"sequelize-cli\": \"^6.2.0\"  }\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nERROR: Cannot find module 'sequelize/types'\n```\n\n```text\n\"use strict\";\n//const { DataTypes } = require(\"sequelize/types\"); // Remove this line\n\nmodule.exports = {\n  up: async (queryInterface, DataTypes) => {\n    await queryInterface.createTable(\"dummytables\", {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: DataTypes.INTEGER,\n      },\n      id: {\n        type: DataTypes.NUMBER,\n      },\n      first_name: {\n        type: DataTypes.STRING,\n        allowNull: false,\n      },\n      last_name: {\n        type: DataTypes.STRING,\n        allowNull: false,\n      },\n    });\n  },\n  down: async (queryInterface, DataTypes) => {\n    await queryInterface.dropTable(\"dummytables\");\n  },\n};\n```\n\n```text\nconst { DataTypes } = require(\"sequelize\");\n```\n\n```text\nfirst_name: {\n    type: Sequelize.STRING,\n    allowNull: false,\n},\n```\n\n```text\nasync up(queryInterface, Sequelize) {\n    ...\n}\n```\n\n```text\nconst Sequelize = require(\"sequelize\");\n```\n\n```text\nDataTypes\n```\n\n```text\nSequelize\n```\n\n```text\nconst {DataTypes} = require('sequelize');\n```\n\n========================================\n\nComments:\n- Are you sure you have that module installed? Show me the dependencies part in the package.json file.\n- `{ \"name\": \"sqlSequelize\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"app.js\", \"dependencies\": { \"express\": \"^4.17.1\", \"mysql2\": \"^2.2.5\", \"sequelize\": \"^6.5.0\" }, \"devDependencies\": {}, \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\" }` @m_hm0ud see\n- Are you using typescript?\n- not using typescript @m_hm0ud\n- Well I searched on npm website and there's no such package called sequelize/types. There's @types/sequelize which is for making sequelize compatible with typescript.\n- i tried that too but no help @m_hm0ud but thank you\n- This question could have an answer for you: stackoverflow.com/questions/65204670/&hellip;\n- github.com/nkhs/node-sequelize : there is migration sample files\n- The better way is to replace the `Sequelize` parameter in the async callback to `DataTypes`, Importing `DataTypes` and presence of `Sequelize` can lead to certain conflicts, atleast that's what I think","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":196,"estimatedTokens":1099}}507{"id":"stack-57522774","source":"stackoverflow","questionId":57522774,"title":"SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize as an ORM to my node js app and Mysql database , \nafter following some tutorials i m adding this code to connect mysql to the node but after taping npm start i m getting this error : \nUnable to connect to the database: { SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306\n\n```\nconst Sequelize = require('sequelize');\n\n // Option 1: Passing parameters separately\n const sequelize = new Sequelize('Education', 'root','', {\n host: '127.0.0.1',\n dialect: 'mysql'\n } );\n\n //test db \n sequelize\n.authenticate()\n.then(() => {\n console.log('Connection has been established successfully.');\n})\n .catch(err => {\n console.error('Unable to connect to the database:', err);\n});\n```\n\n========================================\n\nTop Answer:\nFIX for Node.js use:\n\nIt looks as though the current version of sequelize (7) only works on Node.js versions `^12.22.0`, `^14.17.0` & `^16.0.0`. `www.sequelize.org` says that some other versions may work as well.\n\nUse NVM to install and switch to version 16.0.0:\n\nIf you don't already have node version manager you can install it with\n\n```\n$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash\n```\n\nThen install version 16 with `nvm i 16.0.0` and then tell your application to use it with `nvm use 16.0.0`.\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\n\n // Option 1: Passing parameters separately\n const sequelize = new Sequelize('Education', 'root','', {\n host: '127.0.0.1',\n dialect: 'mysql'\n } );\n\n  //test db \n sequelize\n.authenticate()\n.then(() => {\n  console.log('Connection has been established successfully.');\n})\n .catch(err => {\n console.error('Unable to connect to the database:', err);\n});\n```\n\n```js\n// Option 1: Passing parameters separately\nconst sequelize = new Sequelize('Education', 'root', '', {\n  host: '127.0.0.1',\n  dialect: 'mysql',\n  dialectOptions: {\n    socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'\n  }\n});\n```\n\n```text\nsocketPath\n```\n\n```text\nconst sequelize = new Sequelize('dbname', 'dbuser', 'pass', {\n    dialect: 'mysql',\n    host: \"127.0.0.1\",\n    operatorAlias:false,\n    logging:false,\n    pool: {\n        max: 5,\n        idle: 30000,\n        acquire: 60000,\n    },\n    \n})\n```\n\n```text\n$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash\n```\n\n```text\n^12.22.0\n```\n\n```text\n^14.17.0\n```\n\n```text\n^16.0.0\n```\n\n```text\nwww.sequelize.org\n```\n\n```text\nnvm i 16.0.0\n```\n\n```text\nnvm use 16.0.0\n```\n\n========================================\n\nComments:\n- Do you have mysql server setup on your machine?\n- Do you have same error if you replace '127.0.0.1' with 'localhost'?\n- Problem solved i was using port : 3307 in phpMyadmin instead of 3306 ,\n- I had the same error, and with your help it worked. But why do you have to put socketPath? Why doesn't it just work with host and dialect? In production do I have to leave the socketPath? Thanks.\n- Removing the port option could work only in your set-up. As the author mentioned afterwards, on their set-up their port was different than the default, and thus was the connection error.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":136,"estimatedTokens":878}}508{"id":"stack-19139671","source":"stackoverflow","questionId":19139671,"title":"Sequelize — use UNIX timestamp for DATE fields","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize — use UNIX timestamp for DATE fields\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to force Sequelize use UNIX Timestamp as default time format **both** for createdAt/updatedAt timestamps **and** for custom-defined Sequelize.DATE field types?\n\nThanks!\n\nP.S. I'm using MySQL\n\n========================================\n\nTop Answer:\nWhile `eggyal`'s answer is the proper way to do things in MySQL, some of us might be working in an environment or team that requires us to use a unix timestamp instead of a datetime / timestamp. \n\nI found that a great way to accomplish this is to use hooks inside of sequelize. At the bottom of each of your models, you can add this code:\n\n```\n{\n tableName: 'Addresses',\n hooks : {\n beforeCreate : (record, options) => {\n record.dataValues.createdAt = Math.floor(Date.now() / 1000);\n record.dataValues.updatedAt = Math.floor(Date.now() / 1000);\n },\n beforeUpdate : (record, options) => {\n record.dataValues.updatedAt = Math.floor(Date.now() / 1000);\n }\n }\n }\n```\n\nThis will insert the `createdAt` and `updatedAt` fields as unix timestamps.\n\n========================================\n\nCode:\n```text\n946684800\n```\n\n```text\n2000-01-01 00:00:00Z\n```\n\n```text\nDATE\n```\n\n```text\n{\n        tableName: 'Addresses',\n        hooks : {\n            beforeCreate : (record, options) => {\n                record.dataValues.createdAt = Math.floor(Date.now() / 1000);\n                record.dataValues.updatedAt = Math.floor(Date.now() / 1000);\n            },\n            beforeUpdate : (record, options) => {\n                record.dataValues.updatedAt = Math.floor(Date.now() / 1000);\n            }\n        }\n    }\n```\n\n```text\neggyal\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n========================================\n\nComments:\n- Thanks, I thought about such solition. But what about &#171;However then you're sacrificing the functionality of sequelize.&#187;? You mean I wont be able to perform some date-specified queries?\n- sequelize maps objects to tables. That mapping provides a object oriented interface to the database. Without those values being set, sequelize won't be able to check if the object has been updated. You will have have to rewrite that logic.\n- Storing unix time is a valid way to store time (generally speaking) - interpreting the local Date/Time from it is just a matter of calculating the local/seasonal offset from the UTC time.\n- @rjarmstrong: Isn't that exactly what my answer says? My point was that the OP was asking how to store a date (and a date alone) using a timestamp.\n- The problem is you said that the DATE data type is the correct way to store a date - which is misleading. I'm happy to remove down vote if you qualify this statement with something like 'in Sequelize the recommended way is to use the DATE type'. Unfortunately the Sequelize DATE type also has a limitation in that it does not store milliseconds from what I can tell which may indicate why the timestamp was of interest.\n- @rjarmstrong, I wouldn't agree even with 'in Sequelize the recommended way is to use the DATE type'. It really depends on what exactly you want to store. When you say you want to store \"date\", you must understand whether you want to store the date as the client perceives it (a local time, a time selected in a calendar), or you want to record an unambiguous point in time (regardless of its client-side representation). By Unix timestamp you can determine the exact point in time. By date you can determine the client-side representation. To get both you need some extra info in both cases.\n- 99% of the time the correct way to store a date is as an duration from the epoch e.g. UNIX timestamps. Then when you present it to the user, you ask the OS/browser to do so according to the user's system settings. People obsess about timezones but some users are not even using a Gregorian calendar (!!!).\n- The fields `tableName` and `hooks` are part of the options object of a model. It's the argument after the attributes object when using .define()","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":88,"estimatedTokens":1014}}509{"id":"stack-56334073","source":"stackoverflow","questionId":56334073,"title":"sequelize.js addIndex not using indexName","tags":["mysql","node.js","sequelize.js"],"text":"Title: sequelize.js addIndex not using indexName\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create an index using sequelize.js addIndex function, the index is created but not with the name specified in the indexName option.\n\nI am using the code below\n\n```\nqueryInterface.addIndex('Item',\n ['name', 'description'], {\n indicesType: 'FULLTEXT',\n indexName: 'idx_item_fulltext'\n })\n```\n\nAfter running migration, the index is created with the name 'item_name_description' and not 'idx_item_fulltext' which is the name I specified.\n\n========================================\n\nCode:\n```text\nqueryInterface.addIndex('Item',\n  ['name', 'description'], {\n    indicesType: 'FULLTEXT',\n    indexName: 'idx_item_fulltext'\n  })\n```\n\n```js\nqueryInterface.addIndex('Item', ['name', 'description'], {\n    type: 'FULLTEXT',\n    name: 'idx_item_fulltext'\n})\n```\n\n```text\nsequelize-cli\n```\n\n```text\nsequelize\n```\n\n```text\n5+\n```\n\n```text\nindicesType\n```\n\n```text\nindexName\n```\n\n========================================\n\nComments:\n- I guess `indicesType` does not work as well\n- Could you paste `Seqeulize` version you're using?","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":62,"estimatedTokens":287}}510{"id":"stack-34831639","source":"stackoverflow","questionId":34831639,"title":"how to remove relation for specific instances with sequelize / mysql","tags":["javascript","mysql","node.js","database","sequelize.js"],"text":"Title: how to remove relation for specific instances with sequelize / mysql\nTags: javascript, mysql, node.js, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI created a many-to-many association between courses and users like this:\n\n```\nCourse.belongsToMany(User, { through: 'CourseUser'});\nUser.belongsToMany(Course, { through: 'CourseUser'});\n```\n\nwhich generates a join table called CourseUser.\n\nI add a relation for a specific course and user with the following server side function that happens on the click of a button:\n the userCourse variable looks like this: { UserId: 7, CourseId: 13 }\n\n```\naddUser: function(req, res) {\n var userCourse = req.body;\n db.CourseUser.create(userCourse).then(function () {\n res.sendStatus(200);\n });\n }\n```\n\nIs this the correct way of adding the association between an existing user and an existing course? (if not, what is the correct way)\n\nI would like to have an ability of removing the association when clicking on another button. But I can't quite figure out how to set up the function.\n\n========================================\n\nTop Answer:\nYour model relationship is okay: \n\n```\nCourse.belongsToMany(User, { through: 'CourseUser'}); User.belongsToMany(Course, { through: 'CourseUser'});\n```\n\nand values: \n\n`{ UserId: 7, CourseId: 13 }`\n\nImplementation could look thus for adding a UserCourse relationship: \n\n```\naddUser: function(req, res) {\n const { UserId, CourseId } = req.body;\n db.Course.findOne({\n where: { id: CourseId }\n }).then(course => {\n course.setUsers([UserId])\n res.sendStatus(200);\n }).catch(e => console.log(e));\n}\n```\n\nwhile this could handle user detaching:\n\n```\nremoveUser: function (req, res) {\n const { UserId, CourseId } = req.body;\n db.Course.findOne({\n where: { id: CourseId }\n }).then(course => {\n course.removeUsers([UserId])\n res.sendStatus(200);\n }).catch(e => console.log(e));\n}\n```\n\nI hope this will be helpful however\n\n========================================\n\nCode:\n```text\nCourse.belongsToMany(User, { through: 'CourseUser'});\nUser.belongsToMany(Course, { through: 'CourseUser'});\n```\n\n```text\naddUser: function(req, res) {\n    var userCourse = req.body;\n    db.CourseUser.create(userCourse).then(function () {\n      res.sendStatus(200);\n    });\n  }\n```\n\n```text\nUser.removeCourse(courseObject);\n```\n\n```text\nCourse.removeUser(userObject);\n```\n\n```text\ndb.CourseUser.destroy({\n    where: {...}\n});\n```\n\n```text\ncourseUser.destroy();\n```\n\n```text\nUser\n```\n\n```text\nCourse\n```\n\n```text\naddUser\n```\n\n```text\nUser\n```\n\n```text\nCourse\n```\n\n```text\nCourseUser\n```\n\n```text\nCourseUser\n```\n\n```text\nCourseUser\n```\n\n```text\n.then\n```\n\n```text\n.catch\n```\n\n```text\nCourse.belongsToMany(User, { through: 'CourseUser'}); User.belongsToMany(Course, { through: 'CourseUser'});\n```\n\n```text\naddUser: function(req, res) {\n    const { UserId, CourseId } = req.body;\n    db.Course.findOne({\n        where: { id: CourseId }\n    }).then(course => {\n        course.setUsers([UserId])\n        res.sendStatus(200);\n    }).catch(e => console.log(e));\n}\n```\n\n```text\nremoveUser: function (req, res) {\n    const { UserId, CourseId } = req.body;\n    db.Course.findOne({\n        where: { id: CourseId }\n    }).then(course => {\n        course.removeUsers([UserId])\n        res.sendStatus(200);\n    }).catch(e => console.log(e));\n}\n```\n\n```text\n{ UserId: 7, CourseId: 13 }\n```\n\n========================================\n\nComments:\n- Please accept my answer if it answered your question or tell me in a comment what part is still unclear to you.","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":184,"estimatedTokens":876}}511{"id":"stack-47795113","source":"stackoverflow","questionId":47795113,"title":"Insert/Update PostGis Geometry with Sequelize ORM","tags":["sequelize.js","postgis","geojson"],"text":"Title: Insert/Update PostGis Geometry with Sequelize ORM\nTags: sequelize.js, postgis, geojson\nSource: Stack Overflow\n\nQuestion:\nI have extracted models of some PostGis layers with sequelize-auto, giving:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('table', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n geom: {\n type: DataTypes.GEOMETRY('POINT', 4326),\n allowNull: true,\n },\n...\n```\n\nOn GET sequelize sends the geom to the client as GeoJSON:\n\n```\n{\n \"type\":\"Point\",\n \"coordinates\":[11.92164103734465,57.67219297300486]\n}\n```\n\nWhen I try to save this back PosGis errors with:\n\n```\nERROR: Geometry SRID (0) does not match column SRID (4326)\n```\n\nThis answer gives a god indication of how to add the SRID (How to insert a PostGIS GEOMETRY Point in Sequelize ORM?),\n\n```\nvar point = { \n type: 'Point', \n coordinates: [39.807222,-76.984722],\n crs: { type: 'name', properties: { name: 'EPSG:4326'} }\n};\n\nUser.create({username: 'username', geometry: point }).then(function(newUser) {\n...\n});\n```\n\nI understand that SRID used to be a feature that was removed from sequelize (https://github.com/sequelize/sequelize/issues/4054).\n\nDoes anyone know a way to hook into Sequelize so that the srid is added to the GeoJson sent to PostGis? Where to put it? In a setter on the model?\n\n========================================\n\nTop Answer:\nDeclare the column type as: `DataTypes.GEOMETRY('Point')`, \n\nSet the model attribute as:\n\n```\n{\n type: 'Point',\n coordinates: [ lat, long ],\n crs: { type: 'name', properties: { name: 'EPSG:4326'} }\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('table', {\n  id: {\n    type: DataTypes.INTEGER,\n    allowNull: false,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  geom: {\n    type: DataTypes.GEOMETRY('POINT', 4326),\n    allowNull: true,\n  },\n...\n```\n\n```text\n{\n  \"type\":\"Point\",\n  \"coordinates\":[11.92164103734465,57.67219297300486]\n}\n```\n\n```text\nERROR:  Geometry SRID (0) does not match column SRID (4326)\n```\n\n```text\nvar point = { \n  type: 'Point', \n  coordinates: [39.807222,-76.984722],\n  crs: { type: 'name', properties: { name: 'EPSG:4326'} }\n};\n\nUser.create({username: 'username', geometry: point }).then(function(newUser) {\n...\n});\n```\n\n```text\nmyDatabase.define('user', {\n  name: {\n    type: Sequelize.STRING\n  },\n  geometry: {\n    type: Sequelize.GEOMETRY('POINT', 4326)\n  }\n}, {\n  hooks: {\n    beforeSave: function(instance) {\n      if (instance.geometry && !instance.geometry.crs) {\n        instance.geometry.crs = {\n          type: 'name',\n          properties: {\n            name: 'EPSG:4326'\n          }\n        };\n      }\n    }\n  }\n});\n```\n\n```text\nGEOMETRY\n```\n\n```text\nGEOGRAPHY\n```\n\n```text\nGEOMETRY\n```\n\n```text\nbeforeSave\n```\n\n```text\n{\n  type: 'Point',\n  coordinates: [ lat, long ],\n  crs: { type: 'name', properties: { name: 'EPSG:4326'} }\n}\n```\n\n```text\nDataTypes.GEOMETRY('Point')\n```\n\n========================================\n\nComments:\n- Thanks @mcranston18, that's what I was looking for. As you say, not ideal, but I shall use it :)\n- I've tried this, without joy. beforeSave (sequelize v4.20) isn't getting called - I've put a console.log in that never shows. I can't post the code here, but it looks more or less as yours. Any ideas?\n- Now posted new question, with code: stackoverflow.com/questions/48358408/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.382Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":171,"estimatedTokens":864}}512{"id":"stack-41664565","source":"stackoverflow","questionId":41664565,"title":"How to concat columns in Sequelize with SQLite database","tags":["sqlite","express","sequelize.js"],"text":"Title: How to concat columns in Sequelize with SQLite database\nTags: sqlite, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize for a express project I'm working on.\n\nIn one query I want to retrieve a concatenated result of two columns.\n\nLike:\n\n```\nSELECT first_name || ' ' || last_name AS full_name FROM table\n```\n\nI tried the following syntax and got an error\n\n```\nrouter.get('/persons', function(req, res, next) {\n models.Person.findAll({\n attributes: [models.sequelize.fn('CONCAT', 'first_name', 'last_name')]\n })\n .then(function(persons) {\n res.send(persons);\n });\n});\n```\n\nThe error message:\n\n```\nSELECT CONCAT('first_name', 'last_name') FROM `Persons` AS `Person`;\nPossibly unhandled SequelizeDatabaseError: Error: SQLITE_ERROR: no such function: CONCAT\n```\n\n========================================\n\nTop Answer:\nThis is working for me. Instead of use setter and getter methods\n\n========================================\n\nCode:\n```text\nSELECT first_name || ' ' || last_name AS full_name FROM table\n```\n\n```text\nrouter.get('/persons', function(req, res, next) {\n  models.Person.findAll({\n    attributes: [models.sequelize.fn('CONCAT', 'first_name', 'last_name')]\n  })\n    .then(function(persons) {\n      res.send(persons);\n    });\n});\n```\n\n```text\nSELECT CONCAT('first_name', 'last_name') FROM `Persons` AS `Person`;\nPossibly unhandled SequelizeDatabaseError: Error: SQLITE_ERROR: no such function: CONCAT\n```\n\n```text\nrouter.get('/persons', function(req, res, next) {\n  models.Person.findAll({\n    attributes: [models.sequelize.literal(\"first_name || ' ' || last_name\"), 'full_name']\n  })\n    .then(function(persons) {\n      res.send(persons);\n    });\n});\n```\n\n```text\nmodels.sequelize.literal\n```\n\n```text\nconst { fn, col } = Person.sequelize;\n\nconst res = Person.findAll({\n   attributes: [ [fn('concat', col('first_name'), ' ', col('last_name')), \"FullName\"], ...OthersColumns ]\n})\n```\n\n========================================\n\nComments:\n- Have you tried using `literal`? I don't have Sequelize set up anywhere so I can't check but maybe something like `models.sequelize.literal(\"first_name || ' ' || last_name\")` would work.\n- Thank you! it's working now (:\n- How can I concat string with column value of attributes?\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":93,"estimatedTokens":624}}513{"id":"stack-57542074","source":"stackoverflow","questionId":57542074,"title":"Sequelize findOne returned instance. Row is in dataValues, but direct properties on instance are undefined","tags":["node.js","sequelize.js"],"text":"Title: Sequelize findOne returned instance. Row is in dataValues, but direct properties on instance are undefined\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**Context**: I'm testing a simple model into and out of the database. Not a real test, it's a precursor to some integration tests. Using **Sequelize** and **`findOne`**.\n\n**The problem**: The direct data on the returned model instance, i.e. email.ulid, email.address, email.isVerified are undefined.\n\n**My question**: Why are they undefined?\n\n```\nSequelize: 5.15.0\nTypescript: 3.5.3\nmysql Ver 15.1 Distrib 10.4.6-MariaDB\n```\n\n*Record into database*:\n\n```\nawait testingDatabase.sync({\n force: true\n}).then(async () => {\n await Email.create({\n ulid: the_ulid.bytes,\n address: \"dave@world.com\",\n isVerified: false\n })\n})\n```\n\n*Fetch the record back:*\n\n```\nawait Email.findOne({\n where: { \n address: \"dave@world.com\"\n }\n , rejectOnEmpty: true //to shut typescript up\n}).then( emailData => {\n console.log(\"Email: \", email)\n})\n```\n\n*Console.log* of `email` instance:\n\n```\nEmail: Email { \n dataValues: { \n ulid: , \n address: 'dave@world.com', \n isVerified: false, \n deletedAt: null, \n createdAt: 2019-08-18T05:32:05.000Z, \n updatedAt: 2019-08-18T05:32:05.000Z \n }, \n ...,\n isNewRecord: false,\n ulid: undefined,\n address: undefined,\n isVerified: undefined,\n createdAt: undefined,\n updatedAt: undefined,\n deletedAt: undefined\n }\n```\n\n^^^ As is clear, immediately above, all of the direct attributes on the instance are null.\n\n**The following works**, but with the side-effect that `isVerified` is returned as a `0` rather than `false` and subsequently fails a direct comparison with the original data. Additionally, I lose other functionality of the model instance that will come in handy on more complex models:\n\n```\nEmail.findOne({\n where: { address: \"dave@world.com\" }\n, raw: true \n, rejectOnEmpty: true\n})\n```\n\n**These also work**, but with the consequence that Typescript complains about the returned object not having the properties I then access (although they do exist and the test works):\n\n```\n.then( emailData => {\n console.log(\"All getters: \", emailData.get())\n // AND\n console.log(\"All getters(plain): \", emailData.get({plain: true}))\n // AND\n console.log(\"toJSON: \", emailData.toJSON())\n})\n```\n\n**This next one (suggested by Vivek)**, works insofar as the data is available, but JSON.parse fails to handle the Buffer properly:\n\n```\nconst dataOnly = JSON.parse(JSON.stringify(emailData))\n```\n\nOthers have complained (SE answer) that console.log somehow misprints the instance, yet every other way I access these properties they are still undefined.\n\n========================================\n\nTop Answer:\nI hit the same issue but in a slightly different context.\n\nMy solution was **not** to use the `ESNext` target in my tsconfig.json. Using `ES2021` or any other target solved the problem.\n\n========================================\n\nCode:\n```text\nSequelize: 5.15.0\nTypescript: 3.5.3\nmysql  Ver 15.1 Distrib 10.4.6-MariaDB\n```\n\n```text\nawait testingDatabase.sync({\n  force: true\n}).then(async () => {\n  await Email.create({\n    ulid: the_ulid.bytes,\n    address: \"dave@world.com\",\n    isVerified: false\n  })\n})\n```\n\n```text\nawait Email.findOne({\n  where: { \n    address: \"dave@world.com\"\n  }\n  , rejectOnEmpty: true //to shut typescript up\n}).then( emailData => {\n   console.log(\"Email: \", email)\n})\n```\n\n```text\nEmail:  Email {                                                                                                                                                      \n      dataValues: {                                                                                                                                                      \n        ulid: <Buffer 01 6c a3 36 11 9c 1e 9b a6 ce 60 b7 33 3e e7 21>,                                                                                                  \n        address: 'dave@world.com',                                                                                                                                    \n        isVerified: false,                                                                                                                                               \n        deletedAt: null,                                                                                                                                                 \n        createdAt: 2019-08-18T05:32:05.000Z,                                                                                                                             \n        updatedAt: 2019-08-18T05:32:05.000Z                                                                                                                              \n      },                                                                                                                                                                 \n      ...,\n      isNewRecord: false,\n      ulid: undefined,\n      address: undefined,\n      isVerified: undefined,\n      createdAt: undefined,\n      updatedAt: undefined,\n      deletedAt: undefined\n    }\n```\n\n```text\nEmail.findOne({\n  where: { address: \"dave@world.com\" }\n, raw: true \n, rejectOnEmpty: true\n})\n```\n\n```text\n.then( emailData => {\n  console.log(\"All getters: \", emailData.get())\n  // AND\n  console.log(\"All getters(plain): \", emailData.get({plain: true}))\n  // AND\n  console.log(\"toJSON: \", emailData.toJSON())\n})\n```\n\n```text\nconst dataOnly = JSON.parse(JSON.stringify(emailData))\n```\n\n```text\nfindOne\n```\n\n```text\nemail\n```\n\n```text\nisVerified\n```\n\n```text\n0\n```\n\n```text\nfalse\n```\n\n```text\n\"@babel/proposal-class-properties\"\n```\n\n```text\nplugins: [\n  \"@babel/proposal-class-properties\"\n, ...\n]\n```\n\n```text\n_defineProperty(this, \"yourFieldName\", void 0);\n```\n\n```text\nBabel\n```\n\n```text\ndefineProperty()\n```\n\n```text\n_defineProperty()\n```\n\n```text\nundefined\n```\n\n```text\nfindOne\n```\n\n```text\nEmail.findOne({\n  where: { \n    address: \"dave@world.com\"\n  }\n}).then( emailData => {\n   const dataOnly = JSON.parse(JSON.stringify(emailData));\n   console.log(dataOnly); // <--- YOUR DATA\n   console.log(emailData); // <--- YOUR INSTANCE\n})\n```\n\n```text\n.then( emailData => {\n  console.log(\"All getters: \", emailData.get())\n  // AND\n  console.log(\"All getters(plain): \", emailData.get({plain: true}))\n  return emailData.get({plain: true}); // <-- I think you forgot to return this\n});\n```\n\n```text\nJSON.parse\n```\n\n```text\nJSON.stringify\n```\n\n```text\nESNext\n```\n\n```text\nES2021\n```\n\n========================================\n\nComments:\n- I also tried `mapToModel` with `instance` set, in the hope that it would stimulate the model to populate. It did not.\n- Watching github.com/sequelize/sequelize/issues/10917, although this merely addresses the side-effects of some of the workarounds found so far, not the actual question of \"why are they undefined\".\n- Exact same issue 11326 as this question exists on sequelize github.\n- That's a serviceable attempt, thanks. But unfortunately it falls into the growing list of not-quite-right solutions. JSON.parse doesn't handle the Buffer gracefully, instead it names the type and gives an array of decimal numbers.\n- @PaulParker, where did you get this error : \" but with the consequence that Typescript complains about the returned object not having the properties I then access\"\n- This is a typescript error. I can ignore it and the program still functions properly, it just clutters up my editor. I use `@babel&#47;preset-typescript`, which discards typescript on compile, rather than trying to handle typescript errors. This allows production to continue, even in the face of an intractable Typescript problem.\n- Check the updated answer that might solve your error and for you `emailData.get({plain: true})` is the perfect solution. @PaulParker\n- I am returning it. The Typescript error arises because I try to delete fields from the data, and Typescript doesn't know of the existence of those fields. Both `.get()` and `.toJSON()` are not giving TS any type information.\n- @PaulParker, in that case, you can ignore that error as its just affecting editors\n- Thanks for taking the time to investigate and answer your own question here to help others :)\n- Agreed, thanks for pointing me in the right direction to solving this. Configuring the plugin to exclude my models folder fixed this for me: stackoverflow.com/questions/61960885/&hellip;\n- Sorry, but I am unable to figure out what the *solution* is. What is the solution?\n- @pihentagy it's been a while, but I believe I removed the plugin above.\n- This should be the accepted solution, as of Sept 2021. Works perfectly.","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":290,"estimatedTokens":2161}}514{"id":"stack-42545624","source":"stackoverflow","questionId":42545624,"title":"In a Nodejs Sequelize model, how to obtain type information of attributes?","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: In a Nodejs Sequelize model, how to obtain type information of attributes?\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a working model with `Postgres` and `sequelize` in `NodeJS`. Say the model is `Person` and has `name` and `age` fields. Now I want to dynamically inspect the model class and obtain information about it's attributes, like their *name* and most of all *type*.\n\nUsing `Person.attributes`\nI get some information:\n\n```\nname:\n{ type:\n { options: [Object],\n _binary: undefined,\n _length: 255 },\n```\n\nBut as you can see the `type` object does not inform about `name` being a `varchar` or `boolean`.\n\nDoes anyone know, how to get this information with `sequelize`\n\n========================================\n\nTop Answer:\nYou are looking for native type information, it seems.\n\nI'm not familiar with Sequelize, except I know it uses `node-postgres` driver underneath, which automatically provides the type information with every query that you make.\n\nBelow is a simple example of **dynamically** getting type details for `any_table`, using pg-promise:\n\n```\nvar pgp = require('pg-promise')(/*initialization options*/);\nvar db = pgp(/*connection details*/);\n\ndb.result('SELECT * FROM any_table LIMIT 0', [], a => a.fields)\n .then(fields => {\n // complete details for each column \n })\n .catch(error => {\n // an error occurred\n });\n```\n\nThere are several fields available for each column there, including `name` and `dataTypeID` that you are looking for ;)\n\n**As an update**, following the answer that does use Sequelize for it...\n\nThe difference is that here we get direct raw values as they are provided by PostgreSQL, so `dataTypeID` is raw type Id exactly as PostgreSQL supports it, while `TYPE: STRING` is an interpreted type as implemented by Sequelize. Also, we are getting the type details dynamically here, versus statically in that Sequelize example.\n\n========================================\n\nCode:\n```text\nname:\n{ type:\n  { options: [Object],\n    _binary: undefined,\n    _length: 255 },\n```\n\n```text\nPostgres\n```\n\n```text\nsequelize\n```\n\n```text\nNodeJS\n```\n\n```text\nPerson\n```\n\n```text\nname\n```\n\n```text\nage\n```\n\n```text\nPerson.attributes\n```\n\n```text\ntype\n```\n\n```text\nname\n```\n\n```text\nvarchar\n```\n\n```text\nboolean\n```\n\n```text\nsequelize\n```\n\n```text\nfor( let key in Model.rawAttributes ){\n    console.log('Field: ', key); // this is name of the field\n    console.log('Type: ', Model.rawAttributes[key].type.key); // Sequelize type of field\n}\n```\n\n```text\nField: name\nType: STRING\n```\n\n```text\nField: name\nType: VARCHAR(255)\n```\n\n```text\nrawAtributes\n```\n\n```text\nname\n```\n\n```text\nSequelize.STRING\n```\n\n```text\nModel.rawAttributes[key].type.key\n```\n\n```text\nModel.rawAttributes[key].type.toSql()\n```\n\n```text\ndefaultValue\n```\n\n```text\nModel.rawAttributes[field].defaultValue\n```\n\n```text\nNULL\n```\n\n```text\nModel.rawAttributes[field].allowNull\n```\n\n```text\nvar pgp = require('pg-promise')(/*initialization options*/);\nvar db = pgp(/*connection details*/);\n\ndb.result('SELECT * FROM any_table LIMIT 0', [], a => a.fields)\n    .then(fields => {\n        // complete details for each column \n    })\n    .catch(error => {\n        // an error occurred\n    });\n```\n\n```text\nnode-postgres\n```\n\n```text\nany_table\n```\n\n```text\nname\n```\n\n```text\ndataTypeID\n```\n\n```text\ndataTypeID\n```\n\n```text\nTYPE: STRING\n```\n\n========================================\n\nComments:\n- Any progress here?\n- The author emphasized in his question that he wants to get it dynamically. If I'm not mistaken, this is a static approach.\n- He also asked about *how to get this information with sequelize*. Just let him choose the way that fits his needs most, ok?\n- I believe the most valuable thing is to be able to automatically detect when your static model becomes out of date, and needs to be refreshed.\n- I'm satisfied. Thank you very much. Next problem in line: How to get default values and if a column is NULLable?\n- I have edited the answer to show how to access `defaultValue` and `allowNull` of field\n- You should use comments. Remove your posting pls","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":209,"estimatedTokens":1024}}515{"id":"stack-13864508","source":"stackoverflow","questionId":13864508,"title":":Sequelize how set returned data order","tags":["node.js","syntax-error","sequelize.js"],"text":"Title: :Sequelize how set returned data order\nTags: node.js, syntax-error, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've issues set the returned data order of a findAll query with limit and offset, i'm using example code found in the documentation: `order: 'group DESC'` but it throw an error saying:\n\n```\nError: SQLITE_ERROR: near \"group\": syntax error\n```\n\nHere is the complete function.\n\n```\nA_Model.findAll({\n offset:req.query.page * req.query.rows - req.query.rows,\n limit :req.query.rows // TODO: Of course, I put the trailing comma here ;)\n // TODO: order: 'group DESC'\n })\n.success(function (docs) {\n response_from_server.records = count;\n response_from_server.page = req.query.page;\n response_from_server.total = Math.ceil(count / req.query.rows);\n response_from_server.rows = [];\n\n for (item in docs) {\n response_from_server.rows.push({\n id :docs[item].id,\n cell:[\n docs[item].group,\n docs[item].description,\n docs[item].path,\n docs[item].value\n ]\n });\n }\n\n // Return the gathered data.\n res.json(response_from_server);\n})\n.error(function (error) { \n logger.log('error', error);\n});\n```\n\nThanks in advance.\n\n========================================\n\nCode:\n```text\nError: SQLITE_ERROR: near \"group\": syntax error\n```\n\n```text\nA_Model.findAll({\n     offset:req.query.page * req.query.rows - req.query.rows,\n     limit :req.query.rows // TODO: Of course, I put the trailing comma here ;)\n     // TODO: order: 'group DESC'\n    })\n.success(function (docs) {\n    response_from_server.records = count;\n    response_from_server.page = req.query.page;\n    response_from_server.total = Math.ceil(count / req.query.rows);\n    response_from_server.rows = [];\n\n    for (item in docs) {\n        response_from_server.rows.push({\n            id  :docs[item].id,\n            cell:[\n                docs[item].group,\n                docs[item].description,\n                docs[item].path,\n                docs[item].value\n            ]\n        });\n    }\n\n    // Return the gathered data.\n    res.json(response_from_server);\n})\n.error(function (error) {       \n    logger.log('error', error);\n});\n```\n\n```text\norder: 'group DESC'\n```\n\n```text\nA_Model.findAll({\n offset:req.query.page * req.query.rows - req.query.rows,\n limit :req.query.rows,\n order: '`group` DESC'\n})\n```\n\n========================================\n\nComments:\n- An SQL `group by` needs to define an aggregate function to group by. It appears you haven't defined one. Not sure if node.js even has that capability to do aggregates and group-by's.\n- @EricLeschinski: Thanks for your comment. I recently shifted from `mongodb` to `SQLite` and really know very little about `SQL`. Can you show me an example?\n- @EricLeschinski: Just noted: `group` is a column in the database. Maybe it is a reserved word?\n- In SQL, a 'group by' cannot stand alone. It must have an aggregate function, for example, averaging the price by group. Without doing an aggregation operation, grouping it makes no sense. w3schools.com/sql/sql_groupby.asp\n- @EricLeschinski: What I really want is not grouping but order by a variable named `group`.\n- This functionality is achieved by the SQL \"Order by\" syntax. In node.js there is a 'sort()' method, but that might be less efficient than getting it directly from the database in order. w3schools.com/sql/sql_orderby.asp\n- @EricLeschinski: Thanks. Do you know a way to make it work with Sequelize not SQL itself?\n- Tried it in PostgreSQL and it should be `order: 'group DESC'` i.e. without the backquotes.","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":109,"estimatedTokens":872}}516{"id":"stack-64453510","source":"stackoverflow","questionId":64453510,"title":"How to disable unique constraint on composite key in many-to-many relationship?","tags":["sequelize.js"],"text":"Title: How to disable unique constraint on composite key in many-to-many relationship?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen 2 models are associated in a many-to-many relation in Sequelize through a junction table, a composite key is created out of the 2 foreign keys from the 2 models.\nIn the sequelize documentation found here: https://sequelize.org/master/manual/advanced-many-to-many.html\nit says that it's possible to force the table to have a ID privateKey.\n\nA and C are 2 models in a many-to-many relation. The junction table/model is B.\nModels A and C definition is irrelevant for this example.\n\n```\n//Defining the junction table B with the private key ID\nsequelize.define('B', {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n allowNull: false\n }\n}, { timestamps: false });\n\nA.belongsToMany(Profile, { through: B });\nC.belongsToMany(User, { through: B });\n```\n\nEven when adding my ID private key to that table, a unique constraint of those 2 foreign keys still exists. How do I disable that constraint?\n\n========================================\n\nTop Answer:\nAs suggested by the previous answer\n\nA.belongsToMany(Profile, { through: { model: B, unique: false}});\nC.belongsToMany(User, { through: { model: B, unique: false}});\n\nBut you may also have to define a primaryKey, otherwise Sequelize uses a composite key for the table by default\n\n```\nB.init({\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n allowNull: false,\n },\n}, { sequelize });\n```\n\n========================================\n\nCode:\n```text\n//Defining the junction table B with the private key ID\nsequelize.define('B', {\n  id: {\n    type: DataTypes.INTEGER,\n    primaryKey: true,\n    autoIncrement: true,\n    allowNull: false\n  }\n}, { timestamps: false });\n\nA.belongsToMany(Profile, { through: B });\nC.belongsToMany(User, { through: B });\n```\n\n```text\nA.belongsToMany(Profile, { through: { model: B, unique: false}});\nC.belongsToMany(User, { through:  { model: B, unique: false}});\n```\n\n```text\nunique: false\n```\n\n```js\nB.init({\n  id: {\n    type: DataTypes.INTEGER,\n    primaryKey: true,\n    autoIncrement: true,\n    allowNull: false,\n  },\n}, { sequelize });\n```\n\n========================================\n\nComments:\n- Can I also use custom unique columns? Lets say I want to have a third column which has no relationship to another table but should be part of uniqueness?\n- @rasenkantenstein it's quite easy as you just need to define a standard 'unique' index with your combination column arrays in your through model.","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":93,"estimatedTokens":641}}517{"id":"stack-52941122","source":"stackoverflow","questionId":52941122,"title":"How should the data be sent for datatype TIME in Sequelize/ Node JS","tags":["node.js","sql-server","sequelize.js"],"text":"Title: How should the data be sent for datatype TIME in Sequelize/ Node JS\nTags: node.js, sql-server, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a time column in my mssql db. I want to post data through an API to this table, but this field throws the error - \"Conversion failed when converting date and/or time from character string\". I am sending the time field as a string like \"13:00\". When getting the data from db through sequelize, I get as an ISOString like \"1970-01-01T08:00:00.000Z\", but the data on the db is like \"13:00:00\"(hh:mm:ss). I tried sending \"13:00:00\" and \"1970-01-01T08:00:00.000Z\", both do not seem to work.\n\n========================================\n\nCode:\n```text\nvar http = require('http');\nconst Sequelize = require('sequelize');\nconst sequelize = new Sequelize('DBName', 'UserName', 'Password', {\n  host: 'localhost',  \n  port:12672,\n  dialect: 'mssql',\n  options:{\n    encrypt:false,\n    instancename: 'SQLEXPRESS'\n  }\n});\n\n\n\nconst User2 = sequelize.define('user2', {\n  name: {\n    type: Sequelize.STRING\n  },\n  DateTimeCol: {\n    type: Sequelize.DATE\n  },\n  TimeCol: {\n    type: Sequelize.TIME\n  }\n});\n\nUser2.sync().then(() => {\n   User2.create({\n    name: 'Rahul',\n    DateTimeCol: '2018-01-01T08:00:00.000Z',\n    TimeCol: '13:00'\n  });\n  User2.findAll().then(data => console.log(data));\n});\n\n\nvar server = http.createServer(function(req, res) {\nres.writeHead(200);\nres.end();\n});\nserver.listen(8080);\n```\n\n```text\n13:00\n```\n\n```text\n13:00:00\n```\n\n```text\nTime\n```\n\n```text\nTime\n```\n\n```text\nDate\n```\n\n```text\nConversion failed when converting date and/or time from character string\n```\n\n```text\n13:00\n```\n\n```text\nDate\n```\n\n```text\nTime\n```\n\n```text\nDate\n```\n\n========================================\n\nComments:\n- can you post your table structure and your model definition?\n- You can send as a string, what happened was I tried to insert '24:00' which will fail.\n- That is because 24:00 is actually 00:00\n- postgresql.org/docs/9.0/functions-formatting.html Table 9-22. Template Patterns for Date/Time Formatting","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":101,"estimatedTokens":514}}518{"id":"stack-56353479","source":"stackoverflow","questionId":56353479,"title":"Enable only createdAt time stamp and ignore updatedAt timestamp in Sequelize","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: Enable only createdAt time stamp and ignore updatedAt timestamp in Sequelize\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create some records into table with only the createdAt column filled. I want the updatedAt column to not exist how ever when i create a model it automatically generates the createdAt and updatedAt timestamps.\n\nI tried to use `timestamps : false` but the createdAt column contains empty values.\n\n```\nconst MyTable = sequelize.define(\n 'my_table',\n {\n id: {\n type: DataTypes.INTEGER(11),allowNull: false,\n primaryKey: true,autoIncrement: true,\n },\n person_name: {type: DataTypes.STRING(255),allowNull: false},\n created: {type: DataTypes.DATE,allowNull: true},\n },\n {\n tableName: 'my_table',\n timestamps: false,\n createdAt: 'created',\n },\n);\n```\n\nIs it possible to fix this issue in the model itself without doing any change in the query ?\n\n========================================\n\nCode:\n```text\nconst MyTable = sequelize.define(\n  'my_table',\n  {\n    id: {\n      type: DataTypes.INTEGER(11),allowNull: false,\n      primaryKey: true,autoIncrement: true,\n    },\n    person_name: {type: DataTypes.STRING(255),allowNull: false},\n    created: {type: DataTypes.DATE,allowNull: true},\n  },\n  {\n    tableName: 'my_table',\n    timestamps: false,\n    createdAt: 'created',\n  },\n);\n```\n\n```text\ntimestamps : false\n```\n\n```text\n{\n    tableName: 'my_table',\n    updatedAt: false,\n  }\n```\n\n```text\nupdatedAt\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":66,"estimatedTokens":369}}519{"id":"stack-33324887","source":"stackoverflow","questionId":33324887,"title":"Sequelize-auto for SQLite","tags":["node.js","sqlite","sequelize.js"],"text":"Title: Sequelize-auto for SQLite\nTags: node.js, sqlite, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to autogenerate my data models on sequelize for SQLite using squelize-auto on Windows. I have created my sqlite file with schema only, no data inside.\nAlso installed everything as indicated here.\n\nThe command I'm using looks like this:\n\n```\nsequelize-auto -h localhost -u dontcare -d \"E:\\full\\path\\to\\my\\database.db\" --dialect sqlite\n```\n\nAlso tried with some other path styles like './database.db' etc.\n\nAnd this is the answer I'm getting:\n\n```\nExecuting (default): SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';\nDone!\n```\n\nAfter this, the script creates a folder called \"models\" with nothing inside.\n\nDoes somebody know what's happening here?\n\nMany thanks!\n\n========================================\n\nCode:\n```text\nsequelize-auto -h localhost -u dontcare -d \"E:\\full\\path\\to\\my\\database.db\"  --dialect sqlite\n```\n\n```text\nExecuting (default): SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';\nDone!\n```\n\n```text\nsequelize-auto -h localhost -u dontcare -d databasename  --dialect sqlite -c options.json\n```\n\n```text\n{\n    \"storage\":\"./database_file_name.db\"\n}\n```\n\n========================================\n\nComments:\n- Hi @pepe , I am new to use sequelize-auto .So could you please help me to fix my error and my error is (stackoverflow.com/questions/34525480/&hellip;) please see this link , this is my error.So please guide me ..I am using windows 7 32bit and running my nodejs program on Enide 2015.\n- But what *is* the database name? The filename?\n- sequelize-auto uses sequelize, so you can use the sequelize examples for the various dialects\n- so what is the database name? has anyone figure this out?\n- @NiallFarrington for the sake of SQLite you don't need to specify host user and database values, as your database is just a file whose name has to be indicated in options.json. If you can't skip them on the command, use any value, say \"dontcare\".\n- @JoseNunez why you tell me this?\n- @NiallFarrington sorry, the message was for Maciej Jankowski. Cheers\n- @MaciejJankowski have a look on the previous comment \"@NiallFarrington for the sake of SQLite you don't need to specify...\"\n- `-d databasename` is `yourfilename.db`","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":63,"estimatedTokens":577}}520{"id":"stack-51755110","source":"stackoverflow","questionId":51755110,"title":"Sequelize Typescript on delete cascade throwing errors","tags":["typescript","sequelize.js"],"text":"Title: Sequelize Typescript on delete cascade throwing errors\nTags: typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got a very straightforward FK relationship between Group and GroupAttendee. Whenever I call `Group.destroy()` I'm greeted with a foreign key constraint failure exception on the GroupAttendee entries. I understand how those constraints are supposed to work at the database level but I can't seem to get sequelize-typescript to create?/enforce? them.\n\nI'm including a simplified version of my models to demonstrate my setup:\n\n```\nimport { Model, Column, AllowNull, HasMany, ForeignKey, DataType, BelongsTo } from \"sequelize-typescript\";\nimport { User } from \"./User\";\n\nclass Group extends Model {\n\n @AllowNull(false)\n @Column\n title: string;\n\n @AllowNull(false)\n @Column\n startDate: Date;\n\n @AllowNull(false)\n @Column\n endDate: Date;\n\n @HasMany(() => GroupAttendee)\n attendees: GroupAttendee[];\n}\n\nclass GroupAttendee extends Model {\n\n @ForeignKey(() => User)\n @Column(DataType.INTEGER)\n userId: number;\n\n @ForeignKey(() => Group)\n @Column(DataType.INTEGER)\n groupId: number;\n\n @BelongsTo(() => Group, {\n onUpdate: \"CASCADE\",\n onDelete: \"CASCADE\",\n hooks: true\n })\n group: Group;\n}\n```\n\nHas anyone gotten this to work?\n\n========================================\n\nCode:\n```text\nimport { Model, Column, AllowNull, HasMany, ForeignKey, DataType, BelongsTo } from \"sequelize-typescript\";\nimport { User } from \"./User\";\n\nclass Group extends Model<Group> {\n\n  @AllowNull(false)\n  @Column\n  title: string;\n\n  @AllowNull(false)\n  @Column\n  startDate: Date;\n\n  @AllowNull(false)\n  @Column\n  endDate: Date;\n\n  @HasMany(() => GroupAttendee)\n  attendees: GroupAttendee[];\n}\n\nclass GroupAttendee extends Model<GroupAttendee> {\n\n  @ForeignKey(() => User)\n  @Column(DataType.INTEGER)\n  userId: number;\n\n  @ForeignKey(() => Group)\n  @Column(DataType.INTEGER)\n  groupId: number;\n\n  @BelongsTo(() => Group, {\n    onUpdate: \"CASCADE\",\n    onDelete: \"CASCADE\",\n    hooks: true\n  })\n  group: Group;\n}\n```\n\n```text\nGroup.destroy()\n```\n\n```text\n@HasMany(() => GroupAttendee , {\n    onUpdate: \"CASCADE\",\n    onDelete: \"CASCADE\",\n    hooks: true\n})\nattendees: GroupAttendee[];\n```\n\n```text\nGroup\n```\n\n```text\nGroupAttendee\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":116,"estimatedTokens":558}}521{"id":"stack-18964303","source":"stackoverflow","questionId":18964303,"title":"sequelize migration not working","tags":["sqlite","sequelize.js"],"text":"Title: sequelize migration not working\nTags: sqlite, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI created a migration and ran it. It says it worked fine, but nothing happened. I don't think it is even connecting to my database.\n\n### My Migration file:\n\n```\nvar util = require(\"util\");\nmodule.exports = {\nup : function(migration, DataTypes, done) {\n \nmigration.createTable('nameOfTheNewTable', {\n attr1 : DataTypes.STRING,\n attr2 : DataTypes.INTEGER,\n attr3 : {\n type : DataTypes.BOOLEAN,\n defaultValue : false,\n allowNull : false\n }\n}).success(\n function() {\n\n migration.describeTable('nameOfTheNewTable').success(\n function(attributes) {\n util.puts(\"nameOfTheNewTable Schema: \"\n + JSON.stringify(attributes));\n done();\n });\n\n });\n},\ndown : function(migration, DataTypes, done) {\n // logic for reverting the changes\n}\n};\n```\n\n### My Config.json:\n\n```\n{\n \"development\": {\n \"username\": \"user\",\n \"password\": \"pw\",\n \"database\": \"my-db\",\n \"dialect\" : \"sqlite\",\n \"host\": \"localhost\"\n }\n}\n```\n\n### The command:\n\n```\n./node_modules/sequelize/bin/sequelize --migrate --env development\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\nRunning migrations...\n20130921234513-initial.js\nnameOfTheNewTable Schema: {\"attr1\":{\"type\":\"VARCHAR(255)\",\"allowNull\":true,\"defaultValue\":null},\"attr2\":{\"type\":\"INTEGER\",\"allowNull\":true,\"defaultValue\":null},\"attr3\":{\"type\":\"TINYINT(1)\",\"allowNull\":false,\"defaultValue\":false}}\nCompleted in 8ms\n```\n\nI can run this over and over and the output is always the same. I've tried it on a database which I know to have existing tables and try to describe those tables and still nothing happens.\n\nAm I doing something wrong?\n\n### EDIT:\n\nI'm pretty sure I'm not connecting to the db, but try as I might I cannot connect using the migration. I can connect using `sqlite3 my-db.sqlite` and run commands such as `.tables` to see tables I have created previously, but I cannot for the life of me get the \"nameOfTheNewTable\" table created using a migration. (I want to create indexes in the migration too). I have tried using **\"development\"**, changing values in the `config.json` like the host, database (my-db, ../my-db, my-db.sqlite), etc.\n\nHere's a good example, in the `config.json` I put `\"database\" : \"bad-db\"` and the output from the migration is exactly the same. When it is done, there is no bad-db.sqlite file to be found.\n\n========================================\n\nTop Answer:\nyou most likely have to wait for `migration.createTable` to finish:\n\n```\nmigration.createTable(/*your options*/).success(function() { \n migration.describeTable('nameOfTheNewTable').success(function(attributes) { \n util.puts(\"nameOfTheNewTable Schema: \" + JSON.stringify(attributes)); \n done() \n });\n})\n```\n\n========================================\n\nCode:\n```text\nvar util = require(\"util\");\nmodule.exports = {\nup : function(migration, DataTypes, done) {\n    \nmigration.createTable('nameOfTheNewTable', {\n    attr1 : DataTypes.STRING,\n    attr2 : DataTypes.INTEGER,\n    attr3 : {\n        type : DataTypes.BOOLEAN,\n        defaultValue : false,\n        allowNull : false\n    }\n}).success(\n        function() {\n\n            migration.describeTable('nameOfTheNewTable').success(\n                    function(attributes) {\n                        util.puts(\"nameOfTheNewTable Schema: \"\n                                + JSON.stringify(attributes));\n                        done();\n                    });\n\n        });\n},\ndown : function(migration, DataTypes, done) {\n    // logic for reverting the changes\n}\n};\n```\n\n```text\n{\n  \"development\": {\n    \"username\": \"user\",\n    \"password\": \"pw\",\n    \"database\": \"my-db\",\n    \"dialect\" : \"sqlite\",\n    \"host\": \"localhost\"\n  }\n}\n```\n\n```text\n./node_modules/sequelize/bin/sequelize --migrate --env development\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\nRunning migrations...\n20130921234513-initial.js\nnameOfTheNewTable Schema: {\"attr1\":{\"type\":\"VARCHAR(255)\",\"allowNull\":true,\"defaultValue\":null},\"attr2\":{\"type\":\"INTEGER\",\"allowNull\":true,\"defaultValue\":null},\"attr3\":{\"type\":\"TINYINT(1)\",\"allowNull\":false,\"defaultValue\":false}}\nCompleted in 8ms\n```\n\n```text\nsqlite3 my-db.sqlite\n```\n\n```text\n.tables\n```\n\n```text\nconfig.json\n```\n\n```text\nconfig.json\n```\n\n```text\n\"database\" : \"bad-db\"\n```\n\n```text\nmigration.createTable(/*your options*/).success(function() {  \n    migration.describeTable('nameOfTheNewTable').success(function(attributes) {  \n        util.puts(\"nameOfTheNewTable Schema: \" + JSON.stringify(attributes));  \n        done()  \n    });\n})\n```\n\n```text\nmigration.createTable\n```\n\n========================================\n\nComments:\n- Good point. Updated my code to use the success callback. The output has changed, but the table is still not created.\n- It looks like there is no way for migrations to know what file for sqlite to use, since the 'storage' parameter is not read from config.json. I opened issue #1050 on github: github.com/sequelize/sequelize/issues/1050\n- I'm full of poop. You just need to specify the 'storage' parameter.\n- That makes a ton of sense.","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":186,"estimatedTokens":1274}}522{"id":"stack-58476839","source":"stackoverflow","questionId":58476839,"title":"How do I set a foreign key for a Sequelize model?","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: How do I set a foreign key for a Sequelize model?\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThis is very basic, and should work.. but doesn't. So first my models:\n\n```\nconst Conversation = sequelize.define('Conversation', {\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n ...\n})\nConversation.associate = (models, options) => {\n Conversation.hasOne(models.Audio, options)\n}\n```\n\nand:\n\n```\nmodule.exports = (sequelize /*: sequelize */ , DataTypes /*: DataTypes */ ) => {\n const Audio = sequelize.define(\"Audio\", {\n name: {\n type: DataTypes.STRING,\n unique: true,\n allowNull: true\n },\n })\n\n Audio.associate = (models, options) => {\n Audio.belongsTo(models.Conversation, options)\n }\n```\n\nI have a model loader that does:\n\n```\nfs.readdirSync(`${__dirname}`)\n .filter((modelFile) => {\n return path.extname(modelFile) === '.js' && modelFile !== 'index.js'\n })\n .map((modelFile) => {\n let model = sequelize.import(`./${modelFile}`)\n models[model.name] = model\n\n return model\n })\n .filter((model) => models[model.name].associate)\n .forEach((model) => {\n models[model.name].associate(models, {\n hooks: true,\n onDelete: 'CASCADE'\n });\n })\n```\n\nSo it calls the `associate` method for all models that have it defined. This works, in that, when I `.sync` it, it creates a `ConversationId` field in my `Conversations` table.\n\nWhen I try to execute:\n\n```\nlet updAudio = {\n ConversationId,\n name: 'myname'\n }\n await global.db.models.Audio.create(updAudio, { logging: console.log })\n```\n\n`ConversationId` is not null, but when it saves in the DB, it's null. I've inspected it a hundred times. The raw query looks like:\n\n```\nINSERT INTO \"Audios\" (\"id\",\"name\",\"createdAt\",\"updatedAt\") VALUES (DEFAULT,'myname','2019-10-20 19:59:18.139 +00:00','2019-10-20 19:59:18.139 +00:00') RETURNING *;\n```\n\nSo what happened to `ConversationId`?\n\n========================================\n\nCode:\n```text\nconst Conversation = sequelize.define('Conversation', {\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false\n        },\n        ...\n})\nConversation.associate = (models, options) => {\n    Conversation.hasOne(models.Audio, options)\n}\n```\n\n```text\nmodule.exports = (sequelize /*: sequelize */ , DataTypes /*: DataTypes */ ) => {\n    const Audio = sequelize.define(\"Audio\", {\n        name: {\n            type: DataTypes.STRING,\n            unique: true,\n            allowNull: true\n        },\n    })\n\n    Audio.associate = (models, options) => {\n        Audio.belongsTo(models.Conversation, options)\n    }\n```\n\n```text\nfs.readdirSync(`${__dirname}`)\n        .filter((modelFile) => {\n            return path.extname(modelFile) === '.js' && modelFile !== 'index.js'\n        })\n        .map((modelFile) => {\n            let model = sequelize.import(`./${modelFile}`)\n            models[model.name] = model\n\n            return model\n        })\n        .filter((model) => models[model.name].associate)\n        .forEach((model) => {\n            models[model.name].associate(models, {\n                hooks: true,\n                onDelete: 'CASCADE'\n            });\n        })\n```\n\n```text\nlet updAudio = {\n                ConversationId,\n                name: 'myname'\n            }\n            await global.db.models.Audio.create(updAudio, { logging: console.log })\n```\n\n```text\nINSERT INTO \"Audios\" (\"id\",\"name\",\"createdAt\",\"updatedAt\") VALUES (DEFAULT,'myname','2019-10-20 19:59:18.139 +00:00','2019-10-20 19:59:18.139 +00:00') RETURNING *;\n```\n\n```text\nassociate\n```\n\n```text\n.sync\n```\n\n```text\nConversationId\n```\n\n```text\nConversations\n```\n\n```text\nConversationId\n```\n\n```text\nConversationId\n```\n\n```text\nconst Audio = sequelize.define(\"Audio\", {\n        name: {\n            type: DataTypes.STRING,\n            unique: true,\n            allowNull: true\n        },\n        conversationId : {\n            type: Sequelize.INTEGER,\n            references: 'Conversations' // or \"conversations\"? This is a table name\n            referencesKey: 'id' // the PK column name\n        }\n    })\n```\n\n```text\nconst Audio = sequelize.define(\"Audio\", {\n        name: {\n            type: DataTypes.STRING,\n            unique: true,\n            allowNull: true\n        },\n        conversationId : {\n            type: Sequelize.INTEGER,\n            references: {\n                model: Conversation\n                key: 'id'\n            }\n        }\n    })\n```\n\n```text\nAudio.belongsTo(Conversation, foreignKey: 'conversationId');\n```\n\n```text\nbelongsTo\n```\n\n========================================\n\nComments:\n- Seems to work, but I thought that adding `belongsTo` would be sufficient\n- If you are using third one then no need to write first two.Because third will add an foreign key field automatically","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":211,"estimatedTokens":1185}}523{"id":"stack-53381495","source":"stackoverflow","questionId":53381495,"title":"How to control the inner join query in sequelize using node.js?","tags":["node.js","join","sequelize.js","inner-join"],"text":"Title: How to control the inner join query in sequelize using node.js?\nTags: node.js, join, sequelize.js, inner-join\nSource: Stack Overflow\n\nQuestion:\nDays model:\n\n```\nworkoutId: {\n type: Sequelize.INTEGER,\n},\ntraineeId: {\n type: Sequelize.INTEGER,\n primaryKey: true\n},\ndayNumber: {\n type: Sequelize.INTEGER,\n primaryKey: true\n},\nstatus: {\n type: Sequelize.INTEGER\n},\n```\n\nWorkoutsExercises model:\n\n```\nworkout_id: {\n type: Sequelize.INTEGER,\n primaryKey: true\n},\nexercise_name: {\n type: Sequelize.INTEGER,\n primaryKey: true\n},\ncoach_id: {\n type: Sequelize.INTEGER,\n primaryKey: true\n}\n```\n\nI just want to make an inner join between the two tables to return all exercises in each day, I use the following\n\n```\nconst Days = require('../models/days');\nconst WorkoutsExercises = require('../models/workoutsExercises');\n\nDays.findAll({\n include: [{\n model: WorkoutsExercises,\n required: true\n }] \n})\n```\n\nAnd this function returns the following query:\n\n```\nSELECT\n `day`.`workoutId`,\n `day`.`dayNumber`,\n `day`.`status`,\n `day`.`traineeId`,\n \n `workoutsExercises`.`workout_id` AS `workoutsExercises.workout_id`, \n `workoutsExercises`.`exercise_name` AS `workoutsExercises.exercise_name`, \n `workoutsExercises`.`coach_id` AS `workoutsExercises.coach_id`\n\nFROM `days` AS `day`\n\nINNER JOIN `workoutsExercises` AS `workoutsExercises` \n\nON `day`.`dayNumber` = `workoutsExercises`.`workout_id`;\n```\n\nhow can I change the on condition from (`day`.`dayNumber`) to (`day`.`workoutId`)\n\n========================================\n\nTop Answer:\nIf you have several relations between two models you can create several associations:\n\n```\nUser.hasMany(Task);\nTask.belongsTo(User);\n\nUser.hasMany(Task, {as: \"secondAssociation\", foreignKey, sourceKey});\nTask.belongsTo(User, {as: \"secondAssociation\", foreignKey, targetKey});\n```\n\nAnd you can run this queries with different ON clause, determined by foreignKey (and sourceKey/targetKey) value, that you provide to create associations:\n\n```\nUser.findAll({\n include: [{\n model: Task\n }]\n\nUser.findAll({\n include: [{\n model: Task,\n as: \"secondAssociation\"\n }]\n})\n```\n\nIf you want change ON clause for given query, you can use `include[].on` option of Model.findAll method.\n\n```\nUser.findAll({\n include: [{\n model: Task,\n on: {} //Use Sequelize.Op.col for reference on other column\n }]\n```\n\n========================================\n\nCode:\n```text\nworkoutId: {\n    type: Sequelize.INTEGER,\n},\ntraineeId: {\n  type: Sequelize.INTEGER,\n  primaryKey: true\n},\ndayNumber: {\n  type: Sequelize.INTEGER,\n  primaryKey: true\n},\nstatus: {\n  type: Sequelize.INTEGER\n},\n```\n\n```text\nworkout_id: {\n  type: Sequelize.INTEGER,\n  primaryKey: true\n},\nexercise_name: {\n  type: Sequelize.INTEGER,\n  primaryKey: true\n},\ncoach_id: {\n  type: Sequelize.INTEGER,\n  primaryKey: true\n}\n```\n\n```text\nconst Days = require('../models/days');\nconst WorkoutsExercises = require('../models/workoutsExercises');\n\nDays.findAll({\n  include: [{\n    model: WorkoutsExercises,\n      required: true\n   }]        \n})\n```\n\n```text\nSELECT\n  `day`.`workoutId`,\n  `day`.`dayNumber`,\n  `day`.`status`,\n  `day`.`traineeId`,\n  \n  `workoutsExercises`.`workout_id` AS `workoutsExercises.workout_id`, \n  `workoutsExercises`.`exercise_name` AS `workoutsExercises.exercise_name`, \n  `workoutsExercises`.`coach_id` AS `workoutsExercises.coach_id`\n\nFROM `days` AS `day`\n\nINNER JOIN `workoutsExercises` AS `workoutsExercises` \n\nON `day`.`dayNumber` = `workoutsExercises`.`workout_id`;\n```\n\n```text\nday\n```\n\n```text\ndayNumber\n```\n\n```text\nday\n```\n\n```text\nworkoutId\n```\n\n```text\nWorkoutExercises.hasMany(Day, {foreignKey: 'workout_id'})\nDay.belongsTo(WorkoutExercises, {foreignKey: 'workout_id', targetKey: 'workout_id'})\n```\n\n```text\nDays.findAll({\n  include: [{\n    model: WorkoutsExercises,\n    required: true\n  }]        \n})\n```\n\n```text\nSELECT\n\n  `day`.`dayNumber`,\n  `day`.`dayDate`,\n  `day`.`status`,\n  `day`.`traineeId`, \n  `day`.`workoutId`, \n\n  `workoutsExercises`.`exercise_name` AS `workoutsExercises.exercise_name`,\n  `workoutsExercises`.`workout_id` AS `workoutsExercises.workout_id`,\n  `workoutsExercises`.`coach_id` AS `workoutsExercises.coach_id`\n \n FROM `days` AS `day`\n \n INNER JOIN `workoutsExercises` AS `workoutsExercises`\n \n ON `day`.`workout_id` = `workoutsExercises`.`workout_id`;\n```\n\n```text\nUser.hasMany(Task);\nTask.belongsTo(User);\n\nUser.hasMany(Task, {as: \"secondAssociation\", foreignKey, sourceKey});\nTask.belongsTo(User, {as: \"secondAssociation\", foreignKey, targetKey});\n```\n\n```text\nUser.findAll({\n  include: [{\n    model: Task\n  }]\n\nUser.findAll({\n  include: [{\n    model: Task,\n    as: \"secondAssociation\"\n  }]\n})\n```\n\n```text\nUser.findAll({\n  include: [{\n    model: Task,\n    on: {} //Use Sequelize.Op.col for reference on other column\n  }]\n```\n\n```text\ninclude[].on\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":264,"estimatedTokens":1193}}524{"id":"stack-56113296","source":"stackoverflow","questionId":56113296,"title":"Set encrypt to true on Sequelize-cli migrate for MSSQL","tags":["javascript","sql-server","sequelize.js"],"text":"Title: Set encrypt to true on Sequelize-cli migrate for MSSQL\nTags: javascript, sql-server, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run sequelize-cli, specifically `npx sequelize db:migrate`.\n\nI've created a config file in `config/config.js` which looks like this (obviously with correct credentials):\n\n```\nmodule.exports = {\n development: {\n username: \"USER\",\n password: \"PASSWORD\",\n database: \"DB_NAME\",\n host: \"HOST.net\",\n dialect: 'mssql',\n dialectOptions: {\n encrypt: \"true\" // bool - true - doesn't work either\n }\n }\n};\n```\n\nHowever I'm receiving the following error:\n\n```\nERROR: Server requires encryption, set 'encrypt' config option to true.\n```\n\nAs you can see from my config I believe I have set encrypt to true. This is my understanding of how to set this option from the docs.\n\nHow can I successfully set `encrypt` to true?\n\n========================================\n\nTop Answer:\nEdit your ***config.js***\n\n```\nmodule.exports = {\n url: process.env.DATABASE_URL,\n dialectOptions: {\n ssl: {\n require: true,\n rejectUnauthorized: false,\n },\n },\n};\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  development: {\n    username: \"USER\",\n    password: \"PASSWORD\",\n    database: \"DB_NAME\",\n    host: \"HOST.net\",\n    dialect: 'mssql',\n    dialectOptions: {\n      encrypt: \"true\" // bool - true - doesn't work either\n    }\n  }\n};\n```\n\n```text\nERROR: Server requires encryption, set 'encrypt' config option to true.\n```\n\n```text\nnpx sequelize db:migrate\n```\n\n```text\nconfig/config.js\n```\n\n```text\nencrypt\n```\n\n```text\nmodule.exports = {\n  development: {\n    username: \"USER\",\n    password: \"PASSWORD\",\n    database: \"DB_NAME\",\n    host: \"HOST.net\",\n    dialect: 'mssql',\n    dialectOptions: { \n      options: {\n        encrypt: true\n      }\n    }\n  } \n};\n```\n\n```text\nmodule.exports = {\n  url: process.env.DATABASE_URL,\n  dialectOptions: {\n    ssl: {\n      require: true,\n      rejectUnauthorized: false,\n    },\n  },\n};\n```\n\n========================================\n\nComments:\n- github.com/sequelize/sequelize/issues/3240 this issue also leads me to believe what I have above is correct. Though it isn't working.\n- Well, are you trying to do something like this? `var sequelize = new Sequelize('my - connection - string', { dialect: 'mssql', dialectOptions: { encrypt: true } });`\n- Yes, though doing that does not work either. Same error.\n- Okay, I hope this would work, `module.exports = { development: { username: \"USER\", password: \"PASSWORD\", database: \"DB_NAME\", host: \"HOST.net\", dialect: 'mssql', dialectOptions: { options: { encrypt: true } } } };`\n- Oh wow, that worked - that seems to be a poor implementation/documentation. Thanks if you update your answer I will accept it.\n- Updated. And yes, they do have bad documentation.\n- this should work aswell","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":124,"estimatedTokens":705}}525{"id":"stack-44339446","source":"stackoverflow","questionId":44339446,"title":"How to update Sequelize Model excluding fields","tags":["sequelize.js"],"text":"Title: How to update Sequelize Model excluding fields\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLooking at Sequelize docs, I find how to specify what fields I want to update, but I want specify what fields I **don't** want to update. \n\nSomething like that:\n\n`Model.update(,{excludeFields:['id']})`\n\nIs there any way to do this?\n\n========================================\n\nTop Answer:\nWhen I had this problem, I did not find an way for resolve this in sequelize docs, but I resolved it with something like this:\n\n```\nModel.findOne()\n .then(instance => {\n const fields = instance.attributes.filter(attribute => {\n return !['foo'].includes(attribute);\n });\n\n return instance.update(data, { fields });\n });\n```\n\n========================================\n\nCode:\n```text\nModel.update(,{excludeFields:['id']})\n```\n\n```text\nconst fieldsToExclude = ['password', 'sensitive_info', 'attribute_not_allowed_due_to_user_role']    \nconst myFields = Object.keys(MyModel.rawAttributes).filter( s => !fildsToExclude.includes(s))\nMyModel.update(newValue, {fields: myFields})\n```\n\n```text\n// Remove values that are not in the options.fields\n    if (options.fields && options.fields instanceof Array) {\n      for (const key of Object.keys(values)) {\n        if (options.fields.indexOf(key) < 0) {\n          delete values[key];\n        }\n      }\n    } else {\n      const updatedAtAttr = this._timestampAttributes.updatedAt;\n      options.fields = _.intersection(Object.keys(values), Object.keys(this.tableAttributes));\n      if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) === -1) {\n        options.fields.push(updatedAtAttr);\n      }\n    }\n```\n\n```text\nstatic _expandAttributes(options) {\n    if (_.isPlainObject(options.attributes)) {\n      let attributes = Object.keys(this.rawAttributes);\n\n      if (options.attributes.exclude) {\n        attributes = attributes.filter(elem => {\n          return options.attributes.exclude.indexOf(elem) === -1;\n        });\n      }\n      if (options.attributes.include) {\n        attributes = attributes.concat(options.attributes.include);\n      }\n\n      options.attributes = attributes;\n    }\n  }\n```\n\n```text\nfindByPk\n```\n\n```text\nfindOne\n```\n\n```text\nfindAll\n```\n\n```text\noptions\n```\n\n```text\nfindAll\n```\n\n```text\nfindOne\n```\n\n```text\nfindByPk\n```\n\n```text\nupdate\n```\n\n```text\noptions\n```\n\n```text\nfind*\n```\n\n```text\nupdate\n```\n\n```text\nfields\n```\n\n```text\noptions\n```\n\n```text\nfind*\n```\n\n```text\n_.confirmOptions()\n```\n\n```text\n_expandAttributes()\n```\n\n```text\nModel.findAll({\n  attributes: { exclude: ['baz'] }\n});\n```\n\n```text\nModel.findOne()\n  .then(instance => {\n    const fields = instance.attributes.filter(attribute => {\n      return !['foo'].includes(attribute);\n    });\n\n    return instance.update(data, { fields });\n  });\n```\n\n```text\nif (model) {\n  delete model.password;\n  delete model.sensitive_info;\n}\n```\n\n========================================\n\nComments:\n- Sorry, but that's not correct. While that works for `findAll`, that won't work for `update`\n- I needed this behavior in a `beforeUpdate` hook and since you only have the instance in the hook, setting field to be excluded to `undefined` had the effect of excluding it.","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":171,"estimatedTokens":796}}526{"id":"stack-22360606","source":"stackoverflow","questionId":22360606,"title":"Stop sequelize create table","tags":["node.js","sequelize.js"],"text":"Title: Stop sequelize create table\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nEvery time I call a page, sequelize execute:\nCREATE TABLE IF NOT EXISTS `user_p...\n\nHow can I disable this? the table is created and works fine, I no need sequelize try to create every time.\n\n========================================\n\nCode:\n```text\nsyncOnAssociation\n```\n\n```text\nfalse\n```\n\n```text\nsequelize.sync\n```\n\n========================================\n\nComments:\n- You are probably not going to get much help without posting the code in question.\n- `IF NOT EXISTS` appendix mean table will not be recreated if it already exist. So, could you explain please why do you worry about that? Provide your code please.\n- the link is dead\n- sequelize.readthedocs.io/en/1.7.0/docs/usage/#options But finally I kicked sequelize so I sent him to the moon. Sorry but I do the same with objects and crud querys, more efficient querys and, more development speed, and no strange facts.","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":32,"estimatedTokens":244}}527{"id":"stack-55531860","source":"stackoverflow","questionId":55531860,"title":"Sequelize bulkCreate updateOnDuplicate for postgresQL?","tags":["node.js","postgresql","sequelize.js","bulkinsert","bulkupdate"],"text":"Title: Sequelize bulkCreate updateOnDuplicate for postgresQL?\nTags: node.js, postgresql, sequelize.js, bulkinsert, bulkupdate\nSource: Stack Overflow\n\nQuestion:\nI know there is no support for updateOnDuplicate for postgresQL by Sequelize sequelize doc, so is there a work around for this? \n\nCan it be implemented via \"SQL command\".\n\n========================================\n\nTop Answer:\nNew sequelize (v5) includes updateOnDuplicate feature for all dialects\n\n Fields to update if row key already exists (on duplicate key update)?\n (only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >=\n 9.5). By default, all fields are updated.\n\nCheck here : Docs\n\nYou can use as \n\n```\nmodel.bulkCreate(dataToUpdate, { updateOnDuplicate: [\"user_id\", \"token\", \"created_at\"] })\n```\n\n========================================\n\nCode:\n```text\nbulkUpsert\n```\n\n```text\nmodel.bulkCreate(dataToUpdate, { updateOnDuplicate: [\"user_id\", \"token\", \"created_at\"] })\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.383Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":36,"estimatedTokens":237}}528{"id":"stack-53186006","source":"stackoverflow","questionId":53186006,"title":"how can i use limit in include model using sequelize","tags":["node.js","join","orm","include","sequelize.js"],"text":"Title: how can i use limit in include model using sequelize\nTags: node.js, join, orm, include, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni want to get user's images at limit 2 from model.\n\nModels\n\n\r\n\r\n\n```\nconst = connector.define('', {\r\n no: {\r\n type: Sequelize.INTEGER,\r\n primaryKey: true,\r\n autoIncrement: true\r\n },\r\n follower_id: {\r\n type: Sequelize.INTEGER,\r\n allowNull: true\r\n },\r\n target_id: {\r\n type: Sequelize.INTEGER,\r\n allowNull: true\r\n },\r\n isDelete: {\r\n type: Sequelize.BOOLEAN,\r\n allowNull: false\r\n },\r\n create_dt,\r\n delete_dt\r\n}\r\n\r\nconst User = connector.define('User', {\r\n no: {\r\n type: Sequelize.INTEGER,\r\n primaryKey: true,\r\n autoIncrement: true\r\n },\r\n username: {\r\n type: Sequelize.STRING,\r\n allowNull: false\r\n\r\n },\r\n email: {\r\n type: Sequelize.STRING,\r\n allowNull: false\r\n },\r\n password: {\r\n type: Sequelize.STRING,\r\n allowNull: false\r\n },\r\n profile_img: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n bio: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n phone: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n gender: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n website: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n isDelete: {\r\n type: Sequelize.BOOLEAN,\r\n allowNull: false\r\n },\r\n create_dt,\r\n update_dt,\r\n delete_dt\r\n}\r\n\r\nconst Image = connector.define('Image', {\r\n no: {\r\n type: Sequelize.INTEGER,\r\n primaryKey: true,\r\n autoIncrement: true\r\n },\r\n file: {\r\n type: Sequelize.STRING,\r\n allowNull: false\r\n },\r\n location: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n caption: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n tags: {\r\n type: Sequelize.STRING,\r\n allowNull: true\r\n },\r\n isDelete: {\r\n type: Sequelize.BOOLEAN,\r\n allowNull: false\r\n },\r\n create_dt,\r\n update_dt,\r\n delete_dt,\r\n user_id: {\r\n type: Sequelize.INTEGER,\r\n allowNull: true\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nand, join\n\n```\nUser.hasMany(Image, {foreignKey: 'user_id'})\nImage.belongsTo(User, {foreignKey: 'user_id'})\n\nUser.hasMany(, {foreignKey: 'follower_id'})\n.belongsTo(User, {foreignKey: 'follower_id'})\n\nUser.hasMany(, {foreignKey: 'target_id'})\n.belongsTo(User, {foreignKey: 'target_id'})\n```\n\nso, i tried get user's images from by use include.\n\n\r\n\r\n\n```\nconst followerImages = await .findAll({\r\n attributes: ['target_id'],\r\n where:{\r\n follower_id: loginUser_id\r\n },\r\n include:[\r\n {\r\n model: User,\r\n required: true,\r\n attributes: ['username', 'email', 'profile_img'],\r\n include:[\r\n {\r\n model: Image,\r\n required: true\r\n }\r\n ]\r\n }\r\n ]\r\n })\n```\n\n\r\n\r\n\r\n\nbut i want to get images at limit 2.\n\nso i tried that\n\n\r\n\r\n\n```\nconst followerImages = await .findAll({\r\n attributes: ['target_id'],\r\n where:{\r\n follower_id: loginUser_id\r\n },\r\n include:[\r\n {\r\n model: User,\r\n required: true,\r\n attributes: ['username', 'email', 'profile_img'],\r\n include:[\r\n {\r\n model: Image,\r\n required: true,\r\n limit: 2\r\n }\r\n ]\r\n }\r\n ]\r\n })\n```\n\n\r\n\r\n\r\n\nbut it makes bugs i cant understand.\n\nimages field is a array contain empty object at 4.\n\nall same..\n\nwhat is the problem?\n\nhow can i solve this problem??\n\n========================================\n\nTop Answer:\nMaybe you can apply this solution. I tried turning off duplicating and subQuery by adding a field with a false value in sequelize, like this:\n\n```\nduplicating: false, \nsubQuery: false\n```\n\nfor example as follows:\n\n```\nconst followerImages = await .findAll({\n attributes: ['target_id'],\n where:{\n follower_id: loginUser_id\n },\n include:[\n {\n model: User,\n required: true,\n attributes: ['username', 'email', 'profile_img'],\n include:[\n {\n model: Image,\n required: true\n }\n ]\n }\n ],\n duplicating: false,\n subQuery: false\n })\n```\n\nReference : https://github.com/sequelize/sequelize/issues/3007\n\n========================================\n\nCode:\n```js\nconst Follow = connector.define('Follow', {\n    no: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    follower_id: {\n        type: Sequelize.INTEGER,\n        allowNull: true\n    },\n    target_id: {\n        type: Sequelize.INTEGER,\n        allowNull: true\n    },\n    isDelete: {\n        type: Sequelize.BOOLEAN,\n        allowNull: false\n    },\n    create_dt,\n    delete_dt\n}\n\nconst User = connector.define('User', {\n    no: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    username: {\n        type: Sequelize.STRING,\n        allowNull: false\n\n    },\n    email: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    profile_img: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    bio: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    phone: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    gender: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    website: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    isDelete: {\n        type: Sequelize.BOOLEAN,\n        allowNull: false\n    },\n    create_dt,\n    update_dt,\n    delete_dt\n}\n\nconst Image = connector.define('Image', {\n    no: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    file: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    location: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    caption: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    tags: {\n        type: Sequelize.STRING,\n        allowNull: true\n    },\n    isDelete: {\n        type: Sequelize.BOOLEAN,\n        allowNull: false\n    },\n    create_dt,\n    update_dt,\n    delete_dt,\n    user_id: {\n        type: Sequelize.INTEGER,\n        allowNull: true\n    }\n}\n```\n\n```text\nUser.hasMany(Image, {foreignKey: 'user_id'})\nImage.belongsTo(User, {foreignKey: 'user_id'})\n\nUser.hasMany(Follow, {foreignKey: 'follower_id'})\nFollow.belongsTo(User, {foreignKey: 'follower_id'})\n\nUser.hasMany(Follow, {foreignKey: 'target_id'})\nFollow.belongsTo(User, {foreignKey: 'target_id'})\n```\n\n```js\nconst followerImages = await Follow.findAll({\n            attributes: ['target_id'],\n            where:{\n                follower_id: loginUser_id\n            },\n            include:[\n                {\n                    model: User,\n                    required: true,\n                    attributes: ['username', 'email', 'profile_img'],\n                    include:[\n                        {\n                            model: Image,\n                            required: true\n                        }\n                    ]\n                }\n            ]\n        })\n```\n\n```js\nconst followerImages = await Follow.findAll({\n            attributes: ['target_id'],\n            where:{\n                follower_id: loginUser_id\n            },\n            include:[\n                {\n                    model: User,\n                    required: true,\n                    attributes: ['username', 'email', 'profile_img'],\n                    include:[\n                        {\n                            model: Image,\n                            required: true,\n                            limit: 2\n                        }\n                    ]\n                }\n            ]\n        })\n```\n\n```text\ninclude:[\n    {\n        model: Image,\n        attributes : ['id','user_id','image'] , // <---- don't forget to add foreign key ( user_id )\n        separate : true, // <--- Run separate query\n        limit: 2\n    }\n]\n```\n\n```text\nLimit\n```\n\n```text\nduplicating: false, \nsubQuery: false\n```\n\n```text\nconst followerImages = await Follow.findAll({\n            attributes: ['target_id'],\n            where:{\n                follower_id: loginUser_id\n            },\n            include:[\n                {\n                    model: User,\n                    required: true,\n                    attributes: ['username', 'email', 'profile_img'],\n                    include:[\n                        {\n                            model: Image,\n                            required: true\n                        }\n                    ]\n                }\n            ],\n            duplicating: false,\n            subQuery: false\n        })\n```\n\n========================================\n\nComments:\n- Have you tried putting `limit` at the very top of the query, like: `.findAll({limit: 2, attributes: ['target_id'], etc...})`\n- it's not my intent.. i want to get my 'every follower' s images at limit 2. it will load 2 followers's all images.\n- it's not working. but your advice is helpful to me. i will request 2 queries or slice result array after select except limit. it was my greed to solved by only one query. thank you\n- can't apply `separate: true` if you running `where` clause\n- how can you order ASC now with limit in mind?","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":467,"estimatedTokens":2184}}529{"id":"stack-52153500","source":"stackoverflow","questionId":52153500,"title":"Unhandled rejection SequelizeEagerLoadingError: is not associated to, and Cannot read property 'getTableName' of undefined","tags":["node.js","orm","sequelize.js"],"text":"Title: Unhandled rejection SequelizeEagerLoadingError: is not associated to, and Cannot read property 'getTableName' of undefined\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 3 tables: User, Trip, authoriseDate.\nhere is associate:\nA user has many trips and a user has one authoriseDate\nUser one to many Trips\nUser one to one authoriseDate\nand here is the models\nUser\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const user = sequelize.define('User', {\n id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n email: { type: DataTypes.STRING(50), unique: true },\n phoneNumber: {\n type: DataTypes.STRING(12), unique: true,\n },\n }, {\n classMethods: {\n associate(models) {\n // associations can be defined here\n user.hasOne(models.authoriseDate, { foreignKey: 'userId' });\n user.hasMany(models.Trip, { foreignKey: 'userId' });\n },\n },\n });\n return user;\n};\n```\n\nTrip\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const trip = sequelize.define('Trip', {\n id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n userId: DataTypes.INTEGER,\n status: DataTypes.INTEGER,\n }, {\n classMethods: {\n associate(models) {\n // associations can be defined here\n trip.belongsTo(models.User, { foreignKey: 'userId' });\n },\n },\n });\n return trip;\n};\n```\n\nauthoriseDate\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const authoriseDate = sequelize.define('AuthoriseDate', {\n id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n userId: DataTypes.INTEGER,\n lastAuthorise: DataTypes.DATE,\n }, {\n classMethods: {\n associate(models) {\n // associations can be defined here\n authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });\n },\n },\n });\n return authoriseDate;\n};\n```\n\nbut when I using findAll function \n\n```\nmodels.User.findAll({\n include: [{\n model: models.Trip,\n },\n {\n model: models.authoriseDate,\n }],\n })\n```\n\nhere is my model file\n\n```\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(module.filename);\n//var env = process.env.NODE_ENV || 'development';\n//var config = require(__dirname + './../../../config/config.json')[env];\nvar config = require('../../config/env')\nvar db = {};\n\n// if (config.use_env_variable) {\n// var sequelize = new Sequelize(process.env[config.use_env_variable]);\n// } else {\n// var sequelize = new Sequelize(config.database, config.username, config.password, config);\n// }\n\nvar sequelize = new Sequelize(config.dbName, config.dbUserName, config.dbPassword, {\n host: config.dbHost,\n dialect: config.dbDialect,\n});\n\nfs\n .readdirSync(__dirname)\n .filter(function (file) {\n return (file.indexOf('.') !== 0) && (file !== basename);\n })\n .forEach(function (file) {\n if (file.slice(-3) !== '.js') return;\n var model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function (modelName) {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nI am getting the errors:\n**Unhandled rejection SequelizeEagerLoadingError: Trip is not associated to User, and Cannot read property 'getTableName' of undefined**\nI don't know how to solve these errors, anyone help me please\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const user = sequelize.define('User', {\n    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n    email: { type: DataTypes.STRING(50), unique: true },\n    phoneNumber: {\n      type: DataTypes.STRING(12), unique: true,\n    },\n  }, {\n    classMethods: {\n      associate(models) {\n        // associations can be defined here\n        user.hasOne(models.authoriseDate, { foreignKey: 'userId' });\n        user.hasMany(models.Trip, { foreignKey: 'userId' });\n      },\n    },\n  });\n  return user;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const trip = sequelize.define('Trip', {\n    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n    userId: DataTypes.INTEGER,\n    status: DataTypes.INTEGER,\n  }, {\n    classMethods: {\n      associate(models) {\n        // associations can be defined here\n        trip.belongsTo(models.User, { foreignKey: 'userId' });\n      },\n    },\n  });\n  return trip;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const authoriseDate = sequelize.define('AuthoriseDate', {\n    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n    userId: DataTypes.INTEGER,\n    lastAuthorise: DataTypes.DATE,\n  }, {\n    classMethods: {\n      associate(models) {\n        // associations can be defined here\n        authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });\n      },\n    },\n  });\n  return authoriseDate;\n};\n```\n\n```text\nmodels.User.findAll({\n    include: [{\n      model: models.Trip,\n    },\n    {\n      model: models.authoriseDate,\n    }],\n  })\n```\n\n```text\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(module.filename);\n//var env = process.env.NODE_ENV || 'development';\n//var config    = require(__dirname + './../../../config/config.json')[env];\nvar config = require('../../config/env')\nvar db = {};\n\n// if (config.use_env_variable) {\n//   var sequelize = new Sequelize(process.env[config.use_env_variable]);\n// } else {\n//   var sequelize = new Sequelize(config.database, config.username, config.password, config);\n// }\n\nvar sequelize = new Sequelize(config.dbName, config.dbUserName, config.dbPassword, {\n  host: config.dbHost,\n  dialect: config.dbDialect,\n});\n\nfs\n  .readdirSync(__dirname)\n  .filter(function (file) {\n    return (file.indexOf('.') !== 0) && (file !== basename);\n  })\n  .forEach(function (file) {\n    if (file.slice(-3) !== '.js') return;\n    var model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(function (modelName) {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const authoriseDate = sequelize.define('AuthoriseDate', {\n        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n        userId: DataTypes.INTEGER,\n        lastAuthorise: DataTypes.DATE,\n    });\n\n    authoriseDate.associate = (models) => {\n        // associations can be defined here\n        authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });\n    };\n\n\n    return authoriseDate;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const trip = sequelize.define('Trip', {\n        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n        userId: DataTypes.INTEGER,\n        status: DataTypes.INTEGER,\n    });\n\n    trip.associate = (models) => {\n        // associations can be defined here\n        trip.belongsTo(models.User, { foreignKey: 'userId' });\n    };\n\n    return trip;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const user = sequelize.define('User', {\n        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n        email: { type: DataTypes.STRING(50), unique: true },\n        phoneNumber: {\n            type: DataTypes.STRING(12), unique: true,\n        },\n    });\n\n    user.associate = (models) => {\n        // associations can be defined here\n        user.hasOne(models.AuthoriseDate, { foreignKey: 'userId' });\n        user.hasMany(models.Trip, { foreignKey: 'userId' });\n    };\n\n\n    return user;\n};\n```\n\n```text\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(module.filename);\n//var env = process.env.NODE_ENV || 'development';\n//var config    = require(__dirname + './../../../config/config.json')[env];\n// var config = require('../../config/env')\nvar db = {};\n\nvar sequelize = new Sequelize('test_01', 'root', 'root', {\n    host: 'localhost',\n    dialect: 'mysql',\n});\n\nfs\n    .readdirSync(__dirname)\n    .filter(function (file) {\n        return (file.indexOf('.') !== 0) && (file !== basename);\n    })\n    .forEach(function (file) {\n        if (file.slice(-3) !== '.js') return;\n        var model = sequelize['import'](path.join(__dirname, file));\n        db[model.name] = model;\n    });\n\nconsole.log(db);\n\nObject.keys(db).forEach((modelName) => {\n    if (db[modelName].associate) {\n        db[modelName].associate(db);\n    }\n});\n\n(async () => {\n    await sequelize.sync();\n})();\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n(async () => {\n    const models = require('./models');\n\n    const users = await models.User.findAll({\n        include: [\n            {\n                model: models.Trip,\n            },\n            {\n                model: models.AuthoriseDate,\n            },\n        ],\n    });\n\n    console.log(users);\n})();\n```\n\n========================================\n\nComments:\n- yes i did it in my index models, you can see my update\n- i have to create associate like this ? Project.hasMany(User, {as: 'Workers'}) i though i did it in my model like this classMethods: { associate(models) { // associations can be defined here authoriseDate.belongsTo(models.User, { foreignKey: 'userId', }); }, },\n- No, it's example.You init associate. Are you initialize associative after or before find?\n- so what shiould i do now\n- Show me your model import file\n- i initialize before i using find funtion\n- sorry when i added this code `(async () => { await sequelize.sync(); })();` i get this error *asyncToGenerator( /*#__PURE_**/regeneratorRuntime.mark(function _callee() { ^ ReferenceError: regeneratorRuntime is not defined\n- i just ignore that code and i can get the models Trip now but when i include AuthoriseDate, its raise up this error Unhandled rejection SequelizeDatabaseError: relation \"AuthoriseDates\" does not exist\n- Use Promise. (() => { const models = require('./models'); return models.User.findAll({ include: [ { model: models.Trip, }, { model: models.AuthoriseDate, }, ], }).then(console.log); })();\n- Try it sequelize.sync({ force: true });\n- sequelize.sync({ force: true }); it drop all my database :(\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":392,"estimatedTokens":2596}}530{"id":"stack-49995639","source":"stackoverflow","questionId":49995639,"title":"Load attributes from associated model in sequelize.js","tags":["sql","node.js","orm","sequelize.js"],"text":"Title: Load attributes from associated model in sequelize.js\nTags: sql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two models. User and Manager\n\nUser Model\n\n```\nconst UserMaster = sequelize.define('User', {\n UserId: {\n type: DataTypes.BIGINT,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n RelationshipId: {\n type: DataTypes.STRING,\n allowNull: true,\n foreignKey: true\n },\n UserName: {\n type: DataTypes.STRING,\n allowNull: true\n }\n })\n```\n\nManager model\n\n```\nconst Manager = sequelize.define('Manager', {\n ManagerId: {\n type: DataTypes.BIGINT,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n RelationshipId: {\n type: DataTypes.STRING,\n allowNull: true,\n foreignKey: true\n },\n MangerName: {\n type: DataTypes.STRING,\n allowNull: true\n }\n })\n```\n\nModels are minified to simplyfy the problem\n\nAssociations.. \n\n```\nUser.belongsTo(models.Manager, {\n foreignKey: 'RelationshipId',\n as: 'RM'\n});\n\nManger.hasMany(model.User, {\n foreignKey: 'RelationshipId',\n as: \"Users\"\n})\n```\n\nSo, on user.findAll()\n\n```\nvar userObject = models.User.findAll({\n include: [{\n model: models.Manager,\n required: false,\n as: 'RM',\n attributes: ['ManagerName']\n }]\n});\n```\n\nI get the following.\n\n```\nuserObject = [{\n UserId: 1,\n RelationshipId: 4545,\n UserName: 'Jon',\n RM: {\n ManagerName: 'Sam'\n }\n },\n {\n UserId: 2,\n RelationshipId: 432,\n UserName: 'Jack',\n RM: {\n ManagerName: 'Phil'\n }\n },\n ...\n]\n```\n\nHow can I move 'ManagerName' attribute from Manager model (associated as RM) to UserObject?\nIs it possible to somehow load attributes from eagerly-loaded models without nesting them under a separate object?\nI expected the resulting Object to look Like the object \n\nExpected Object --\n\n```\nuserObject = [{\n UserId: 1,\n RelationshipId: 4545,\n UserName: 'Jon',\n ManagerName: 'Sam' // Thank you.\n\n========================================\n\nCode:\n```text\nconst UserMaster = sequelize.define('User', {\n        UserId: {\n            type: DataTypes.BIGINT,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        RelationshipId: {\n            type: DataTypes.STRING,\n            allowNull: true,\n            foreignKey: true\n        },\n        UserName: {\n            type: DataTypes.STRING,\n            allowNull: true\n        }\n    })\n```\n\n```text\nconst Manager = sequelize.define('Manager', {\n        ManagerId: {\n            type: DataTypes.BIGINT,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        RelationshipId: {\n            type: DataTypes.STRING,\n            allowNull: true,\n            foreignKey: true\n        },\n        MangerName: {\n            type: DataTypes.STRING,\n            allowNull: true\n        }\n    })\n```\n\n```text\nUser.belongsTo(models.Manager, {\n    foreignKey: 'RelationshipId',\n    as: 'RM'\n});\n\nManger.hasMany(model.User, {\n    foreignKey: 'RelationshipId',\n    as: \"Users\"\n})\n```\n\n```text\nvar userObject = models.User.findAll({\n    include: [{\n        model: models.Manager,\n        required: false,\n        as: 'RM',\n        attributes: ['ManagerName']\n    }]\n});\n```\n\n```text\nuserObject = [{\n        UserId: 1,\n        RelationshipId: 4545,\n        UserName: 'Jon',\n        RM: {\n            ManagerName: 'Sam'\n        }\n    },\n    {\n        UserId: 2,\n        RelationshipId: 432,\n        UserName: 'Jack',\n        RM: {\n            ManagerName: 'Phil'\n        }\n    },\n    ...\n]\n```\n\n```text\nuserObject = [{\n        UserId: 1,\n        RelationshipId: 4545,\n        UserName: 'Jon',\n        ManagerName: 'Sam' // <-- from Manager model\n    },\n    {\n        UserId: 2,\n        RelationshipId: 432,\n        UserName: 'Jack',\n        ManagerName: 'Phil' // <-- from Manager model\n    },\n    ...\n]\n```\n\n```text\nvar userObject = models.User.findAll({\nraw:true,\nattributes: {\ninclude: [Sequelize.col('RM.ManagerName'), 'ManagerName']\n},\n    include: [{\n        model: models.Manager,\n        required: false,\n        as: 'RM',\n        attributes: []\n    }]\n});\n```\n\n```text\nraw: true\n```\n\n```text\nattributes\n```\n\n========================================\n\nComments:\n- use `raw = true` otherwise sequelize always will do that\n- But that will return me RM.ManagerName. How do I rename (or manupulate) this to just ManagerName ?\n- Further adding ` attributes: { include: [Sequelize.col('RM.ManagerName'), 'ManagerName'] }` worked. Thank you @Ellebkey\n- Thanks this saved me a lot of time. The key solution is to use 'Sequelize.col' to replace an associated model's attribute name.\n- With TS get the error: Type 'Col' is not assignable to type 'string | ProjectionAlias'. Type 'Col' is not assignable to type 'ProjectionAlias'","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":251,"estimatedTokens":1174}}531{"id":"stack-42409944","source":"stackoverflow","questionId":42409944,"title":"What's the difference between \"migration:create\" and \"migration:generate\"?","tags":["javascript","node.js","sequelize.js"],"text":"Title: What's the difference between \"migration:create\" and \"migration:generate\"?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've run help command on sequelize and saw that there are two different commands with the same description:\n\n```\n$ sequelize help:migration:create\n\nSequelize [Node: 6.9.5, CLI: 2.5.1, ORM: 3.8.0, mysql: 2.5.0]\n\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\nCOMMANDS\n sequelize migration:create -- Generates a new migration file.\n sequelize migration:generate -- Generates a new migration file.\n```\n\nIs there any difference between them?\n\n========================================\n\nTop Answer:\nThere is a small difference between create and generate:\n\n- Create: This will create migration files that will have empty up and down query objects, in which you can write down your queries to update the database.\nGenerate: This will generate the migrations with up and down queries by observing your database changes.\nYou can see more of migration on the official sites.\n\n========================================\n\nCode:\n```text\n$ sequelize help:migration:create\n\nSequelize [Node: 6.9.5, CLI: 2.5.1, ORM: 3.8.0, mysql: 2.5.0]\n\nLoaded configuration file \"config\\config.json\".\nUsing environment \"development\".\nCOMMANDS\n    sequelize migration:create   -- Generates a new migration file.\n    sequelize migration:generate -- Generates a new migration file.\n```\n\n```text\nmigration:generate\n```\n\n```text\nmigration:create\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":376}}532{"id":"stack-37893128","source":"stackoverflow","questionId":37893128,"title":"Why Sequelize issues \"SHOW INDEX FROM `table`\"?","tags":["javascript","sql","node.js","orm","sequelize.js"],"text":"Title: Why Sequelize issues \"SHOW INDEX FROM `table`\"?\nTags: javascript, sql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIf you would enable `Sequelize` logging, you would see that during the \"sync\" phase and right after creating a table, `Sequelize` executes `SHOW INDEX FROM table` query. The question is - why?\n\nTo be more specific, here is the code I'm executing:\n\n```\nvar Sequelize = require('sequelize');\n\nvar connection = new Sequelize('demo_schema', 'root', 'password');\n\nvar Article = connection.define('article', {\n slug: {\n type: Sequelize.STRING,\n primaryKey: true\n },\n title: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false\n },\n body: {\n type: Sequelize.TEXT\n }\n}, {\n timestamps: false\n});\n\nconnection.sync({\n force: true,\n logging: console.log\n}).then(function () {\n // TODO\n});\n```\n\nHere is the output on the console:\n\n```\nExecuting (default): DROP TABLE IF EXISTS `articles`;\nExecuting (default): DROP TABLE IF EXISTS `articles`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `articles` (`slug` VARCHAR(255) , `title` VARCHAR(255) NOT NULL UNIQUE, `body` TEXT, UNIQUE `articles_title_unique` (`title`), PRIMARY KEY (`slug`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `articles`\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\n\nvar connection = new Sequelize('demo_schema', 'root', 'password');\n\nvar Article = connection.define('article', {\n    slug: {\n        type: Sequelize.STRING,\n        primaryKey: true\n    },\n    title: {\n        type: Sequelize.STRING,\n        unique: true,\n        allowNull: false\n    },\n    body:  {\n        type: Sequelize.TEXT\n    }\n}, {\n    timestamps: false\n});\n\nconnection.sync({\n    force: true,\n    logging: console.log\n}).then(function () {\n   // TODO\n});\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS `articles`;\nExecuting (default): DROP TABLE IF EXISTS `articles`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `articles` (`slug` VARCHAR(255) , `title` VARCHAR(255) NOT NULL UNIQUE, `body` TEXT, UNIQUE `articles_title_unique` (`title`), PRIMARY KEY (`slug`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `articles`\n```\n\n```text\nSequelize\n```\n\n```text\nSequelize\n```\n\n```text\nSHOW INDEX FROM table\n```\n\n```js\nsequelize.define('user', {}, {\n  indexes: [\n    // Create a unique index on email\n    {\n      unique: true,\n      fields: ['email']\n    }\n  ]\n})\n```\n\n```js\n// this.QueryInterface.showIndex produces the statement `SHOW INDEX FROM [table of the model]`. It returns a promise containing the found indexes.\n.then(() => this.QueryInterface.showIndex(this.getTableName(options), options))\n// `indexes` will contain the indexes which are present on the existing table.\n// If you force sync, this will always be empty since the table is new.\n.then(indexes => {\n  // Assign an auto-generated name to indexes which are not named by the user\n  this.options.indexes = this.QueryInterface.nameIndexes(this.options.indexes, this.tableName);\n\n  // Fill `indexes` with only the indexes from your model which are not present on the table.\n  indexes = _.filter(this.options.indexes, item1 => !_.some(indexes, item2 => item1.name === item2.name));\n\n  // .map iterates over `indexes` and adds an index for each entry.\n  // Remeber, this is for indexes which are present in the model definition but not present on the table.\n  return Promise.map(indexes, index => this.QueryInterface.addIndex(\n    this.getTableName(options),\n    _.assign({\n      logging: options.logging,\n      benchmark: options.benchmark,\n      transaction: options.transaction\n    }, index),\n    this.tableName\n  ));\n})\n```\n\n```text\nSHOW INDEX FROM\n```\n\n```text\nSHOW INDEX FROM\n```\n\n========================================\n\nComments:\n- Thank you very much for the detailed break down! Now we have a completely clear picture.\n- Does it remove indexes that weren't defined in ORM?\n- No, it only adds new indexes. If you would like to remove an index, you can do it manually with the removeIndex method of the queryInterface within migrations. Further information at docs.sequelizejs.com/en/latest/docs/migrations/&hellip;.","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":152,"estimatedTokens":1037}}533{"id":"stack-39584169","source":"stackoverflow","questionId":39584169,"title":"MySQL with Sequelize: ER_BAD_DB_ERROR: Unknown database","tags":["mysql","node.js","sequelize.js"],"text":"Title: MySQL with Sequelize: ER_BAD_DB_ERROR: Unknown database\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am following a tutorial and below is the code:\n\n```\nvar Sequelize = require('sequelize')\nvar sequelize = new Sequelize('basic-mysql-database.mysql', 'root', 'password', {\n 'dialect': 'mysql',\n 'host': \"localhost\",\n \"port\": \"3306\"\n});\n\nvar Todo = sequelize.define('todo', {\n description: {\n type: Sequelize.STRING\n },\n completed: {\n type: Sequelize.BOOLEAN\n\n }\n})\n\nsequelize.sync().then(function(){\n console.log('Everything is synced')\n\n Todo.create({\n description: 'Walking my dog',\n completed: false\n }).then(function (todo){\n console.log('Finished!')\n console.log(todo)\n })\n});\n```\n\nI have installed MySQL. When I go into `Settings` > `MySQL` and it says `MySQL Server instance is running` \n\nWhen I run `node testDB.js` I get the following error:\n\n```\nUnhandled rejection SequelizeConnectionError: ER_BAD_DB_ERROR: Unknown database 'basic-mysql-database.mysql'\n at Handshake._callback (/Users/Kausi/Documents/Development/todo-api/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:63:20)\n at Handshake.Sequence.end (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/sequences/Sequence.js:85:24)\n at Handshake.ErrorPacket (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/sequences/Handshake.js:105:8)\n at Protocol._parsePacket (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/Protocol.js:280:23)\n at Parser.write (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/Parser.js:74:12)\n at Protocol.write (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n at Socket. (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/Connection.js:109:28)\n at emitOne (events.js:77:13)\n at Socket.emit (events.js:169:7)\n at readableAddChunk (_stream_readable.js:153:18)\n at Socket.Readable.push (_stream_readable.js:111:10)\n at TCP.onread (net.js:536:20)\n```\n\nI have never created any schema/table. I do have MySQL Workbench that I can create the schema and 'Todo' table with; however, I was under the impression that `Sequelize` does this on the fly? What am I doing wrong?\n\n========================================\n\nTop Answer:\nIn mac I navigated to /Applications/MAMP/bin/phpMyAdmin/config.inc.php\n\nAnd found that my username was \"root\" and password was also \"root\"\n\n```\n$cfg['Servers'][$i]['user'] = 'root'; \n$cfg['Servers'][$i]['password'] = 'root';\n```\n\nhttps://stackoverflow.com/a/78066825/12228079\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize')\nvar sequelize = new Sequelize('basic-mysql-database.mysql', 'root', 'password', {\n    'dialect': 'mysql',\n    'host': \"localhost\",\n    \"port\": \"3306\"\n});\n\nvar Todo = sequelize.define('todo', {\n    description: {\n        type: Sequelize.STRING\n    },\n    completed: {\n        type: Sequelize.BOOLEAN\n\n    }\n})\n\nsequelize.sync().then(function(){\n    console.log('Everything is synced')\n\n    Todo.create({\n        description: 'Walking my dog',\n        completed: false\n    }).then(function (todo){\n        console.log('Finished!')\n        console.log(todo)\n    })\n});\n```\n\n```text\nUnhandled rejection SequelizeConnectionError: ER_BAD_DB_ERROR: Unknown database 'basic-mysql-database.mysql'\n    at Handshake._callback (/Users/Kausi/Documents/Development/todo-api/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:63:20)\n    at Handshake.Sequence.end (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/sequences/Sequence.js:85:24)\n    at Handshake.ErrorPacket (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/sequences/Handshake.js:105:8)\n    at Protocol._parsePacket (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/Protocol.js:280:23)\n    at Parser.write (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/Parser.js:74:12)\n    at Protocol.write (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n    at Socket.<anonymous> (/Users/Kausi/Documents/Development/todo-api/node_modules/mysql/lib/Connection.js:109:28)\n    at emitOne (events.js:77:13)\n    at Socket.emit (events.js:169:7)\n    at readableAddChunk (_stream_readable.js:153:18)\n    at Socket.Readable.push (_stream_readable.js:111:10)\n    at TCP.onread (net.js:536:20)\n```\n\n```text\nSettings\n```\n\n```text\nMySQL\n```\n\n```text\nMySQL Server instance is running\n```\n\n```text\nnode testDB.js\n```\n\n```text\nSequelize\n```\n\n```text\n$cfg['Servers'][$i]['user']          = 'root';      \n$cfg['Servers'][$i]['password']      = 'root';\n```\n\n========================================\n\nComments:\n- I don't think sequelize can make a database for you. It will only make a tables for you. Create that database first then just let the sequlizer create your table (just create your database)\n- but what if we want to do this job with our app... like don't have to create our database manually just our will do this for us.. is their any way??","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":154,"estimatedTokens":1285}}534{"id":"stack-61845632","source":"stackoverflow","questionId":61845632,"title":"SequelizeEagerLoadingError: model is not associated to otherModel","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: SequelizeEagerLoadingError: model is not associated to otherModel\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've seen this problem a lot in different forums but I haven't been able to fix it. I'm using Express and PostgreSQL with Sequelize.\n\nBasically I have two models: Campus and academic manager. It's a one to one relation between the two, Campus has one academic manager.\n\nI've implemented both models and the association works, I can see it beeing displayed in mi database in the postgres server. But when I try to implement my get request of campus, I try to include the manager information, without success. I keep receiving the same error:\n\n SequelizeEagerLoadingError: academic_manager is not associated to campus!\n\nI believe my problem has to do with *include*\n\nHere are my code snippets:\n\n**campus.js**\n\n```\nconst campus = (sequelize, DataTypes) =>{\n const Campus = sequelize.define('campus', {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n manager: {\n type: DataTypes.INTEGER,\n allowNull: false,\n references: {\n model: 'academic_manager',\n key: 'id'\n }\n } \n }); \n\n Campus.associate = models => {\n Campus.hasOne(models.Manager, { foreignKey: 'id'});\n }\n\n return Campus; \n};\n\nexport default campus;\n```\n\n**academic_manager.js**\n\n```\nconst manager = (sequelize, DataTypes) =>{\n const Manager = sequelize.define('academic_manager', {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false\n } \n }); \n\n Manager.associate = models => {\n Manager.belongsTo(models.Campus, { foreignKey: 'id'});\n }\n\n return Manager; \n};\n\nexport default manager;\n```\n\nAnd the get method:\n\n```\nrouter.get('/', async (req, res) => {\n const campus = await req.context.models.Campus.findAll({\n include: [\n { model: req.context.models.Manager }\n ]\n });\n return res.send(campus);\n});\n```\n\nThe get request works without the include. I know the association is achieved because when I describe my campus table and my manager table I have this:\n\n```\nTABLE \"campus\" CONSTRAINT \"campus_manager_fkey\" FOREIGN KEY (manager) REFERENCES academic_manager(id)\n```\n\n========================================\n\nTop Answer:\nYour model definition has several problems. Sequelize might be confused as to whether you wanted to **associate** the models, or just have them **referencing** each other. \n\nYou have added associations which implements relational constraints, but also added reference key which is meant to allow reference but not implement constraints.\n\nMight want to read:\n\n- How to implement many to many association in sequelize\n\n- https://sequelize.org/v5/manual/associations.html\n\nI have commented your code:\n\n### campus.js\n\n```\nconst Campus = (sequelize, DataTypes) =>{\n const Campus = sequelize.define('Campus', {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n }\n // this is not correct.\n // read when to use reference key further below\n /* manager: {\n type: DataTypes.INTEGER,\n allowNull: false,\n references: {\n model: 'academic_manager',\n key: 'id' \n }\n\n } */\n }); \n\n Campus.associate = models => {\n // Campus.hasOne(models.Manager, { foreignKey: 'id'});\n // foreignKey `id` is wrong. Your models already by default have `id`, which is their own.\n // you either define the name as `campus_id`, or just let sequelize handle it for you by not defining it at all and just use `Campus.hasOne(models.Manager)`.\n // but generally it's good practice to define, otherwise when you need it, you have to figure out what did sequelize help you name it as.\n // read: https://sequelize.org/master/manual/assocs.html#providing-the-foreign-key-name-directly\n Campus.hasOne(models.Manager, { foreignKey: 'campus_id'); // this means please inject `campus_id` into `Manager` \n }\n\n return Campus; \n};\n\nexport default Campus;\n```\n\n### academic_manager.js\n\n```\nconst Manager = (sequelize, DataTypes) =>{\n const Manager = sequelize.define('Manager', {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }); \n\n Manager.associate = models => {\n // you don't define foreignKey here. because by doing so you are saying\n // you want to inject this foreignKey into `Campus`, which you are not.\n Manager.belongsTo(models.Campus);\n }\n\n return Manager; \n};\n\nexport default Manager;\n```\n\n### Additional Info - When to use this referenceKey?\n\nIn relational databases, the rule of thumb is that between any 2 model, you should only have 1 path, otherwise it forms a cyclic dependency, which can potentially cause problems.\n\n### Imagine you have the third entity `Location`\n\n```\nCampus.hasOne(Manager)\nManager.belongsTo(Campus)\n\nLocation.hasOne(Campus)\nLocation.belongsTo(Campus)\n```\n\nAll is well and good. Lets for a moment imaginatively assume that the `Manager` stays on the `Campus`, you can find out their `Location` like this\n\n```\nManager -> Campus -> Location\n```\n\nUntil such time you have decided that it is a true statement that `Manager` will always stay in that `Location` and nowhere else, and your application have more frequently required this information, you will be tempted to do this:\n\n```\nLocation.hasOne(Manager)\nManager.belongsTo(Location)\n```\n\nYou now have another path `Location -> Manager`, and you completed the circular reference of `Location -> Manager -> Campus -> Location -> Manager....`\n\nTo break this, you must make a choice between which relationship is more important, or more commonly accessed. In this case it may seem that the relationship between `Location` and `Manager` is not all that important, then just continue using `Manager -> Campus -> Location`.\n\n### But you want the cake and also eat it\n\nThis is where you don't associate the models, and just use **reference keys** or use `constraints: false`. Read https://sequelize.org/master/manual/constraints-and-circularities.html\n\n`constraints: false` is my usual choice because it still provides me with all the sequelize methods as though the models are associated. But to be very strict, you are by right to be using `reference keys` at most. Then do a manual join, or do 2 queries by using the reference key you found to locate its data on its referenced table.\n\n========================================\n\nCode:\n```text\nconst campus = (sequelize, DataTypes) =>{\n    const Campus = sequelize.define('campus', {\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false,\n        },\n        manager: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            references: {\n                model: 'academic_manager',\n                key: 'id'\n            }\n        } \n    });    \n\n    Campus.associate = models => {\n        Campus.hasOne(models.Manager, { foreignKey: 'id'});\n    }\n\n    return Campus; \n};\n\nexport default campus;\n```\n\n```text\nconst manager = (sequelize, DataTypes) =>{\n    const Manager = sequelize.define('academic_manager', {\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false,\n        },\n        email: {\n            type: DataTypes.STRING,\n            allowNull: false\n        } \n    });    \n\n    Manager.associate = models => {\n        Manager.belongsTo(models.Campus, { foreignKey: 'id'});\n    }\n\n    return Manager; \n};\n\nexport default manager;\n```\n\n```text\nrouter.get('/', async (req, res) => {\n    const campus = await req.context.models.Campus.findAll({\n        include: [\n            { model: req.context.models.Manager }\n        ]\n    });\n    return res.send(campus);\n});\n```\n\n```text\nTABLE \"campus\" CONSTRAINT \"campus_manager_fkey\" FOREIGN KEY (manager) REFERENCES academic_manager(id)\n```\n\n```text\nObject.keys(models).forEach(key => {\n  if ('associate' in models[key]) {\n    models[key].associate(models);\n  }\n});\n```\n\n```js\nconst Campus = (sequelize, DataTypes) =>{\n    const Campus = sequelize.define('Campus', {\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false,\n        }\n        // this is not correct.\n        // read when to use reference key further below\n        /* manager: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            references: {\n                model: 'academic_manager',\n                key: 'id' \n            }\n\n        } */\n    });    \n\n    Campus.associate = models => {\n        // Campus.hasOne(models.Manager, { foreignKey: 'id'});\n        // foreignKey `id` is wrong. Your models already by default have `id`, which is their own.\n        // you either define the name as `campus_id`, or just let sequelize handle it for you by not defining it at all and just use `Campus.hasOne(models.Manager)`.\n        // but generally it's good practice to define, otherwise when you need it, you have to figure out what did sequelize help you name it as.\n        // read: https://sequelize.org/master/manual/assocs.html#providing-the-foreign-key-name-directly\n        Campus.hasOne(models.Manager, { foreignKey: 'campus_id'); // this means please inject `campus_id` into `Manager` \n    }\n\n    return Campus; \n};\n\nexport default Campus;\n```\n\n```js\nconst Manager = (sequelize, DataTypes) =>{\n    const Manager = sequelize.define('Manager', {\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false,\n        },\n        email: {\n            type: DataTypes.STRING,\n            allowNull: false\n        }\n    });    \n\n    Manager.associate = models => {\n        // you don't define foreignKey here. because by doing so you are saying\n        // you want to inject this foreignKey into `Campus`, which you are not.\n        Manager.belongsTo(models.Campus);\n    }\n\n    return Manager; \n};\n\nexport default Manager;\n```\n\n```text\nCampus.hasOne(Manager)\nManager.belongsTo(Campus)\n\nLocation.hasOne(Campus)\nLocation.belongsTo(Campus)\n```\n\n```text\nManager -> Campus -> Location\n```\n\n```text\nLocation.hasOne(Manager)\nManager.belongsTo(Location)\n```\n\n```text\nLocation\n```\n\n```text\nManager\n```\n\n```text\nCampus\n```\n\n```text\nLocation\n```\n\n```text\nManager\n```\n\n```text\nLocation\n```\n\n```text\nLocation -> Manager\n```\n\n```text\nLocation -> Manager -> Campus -> Location -> Manager....\n```\n\n```text\nLocation\n```\n\n```text\nManager\n```\n\n```text\nManager -> Campus -> Location\n```\n\n```text\nconstraints: false\n```\n\n```text\nconstraints: false\n```\n\n```text\nreference keys\n```\n\n========================================\n\nComments:\n- Thanks for the links! I'm new to sequelize so this gets rather confusing. I tried you code corrections, and still got the same error when I attempt to use include in my GET request *SequelizeEagerLoadingError: academic_manager is not associated to campus!*. I tried using aliases as one of the links explalined: I deleted the association from campus and added `Manager.belongsTo(models.Campus, { as: 'managers' }` in the manager model and modified the GET request to `include: 'managers'` but then I got the following error: *Error: Association with alias \"managers\" does not exist on campus*\n- I tried adding the association in Campus again, but got the same error, specifying the foreign key. And without writing the foreign key too.\n- try making all your model names consistent. i think you defined `academic_manager` as the Manager table. And in your associate, it could be Models.academic_manager.\n- I realized it was a really dumb mistake, I forgot to actually make the associations happen. This is my first post here, thanks for your answers, should I delete my question? or just update it?\n- Keep everything, the answer is clear and might help someone else (like me)","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":423,"estimatedTokens":2875}}535{"id":"stack-42741703","source":"stackoverflow","questionId":42741703,"title":"Can't connect to Postgres container with Docker Compose from Sequelize","tags":["postgresql","docker","docker-compose","sequelize.js"],"text":"Title: Can't connect to Postgres container with Docker Compose from Sequelize\nTags: postgresql, docker, docker-compose, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI can't connect to the default Postgres image from a separate docker service running node & Sequelize. \n\nI'm assuming that my setup of the container is not correct and also perhaps my connection info is incorrect too because I when I run `docker-compose --build` I cannot connect to my database using the connection info:\n\n```\nHost: 0.0.0.0\nPort: 5432\nUser: guy\nPassword: password\nDatabase: engauge\n```\n\nThe error message is\n\n```\nUnable to connect to the database: { SequelizeConnectionRefusedError: connect ECONNREFUSED 0.0.0.0:5432\nat /usr/src/app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:98:20\n```\n\nI am running with a YML file that looks like this\n\n```\nversion: '2' # specify docker-compose version\n\n# Define the services/containers to be run\nservices:\n web: # name of the first service\n build: . # specify the directory of the Dockerfile\n ports:\n - \"3000:3000\" # specify port forewarding\n links:\n - database\n database: # name of the third service\n image: postgres # specify image to build container from\n ports:\n - \"5432:5432\" # specify port forewarding\n environment:\n - POSTGRES_USER:'guy'\n - POSTGRES_PASSWORD:'password'\n - POSTGRES_DB:'engauge'\n```\n\nAnd my connection from within my web service looks like this\n\n```\nconst sequelize = new Sequelize('postgresql://guy:password@0.0.0.0/engauge');\n```\n\n========================================\n\nCode:\n```text\nHost: 0.0.0.0\nPort: 5432\nUser: guy\nPassword: password\nDatabase: engauge\n```\n\n```text\nUnable to connect to the database: { SequelizeConnectionRefusedError: connect ECONNREFUSED 0.0.0.0:5432\nat /usr/src/app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:98:20\n```\n\n```text\nversion: '2' # specify docker-compose version\n\n# Define the services/containers to be run\nservices:\n  web: # name of the first service\n    build: . # specify the directory of the Dockerfile\n    ports:\n      - \"3000:3000\" # specify port forewarding\n    links:\n      - database\n  database: # name of the third service\n    image: postgres # specify image to build container from\n    ports:\n      - \"5432:5432\" # specify port forewarding\n    environment:\n         - POSTGRES_USER:'guy'\n         - POSTGRES_PASSWORD:'password'\n         - POSTGRES_DB:'engauge'\n```\n\n```text\nconst sequelize = new Sequelize('postgresql://guy:password@0.0.0.0/engauge');\n```\n\n```text\ndocker-compose --build\n```\n\n```text\ndatabase\n```\n\n========================================\n\nComments:\n- You can only listen on 0.0.0.0, you cannot connect to it. Have you tried 127.0.0.1? (Or whatever the container's IP address is. )\n- Thanks so much! I'll also add that I had to clear the existing volumes and containers after making this change for them to take effect.\n- I don't see any volumes listed above. With compose, you can just run `docker-compose up -d` to apply new container configs. It's usually smart enough to see which have changed settings and recreate the necessary containers.","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":108,"estimatedTokens":776}}536{"id":"stack-19681970","source":"stackoverflow","questionId":19681970,"title":"Sequelize hooks, any way to get Express' user?","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize hooks, any way to get Express' user?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize and hooks (see here: https://github.com/sequelize/sequelize/pull/894). I'm trying to implement a kind of logging system, and would prefer to log on hooks instead of in my controllers. Anyone has any ideas on how I would be able to get my user from req.user into my hooks functions?\n\n```\ndb.define('vehicle', {\n\n ...\n\n}, {\n hooks: {\n beforeUpdate: function(values, cb){\n\n // Want to get my user in here.\n\n }\n }\n});\n```\n\n========================================\n\nTop Answer:\nThere is one simple solution that I am using in my project.\n\n1) First when you create or update any model, pass your data in option argument like below:\n\n```\nmodel.create({},{ user: req.user}); // Or\nmodel.update({},{ user: req.user});\n```\n\n2) Then, access your data inside the hook\n\n```\nUser.addHook(\"afterUpdate\", function(instance, options){\n console.log(' user data', options.user);\n});\n```\n\n========================================\n\nCode:\n```text\ndb.define('vehicle', {\n\n    ...\n\n}, {\n    hooks: {\n        beforeUpdate: function(values, cb){\n\n            // Want to get my user in here.\n\n        }\n    }\n});\n```\n\n```text\nreq.context.findById = function(model){\n  // Strip model from arguments\n  Array.prototype.shift.apply(arguments);\n  // Apply original function\n  return model.findById.apply(model, arguments).then(function(result){\n    result.context = {\n      user: req.user\n    }\n    return result;\n  });\n};\n```\n\n```text\napp.put(\"/api/user/:id\", app.isAuthenticated, function (req, res, next) {\n   // Here is the important part, user req.context.findById(model, id) instead of model.findById(id)\n   req.context.findById(User, req.params.id).then(function(item){\n      // item.context.user is now req.user\n      if(!user){\n         return next(new Error(\"User with id \" + id + \" not found\"));\n      }\n      user.updateAttributes(req.body).then(function(user) {\n         res.json(user);\n      }).catch(next);\n   }).catch(next);\n});\n```\n\n```text\nUser.addHook(\"afterUpdate\", function(instance){\n   if(instance.context && instance.context.user){\n      console.log(\"A user was changed by \" + instance.context.user.id);\n   }\n});\n```\n\n```text\nreq.findById(model, id)\n```\n\n```text\nUser.findById(id)\n```\n\n```text\ninstance.context.user\n```\n\n```text\n...\nbeforeUpdate: function(vehicle,cb){\n  vehicle.getUser()\n  .then(function(user){\n    console.log(user)\n  })\n}\n```\n\n```text\nbeforeUpdate: function(vehicle,cb){\n  User.find(vehicle.uid)\n  .then(function(user){\n    console.log(user)\n  })\n}\n```\n\n```text\nmodel.create({},{ user: req.user}); // Or\nmodel.update({},{ user: req.user});\n```\n\n```text\nUser.addHook(\"afterUpdate\", function(instance, options){\n    console.log(' user data', options.user);\n});\n```\n\n========================================\n\nComments:\n- Accepted, even tough the question was asked *last year* and it doesn't really answer the question.\n- I was checking this solution. For your information, I have written in TypeScript and getting the error `Object literal may only specify known properties, and 'authInfo' does not exist in type 'CreateOptions'.` Any suggestion?\n- I solved using Module Augmentation ``` declare module \"sequelize\" { interface CreateOptions { authInfo?: any; } interface UpdateOptions { authInfo?: any; } interface SaveOptions{ authInfo?: any; } interface BulkCreateOptions{ authInfo?: any; } } ```","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":147,"estimatedTokens":864}}537{"id":"stack-39399018","source":"stackoverflow","questionId":39399018,"title":"Sequelize upsert() never updates and only inserts","tags":["javascript","sql","postgresql","sequelize.js","upsert"],"text":"Title: Sequelize upsert() never updates and only inserts\nTags: javascript, sql, postgresql, sequelize.js, upsert\nSource: Stack Overflow\n\nQuestion:\nSo I'm trying to use the `model.upsert()` of `sequelize` and all i receive is inserts , no matter what i change in the query.\n\nI have a Transaction model that has some fields, with the default generated id.\n\nreading the sequelize's `upsert` documentation i noticed this:\n\n An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table.\n\nSo i was guessing i have to define the `id` of the Transaction in the model definition, and so i did with no luck as it still only creates new entries..\n\n```\nTransactionModel = {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n {.......}\n}\n```\n\nWhat am i doing wrong, what did i miss?\n\nAny explanation and solution will be highly appreciated, thanks in advance!\n\n### EDIT:\n\nThis is the upsert code: \n\n```\ncreateOrUpdateTransaction: {\n type: Transaction,\n args: {\n payerAccountNumber: {type: new GraphQLNonNull(GraphQLInt)},\n recipientAccountNumber: {type: new GraphQLNonNull(GraphQLInt)},\n amount: {type: new GraphQLNonNull(GraphQLFloat)},\n currency: {type: new GraphQLNonNull(GraphQLString)},\n paymentMethod: {type: new GraphQLNonNull(GraphQLString)},\n cardNumber: {type: GraphQLFloat},\n cardName: {type: GraphQLString},\n cardNetwork: {type: GraphQLString},\n cashMachineId: {type: GraphQLFloat},\n receiptNumber: {type: new GraphQLNonNull(GraphQLFloat)},\n invoiceNumber: {type: new GraphQLNonNull(GraphQLFloat)},\n receiptCopy: {type: new GraphQLNonNull(GraphQLString)},\n description: {type: GraphQLString},\n bankDescription: {type: GraphQLString},\n bankReference: {type: new GraphQLNonNull(GraphQLString)},\n bankSubCurrencyAccount: {type: new GraphQLNonNull(GraphQLString)},\n tags: {type: new GraphQLList(GraphQLString)},\n notes: {type: GraphQLString}\n },\n resolve: (root, args) => {\n return db.models.transaction.upsert({\n time: new Date().toString(),\n payerAccountNumber: args.payerAccountNumber,\n recipientAccountNumber: args.recipientAccountNumber,\n amount: args.amount,\n currency: args.currency,\n paymentMethod: args.paymentMethod,\n cardNumber: args.cardNumber,\n cardName: args.cardName,\n cardNetwork: args.cardNetwork,\n cashMachineId: args.cashMachineId,\n receiptNumber: args.receiptNumber,\n invoiceNumber: args.invoiceNumber,\n receiptCopy: args.receiptCopy,\n description: args.description,\n bankDescription: args.bankDescription,\n bankReference: args.bankReference,\n bankSubCurrencyAccount: args.bankSubCurrencyAccount,\n tags: args.tags,\n notes: args.notes,\n bankAccountAccountNumber: args.payerAccountNumber\n })\n }\n }\n```\n\nAs this is part of a `Mutation` in `GraphQL`.\n\nIt might be worth noting that this was `addTransaction` before and all i changed was to `db.models.transaction.upsert()` from `db.models.transaction.create()`\n\n========================================\n\nCode:\n```text\nTransactionModel = {\n    id: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    {.......}\n}\n```\n\n```text\ncreateOrUpdateTransaction: {\n            type: Transaction,\n            args: {\n                payerAccountNumber: {type: new GraphQLNonNull(GraphQLInt)},\n                recipientAccountNumber: {type: new GraphQLNonNull(GraphQLInt)},\n                amount: {type: new GraphQLNonNull(GraphQLFloat)},\n                currency: {type: new GraphQLNonNull(GraphQLString)},\n                paymentMethod: {type: new GraphQLNonNull(GraphQLString)},\n                cardNumber: {type: GraphQLFloat},\n                cardName: {type: GraphQLString},\n                cardNetwork: {type: GraphQLString},\n                cashMachineId: {type: GraphQLFloat},\n                receiptNumber: {type: new GraphQLNonNull(GraphQLFloat)},\n                invoiceNumber: {type: new GraphQLNonNull(GraphQLFloat)},\n                receiptCopy: {type: new GraphQLNonNull(GraphQLString)},\n                description: {type: GraphQLString},\n                bankDescription: {type: GraphQLString},\n                bankReference: {type: new GraphQLNonNull(GraphQLString)},\n                bankSubCurrencyAccount: {type: new GraphQLNonNull(GraphQLString)},\n                tags: {type: new GraphQLList(GraphQLString)},\n                notes: {type: GraphQLString}\n            },\n            resolve: (root, args) => {\n                return db.models.transaction.upsert({\n                    time: new Date().toString(),\n                    payerAccountNumber: args.payerAccountNumber,\n                    recipientAccountNumber: args.recipientAccountNumber,\n                    amount: args.amount,\n                    currency: args.currency,\n                    paymentMethod: args.paymentMethod,\n                    cardNumber: args.cardNumber,\n                    cardName: args.cardName,\n                    cardNetwork: args.cardNetwork,\n                    cashMachineId: args.cashMachineId,\n                    receiptNumber: args.receiptNumber,\n                    invoiceNumber: args.invoiceNumber,\n                    receiptCopy: args.receiptCopy,\n                    description: args.description,\n                    bankDescription: args.bankDescription,\n                    bankReference: args.bankReference,\n                    bankSubCurrencyAccount: args.bankSubCurrencyAccount,\n                    tags: args.tags,\n                    notes: args.notes,\n                    bankAccountAccountNumber: args.payerAccountNumber\n                })\n            }\n        }\n```\n\n```text\nmodel.upsert()\n```\n\n```text\nsequelize\n```\n\n```text\nupsert\n```\n\n```text\nid\n```\n\n```text\nMutation\n```\n\n```text\nGraphQL\n```\n\n```text\naddTransaction\n```\n\n```text\ndb.models.transaction.upsert()\n```\n\n```text\ndb.models.transaction.create()\n```\n\n```text\ncreateOrUpdateTransaction: {\n    type: Transaction,\n    args: {\n        // Omitted code...\n    },\n    resolve: (root, args) => {\n        return db.models.transaction.upsert({\n            // The id property must be defined in the args object for \n            // it to match to an existing row. If args.id is undefined \n            // it will insert a new row.\n            id: args.id, \n            time: new Date().toString(),\n            payerAccountNumber: args.payerAccountNumber,\n            recipientAccountNumber: args.recipientAccountNumber,\n            amount: args.amount,\n            currency: args.currency,\n            paymentMethod: args.paymentMethod,\n            cardNumber: args.cardNumber,\n            cardName: args.cardName,\n            cardNetwork: args.cardNetwork,\n            // Omitted fields ...\n        })\n    }\n}\n```\n\n========================================\n\nComments:\n- Having never used sequelize, my complete guess here is that the autoIncrement aspect (or something you're doing with it) is messing you up somehow.\n- Manually creating transaction in the DB does produce sequential id so i guess that one is fine. with or without this id (meaning with the default generated id) it only inserts\n- Are you sure the ID you are using when upserting is a Number? Wouldn't surprise me if it fails if it's a string.\n- @GrimurD When I'm using the default generated ID it supposed to always be a number, and when i set my `id` on the Transaction model, you can see i defined it as `Sequelize.INTEGER`, and used `autoIncreament` so its supposed to be automatically\n- I mean when you are upserting you must specify the ID of the model that may or may not exist(if id is undefined/null it is inserted not updated, but if the id is a Number and it is found in the db, it's updated). And I wanted to make sure that the ID when you are upserting is a valid number.\n- @GrimurD I read the documentation docs.sequelizejs.com/en/latest/api/model/&hellip; and it looks like you use `upsert` just like you'd use `create`, passing it data for the entry and it checks if it exists or not by the id of the model, do i misunderstand it?\n- Well you must make sure you are actually passing in the ID of the model if it already exists so it is found. But what I meant that when you do, you must make sure it is of the correct type. Even if the id is 1 you must make sure it's a number but not for example a string. If it's a string it might not match.\n- @GrimurD to make it clear, this is how i upsert => `db.models.transaction.upsert(transaction);`, if i understand you correctly, you're saying this is not the right way and im missing validating the id even if the id is generated. please do explain how to use `upsert` with an example, highly appreciate it\n- Please update your question with a more detailed code sample showing how you are doing upsert.\n- Hey again GrimurD, thanks for all the help. Yet I'm unable to understand what am i supposed to do if the id of my row is just the default sequential generated id?\n- When you retrieve a transaction one of the properties of the transaction is the id. I assume that at some point you are retrieving the transaction before you update it? Well you use the id you got when you retrieved it to update it. If you can't do that, upsert is not the method to use. Instead you will have to use some of the properties you have in the args object to find if there is already a row with those values. Then if it finds something you update that. If it doesn't you will do a regular create(). I don't think I can explain it any better :)\n- Well thanks a lot, that worked, ill give an edit to your answer about the generated ids :)","metadata":{"transformedAt":"2026-08-18T18:33:34.384Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":232,"estimatedTokens":2414}}538{"id":"stack-56122602","source":"stackoverflow","questionId":56122602,"title":"Understanding Associations in Sequelize","tags":["mysql","node.js","join","sequelize.js","associations"],"text":"Title: Understanding Associations in Sequelize\nTags: mysql, node.js, join, sequelize.js, associations\nSource: Stack Overflow\n\nQuestion:\nI'm trying to understand associations in Sequelize. I'm starting from existing database tables so some of the fields may not match up to the defaults in Sequelize. I've used Sequelizer to generate my models directly from the database. \nI'm accustomed to writing queries but now I'm trying to learn how an ORM like Sequelize works.\n\nHere's my models. \n\n**models/user.js**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const User = sequelize.define(\n \"User\",\n {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n field: \"id\"\n },\n username: {\n type: DataTypes.STRING(20),\n allowNull: false,\n field: \"username\"\n },\n fullname: {\n type: DataTypes.STRING(60),\n allowNull: false,\n field: \"fullname\"\n },\n createdat: {\n type: DataTypes.DATE,\n allowNull: false,\n field: \"createdat\"\n },\n updateat: {\n type: DataTypes.DATE,\n allowNull: true,\n field: \"updateat\"\n },\n deletedat: {\n type: DataTypes.DATE,\n allowNull: true,\n field: \"deletedat\"\n }\n },\n {\n tableName: \"users\",\n timestamps: false\n }\n );\n\n User.associate = function(models) {\n models.User.hasMany(models.Ticket),\n { as: \"createdbyname\", foreignKey: \"createdby\" };\n };\n return User;\n};\n```\n\n**models/ticket.js**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Ticket = sequelize.define(\n \"Ticket\",\n {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n field: \"id\"\n },\n details: {\n type: DataTypes.STRING(45),\n allowNull: true,\n field: \"details\"\n },\n assignedto: {\n type: DataTypes.INTEGER(11),\n allowNull: true,\n field: \"assignedto\"\n },\n createdby: {\n type: DataTypes.INTEGER(11),\n allowNull: true,\n field: \"createdby\"\n },\n createdat: {\n type: DataTypes.DATE,\n allowNull: false,\n field: \"createdat\"\n },\n updatedat: {\n type: DataTypes.DATE,\n allowNull: true,\n field: \"updatedat\"\n },\n deletedat: {\n type: DataTypes.DATE,\n allowNull: true,\n field: \"deletedat\"\n }\n },\n {\n tableName: \"tickets\",\n timestamps: false\n }\n );\n\n Ticket.associate = function(models) {\n models.Ticket.belongsTo(models.User,\n { foreignKey: \"createdby\" });\n };\n return Ticket;\n};\n```\n\nIn my route handler, I'm calling User.findAll as follows:\n\n```\nmodels.User.findAll({\n include: [models.Ticket]\n })\n```\n\nThe result I expect to see is a query that looks like this:\n\n```\nSELECT \n `User`.`id`,\n `User`.`username`,\n `User`.`fullname`,\n `User`.`createdat`,\n `User`.`updateat`,\n `User`.`deletedat`,\n `Tickets`.`id` AS `Tickets.id`,\n `Tickets`.`details` AS `Tickets.details`,\n `Tickets`.`assignedto` AS `Tickets.assignedto`,\n `Tickets`.`createdby` AS `Tickets.createdby`,\n `Tickets`.`createdat` AS `Tickets.createdat`,\n `Tickets`.`updatedat` AS `Tickets.updatedat`,\n `Tickets`.`deletedat` AS `Tickets.deletedat`\nFROM\n `users` AS `User`\nLEFT OUTER JOIN\n `tickets` AS `Tickets` ON `User`.`id` = `Tickets`.`createdby`\n```\n\nThe query I see running in the console is:\n\n```\nSELECT \n `User`.`id`,\n `User`.`username`,\n `User`.`fullname`,\n `User`.`createdat`,\n `User`.`updateat`,\n `User`.`deletedat`,\n `Tickets`.`id` AS `Tickets.id`,\n `Tickets`.`details` AS `Tickets.details`,\n `Tickets`.`assignedto` AS `Tickets.assignedto`,\n `Tickets`.`createdby` AS `Tickets.createdby`,\n `Tickets`.`createdat` AS `Tickets.createdat`,\n `Tickets`.`updatedat` AS `Tickets.updatedat`,\n `Tickets`.`deletedat` AS `Tickets.deletedat`,\n `Tickets`.`UserId` AS `Tickets.UserId`\nFROM\n `users` AS `User`\nLEFT OUTER JOIN\n `tickets` AS `Tickets` ON `User`.`id` = `Tickets`.`UserId`;\n```\n\nNote difference in LEFT OUTER JOIN clause. This is throwing an error as follows:\n\n```\nUnhandled rejection SequelizeDatabaseError: Unknown column 'Tickets.UserId' in 'field list'\n```\n\nI need some help figuring out where I've gone wrong here.\n\n========================================\n\nTop Answer:\n```\nPlant.findAll({\r\n include: Farm,\r\n order: [['name', 'ASC']]\r\n })\r\n .then(data=> {\r\n res.send(data)\r\n })\r\n .catch(err => {\r\n res.send(err)\r\n console.log(err);\r\n \r\n })\r\n \r\nlet arrQuery = [\r\n queryInterface.addColumn('farms', 'dayPlayed' , Sequelize.STRING),\r\n queryInterface.removeColumn('plants', 'dayPlayed' , Sequelize.STRING),\r\n ]\r\n return Promise.all(arrQuery)\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const User = sequelize.define(\n    \"User\",\n    {\n      id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        primaryKey: true,\n        field: \"id\"\n      },\n      username: {\n        type: DataTypes.STRING(20),\n        allowNull: false,\n        field: \"username\"\n      },\n      fullname: {\n        type: DataTypes.STRING(60),\n        allowNull: false,\n        field: \"fullname\"\n      },\n      createdat: {\n        type: DataTypes.DATE,\n        allowNull: false,\n        field: \"createdat\"\n      },\n      updateat: {\n        type: DataTypes.DATE,\n        allowNull: true,\n        field: \"updateat\"\n      },\n      deletedat: {\n        type: DataTypes.DATE,\n        allowNull: true,\n        field: \"deletedat\"\n      }\n    },\n    {\n      tableName: \"users\",\n      timestamps: false\n    }\n  );\n\n  User.associate = function(models) {\n        models.User.hasMany(models.Ticket),\n        { as: \"createdbyname\", foreignKey: \"createdby\" };\n  };\n  return User;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Ticket = sequelize.define(\n    \"Ticket\",\n    {\n      id: {\n        type: DataTypes.INTEGER(11),\n        allowNull: false,\n        primaryKey: true,\n        field: \"id\"\n      },\n      details: {\n        type: DataTypes.STRING(45),\n        allowNull: true,\n        field: \"details\"\n      },\n      assignedto: {\n        type: DataTypes.INTEGER(11),\n        allowNull: true,\n        field: \"assignedto\"\n      },\n      createdby: {\n        type: DataTypes.INTEGER(11),\n        allowNull: true,\n        field: \"createdby\"\n      },\n      createdat: {\n        type: DataTypes.DATE,\n        allowNull: false,\n        field: \"createdat\"\n      },\n      updatedat: {\n        type: DataTypes.DATE,\n        allowNull: true,\n        field: \"updatedat\"\n      },\n      deletedat: {\n        type: DataTypes.DATE,\n        allowNull: true,\n        field: \"deletedat\"\n      }\n    },\n    {\n      tableName: \"tickets\",\n      timestamps: false\n    }\n  );\n\n  Ticket.associate = function(models) {\n        models.Ticket.belongsTo(models.User,\n            { foreignKey: \"createdby\" });\n  };\n  return Ticket;\n};\n```\n\n```text\nmodels.User.findAll({\n    include: [models.Ticket]\n  })\n```\n\n```text\nSELECT \n    `User`.`id`,\n    `User`.`username`,\n    `User`.`fullname`,\n    `User`.`createdat`,\n    `User`.`updateat`,\n    `User`.`deletedat`,\n    `Tickets`.`id` AS `Tickets.id`,\n    `Tickets`.`details` AS `Tickets.details`,\n    `Tickets`.`assignedto` AS `Tickets.assignedto`,\n    `Tickets`.`createdby` AS `Tickets.createdby`,\n    `Tickets`.`createdat` AS `Tickets.createdat`,\n    `Tickets`.`updatedat` AS `Tickets.updatedat`,\n    `Tickets`.`deletedat` AS `Tickets.deletedat`\nFROM\n    `users` AS `User`\nLEFT OUTER JOIN\n    `tickets` AS `Tickets` ON `User`.`id` = `Tickets`.`createdby`\n```\n\n```text\nSELECT \n    `User`.`id`,\n    `User`.`username`,\n    `User`.`fullname`,\n    `User`.`createdat`,\n    `User`.`updateat`,\n    `User`.`deletedat`,\n    `Tickets`.`id` AS `Tickets.id`,\n    `Tickets`.`details` AS `Tickets.details`,\n    `Tickets`.`assignedto` AS `Tickets.assignedto`,\n    `Tickets`.`createdby` AS `Tickets.createdby`,\n    `Tickets`.`createdat` AS `Tickets.createdat`,\n    `Tickets`.`updatedat` AS `Tickets.updatedat`,\n    `Tickets`.`deletedat` AS `Tickets.deletedat`,\n    `Tickets`.`UserId` AS `Tickets.UserId`\nFROM\n    `users` AS `User`\nLEFT OUTER JOIN\n    `tickets` AS `Tickets` ON `User`.`id` = `Tickets`.`UserId`;\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: Unknown column 'Tickets.UserId' in 'field list'\n```\n\n```text\nmodels.Ticket.belongsTo(models.User, { foreignKey: \"createdby\" });\n```\n\n```text\nmodels.Ticket.belongsTo(models.User, { targetKey: \"createdby\" });\n```\n\n```text\nbelongsTo\n```\n\n```text\nforeignKey\n```\n\n```text\ntargetKey\n```\n\n```text\nforeignKey\n```\n\n```text\nsourceModel.belongsTo(targetModel, options)\n```\n\n```text\ntargetKey\n```\n\n```text\nforeignKey\n```\n\n```text\ncreatedBy\n```\n\n```text\nTicket\n```\n\n```text\nUser\n```\n\n```text\ncreatedBy\n```\n\n```text\nTicket\n```\n\n```text\nTicket.UserID\n```\n\n```text\nbelongsTo\n```\n\n```js\nPlant.findAll({\n        include: Farm,\n        order: [['name', 'ASC']]\n        })\n        .then(data=> {\n            res.send(data)\n        })\n        .catch(err => {\n            res.send(err)\n            console.log(err);\n            \n        })\n        \nlet arrQuery = [\n      queryInterface.addColumn('farms', 'dayPlayed' , Sequelize.STRING),\n      queryInterface.removeColumn('plants', 'dayPlayed' , Sequelize.STRING),\n    ]\n      return Promise.all(arrQuery)\n```\n\n========================================\n\nComments:\n- I found this thread useful for same reasons of brilang i order to point me in the right direction to define the associations in modles. Next step is how to populate the relations. I am reading documentation about setUser or addUser but none is working. Help or sugestions will be apreciated.\n- Thank you. I got this sample working. I've moved on to other libraries as I'm experimenting and learning what works and doesn't for me.\n- Some text explanation would be helpful, especially since running the snippet yields an error","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":462,"estimatedTokens":2359}}539{"id":"stack-36102501","source":"stackoverflow","questionId":36102501,"title":"in sequelize is it possible to paginate the Nested request using Nested eager loading?","tags":["node.js","sequelize.js"],"text":"Title: in sequelize is it possible to paginate the Nested request using Nested eager loading?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using the Nested eager loading funcionality, this is the sequelize example:\n\n```\nUser.findAll({\n include: [{\n model: Tool,\n as: 'Instruments',\n include: [{\n model: Teacher,\n where: {\n school: \"Woodstock Music School\"\n },\n required: false\n }]\n }]\n}).then(function(users) {\n /* ... */\n})\n```\n\nImagine you want to do an `endpoint` 'summary' and you want to include the `Teacher model`, but only the first three results\n\nIt is possible using only the Nested eager loading?\n\nSequelize provides a way to achieve this purpose?\n\n========================================\n\nTop Answer:\nYou can use limit and offset with teacher model \n\n```\nUser.findAll({\n include: [{\n model: Tool,\n as: 'Instruments',\n include: [{\n model: Teacher,\n where: {\n school: \"Woodstock Music School\"\n },\n limit: 3,\n required: false\n }\n ]\n }\n ]\n}).then(function (users) {\n /* ... */\n})\n```\n\n========================================\n\nCode:\n```text\nUser.findAll({\n  include: [{\n    model: Tool,\n    as: 'Instruments',\n    include: [{\n      model: Teacher,\n      where: {\n        school: \"Woodstock Music School\"\n      },\n      required: false\n    }]\n  }]\n}).then(function(users) {\n  /* ... */\n})\n```\n\n```text\nendpoint\n```\n\n```text\nTeacher model\n```\n\n```text\nUser.findAll({\n    include: [{\n            model: Tool,\n            as: 'Instruments',\n            include: [{\n                    model: Teacher,\n                    where: {\n                        school: \"Woodstock Music School\"\n                    },\n                      limit: 3,\n                    required: false\n                }\n            ]\n        }\n    ]\n}).then(function (users) {\n    /* ... */\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":106,"estimatedTokens":450}}540{"id":"stack-16847724","source":"stackoverflow","questionId":16847724,"title":"Find or create with SequelizeJS","tags":["node.js","express","sequelize.js"],"text":"Title: Find or create with SequelizeJS\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI try to use the \"findOrCreate\" function of SequelizeJS but it doesn't work.\n\nThe variable \"created\" is \"undefined\", so I don't know why because it's a variable used by SequelizeJS...\n\n```\nfor( var i = 0; i < tags.length; i++ ){\n global.db.Tag.findOrCreate({name: tags[i]}).success( function(tag, created){\n if( created ){\n global.db.PostTag.create({\n PostId: id,\n TagId: tag.id\n });\n }\n });\n}\n```\n\n========================================\n\nTop Answer:\nFor me the answer was changing my promise resolver from .then to a .spread. This has something to do with the format that Sequelize returns data.\n\n```\nfor( var i = 0; i < tags.length; i++ ){\n global.db.Tag.findOrCreate({\n name: tags[i]\n }).spread( function(tag, created){\n if( created ){\n global.db.PostTag.create({\n PostId: id,\n TagId: tag.id\n });\n }\n });\n}\n```\n\n========================================\n\nCode:\n```text\nfor( var i = 0; i < tags.length; i++ ){\n    global.db.Tag.findOrCreate({name: tags[i]}).success( function(tag, created){\n        if( created ){\n            global.db.PostTag.create({\n                PostId: id,\n                TagId: tag.id\n            });\n        }\n    });\n}\n```\n\n```js\nglobal.db.Tag.findOrCreate({\n    where:{\n        name: tags[i]\n    }, \n    defaults: {\n    //properties you want on create\n    }\n}).then( function(tag){\n    var created  = tag[1];\n    tag = tag[0]; //new or found\n    if( created ){\n\n    }\n}).fail(function(err) {\n\n});\n```\n\n```text\nfor( var i = 0; i < tags.length; i++ ){\n    global.db.Tag.findOrCreate({\n        name: tags[i]\n    }).spread( function(tag, created){\n        if( created ){\n            global.db.PostTag.create({\n                PostId: id,\n                TagId: tag.id\n            });\n        }\n    });\n}\n```\n\n```text\nTag.findOrCreate({\n     where: { condition: value },\n     // in the event that it is not found\n     defaults: { /* properties of the model to create */ }\n })\n     .then(tag => res.send(tag))\n     .catch(err => res.send(err))`\n```\n\n```text\n{\n    {\n        /* tagProperties */\n    },\n    /* true if the tag was created\n       false if the tag was found */\n}\n```\n\n========================================\n\nComments:\n- Which version are you using? I believe that change might not have been published to npm, so could you try using the latest version from github.com/sequelize/sequelize?\n- This is correct. `.spread` is the correct way for handling findOrCreate for anybody stumbling upon this quesiton. **From the sequelize docs:** *\"By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use .spread to access the results.\"* docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html\n- Use can also just use `await` which gives you a two-element array, then deconstruct or grab element `[0]`.\n- Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues.","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":119,"estimatedTokens":806}}541{"id":"stack-58420410","source":"stackoverflow","questionId":58420410,"title":"Model Loader for Sequelize v5 & Typescript","tags":["typescript","express","sequelize.js"],"text":"Title: Model Loader for Sequelize v5 & Typescript\nTags: typescript, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHave used Sequelize before for projects ( v4 ), but attempting to start a new project with Sequelize v5 & Typescript\n\nI have followed Sequelize's documentation for how to define Models at:\nhttps://sequelize.org/master/manual/typescript.html#usage-of--code-sequelize-define--code-\n\nI have a working ORM now, but **only when importing the actual model for use**, not through importing the db from the model loader.\n\ni.e. `import { User } from \"../db/models/user\";`\n\nimporting the db, just returns **undefined** when trying to access db.User.\n\nTrying to figure out how to get the model loader to place nice with the Sequelize V5 and Typescript, but currently its coming up empty.\n\nNow, I can tell that its searching for **.js** files. So obviously it won't be picking up the user.ts file. Changing this to **.ts** then gives me the error....\n\n```\nat Sequelize.import (/node_modules/sequelize/lib/sequelize.js:486:38)\n at fs_1.default.readdirSync.filter.forEach.file (/src/db/models/index.ts:26:35)\n at Array.forEach ()\n at Object. (/src/db/models/index.ts:25:4)\n```\n\nI have been trying to get a clear answer from web searches, but seem to come up empty. It was a headache enough with trying to get everything to play nice.... and at this point I am running migrations/seeders as js files because I don't want to deal with the **sequelize-typescript-cli** or **sequelize-typescript**\n\n`src/db/models/user.ts`\n**User Model**\n\n```\nimport { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';\nimport { HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, Association, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin } from 'sequelize';\nconst db = require('./index')\nimport * as bcrypt from \"bcryptjs\";\n\nexport interface UserAttributes extends Model {\n id: string;\n email: string;\n username: string;\n password: string;\n createdAt: Date;\n updatedAt: Date;\n validatePassword(password: string): boolean;\n generateHash(password: string): string;\n}\n\nexport type UserModel = typeof Model & {\n new (): UserAttributes;\n};\n\nexport const User = db.sequelize.define(\"User\", {\n id: {\n type: DataTypes.UUID,\n allowNull: false,\n primaryKey: true\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true\n },\n username: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false,\n }\n},\n{\n tableName: \"User\",\n freezeTableName: true,\n });\n\n User.prototype.validatePassword = function (password: string) {\n\n return bcrypt.compareSync(password, this.password)\n }\n\n User.prototype.generateHash = function (password: string) {\n return bcrypt.hashSync(password, bcrypt.genSaltSync(10))\n }\n```\n\n`src/db/models/index.ts`\n**Model Loader**\n\n```\n'use strict';\n\nimport fs from \"fs\";\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(module.filename);\n\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(`${__dirname}/../config/config.json`)[env];\n\ninterface DB {\n [key: string]: any;\n}\n\nvar db: DB = {};\n\nconst sequelize = new Sequelize(config.database, config.username, config.password, config);\n\nfs.readdirSync(__dirname)\n .filter(file => {\n return (\n file.indexOf(\".\") !== 0 && file !== basename && file.slice(-3) === \".js\"\n );\n })\n .forEach(file => {\n const model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n });\n// Important: creates associations based on associations defined in associate function in the model files\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nFurthermore reading https://sequelize.org/master/manual/typescript.html#usage\n\nThere seems to be a little clearer ( but somewhat more redundant way ) of defining Models, but then how is this **init** method called when initializing Sequelize from index.js?\n\n========================================\n\nCode:\n```text\nat Sequelize.import (/node_modules/sequelize/lib/sequelize.js:486:38)\n    at fs_1.default.readdirSync.filter.forEach.file (/src/db/models/index.ts:26:35)\n    at Array.forEach (<anonymous>)\n    at Object.<anonymous> (/src/db/models/index.ts:25:4)\n```\n\n```text\nimport { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';\nimport { HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, Association, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin } from 'sequelize';\nconst db = require('./index')\nimport * as bcrypt from \"bcryptjs\";\n\nexport interface UserAttributes extends Model {\n  id: string;\n  email: string;\n  username: string;\n  password: string;\n  createdAt: Date;\n  updatedAt: Date;\n  validatePassword(password: string): boolean;\n  generateHash(password: string): string;\n}\n\nexport type UserModel = typeof Model & {\n  new (): UserAttributes;\n};\n\nexport const User = <UserModel>db.sequelize.define(\"User\", {\n  id: {\n    type: DataTypes.UUID,\n    allowNull: false,\n    primaryKey: true\n  },\n  email: {\n    type: DataTypes.STRING,\n    allowNull: false,\n    unique: true\n  },\n  username: {\n    type: DataTypes.STRING,\n    allowNull: false,\n    unique: true\n  },\n  password: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  }\n},\n{\n  tableName: \"User\",\n  freezeTableName: true,\n });\n\n User.prototype.validatePassword = function (password: string) {\n\n  return bcrypt.compareSync(password, this.password)\n }\n\n User.prototype.generateHash = function (password: string) {\n    return bcrypt.hashSync(password, bcrypt.genSaltSync(10))\n  }\n```\n\n```text\n'use strict';\n\nimport fs from \"fs\";\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(module.filename);\n\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(`${__dirname}/../config/config.json`)[env];\n\ninterface DB {\n  [key: string]: any;\n}\n\nvar db: DB = {};\n\nconst sequelize = new Sequelize(config.database, config.username, config.password, config);\n\nfs.readdirSync(__dirname)\n  .filter(file => {\n    return (\n      file.indexOf(\".\") !== 0 && file !== basename && file.slice(-3) === \".js\"\n    );\n  })\n  .forEach(file => {\n    const model = sequelize.import(path.join(__dirname, file));\n    db[model.name] = model;\n  });\n// Important: creates associations based on associations defined in associate function in the model files\nObject.keys(db).forEach(modelName => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nimport { User } from \"../db/models/user\";\n```\n\n```text\nsrc/db/models/user.ts\n```\n\n```text\nsrc/db/models/index.ts\n```\n\n```text\nimport { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';\nimport { Association, HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin } from 'sequelize';\nimport { Identity } from './identity';\nexport class User extends Model {\n  public id!: string; // Note that the `null assertion` `!` is required in strict mode.\n  public active!: boolean;\n\n  // timestamps!\n  public readonly createdAt!: Date;\n  public readonly updatedAt!: Date;\n\n  public getIdentities!: HasManyGetAssociationsMixin<Identity>; // Note the null assertions!\n  public addIdentity!: HasManyAddAssociationMixin<Identity, number>;\n  public hasIdentity!: HasManyHasAssociationMixin<Identity, number>;\n  public countIdentities!: HasManyCountAssociationsMixin;\n  public createIdentity!: HasManyCreateAssociationMixin<Identity>;\n\n  // You can also pre-declare possible inclusions, these will only be populated if you\n  // actively include a relation.\n  public readonly identities?: Identity[]; // Note this is optional since it's only populated when explicitly requested in code\n\n  public static associations: {\n    identities: Association<User, Identity>;\n  };\n\n}\n\nexport function initUser(sequelize: Sequelize): void {\n  User.init({\n    id: {\n      type: DataTypes.UUID,\n      primaryKey: true,\n    },\n    active: {\n      type:DataTypes.BOOLEAN,\n      defaultValue: true,\n      allowNull: false\n    }\n  }, {\n    tableName: 'User', \n    sequelize: sequelize, // this bit is important\n  });\n\n\n}\n\nexport function associateUser(): void {\n  // Here we associate which actually populates out pre-declared `association` static and other methods.\n  User.hasMany(Identity, {\n    sourceKey: 'id',\n    foreignKey: 'UserId',\n    as: 'identities' // this determines the name in `associations`!\n  });\n}\n```\n\n```text\nimport { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';\nimport { Association, HasOneGetAssociationMixin, HasOneCreateAssociationMixin } from 'sequelize';\nimport { User } from './user'\n\nimport * as bcrypt from \"bcryptjs\";\n\nexport class Identity extends Model {\n  public id!: string; // Note that the `null assertion` `!` is required in strict mode.\n  public username!: string;\n  public password!: string;\n  public UserId: string;\n  public active!: boolean;\n\n  // timestamps!\n  public readonly createdAt!: Date;\n  public readonly updatedAt!: Date;\n\n  public getUser!: HasOneGetAssociationMixin<User>; // Note the null assertions!\n\n  // You can also pre-declare possible inclusions, these will only be populated if you\n  // actively include a relation.\n  public readonly user?: User; // Note this is optional since it's only populated when explicitly requested in code\n\n  public static associations: {\n    user: Association<Identity, User>;\n  };\n\n  public validatePassword(password: string) : boolean {\n    return bcrypt.compareSync(password, this.password)\n  }\n}\n\nexport function initIdentity(sequelize: Sequelize): void {\n  Identity.init({\n    id: {\n      type: DataTypes.UUID,\n      primaryKey: true,\n    },\n    username: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true\n    },\n    password: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    UserId: {\n      type: DataTypes.UUID,\n      allowNull: true\n    },\n    active: {\n      type:DataTypes.BOOLEAN,\n      defaultValue: true,\n      allowNull: false\n    }\n  }, {\n    tableName: 'Identity', \n    sequelize: sequelize, // this bit is important\n  });\n\n}\n\nexport function associateIdentity(): void {\n  // Here we associate which actually populates out pre-declared `association` static and other methods.\n  Identity.belongsTo(User, {targetKey: 'id'});\n}\n```\n\n```text\nimport { initUser, associateUser } from \"./user\";\nimport { initIdentity, associateIdentity } from \"./identity\";\n\nconst Sequelize = require('sequelize');\n\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(`${__dirname}/../config/config.json`)[env];\n\n\ninterface DB {\n  [key: string]: any;\n}\n\nconst sequelize = new Sequelize(config.database, config.username, config.password, config);\n\ninitUser(sequelize);\ninitIdentity(sequelize)\n\nassociateUser();\nassociateIdentity();\n\nconst db = {\n  sequelize,\n  Sequelize,\n  User: sequelize.models.User,\n  Identity: sequelize.models.Identity\n}\n\nmodule.exports = db;\n```\n\n```text\n'use strict'\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable({tableName:'Identity'}, {\n      id: {\n        type: Sequelize.UUID,\n        defaultValue: Sequelize.UUIDV4,\n        allowNull: false,\n        autoIncrement: false,\n        primaryKey: true,\n      },\n      username: {\n        type: Sequelize.STRING,\n        allowNull: false,\n        unique: true,\n      },\n      password: {\n        type: Sequelize.STRING,\n        allowNull: false,\n      },\n      UserId: {\n        type: Sequelize.UUID,\n        references: {\n          model: 'User', // name of Target model\n          key: 'id', // key in Target model that we're referencing\n        },\n        onUpdate: 'CASCADE',\n        onDelete: 'SET NULL',\n      },\n      active: {\n        type: Sequelize.BOOLEAN,\n        defaultValue: true,\n        allowNull: false,\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n        defaultValue: Sequelize.NOW\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n        defaultValue: Sequelize.NOW\n      },\n    })\n  },\n  down: (queryInterface) => {\n    return queryInterface.dropTable({tableName:'Identity', schema:'public'})\n  }\n}\n```\n\n```text\n'use strict'\nvar moment = require('moment');\nvar uuidv4 = require('uuid/v4');\nconst bcrypt = require('bcryptjs');\n\nmodule.exports = {\n  up: async (queryInterface) => {   \n      // User\n      const user1Id = uuidv4();\n      await queryInterface.bulkInsert('User', \n        [\n          {\n            id:user1Id,\n            createdAt: new Date( moment.utc().format() ), \n            updatedAt: new Date( moment.utc().format() )\n          }\n        ], \n      )\n      await queryInterface.bulkInsert('Identity', \n        [\n          {\n            id:uuidv4(),\n            username: \"user1\",\n            password: bcrypt.hashSync('password', bcrypt.genSaltSync(10)),\n            UserId: user1Id,\n            createdAt: new Date( moment.utc().format() ), \n            updatedAt: new Date( moment.utc().format() )\n          }\n        ], \n      )\n\n      const user2Id = uuidv4();\n      await queryInterface.bulkInsert('User', \n        [\n          {\n            id:user2Id,\n            createdAt: new Date( moment.utc().format() ), \n            updatedAt: new Date( moment.utc().format() )\n          }\n        ], \n      )\n      await queryInterface.bulkInsert('Identity', \n        [\n          {\n            id:uuidv4(),\n            username: \"user2\",\n            password: bcrypt.hashSync('password', bcrypt.genSaltSync(10)),\n            UserId: user2Id,\n            createdAt: new Date( moment.utc().format() ), \n            updatedAt: new Date( moment.utc().format() )\n          }\n        ], \n      )\n\n      const user3Id = uuidv4();\n      await queryInterface.bulkInsert('User', \n        [\n          {\n            id:user3Id,\n            createdAt: new Date( moment.utc().format() ), \n            updatedAt: new Date( moment.utc().format() )\n          }\n        ], \n      )\n      await queryInterface.bulkInsert('Identity', \n        [\n          {\n            id:uuidv4(),\n            username: \"user3\",\n            password: bcrypt.hashSync('password', bcrypt.genSaltSync(10)),\n            UserId: user3Id,\n            createdAt: new Date( moment.utc().format() ), \n            updatedAt: new Date( moment.utc().format() )\n          }\n        ], \n      )\n\n\n  },\n  down: async (queryInterface) => {\n    await queryInterface.bulkDelete({ tableName: 'User'}, null, {})\n  }\n}\n```\n\n```text\nsequelize db:migrate\nsequelize db:seed:all\n```\n\n```text\n/src/db/models/user.ts\n```\n\n```text\n/src/db/models/identity.ts\n```\n\n```text\ninit<model>\n```\n\n```text\nassociate<model>\n```\n\n```text\nidentity.ts\n```\n\n```text\n/src/db/index.ts\n```\n\n```text\ndefine\n```\n\n```text\ndefine\n```\n\n```text\ninit<model>\n```\n\n```text\nassociate<model>\n```\n\n```text\n20191017135846-create-identity.js\n```\n\n```text\n20191015141822-seed-users.js\n```\n\n========================================\n\nComments:\n- Thanks for taking the time to answer your own question. You would like feedback and I would like to give you feedback, but not now, I'm super busy. Can you remind me in a few weeks? Feel free to ping me here or on the github issue (@papb).","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":614,"estimatedTokens":3875}}542{"id":"stack-38183242","source":"stackoverflow","questionId":38183242,"title":"Sequelize Transactions : ER_LOCK_WAIT_TIMEOUT","tags":["mysql","transactions","sequelize.js"],"text":"Title: Sequelize Transactions : ER_LOCK_WAIT_TIMEOUT\nTags: mysql, transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni've problem with sequelize transactions with mysql(5.6.17),i've one insert statement and two updates which should all done or none,howerver in the end `transactions.create` seems rolling back but `driver.update` executes and doesn't rollback and third update which is `trip.update` statement without any changes or rollback,the console hangs and after a few seconds throw this error:\n\n```\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): START TRANSACTION;\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): SET autocommit = 1;\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): INSERT INTO `transactions` (`id`,`tId`,`total_price`,`company_share`,`driver_share`,`at`) VALUES (DEFAULT,'13',1000,100,900,'2016-07-04 10:44:43');\nExecuting (default): UPDATE `driver` SET `balance`=`balance` - 100 WHERE `id` = '1'\nExecuting (default): UPDATE `trip` SET `paid`=1 WHERE `id` = '13'\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): ROLLBACK;\n5---SequelizeDatabaseError: ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction\n```\n\nthe transaction section is:\n\n```\nvar Sequelize = require('sequelize');\nvar config = {};\nconfig.sequelize = new Sequelize('mydb', 'root', null, {\n host: 'localhost',\n port: 3306,\n dialect: 'mysql',\n logging: true,\n pool: {\n max: 100,\n min: 0,\n idle: 10000\n },\n define: {\n timestamps: false\n }\n});\nrequire('sequelize-isunique-validator')(Sequelize);\nvar driver = require('./../models/driver.js')(config.sequelize, Sequelize);\nvar transactions = require('./../models/transactions.js')(config.sequelize, Sequelize);\nvar trip = require('./../models/trip.js')(config.sequelize, Sequelize);\n\nreturn config.sequelize.transaction({isolationLevel:Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED},function (t) {\nreturn transactions.create({tId: tripId, total_price: totalPrice, company_share: companyShare, driver_share: driverShare}, {transaction: t})\n .then(function (result) {\n return driver.update({balance: config.sequelize.literal('`balance` - '+companyShare)}, {where: {id: dId}}, {transaction: t})\n .then(function (result) {\n return trip.update({paid: 1}, {where: {id: tripId}}, {transaction: t});\n });\n});\n\n}).then(function (result) {\n RequestQueue.hmset(ticket,\"ticketState\",value.Paid);\n res.json({'status': 'success','change':(-company_share)});\n}).catch(function (err) {\n global.console.log('5---'+err);\n res.json({'status': 'failed'});\n});\n```\n\nI'm sure my models are correct because I used them somewhere else without any problem on crud and not putting them here in order to keeps the question clean and on topic but if it helps ask in comments,tnx!\n\n========================================\n\nCode:\n```text\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): START TRANSACTION;\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): SET autocommit = 1;\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): INSERT INTO `transactions` (`id`,`tId`,`total_price`,`company_share`,`driver_share`,`at`) VALUES (DEFAULT,'13',1000,100,900,'2016-07-04 10:44:43');\nExecuting (default): UPDATE `driver` SET `balance`=`balance` - 100 WHERE `id` = '1'\nExecuting (default): UPDATE `trip` SET `paid`=1 WHERE `id` = '13'\nExecuting (42a68c8e-8347-45af-b9a2-7b0e7a89606b): ROLLBACK;\n5---SequelizeDatabaseError: ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar config = {};\nconfig.sequelize = new Sequelize('mydb', 'root', null, {\n    host: 'localhost',\n    port: 3306,\n    dialect: 'mysql',\n    logging: true,\n    pool: {\n        max: 100,\n        min: 0,\n        idle: 10000\n    },\n    define: {\n        timestamps: false\n    }\n});\nrequire('sequelize-isunique-validator')(Sequelize);\nvar driver = require('./../models/driver.js')(config.sequelize, Sequelize);\nvar transactions = require('./../models/transactions.js')(config.sequelize, Sequelize);\nvar trip = require('./../models/trip.js')(config.sequelize, Sequelize);\n\n\nreturn config.sequelize.transaction({isolationLevel:Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED},function (t) {\nreturn transactions.create({tId: tripId, total_price: totalPrice, company_share: companyShare, driver_share: driverShare}, {transaction: t})\n    .then(function (result) {\n    return driver.update({balance: config.sequelize.literal('`balance` - '+companyShare)}, {where: {id: dId}}, {transaction: t})\n        .then(function (result) {\n            return trip.update({paid: 1}, {where: {id: tripId}}, {transaction: t});\n        });\n});\n\n}).then(function (result) {\n    RequestQueue.hmset(ticket,\"ticketState\",value.Paid);\n    res.json({'status': 'success','change':(-company_share)});\n}).catch(function (err) {\n    global.console.log('5---'+err);\n    res.json({'status': 'failed'});\n});\n```\n\n```text\ntransactions.create\n```\n\n```text\ndriver.update\n```\n\n```text\ntrip.update\n```\n\n```text\n.then(function (result) {\n        return driver.update({balance: config.sequelize.literal('`balance` - ' + companyShare)}, {\n                    where: {id: dId},\n                    transaction: t\n                })\n                .then(function (result) {\n                    return trip.update({paid: 1}, {where: {id: tripId}, transaction: t});\n                });\n```\n\n```text\ntransaction\n```\n\n```text\noptions\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":147,"estimatedTokens":1400}}543{"id":"stack-37683186","source":"stackoverflow","questionId":37683186,"title":"Trying to query postgres JSON data type with sequelize","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Trying to query postgres JSON data type with sequelize\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a newly created column in my table I need to query in one of my server controllers. This data in this column will be of JSON type and is named \"meta\". It will look something like this when completed\n\n```\n{\n \"audit\": {\"date\": 1465311598315, \"user\": 20191932891}\n}\n```\n\ncurrently all of the entries in this table have the empty JSON column with a NULL value. \n\nIn one of my server controllers I need to grab all entries where where meta is null or meta.audit.date is more than 90 days old. My query looks something like this\n\n```\ndb.Question.findAll({\n where: {\n status: 'active',\n PassageId: {\n $eq: null\n },\n meta: {\n audit: {\n date: {\n $or: {\n $lte: threeMonthsAgo,\n $eq: null\n }\n }\n }\n }\n }\n});\n```\n\nIn this case three months ago is the date three months ago as a number.\n\nNo results are being returned and I get this error in my console:\n\n```\nUnhandled rejection SequelizeDatabaseError: operator does not exist: text <= bigint\n```\n\n========================================\n\nCode:\n```text\n{\n  \"audit\": {\"date\": 1465311598315, \"user\": 20191932891}\n}\n```\n\n```text\ndb.Question.findAll({\n  where: {\n    status: 'active',\n    PassageId: {\n      $eq: null\n    },\n    meta: {\n      audit: {\n        date: {\n          $or: {\n            $lte: threeMonthsAgo,\n            $eq: null\n          }\n        }\n      }\n    }\n  }\n});\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: operator does not exist: text <= bigint\n```\n\n```text\ndb.Question.findAll({\n  where: {\n    status: 'active',\n    PassageId: {\n      $eq: null\n    },\n    {\n      $or: [{\n        'meta.audit.date': {\n          $eq: null\n        }\n      }, {\n        'meta.audit.date': {\n          $lte: threeMonthsAgo\n        }\n      }]\n    }\n\n  }\n});\n```\n\n========================================\n\nComments:\n- Since date type is stored as string in JSON, here 'meta.audit.date' is a string. Do you need to convert it to date before comparing with `threeMonthsAgo` which is a date I assume?","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":523}}544{"id":"stack-37110227","source":"stackoverflow","questionId":37110227,"title":"How do you query a table with a schema in Sequelize.js?","tags":["postgresql","sequelize.js"],"text":"Title: How do you query a table with a schema in Sequelize.js?\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table called 'wallets' in the 'dbo' schema of my postgresql database.\nWhen I try to query it I get the error:\n\n```\nExecuting (default): SELECT \"wallets_id\", \"confirmed_balance\", \"unconfirmed_balance\", \"created_at\", \"updated_at\" FROM \"dbo.wallets\" AS \"dbo.wallets\";\nUnhandled rejection SequelizeDatabaseError: relation \"dbo.wallets\" does not exist\n```\n\nThis is my code:\n\n```\nget_dbo__wallets() : any {\n const options = this.getDatabaseDefaultOptions('dbo.wallets');\n const entity : types.IObjectWithStringKey = {};\n entity['wallets_id'] = {type: Sequelize.UUID, primaryKey: true, allowNull : false};\n entity['confirmed_balance'] = Sequelize.BIGINT;\n entity['unconfirmed_balance'] = Sequelize.BIGINT;\n return this._db.define('dbo.wallets', entity, options);\n}\n\ngetDatabaseDefaultOptions(tableName : string) : types.IObjectWithStringKey {\n const options : types.IObjectWithStringKey = {};\n options['timestamps'] = true;\n options['createdAt'] = 'created_at';\n options['updatedAt'] = 'updated_at';\n options['underscored'] = false;\n\n options['paranoid'] = false;\n options['deletedAt'] = false;\n\n options['freezeTableName'] = true;\n options['tableName'] = tableName;\n return options;\n}\n\n//and then I call: get_dbo__wallets().all()\n```\n\n**What should I change in the model definition to set the schema name correctly?**\n\n========================================\n\nCode:\n```text\nExecuting (default): SELECT \"wallets_id\", \"confirmed_balance\", \"unconfirmed_balance\", \"created_at\", \"updated_at\" FROM \"dbo.wallets\" AS \"dbo.wallets\";\nUnhandled rejection SequelizeDatabaseError: relation \"dbo.wallets\" does not exist\n```\n\n```text\nget_dbo__wallets() : any {\n    const options = this.getDatabaseDefaultOptions('dbo.wallets');\n    const entity : types.IObjectWithStringKey = {};\n    entity['wallets_id'] = {type: Sequelize.UUID, primaryKey: true, allowNull : false};\n    entity['confirmed_balance'] = Sequelize.BIGINT;\n    entity['unconfirmed_balance'] = Sequelize.BIGINT;\n    return this._db.define('dbo.wallets', entity, options);\n}\n\ngetDatabaseDefaultOptions(tableName : string) : types.IObjectWithStringKey {\n    const options : types.IObjectWithStringKey = {};\n    options['timestamps'] = true;\n    options['createdAt'] = 'created_at';\n    options['updatedAt'] = 'updated_at';\n    options['underscored'] = false;\n\n    options['paranoid'] = false;\n    options['deletedAt'] = false;\n\n    options['freezeTableName'] = true;\n    options['tableName'] = tableName;\n    return options;\n}\n\n//and then I call:  get_dbo__wallets().all()\n```\n\n```text\noptions['schema'] = 'dbo';\n```\n\n========================================\n\nComments:\n- you can add dbo to search_path for the user and ommit schema name\n- or `var initSequelize = new Sequelize( 'database', 'username', 'password', {dialect :'postgres', port:'5432',schema:dbo});`\n- Thanks. But I want to define it per table - because different tables are in different schemas. e.g. dbo.wallets, enum.sexes, banking.transactions.\n- then set search_path for user and omit schema name I guess\n- But what if I have banking.transactions and dbo.transactions? If I omit the schema it'll break. I need to specify schema on the table definition\n- then you have to build several `new Sequelize` object I believe\n- No, that won't work either, because queries need to pull data from multiple tables in different schemas. There must be a proper way of doing this in Sequelize.\n- Let us continue this discussion in chat.\n- Alternatively you could change the `search_path` for that database user.","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":97,"estimatedTokens":911}}545{"id":"stack-35182330","source":"stackoverflow","questionId":35182330,"title":"Cant retrieve the model name for Sequelize with mysql","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: Cant retrieve the model name for Sequelize with mysql\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to nodejs and the Sequelize ORM framework. I am trying to get it to work with mysql. I have made some great progress but at the moment I am stuck at the part where sequelize needs to load in the models. But I am getting an error where the name is retrieved from the file.\n\nwww\n\n```\nvar debug = require('debug')('sampleapp')\nvar app = require('../server');\nvar models = require('../model');\n\napp.set('port', process.env.PORT || 3000);\n\n//server running\nmodels.sequelize.sync().then(function () {\n var server = app.listen(app.get('port'), function(){\n debug('The magic is happening on port '+server.address().port);\n });\n});\n```\n\nindex.js\n\n```\n\"use strict\"\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar debug = require('debug');\nvar env = process.env.NODE_ENV || \"development\";\nvar config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\nvar db = {};\n\nfs.readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== 'index.js')\n })\n .forEach(function(file) {\n var model = sequelize['import'](path.join(__dirname, file))\n db[model.name] = model\n });\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nuser.js\n\n```\nmodule.exports = function(sequelize, DataType){\n\n var User = sequelize.define('user', {\n name: DataType.STRING,\n password: DataType.STRING,\n lastName: DataType.STRING,\n email: DataType.STRING,\n gender: DataType.CHAR,\n cellNumber: DataType.INTEGER\n }, {\n instanceMethods : {\n create : function(onSuccess, onError){\n var name = this.name;\n var lastName = this.lastName;\n var email = this.email;\n var gender = this.gender;\n var cellNumber = this.cellNumber;\n var password = this.password;\n\n var shasum = crypto.createHash('sha1');\n shasum.update(password);\n password = shasum.digest('hex');\n\n User.build({name: name, lastName: lastName, email: email, gender: gender, cellNumber: cellNumber, password: password})\n .save().success(onSuccess).error(onError);\n }\n }\n });\n};\n```\n\nI keep getting this error at db[model.name] = model :\n\n TypeError: Cannot read property 'name' of undefined\n\nHave been on this error for a while now. any help would be greatly appreciated\n\n========================================\n\nTop Answer:\nThe problem is it can't find the model you have created.\n\n```\nreturn User\n```\n\nworked for me.\n\n========================================\n\nCode:\n```text\nvar debug = require('debug')('sampleapp')\nvar app = require('../server');\nvar models = require('../model');\n\napp.set('port', process.env.PORT || 3000);\n\n//server running\nmodels.sequelize.sync().then(function () {\n  var server = app.listen(app.get('port'), function(){\n    debug('The magic is happening on port '+server.address().port);\n  });\n});\n```\n\n```text\n\"use strict\"\nvar fs        = require('fs');\nvar path      = require('path');\nvar Sequelize = require('sequelize');\nvar debug = require('debug');\nvar env = process.env.NODE_ENV || \"development\";\nvar config    = require(path.join(__dirname, '..', 'config', 'config.json'))[env];\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\nvar db        = {};\n\nfs.readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf(\".\") !== 0) && (file !== 'index.js')\n  })\n  .forEach(function(file) {\n    var model = sequelize['import'](path.join(__dirname, file))\n    db[model.name] = model\n  });\n\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nmodule.exports = function(sequelize, DataType){\n\n  var User = sequelize.define('user', {\n    name: DataType.STRING,\n    password: DataType.STRING,\n    lastName: DataType.STRING,\n    email: DataType.STRING,\n    gender: DataType.CHAR,\n    cellNumber: DataType.INTEGER\n  }, {\n    instanceMethods : {\n      create : function(onSuccess, onError){\n        var name = this.name;\n        var lastName = this.lastName;\n        var email = this.email;\n        var gender = this.gender;\n        var cellNumber = this.cellNumber;\n        var password = this.password;\n\n        var shasum = crypto.createHash('sha1');\n        shasum.update(password);\n        password = shasum.digest('hex');\n\n        User.build({name: name, lastName: lastName, email: email, gender: gender, cellNumber: cellNumber, password: password})\n          .save().success(onSuccess).error(onError);\n      }\n    }\n  });\n};\n```\n\n```text\n(file.slice(-3) === '.js')\n```\n\n```text\n.filter(function(file) {\n    return (file.indexOf('.') !== 0) && (file !== \"index.js\") && (file.slice(-3) === '.js');\n})\n```\n\n```text\nvar sequelize = new Sequelize(foo, bar, baz);\nsequelize.authenticate().then(function() {\n  console.log('Database connected and authenticated!');\n  return true;\n}).catch(function(err) {\n  console.error('Failed to connect and authenticate', err);\n  return false;\n});\n```\n\n```text\nmodel\n```\n\n```text\n.js\n```\n\n```text\nPromise\n```\n\n```text\nfs.readdirSync()\n```\n\n```text\nreturn User\n```\n\n========================================\n\nComments:\n- thanks for your descriptive reply. It helped a lot. where would you recommend putting the db check? in the app.js?\n- Of course! I'm glad I could help! Honestly that db check function can be run anywhere, its only purpose is to verify that you have connectivity to the database. It basically just authenticates and runs a simple query `SELECT 1 + 1` to make sure it can do what it needs to. I wouldn't recommend it existing anywhere but where you bootstrap your application.\n- Might also be because your're not returning anything in your model file","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":227,"estimatedTokens":1446}}546{"id":"stack-50546653","source":"stackoverflow","questionId":50546653,"title":"How to prevent Sequelize from converting Date object to local time","tags":["node.js","sequelize.js","utc"],"text":"Title: How to prevent Sequelize from converting Date object to local time\nTags: node.js, sequelize.js, utc\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize for a node project. It's connecting to a Postgres databsae, which contains a table with a `DATE` field (unlike `TIMESTAMP WITH TIMEZONE`, `DATE` has not time data).\n\nIn the code I'm modeling the date using a javascript `Date` object, which stores the time as UTC midnight. When I use that to insert a record into the table using that `Date` object, sequelize is apparently coverting it to local time first because the records are always 1 day behind. So if I want to insert 2000-10-31 into the database I end up with 2000-10-30. I am in UTC-5.\n\nHow do I tell sequelize to not convert the Date to a local time before inserting into the database?\n\nHere is some sample code. I also created a repository if you want to run it yourself.\n\n```\nvar Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('testdb', 'postgres', '???', {\n host: 'localhost',\n dialect: 'postgres'\n});\n\nTestTable = sequelize.define('date_test',\n {\n id: {\n primaryKey: true,\n type: Sequelize.INTEGER,\n autoIncrement: true\n },\n\n someDate: {\n field: 'some_date',\n type: Sequelize.DATEONLY\n }\n },\n {\n timestamps: false,\n freezeTableName: true\n }\n);\n\n// midnight UTC on Halloween 🎃\nvar date = new Date(Date.UTC(2000, 9, 31));\n\n// converts to local time resulting in 2000-10-30\nTestTable.create({ someDate: date })\n .then(function() {\n // also apparently converts to local time resulting in 2000-10-30\n return TestTable.create({ someDate: date.toUTCString() });\n })\n .then(function() {\n // convert to string, definitely works but seems unnecessary\n var strDate = date.getUTCFullYear() + '-' + pad2(date.getUTCMonth() + 1) + '-' + pad2(date.getUTCDate());\n return TestTable.create({ someDate: strDate });\n })\n .then(function() {\n // cerate a new local Date, also works but seems hacky\n var newDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());\n return TestTable.create({ someDate: newDate });\n })\n .then(function() {\n process.exit(0);\n });\n\nfunction pad2(n) {\n if (n.length === 1) {\n return '0' + n;\n }\n\n return n;\n}\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('testdb', 'postgres', '???', {\n    host: 'localhost',\n    dialect: 'postgres'\n});\n\nTestTable = sequelize.define('date_test',\n    {\n        id: {\n            primaryKey: true,\n            type: Sequelize.INTEGER,\n            autoIncrement: true\n        },\n\n        someDate: {\n            field: 'some_date',\n            type: Sequelize.DATEONLY\n        }\n    },\n    {\n        timestamps: false,\n        freezeTableName: true\n    }\n);\n\n// midnight UTC on Halloween 🎃\nvar date = new Date(Date.UTC(2000, 9, 31));\n\n// converts to local time resulting in 2000-10-30\nTestTable.create({ someDate: date })\n    .then(function() {\n        // also apparently converts to local time resulting in 2000-10-30\n        return TestTable.create({ someDate: date.toUTCString() });\n    })\n    .then(function() {\n        // convert to string, definitely works but seems unnecessary\n        var strDate = date.getUTCFullYear() + '-' + pad2(date.getUTCMonth() + 1) + '-' + pad2(date.getUTCDate());\n        return TestTable.create({ someDate: strDate });\n    })\n    .then(function() {\n        // cerate a new local Date, also works but seems hacky\n        var newDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());\n        return TestTable.create({ someDate: newDate });\n    })\n    .then(function() {\n        process.exit(0);\n    });\n\n\nfunction pad2(n) {\n    if (n.length === 1) {\n        return '0' + n;\n    }\n\n    return n;\n}\n```\n\n```text\nDATE\n```\n\n```text\nTIMESTAMP WITH TIMEZONE\n```\n\n```text\nDATE\n```\n\n```text\nDate\n```\n\n```text\nDate\n```\n\n```text\nvar date = new Date(2000, 9, 31);\n```\n\n```text\nDATEONLY\n```\n\n```text\nYYYY-MM-DD\n```\n\n```text\nDATEONLY\n```\n\n```text\ndate.toUTCString()\n```\n\n```text\n2000-11-01 05:00\n```\n\n========================================\n\nComments:\n- Sequelize is not creating the date field as type `TIMESTAMP WITH TIMEZONE` because I'm not using the `Sequelize.DATE` type. I'm using `Sequelize.DATEONLY`, which creates a postgres `DATE` field, which has no time data.\n- How are you inspecting the value of the table? In postgresql or javascript?\n- I'm looking at them in postgres\n- If you run `SELECT your_date_field AT TIME ZONE 'GMT' FROM your_table` does it show the correct date? Sorry, I don't have a postgresql installation handy...\n- It shows `2018-10-31 05:00:00` which is the correct date, but is the time meaningful since postgres doesn't store time values in DATE fields? It looks like it's assuming it's midnight my time (UTC-5) and then converting it to UTC by adding 5 hours.\n- I see, so sequelize is using moment to convert my UTC time to a local time, which is rolling it back to the previous day because of my timezone. So I guess the proper fix would be to create a local `Date` object using the values from the UTC `Date` object? Like this: `var localDate = new Date(utcDate.getUTCFullYear(), utcDate.getUTCMonth(), utcDate.getUTCDate())`? That should create a local `Date` object set to midnight on the date I want.\n- Since the `DATEONLY` sequelize field doesn't care about timezone, I would skip the UTC part and just create your date like this: `var date = new Date(2000, 9, 31);`\n- But I have to know which values to pass into the `Date` constructor and those are coming from other `Date` objects whose time values are midnight UTC.\n- Apologies, yes I can't see any cleaner way to do it. If you store the dates as midnight local time, you can just pass those straight in. But if you are getting them in UTC time for whatever reason, you will have to use the `utcDate.getUTC...()` functions - or you could add the local time offset to the UTC date, but that seems equally hacky.","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":191,"estimatedTokens":1486}}547{"id":"stack-45643823","source":"stackoverflow","questionId":45643823,"title":"Sequelize : Cannot connect to SQL Server - incorrect port is being passed","tags":["sql-server","node.js","sequelize.js"],"text":"Title: Sequelize : Cannot connect to SQL Server - incorrect port is being passed\nTags: sql-server, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to connect to a SQL Server instance but the wrong port is being defined when I attempt to connect.\n\n Unable to connect to the database: { SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306\n\n at Handshake._callback (C:\\test\\ExpressGeneric\\node_modules\\sequelize\\lib\\dialects\\mysql\\connection-manager.js:80:20)\n\n at Handshake.Sequence.end (C:\\test\\ExpressGeneric\\node_modules\\mysql\\lib\\protocol\\sequences\\Sequence.js:88:24)\n\n at Protocol.handleNetworkError (C:\\test\\ExpressGeneric\\node_modules\\mysql\\lib\\protocol\\Protocol.js:363:14)\n\n at Connection._handleNetworkError (C:\\test\\ExpressGeneric\\node_modules\\mysql\\lib\\Connection.js:428:18)\n at emitOne (events.js:96:13)\n at Socket.emit (events.js:188:7)\n at emitErrorNT (net.js:1277:8)\n at _combinedTickCallback (internal/process/next_tick.js:80:11)\n at process._tickCallback (internal/process/next_tick.js:104:9)\n name: 'SequelizeConnectionRefusedError',\n message: 'connect ECONNREFUSED 127.0.0.1:3306',\n\nI have no idea why this is happening. \n\nHere are my configuration settings. I only changed the pass and db for this post, I am using the correct credentials when connecting.\n\n```\nconfig.sql = {\n host: 'sql2012dev',\n database: 'db',\n user: 'sa',\n password: 'pass'\n}\n```\n\nAnd here is my connection. \n\n```\nconst sequelize = new Sequelize(config.sql.database, config.sql.user, config.sql.password, {\n host: config.sql.host,\n dialect: 'mssql',\n port: '1433',\n driver: 'tedious',\n dialectOptions:{\n instanceName: MSSQLSERVER \n },\n define: {\n timestamps: false\n },\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n },\n})\n```\n\nI'm able to connect to it remotely just fine using the management studio. Named Pipes and SQL Browser is enabled.\n\nI also had to run npm mysql just to get the app to start.\n\nHere are my dependencies just in case\n\n```\n\"dependencies\": {\n \"async\": \"2.1.5\",\n \"body-parser\": \"1.17.1\",\n \"client-sessions\": \"0.7.0\",\n \"cookie-parser\": \"1.4.3\",\n \"crypto\": \"0.0.3\",\n \"debug\": \"2.6.2\",\n \"ejs\": \"2.5.6\",\n \"express\": \"4.15.2\",\n \"helmet\": \"3.5.0\",\n \"jquery\": \"3.1.1\",\n \"moment\": \"2.17.1\",\n \"morgan\": \"1.8.1\",\n \"mssql\": \"^4.0.4\",\n \"nsp\": \"2.6.3\",\n \"sendgrid\": \"4.8.0\",\n \"sequelize\": \"^3.14.1\",\n \"tedious\": \"^2.0.0\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nHave you changed the default port of mysql. If not then use default port in your configuration.\n\n```\nconst sequelize = new Sequelize(config.sql.database, config.sql.user, config.sql.password, {\n host: config.sql.host,\n dialect: 'mssql',\n port: '3306', //-------------> change port here\n driver: 'tedious',\n dialectOptions:{\n instanceName: MSSQLSERVER \n },\n define: {\n timestamps: false\n },\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n },\n})\n```\n\nAlso make sure your server is started and accessible from the machine where you are running your application.\n\n========================================\n\nCode:\n```text\nconfig.sql = {\n    host: 'sql2012dev',\n    database: 'db',\n    user: 'sa',\n    password: 'pass'\n}\n```\n\n```text\nconst sequelize = new Sequelize(config.sql.database, config.sql.user, config.sql.password, {\n  host: config.sql.host,\n  dialect: 'mssql',\n  port: '1433',\n  driver: 'tedious',\n  dialectOptions:{\n   instanceName: MSSQLSERVER \n  },\n  define: {\n    timestamps: false\n  },\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  },\n})\n```\n\n```text\n\"dependencies\": {\n    \"async\": \"2.1.5\",\n    \"body-parser\": \"1.17.1\",\n    \"client-sessions\": \"0.7.0\",\n    \"cookie-parser\": \"1.4.3\",\n    \"crypto\": \"0.0.3\",\n    \"debug\": \"2.6.2\",\n    \"ejs\": \"2.5.6\",\n    \"express\": \"4.15.2\",\n    \"helmet\": \"3.5.0\",\n    \"jquery\": \"3.1.1\",\n    \"moment\": \"2.17.1\",\n    \"morgan\": \"1.8.1\",\n    \"mssql\": \"^4.0.4\",\n    \"nsp\": \"2.6.3\",\n    \"sendgrid\": \"4.8.0\",\n    \"sequelize\": \"^3.14.1\",\n    \"tedious\": \"^2.0.0\"\n  }\n}\n```\n\n```html\nvar sequelize = new Sequelize(db,userName,password,{\n    dialect: 'mssql',\n    host: hostName,\n    port: 1433,\n    logging: false,\n    dialectOptions: {\n      requestTimeout: 30000,\n      encrypt: true\n    }\n  })\n```\n\n```text\nconst sequelize = new Sequelize(config.sql.database, config.sql.user, config.sql.password, {\n  host: config.sql.host,\n  dialect: 'mssql',\n  port: '3306', //-------------> change port here\n  driver: 'tedious',\n  dialectOptions:{\n   instanceName: MSSQLSERVER \n  },\n  define: {\n    timestamps: false\n  },\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  },\n})\n```\n\n========================================\n\nComments:\n- You have not specified the port number in your configuration. Specify the port in your configuration as specified in NodeJsConnection\n- I'm not using MySQL. I'm using Microsoft SQL Server. I have not changed the port and yes, it is on and I am able to connect to it remotely, just as I stated in my post. The problem is that port 3306 is being defined somewhere else and I have no idea why. I do not want to use port 3306 because that is not the port that is being used by the database server. The port that is being used is 1433.\n- In the first example you were using port as a string '1433', instead of 1433 as number","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":209,"estimatedTokens":1297}}548{"id":"stack-45903574","source":"stackoverflow","questionId":45903574,"title":"Connect to a local SQL Server db with sequelize","tags":["sql-server","sequelize.js"],"text":"Title: Connect to a local SQL Server db with sequelize\nTags: sql-server, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHaving completed the SQL Server installer, the given connection string is `Server=localhost\\MSSQLSERVER01;Database=master;Trusted_Connection=True;`, which seems like a strange format, and if I try to connect to the db with sequelize using that connection string:\n\n```\nvar sequelize = new Sequelize(process.env.DB_STRING);\n```\n\nI get the error:\n\n TypeError: Cannot read property 'replace' of null\n\n \n at new Sequelize\n (C:\\Users\\George\\Source\\Repos\\TestProj\\node_modules\\sequelize\\lib\\sequelize.js:132:40)\n at Object.\n (C:\\Users\\George\\Source\\Repos\\TestProj\\models\\index.js:13:21) at\n Module._compile (module.js:570:32)\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize(process.env.DB_STRING);\n```\n\n```text\nServer=localhost\\MSSQLSERVER01;Database=master;Trusted_Connection=True;\n```\n\n```text\nvar sequelize = new Sequelize({\n  dialect: 'mssql',\n  dialectModulePath: 'sequelize-msnodesqlv8',\n  dialectOptions: {\n    instanceName: 'MSSQLSERVER01',\n    trustedConnection: true\n  },\n  host: 'localhost',\n  database: 'master'\n});\n```\n\n```text\nvar sequelize = new Sequelize({\n  dialect: 'mssql',\n  dialectModulePath: 'sequelize-msnodesqlv8',\n  dialectOptions: {\n    connectionString: 'Server=localhost\\MSSQLSERVER01;Database=master; Trusted_Connection=yes;'\n  },\n});\n```\n\n```text\nsequelize-msnodesqlv8\n```\n\n```text\nMaster\n```\n\n========================================\n\nComments:\n- Related for PostgreSQL: stackoverflow.com/questions/46207155/&hellip;\n- Thanks! Hmm I am getting issue `Unhandled rejection SequelizeConnectionError: [Microsoft][SQL Server Native Client 11.0]Invalid value specified for connection string attribute 'Trusted_Connection'` with your second snippet?\n- @GeorgeEdwards Try Integrated Security=SSPI; instead of Trusted_Connection=True;. Or Trusted_Connection=yes;\n- Hmm, now I just get `Unhandled rejection SequelizeConnectionError: [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [53]`\n- Can you connect to `localhost\\MSSQLSERVER01` using SSMS and Windows Authentication? You should verify that, looks like it does not allow you to connect. Check this.\n- @GeorgeEdwards But this is another problem which is not really connected with your original question.\n- I can connect fine in ssms, but not with sequelize?\n- @GeorgeEdwards Your web server probably running under system account. Either add that account to SQL logins or use sql authentication.\n- If I do a `whoami` in command prompt, I get `surface\\george` which if I run `CREATE LOGIN [surface\\george] FROM WINDOWS;` in my db, I get the error, `The server principal 'surface\\george' already exists.`\n- The probl&#233;m is not with your user account, but with the account you run your program, a web server I assume.\n- Oh I see, I am using an express on nodejs, running sequelize. How would I find out the account that is running with?\n- No idea, depends on how do you launch it. Check `services.msc` if it's there.\n- But more usual is to use SQL authentication for a web server, not integrated windows authentication.\n- This for my development, I use SQL auth for my remote (and prod) enviroments. See this question - we think maybe sequelize doesn't support this?\n- sequelize-msnodesqlv8 should supprt SQL connection with integrated authentication. Standart Sequelize does not support it.\n- Yes, but I can't seem to get either to support it","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":882}}549{"id":"stack-35222934","source":"stackoverflow","questionId":35222934,"title":"Sequelize.js: how to handle reconnection with MySQL","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize.js: how to handle reconnection with MySQL\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've always used Mongo with Node, but now due to an existing datasource I need to connect a node app with Mysql.\n\nSequelize seems a good solution, but I don't get how to handle connection error, reconnection and re-tries.\n\nTo check for connection error on first run `.authenticate().then().catch(function(error){...});`\nBut what if I loose connection and want to reconnect?\n\n========================================\n\nTop Answer:\nI verified the version 4.11.1 of sequelize has this issue fixed.\nThe queries will fail when the database server is down, but will recover to reconnect and succeed when the database server is up.\n\n(You don't need to restart the application as faced with previous versions.)\n\n========================================\n\nCode:\n```text\n.authenticate().then().catch(function(error){...});\n```\n\n========================================\n\nComments:\n- what do you mean with \"this error is handled in sequelize\"?\n- If the connection is lost, the lib will reconnect automatically.\n- that's great! How I could test it stopping mysql server while the app is running? Will it automatically log something? Thanks for help!\n- It is a good question, actually I don't know. :D But yeh, restart the sql server is a good test case. :)\n- Did you need to add custom retry options to the Sequelize instance? Looking at the source for sequelize it looks like it will only retry on `SQLITE_BUSY: Database is locked` errors by default.\n- I didn't use any custom retry option. `var seqDb = new Sequelize(config.dbUri, { operatorsAliases: false }); module.exports = seqDb; seqDb.sync() .then(() => { console.log('Connected to DB...'); }) .catch(err => { console.log('Error connecting to DB: ' + err.message); });`","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":36,"estimatedTokens":460}}550{"id":"stack-59937776","source":"stackoverflow","questionId":59937776,"title":"How to use Sequelize create with nested objects and relations","tags":["javascript","node.js","orm","sequelize.js","relational-database"],"text":"Title: How to use Sequelize create with nested objects and relations\nTags: javascript, node.js, orm, sequelize.js, relational-database\nSource: Stack Overflow\n\nQuestion:\nI have 3 models. User, Item and Location.\n\n```\nUser.hasMany(Item)\nLocation.hasMany(Item)\nItem.belongsTo(User)\nItem.belongsTo(Location)\n```\n\nthis runs, but does not create the location foreign key nor location row in locations table.\n\n```\nmodels.User.create(\n {\n username: 'ddavids',\n email: 'hello@david.com',\n password: '12345678',\n items: [\n {\n itemName: 'Good Book',\n orderDate: '2020-01-20',\n locations: { locationName: 'floor' }\n },\n {\n itemName: 'Bad Book',\n orderDate: '2020-01-21',\n locations: { locationName: 'shelf' }\n }\n ]\n },\n {\n include: [{ model: models.Item, include: [models.Location] }]\n }\n )\n```\n\nThis creates the items and locations correctly but obviously not under a user.\n\n```\nmodels.Location.create(\n {\n locationName: 'floor',\n items: [\n {\n itemName: 'Good Book',\n orderDate: '2020-01-20',\n locations: { locationName: 'floor' }\n },\n {\n itemName: 'Bad Book',\n orderDate: '2020-01-21',\n locations: { locationName: 'shelf' }\n }\n ]\n },\n { include: [models.Item] }\n )\n```\n\nWhat I can't figure out is if my relations are the wrong way to go about this or if its a limitation of create and I should move on or what.\nMy end goal will be something along the lines of.\n\n```\nUser.hasMany(Order)\n Order.belongsTo(User)\n Order.hasMany(Item)\n Item.belongsTo(Order)\n Location.hasMany(Item)\n Item.belongsTo(location)\n Supplier.hasMany(Item)\n Item.belongsTo(Supplier)\n```\n\nI am currently using create just to create some fake data for when I make changes. So if there is a better way to seed the database that would be my end goal.\n\n========================================\n\nCode:\n```text\nUser.hasMany(Item)\nLocation.hasMany(Item)\nItem.belongsTo(User)\nItem.belongsTo(Location)\n```\n\n```text\nmodels.User.create(\n    {\n      username: 'ddavids',\n      email: 'hello@david.com',\n      password: '12345678',\n      items: [\n        {\n          itemName: 'Good Book',\n          orderDate: '2020-01-20',\n          locations: { locationName: 'floor' }\n        },\n        {\n          itemName: 'Bad Book',\n          orderDate: '2020-01-21',\n          locations: { locationName: 'shelf' }\n        }\n      ]\n    },\n    {\n      include: [{ model: models.Item, include: [models.Location] }]\n    }\n   )\n```\n\n```text\nmodels.Location.create(\n    {\n      locationName: 'floor',\n      items: [\n        {\n          itemName: 'Good Book',\n          orderDate: '2020-01-20',\n          locations: { locationName: 'floor' }\n        },\n        {\n          itemName: 'Bad Book',\n          orderDate: '2020-01-21',\n          locations: { locationName: 'shelf' }\n        }\n      ]\n    },\n    { include: [models.Item] }\n   )\n```\n\n```text\nUser.hasMany(Order)\n Order.belongsTo(User)\n Order.hasMany(Item)\n Item.belongsTo(Order)\n Location.hasMany(Item)\n Item.belongsTo(location)\n Supplier.hasMany(Item)\n Item.belongsTo(Supplier)\n```\n\n```js\nimport { sequelize } from '../../db';\nimport { Model, DataTypes } from 'sequelize';\n\nclass User extends Model {}\nUser.init(\n  {\n    username: DataTypes.STRING,\n    email: DataTypes.STRING,\n    password: DataTypes.STRING,\n  },\n  { sequelize, modelName: 'user' },\n);\n\nclass Location extends Model {}\nLocation.init(\n  {\n    locationName: DataTypes.STRING,\n  },\n  { sequelize, modelName: 'location' },\n);\n\nclass Item extends Model {}\nItem.init(\n  {\n    itemName: DataTypes.STRING,\n    orderDate: DataTypes.STRING,\n  },\n  { sequelize, modelName: 'item' },\n);\n\nUser.hasMany(Item);\nLocation.hasMany(Item);\nItem.belongsTo(User);\nItem.belongsTo(Location);\n\n(async function test() {\n  try {\n    await sequelize.sync({ force: true });\n    await User.create(\n      {\n        username: 'ddavids',\n        email: 'hello@david.com',\n        password: '12345678',\n        items: [\n          {\n            itemName: 'Good Book',\n            orderDate: '2020-01-20',\n            location: { locationName: 'floor' },\n          },\n          {\n            itemName: 'Bad Book',\n            orderDate: '2020-01-21',\n            location: { locationName: 'shelf' },\n          },\n        ],\n      },\n      {\n        include: [{ model: Item, include: [Location] }],\n      },\n    );\n  } catch (error) {\n    console.log(error);\n  } finally {\n    await sequelize.close();\n  }\n})();\n```\n\n```sh\nnode-sequelize-examples=# select * from \"user\";\n id | username |      email      | password\n----+----------+-----------------+----------\n  1 | ddavids  | hello@david.com | 12345678\n(1 row)\n\nnode-sequelize-examples=# select * from \"location\";\n id | locationName\n----+--------------\n  1 | floor\n  2 | shelf\n(2 rows)\n\nnode-sequelize-examples=# select * from \"item\";\n id | itemName  | orderDate  | userId | locationId\n----+-----------+------------+--------+------------\n  1 | Good Book | 2020-01-20 |      1 |          1\n  2 | Bad Book  | 2020-01-21 |      1 |          2\n(2 rows)\n```\n\n```text\nLocation\n```\n\n```text\nItem\n```\n\n```text\nlocations: { locationName: 'floor' }\n```\n\n```text\nlocation: { locationName: 'floor' }\n```\n\n```text\nItem\n```\n\n```text\nindex.ts\n```\n\n```text\n\"sequelize\": \"^5.21.3\",\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":265,"estimatedTokens":1286}}551{"id":"stack-25700004","source":"stackoverflow","questionId":25700004,"title":"How can I do a group by across 3 tables with Sequelize?","tags":["sequelize.js"],"text":"Title: How can I do a group by across 3 tables with Sequelize?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy models are:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var CommitFileStatistic;\n return CommitFileStatistic = sequelize.define('CommitFileStatistic', {\n additions: {\n type: DataTypes.INTEGER,\n allowNull: false\n },\n deletions: {\n type: DataTypes.INTEGER,\n allowNull: false\n },\n status: {\n type: DataTypes.STRING,\n allowNull: false\n },\n fileSize: {\n type: DataTypes.INTEGER,\n allowNull: true\n },\n levenshteinDelta: {\n type: DataTypes.INTEGER,\n allowNull: true\n },\n fileHash: {\n type: DataTypes.STRING,\n allowNull: true\n }\n }, {\n classMethods: {\n associate: function(models) {\n CommitFileStatistic.belongsTo(models.Commit);\n return CommitFileStatistic.belongsTo(models.SourceFile);\n }\n }\n });\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n var SourceFile;\n return SourceFile = sequelize.define('SourceFile', {\n filename: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n classMethods: {\n associate: function(models) {\n return SourceFile.belongsTo(models.Repository);\n }\n }\n });\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n var Commit;\n return Commit = sequelize.define('Commit', {\n sha: {\n type: DataTypes.STRING,\n allowNull: false\n },\n commitTime: {\n type: DataTypes.INTEGER,\n allowNull: false\n },\n message: {\n type: DataTypes.TEXT,\n allowNull: false\n },\n isParsed: {\n type: DataTypes.BOOLEAN,\n allowNull: false,\n defaultValue: false\n }\n }, {\n classMethods: {\n associate: function(models) {\n Commit.hasMany(models.Branch);\n return Commit.hasMany(models.Commit, {\n as: 'Parent',\n through: 'ParentCommit'\n });\n }\n }\n });\n};\n```\n\nI want to do a query that would basically do: `SELECT COUNT(*) AS fileCount, sf.* FROM CommitFileStatistics cfs, Commits c, SourceFiles sf WHERE cfs.CommitId = c.id AND cfs.SourceFileId = sf.id AND c.RepositoryId = 2 GROUP BY cfs.SourceFileId ORDER BY fileCount DESC` however I want to use the ORM instead of a raw query. Is this possible?\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var CommitFileStatistic;\n  return CommitFileStatistic = sequelize.define('CommitFileStatistic', {\n    additions: {\n      type: DataTypes.INTEGER,\n      allowNull: false\n    },\n    deletions: {\n      type: DataTypes.INTEGER,\n      allowNull: false\n    },\n    status: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    fileSize: {\n      type: DataTypes.INTEGER,\n      allowNull: true\n    },\n    levenshteinDelta: {\n      type: DataTypes.INTEGER,\n      allowNull: true\n    },\n    fileHash: {\n      type: DataTypes.STRING,\n      allowNull: true\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        CommitFileStatistic.belongsTo(models.Commit);\n        return CommitFileStatistic.belongsTo(models.SourceFile);\n      }\n    }\n  });\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n  var SourceFile;\n  return SourceFile = sequelize.define('SourceFile', {\n    filename: {\n      type: DataTypes.STRING,\n      allowNull: false\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        return SourceFile.belongsTo(models.Repository);\n      }\n    }\n  });\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n  var Commit;\n  return Commit = sequelize.define('Commit', {\n    sha: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    commitTime: {\n      type: DataTypes.INTEGER,\n      allowNull: false\n    },\n    message: {\n      type: DataTypes.TEXT,\n      allowNull: false\n    },\n    isParsed: {\n      type: DataTypes.BOOLEAN,\n      allowNull: false,\n      defaultValue: false\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Commit.hasMany(models.Branch);\n        return Commit.hasMany(models.Commit, {\n          as: 'Parent',\n          through: 'ParentCommit'\n        });\n      }\n    }\n  });\n};\n```\n\n```text\nSELECT COUNT(*) AS fileCount, sf.* FROM CommitFileStatistics cfs, Commits c, SourceFiles sf WHERE cfs.CommitId = c.id AND cfs.SourceFileId = sf.id AND c.RepositoryId = 2 GROUP BY cfs.SourceFileId ORDER BY fileCount DESC\n```\n\n```text\nreturn CommitFileStatistic.findAll({\n  attributes: [[Sequelize.fn('COUNT', '*'), 'fileCount']],\n  include: [\n    { model: Commit, attributes: [] },\n    { model: SourceFile, attributes: [] }\n  ],\n  group: ['SourceFileId'],\n  order: [['fileCount', 'DESC']]\n});\n```\n\n```text\nSELECT \n    `CommitFileStatistic`.`id`, \n    COUNT('*') AS `fileCount`, \n    `Commit`.`id` AS `Commit.id`, \n    `SourceFile`.`id` AS `SourceFile.id` \nFROM \n    `commit_file_statistics` AS `CommitFileStatistic` \nLEFT OUTER JOIN `commits` AS `Commit` \n    ON `Commit`.`id` = `CommitFileStatistic`.`CommitId` \nLEFT OUTER JOIN `source_files` AS `SourceFile` \n    ON `SourceFile`.`id` = `CommitFileStatistic`.`SourceFileId` \nGROUP BY `SourceFileId` \nORDER BY `fileCount` DESC;\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.385Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":219,"estimatedTokens":1228}}552{"id":"stack-36394450","source":"stackoverflow","questionId":36394450,"title":"Associating 3 tables in SEQUELIZE","tags":["sequelize.js"],"text":"Title: Associating 3 tables in SEQUELIZE\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to associate 3 tables in sequelize.\n\nThe models I have created are as follows.\n\nhttps://i.sstatic.net/HK00u.png\n\nUsers model\n\n```\nvar Sequelize = require('sequelize');\n\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define('User', {\n uuid: {\n type: Sequelize.STRING,\n primaryKey: true\n },\n first_name: {\n type: Sequelize.STRING,\n allowNull: false\n },\n last_name: {\n type: Sequelize.STRING,\n allowNull: false\n },\n birth_date: {\n type: Sequelize.DATE,\n allowNull: false\n },\n gender: {\n type: Sequelize.STRING,\n allowNull: true\n },\n email_id: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n isEmail: true\n }\n },\n contact_number: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n isNumeric: true\n }\n }\n }, {\n classMethods: {\n associate: function(models) {\n User.hasMany(models.UserSchool)\n }\n }\n });\n\n return User;\n};\n```\n\nSchools model\n\n```\nvar Sequelize = require('sequelize');\n\nmodule.exports = function(sequelize, DataTypes) {\n var School = sequelize.define('School', {\n school_id: {\n type: Sequelize.STRING,\n primaryKey: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false\n },\n address: {\n type: Sequelize.TEXT,\n allowNull: false\n },\n city: {\n type: Sequelize.STRING,\n allowNull: false\n }\n }, {\n classMethods: {\n associate: function(models) {\n School.hasMany(models.UserSchool)\n }\n }\n });\n\n return School;\n};\n```\n\nUserSchools model\n\n```\nvar Sequelize = require('sequelize');\n\nmodule.exports = function(sequelize, DataTypes) {\n var UserSchool = sequelize.define('UserSchool', {\n year_of_joining: {\n type: Sequelize.DATE,\n allowNull: true\n },\n year_of_passing: {\n type: Sequelize.DATE,\n allowNull: true\n },\n school_type: {\n type: Sequelize.STRING,\n allowNull: false\n },\n course: {\n type: Sequelize.STRING,\n allowNull: true\n }\n }, {\n classMethods: {\n associate: function(models) {\n UserSchool.belongsTo(models.User, {\n onDelete: \"CASCADE\",\n foreignKey: {\n allowNull: true\n }\n }),\n UserSchool.belongsTo(models.School, {\n onDelete: \"CASCADE\",\n foreignKey: {\n allowNull: true\n }\n });\n }\n }\n });\n\n return UserSchool;\n};\n```\n\nWhen I retrieve users the userschools object is associated but school object is not to userschools. How can I create a 3 way association to retrieve the complete data?\n\nThanks in advance.\n\n========================================\n\nTop Answer:\n```\nUser.belongsToMany(models.School, {\n through: {\n model: models.UserSchool\n },\n foreignKey: 'uuid'\n});\n\nSchool.belongsToMany(models.User, {\n through: {\n model: models.UserSchool\n },\n foreignKey: 'school_id'\n});\n```\n\nThis should solve your problem.\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define('User', {\n    uuid: {\n      type: Sequelize.STRING,\n      primaryKey: true\n    },\n    first_name: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    last_name: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    birth_date: {\n      type: Sequelize.DATE,\n      allowNull: false\n    },\n    gender: {\n      type: Sequelize.STRING,\n      allowNull: true\n    },\n    email_id: {\n      type: Sequelize.STRING,\n      allowNull: false,\n      validate: {\n        isEmail: true\n      }\n    },\n    contact_number: {\n      type: Sequelize.STRING,\n      allowNull: false,\n      validate: {\n        isNumeric: true\n      }\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        User.hasMany(models.UserSchool)\n      }\n    }\n  });\n\n  return User;\n};\n```\n\n```text\nvar Sequelize = require('sequelize');\n\nmodule.exports = function(sequelize, DataTypes) {\n  var School = sequelize.define('School', {\n    school_id: {\n      type: Sequelize.STRING,\n      primaryKey: true\n    },\n    name: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    address: {\n      type: Sequelize.TEXT,\n      allowNull: false\n    },\n    city: {\n      type: Sequelize.STRING,\n      allowNull: false\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        School.hasMany(models.UserSchool)\n      }\n    }\n  });\n\n  return School;\n};\n```\n\n```text\nvar Sequelize = require('sequelize');\n\nmodule.exports = function(sequelize, DataTypes) {\n  var UserSchool = sequelize.define('UserSchool', {\n    year_of_joining: {\n      type: Sequelize.DATE,\n      allowNull: true\n    },\n    year_of_passing: {\n      type: Sequelize.DATE,\n      allowNull: true\n    },\n    school_type: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    course: {\n      type: Sequelize.STRING,\n      allowNull: true\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        UserSchool.belongsTo(models.User, {\n          onDelete: \"CASCADE\",\n          foreignKey: {\n            allowNull: true\n          }\n        }),\n        UserSchool.belongsTo(models.School, {\n          onDelete: \"CASCADE\",\n          foreignKey: {\n            allowNull: true\n          }\n        });\n      }\n    }\n  });\n\n  return UserSchool;\n};\n```\n\n```text\nclassMethods: {\n  associate: function(models) {\n    // associations can be defined here\n    User.belongsToMany(models.School, {\n        through: {\n            model: models.UserSchool\n        },\n        foreignKey: 'uuid'\n    });\n  }\n}\n```\n\n```text\nclassMethods: {\n  associate: function(models) {\n    //associations can be defined here\n    School.belongsToMany(models.User, {\n        through: {\n            model: models.UserSchool\n        },\n        foreignKey: 'school_id'\n    });\n  }\n}\n```\n\n```text\nUser.belongsToMany(models.School, {\n    through: {\n        model: models.UserSchool\n    },\n    foreignKey: 'uuid'\n});\n\nSchool.belongsToMany(models.User, {\n    through: {\n        model: models.UserSchool\n    },\n    foreignKey: 'school_id'\n});\n```\n\n```text\ninclude: [\n            {\n                model: Models.UserSchools,\n                include: [\n                    {\n                        model: Models.Schools,\n                    },\n                ],\n            },\n        ];\n```\n\n========================================\n\nComments:\n- Let me know if there is a better way to save this kind of data in MySQL. Merging Schools and UserSchools table is not an option as I need to maintain a table with unique School Id's :)\n- Worked like a charm. Thanks a lot :) Its true what they say about Sequelize documentation (Its not that great but Sequelize by itself is awesome) :)\n- Hey can you help me with associating 4 tables? stackoverflow.com/questions/41671377/&hellip;\n- Can you help me with associating 4 tables? Would be very helpful stackoverflow.com/questions/41671377/&hellip; Thanks","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":365,"estimatedTokens":1678}}553{"id":"stack-24321135","source":"stackoverflow","questionId":24321135,"title":"How do you specify a read replica using Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: How do you specify a read replica using Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do you specify a read replica using Sequelize?\n\nI have created a very basic test based on their documentation.\n\nhttps://github.com/sequelize/sequelize/blob/master/docs/usage.md\n\n```\nvar Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize('database', 'root', '', {\n dialect: 'mysql',\n port: 3306,\n replication: {\n read: [\n { host: 'host1' }\n ],\n write: { host: 'host2' }\n },\n pool: { // If you want to override the options used for the read pool you can do so here\n maxConnections: 20,\n maxIdleTime: 30000\n }\n})\n\nvar Test = sequelize.define('grammar_scores', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n user_id: {\n type: Sequelize.INTEGER,\n index: true\n }\n}, {\n underscored: true\n});\n\nTest.findAll({ where:{user_id:89} }).success(console.log);\n```\n\nwhich throws the following error...\n\n```\n/Users/tim/code/sequelizetest/node_modules/sequelize/lib/dialects/mysql/connector-manager.js:333\nif (config.pool !== null && config.pool.handleDisconnects) {\n^\n TypeError: Cannot read property 'handleDisconnects' of undefined\n at module.exports.connect (/Users/tim/code/sequelizetest/node_modules/sequelize/lib/dialects/mysql/connector-manager.js:333:44)\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize('database', 'root', '', {\n    dialect: 'mysql',\n    port: 3306,\n    replication: {\n        read: [\n            { host: 'host1' }\n        ],\n        write: { host: 'host2' }\n    },\n    pool: { // If you want to override the options used for the read pool you can do so here\n        maxConnections: 20,\n        maxIdleTime: 30000\n    }\n})\n\n\nvar Test = sequelize.define('grammar_scores', {\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    user_id: {\n        type: Sequelize.INTEGER,\n        index: true\n    }\n}, {\n    underscored: true\n});\n\nTest.findAll({ where:{user_id:89} }).success(console.log);\n```\n\n```text\n/Users/tim/code/sequelizetest/node_modules/sequelize/lib/dialects/mysql/connector-manager.js:333\nif (config.pool !== null && config.pool.handleDisconnects) {\n^\n    TypeError: Cannot read property 'handleDisconnects' of undefined\n    at module.exports.connect (/Users/tim/code/sequelizetest/node_modules/sequelize/lib/dialects/mysql/connector-manager.js:333:44)\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":102,"estimatedTokens":620}}554{"id":"stack-51025837","source":"stackoverflow","questionId":51025837,"title":"sequelize: find in json array","tags":["node.js","postgresql","sequelize.js"],"text":"Title: sequelize: find in json array\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn sequelize i have a model:\n\n```\n{\n modelId: {\n type: DataTypes.UUID ,\n allowNull: false,\n primaryKey: true,\n defaultValue: DataTypes.UUIDV4 \n }\n name: DataTypes.STRING(1024),\n type: DataTypes.STRING,\n obj: DataTypes.JSON\n}\n```\n\nand in DB, my obj is an array like this:\n\n```\n[{\n id: '123456',\n text: 'test',\n name 'xpto'\n},{\n id: '32554',\n text: 'test2',\n name 'xpte'\n},{\n id: '36201',\n text: 'test3',\n name 'xpta'\n}]\n```\n\ni tried these:\n\n```\nbtp.findAll({\n where: {\n obj:{\n [Op.contains]:[{id: req.body.id}]\n }\n },\n attributes: ['modelId','name','type','obj']\n })\n```\n\nbut does not work, return this error:\n\n```\n{\"name\": \"SequelizeDatabaseError\",\n\"parent\": {\n \"name\": \"error\",\n \"length\": 128,\n \"severity\": \"ERROR\",\n \"code\": \"42704\",\n \"file\": \"parse_coerce.c\",\n \"line\": \"1832\",\n \"routine\": \"enforce_generic_type_consistency\",\n \"sql\":\".....\"}\n```\n\nso, i need to find in database all entries have in obj, id: '123456'\n\nmy question is the same than this:\nhttps://github.com/sequelize/sequelize/issues/7349\n\nbut thats does not working for me, i need to return all entries that contains...\ni'm using \"sequelize\": \"4.28.6\", and \"pg-hstore\": \"^2.3.2\",\n\ncan any one help?\n\n========================================\n\nCode:\n```text\n{\n   modelId: {\n      type:  DataTypes.UUID ,\n      allowNull: false,\n      primaryKey: true,\n      defaultValue: DataTypes.UUIDV4 \n    }\n   name: DataTypes.STRING(1024),\n   type: DataTypes.STRING,\n   obj: DataTypes.JSON\n}\n```\n\n```text\n[{\n   id: '123456',\n   text: 'test',\n   name 'xpto'\n},{\n   id: '32554',\n   text: 'test2',\n   name 'xpte'\n},{\n   id: '36201',\n   text: 'test3',\n   name 'xpta'\n}]\n```\n\n```text\nbtp.findAll({\n        where: {\n          obj:{\n             [Op.contains]:[{id: req.body.id}]\n          }\n        },\n        attributes: ['modelId','name','type','obj']\n      })\n```\n\n```text\n{\"name\": \"SequelizeDatabaseError\",\n\"parent\": {\n    \"name\": \"error\",\n    \"length\": 128,\n    \"severity\": \"ERROR\",\n    \"code\": \"42704\",\n    \"file\": \"parse_coerce.c\",\n    \"line\": \"1832\",\n    \"routine\": \"enforce_generic_type_consistency\",\n     \"sql\":\".....\"}\n```\n\n```text\nobj: DataTypes.JSONB\n```\n\n```text\n@>\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":141,"estimatedTokens":561}}555{"id":"stack-32994483","source":"stackoverflow","questionId":32994483,"title":"how to update the field 'updated_at' of a sequelize model without modifiyng any attributes","tags":["node.js","postgresql","timestamp","sequelize.js"],"text":"Title: how to update the field 'updated_at' of a sequelize model without modifiyng any attributes\nTags: node.js, postgresql, timestamp, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize 2.0.0 with PostgreSQL. \n**I would like to know if it's possible to update the field 'updated_at' of a model with one method. If yes, how can I achieve that?**\n\nFor instance, in others frameworks, like Laravel, you have model.touch() to automatically update the 'updated_at' of a model. \n\nI've already tried to use model.save() but as the sequelize doc says, calling this method without attributes does nothing. Also, in the doc, I didn't find anything that allow me to do what I need to do simply.\n\nThanks in advance for help.\n\nEdit: \nTo give an example of what I'm trying to achieved, I've already had an instance of my model: \n `Model.findById(1).then(function(myInstance){\n [...]\n myInstance.update() //here, I didn't change any attributes of myInstance and I would like to update the field udpated_at without doing another query.\n [...]\n}):`\nThe question is : How can I update the field updated_at of my previous instance with one method?\n\n========================================\n\nTop Answer:\nMy solution is a little hackey. I had to update a field on the instance to be different than what it was supposed to be, so that sequelize thought that the field changed, even if it didn't; and make sure the proper field data was passed in afterwards.\n\nFor example, let's say the variable `myInstance` has a field named `title`, and a variable `data` holds the unchanged (or new) title ( `{title:\"OLD_OR_NEW_TITLE\"}` ). If I add to the code `myInstance.set('title', data.title+'_FAKE')`, then when the update/save method is called ( `myInstance.update(data)` ), sequelize will think that the field has changed, even though it might not have.\n\n========================================\n\nCode:\n```text\nModel.findById(1).then(function(myInstance){\n     [...]\n     myInstance.update() //here, I didn't change any attributes of myInstance and I would like to update the field udpated_at without doing another query.\n     [...]\n}):\n```\n\n```text\nmyInstance.set('updatedAt', new Date());\nmyInstance.save().then(function() {\n  // my nice callback stuff\n});\n```\n\n```text\nPost.update({\n  updatedAt: null,\n}, {\n  where: {\n    deletedAt: {\n      $ne: null\n    }\n  }\n});\n```\n\n```text\nmyInstance\n```\n\n```text\ntitle\n```\n\n```text\ndata\n```\n\n```text\n{title:\"OLD_OR_NEW_TITLE\"}\n```\n\n```text\nmyInstance.set('title', data.title+'_FAKE')\n```\n\n```text\nmyInstance.update(data)\n```\n\n========================================\n\nComments:\n- I would like to avoid this query because I've already had an instance of my class. Now I'm trying to do the update with this instance.\n- The provided instance method doesn't seem to be working for me.\n- Since you referenced 'updated_at' above instead of 'updatedAt', perhaps you need to reference the correct field. This could also (confusingly be the case) if you have your configuration set to `{ timestamps: true, updatedAt: 'updated_at' }` or something similar. You need to reference the underscored version, not the camel case version.\n- ow can we set updatedAt to the database current timestamp? In postgres: 'updated_at = now()' We don't want to set the date from nodejs (slightly different), also don't want to use db triggers.\n- I don't know about PostgreSQL but the following works in MySQL for me: `myInstace.changed('updatedAt', true); myInstance.save();`","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":92,"estimatedTokens":870}}556{"id":"stack-61102709","source":"stackoverflow","questionId":61102709,"title":"How export and use models in sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: How export and use models in sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni use sequelize in my node.js project, and i dont know how to export and use table model in another file. \nI save table models in folder for example Profile.js\n\n```\nmodule.exports = (sequielize, DataTypes) => sequielize.define('Profile', {\n ID: {\n type: DataTypes.INTEGER,\n autoIncrement: true,\n primaryKey: true,\n allowNull: false\n },\n Login: {\n type: DataTypes.STRING(24),\n allowNull: false\n },\n SocialClub: {\n type: DataTypes.STRING(128),\n allowNull: false\n },\n Email: {\n type: DataTypes.STRING(64),\n allowNull: false\n },\n RegIP: {\n type: DataTypes.STRING(17),\n allowNull: false\n },\n LastIP:\n {\n type: DataTypes.STRING(17),\n allowNull: false\n },\n RegDate: {\n type: DataTypes.DATE,\n defaultValue: DataTypes.NOW,\n allowNull: false\n },\n LastDate: {\n type: DataTypes.DATE,\n defaultValue: DataTypes.NOW,\n allowNull: false\n }\n});\n```\n\nAnd I have such database module database.js:\n\n```\nconst Sequelize = require('sequelize');\nconst fs = require('fs')\nconst path = require('path')\nconst config = require('../configs/server_conf');\n\ndb = {};\n\nconst sequelize = new Sequelize(\n config.db_settings.database,\n config.db_settings.user,\n config.db_settings.password,\n config.db_settings.options);\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\ndb.checkConnection = async function() {\n sequelize.authenticate().then(() => {\n\n console.log('Подключение к базе данных прошло успешно!');\n\n //import db models\n fs.readdirSync(path.join(__dirname, '..', 'models')).forEach(file => {\n var model = sequelize.import(path.join(__dirname, '..', 'models', file));\n db[model.name] = model;\n\n });\n\n sequelize.sync({\n force: true\n }).then(() => {\n console.log('synchroniseModels: Все таблицы были созданы!');\n }).catch(err => console.log(err));\n\n mp.events.call(\"initServerFiles\");\n\n }).catch(err => {\n console.error('Невозможно подключиться к базе данных:', err);\n });\n}\n\nmodule.exports = db;\n```\n\nAnd i have such an index.js file where i'm exporting checkConnection function:\n\n```\n\"use strict\"\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst { checkConnection } = require('./modules/database.js');\nvar Events = [];\n\nmp.events.add(\n{\n \"initServerFiles\" : () =>\n {\n fs.readdirSync(path.resolve(__dirname, 'events')).forEach(function(i) {\n Events = Events.concat(require('./events/' + i));\n });\n\n Events.forEach(function(i) {\n mp.events.add(i);\n console.log(i);\n });\n\n mp.events.call('initServer');\n\n console.log(\"Загрузка всех файлов прошла успешно!\");\n }\n});\n\ncheckConnection();\n```\n\nSo in a nutshell, how i can export my Profile table and use it, for example:\n\n```\nProfile.create({\n Login: \"0xWraith\",\n SocialClub: \"0xWraith\",\n Email: \"mail@gmail.com\",\n RegIP: \"127.0.0.1\",\n LastIP: \"127.0.0.1\",\n LastDate: \"07.04.2020\"\n }).then(res => {\n console.log(res);\n }).catch(err=>console.log(err));\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequielize, DataTypes) => sequielize.define('Profile', {\n  ID: {\n    type: DataTypes.INTEGER,\n    autoIncrement: true,\n    primaryKey: true,\n    allowNull: false\n  },\n  Login: {\n    type: DataTypes.STRING(24),\n    allowNull: false\n  },\n  SocialClub: {\n    type: DataTypes.STRING(128),\n    allowNull: false\n  },\n  Email: {\n    type: DataTypes.STRING(64),\n    allowNull: false\n  },\n  RegIP: {\n    type: DataTypes.STRING(17),\n    allowNull: false\n  },\n  LastIP:\n  {\n    type: DataTypes.STRING(17),\n    allowNull: false\n  },\n  RegDate: {\n    type: DataTypes.DATE,\n    defaultValue: DataTypes.NOW,\n    allowNull: false\n  },\n  LastDate: {\n    type: DataTypes.DATE,\n    defaultValue: DataTypes.NOW,\n    allowNull: false\n  }\n});\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst fs = require('fs')\nconst path = require('path')\nconst config = require('../configs/server_conf');\n\ndb = {};\n\nconst sequelize = new Sequelize(\n    config.db_settings.database,\n    config.db_settings.user,\n    config.db_settings.password,\n    config.db_settings.options);\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\ndb.checkConnection = async function() {\n    sequelize.authenticate().then(() => {\n\n        console.log('Подключение к базе данных прошло успешно!');\n\n        //import db models\n        fs.readdirSync(path.join(__dirname, '..', 'models')).forEach(file => {\n            var model = sequelize.import(path.join(__dirname, '..', 'models', file));\n            db[model.name] = model;\n\n        });\n\n        sequelize.sync({\n            force: true\n        }).then(() => {\n            console.log('synchroniseModels: Все таблицы были созданы!');\n        }).catch(err => console.log(err));\n\n        mp.events.call(\"initServerFiles\");\n\n    }).catch(err => {\n        console.error('Невозможно подключиться к базе данных:', err);\n    });\n}\n\nmodule.exports = db;\n```\n\n```text\n\"use strict\"\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst { checkConnection } = require('./modules/database.js');\nvar Events = [];\n\nmp.events.add(\n{\n    \"initServerFiles\" : () =>\n    {\n        fs.readdirSync(path.resolve(__dirname, 'events')).forEach(function(i) {\n            Events = Events.concat(require('./events/' + i));\n        });\n\n        Events.forEach(function(i) {\n            mp.events.add(i);\n            console.log(i);\n        });\n\n        mp.events.call('initServer');\n\n        console.log(\"Загрузка всех файлов прошла успешно!\");\n    }\n});\n\ncheckConnection();\n```\n\n```text\nProfile.create({\n            Login: \"0xWraith\",\n            SocialClub: \"0xWraith\",\n            Email: \"mail@gmail.com\",\n            RegIP: \"127.0.0.1\",\n            LastIP: \"127.0.0.1\",\n            LastDate: \"07.04.2020\"\n        }).then(res => {\n             console.log(res);\n        }).catch(err=>console.log(err));\n```\n\n```text\nconst db = require('./modules/database.js');\n...\ndb.Profile.create({\n            Login: \"0xWraith\",\n            SocialClub: \"0xWraith\",\n            Email: \"mail@gmail.com\",\n            RegIP: \"127.0.0.1\",\n            LastIP: \"127.0.0.1\",\n            LastDate: \"07.04.2020\"\n        }).then(res => {\n             console.log(res);\n        }).catch(err=>console.log(err));\n```\n\n========================================\n\nComments:\n- Thanks it's working now, cause my error was that i was trying to export like this ``` const {Profile} = require('./modules/database.js'); Profile.create(...); ```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":298,"estimatedTokens":1597}}557{"id":"stack-63368787","source":"stackoverflow","questionId":63368787,"title":"Sequelize findOrCreate(...).spread is not a function","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize findOrCreate(...).spread is not a function\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using the sequelize 6. When I'm runing `findOrCreate().spread` it says \"findOrCreate(...).spread is not a function\". Here is my code:\n\n```\nconst response = await Response.findOrCreate({\n where: {\n participantId,\n questionId,\n },\n defaults: responseNewDetail,\n})\n return res.status(200).send({ status: 0, data: response })\n```\n\nThis is working fine, but it does not seperate the created status and the model value.\nWhen I'm trying to use spread:\n\n```\nResponse.findOrCreate({\n where: {\n participantId,\n questionId,\n },\n defaults: responseNewDetail,\n}).spread(function(response,created){\n return res.status(200).send({ status: 0, data: response })\n})\n```\n\nIt says \"Response.findOrCreate(...).spread is not a function\".\nThis is the model file(response.js):\n\n```\nconst { Sequelize } = require(\"sequelize\")\n\nmodule.exports = (sequelize, DataTypes) =>\n sequelize.define(\n \"Response\",\n {\n responseId: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n allowNull: false,\n field: \"Response_ID\",\n autoIncrement: true,\n },\n companyId: {\n type: DataTypes.INTEGER,\n allowNull: false,\n field: \"Company_ID\",\n },\n...\n )\n```\n\nResponse model:\n\n```\nconst ResponseModel = require(\"../models/response\")\nconst Response = ResponseModel(sequelize, DataTypes)\n```\n\nDoes anyone know what's wrong?\n\n========================================\n\nTop Answer:\neleborating Brian's Answer :-\n\n`findOrCreate` returns two values first model instance and second created status,\nso you can use\n\n```\nconst [model,created] = ModelName.findOrCreate();\n```\n\n(Model Response in your case)\n\nto get created status.\n\n========================================\n\nCode:\n```text\nconst response = await Response.findOrCreate({\n    where: {\n        participantId,\n        questionId,\n    },\n    defaults: responseNewDetail,\n})\n    return res.status(200).send({ status: 0, data: response })\n```\n\n```text\nResponse.findOrCreate({\n    where: {\n        participantId,\n        questionId,\n    },\n    defaults: responseNewDetail,\n}).spread(function(response,created){\n    return res.status(200).send({ status: 0, data: response })\n})\n```\n\n```text\nconst { Sequelize } = require(\"sequelize\")\n\nmodule.exports = (sequelize, DataTypes) =>\n    sequelize.define(\n        \"Response\",\n        {\n            responseId: {\n                type: DataTypes.INTEGER,\n                primaryKey: true,\n                allowNull: false,\n                field: \"Response_ID\",\n                autoIncrement: true,\n            },\n            companyId: {\n                type: DataTypes.INTEGER,\n                allowNull: false,\n                field: \"Company_ID\",\n            },\n...\n    )\n```\n\n```text\nconst ResponseModel = require(\"../models/response\")\nconst Response = ResponseModel(sequelize, DataTypes)\n```\n\n```text\nfindOrCreate().spread\n```\n\n```text\nconst response = await Response.findOrCreate({\n    where: {\n        participantId,\n        questionId,\n    },\n    defaults: responseNewDetail,\n})\n    return res.status(200).send({ status: 0, data: response })\n```\n\n```text\nconst [ response, created ] = await Response.findOrCreate({\n    where: {\n        participantId,\n        questionId,\n    },\n    defaults: responseNewDetail,\n})\n    return res.status(200).send({ status: 0, data: response })\n```\n\n```text\nsetImmediate(async () => {\n    // async things here\n});\n```\n\n```js\nconst [model,created] = ModelName.findOrCreate();\n```\n\n```text\nfindOrCreate\n```\n\n========================================\n\nComments:\n- In your second example, the one with `.spread()`, are you still using `await Response.findOrCreate`?\n- I'm expecting to use await as the first one if I can.But the problem here is the `.spread()` is not a function, I want to return the model only instead of include the created status. I'm using the same as stackoverflow.com/questions/53042399/&hellip;, but not working.\n- why `response` doesn't return `id` ?","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":184,"estimatedTokens":995}}558{"id":"stack-36392113","source":"stackoverflow","questionId":36392113,"title":"Import SQL dump within Node environment","tags":["sql","node.js","sequelize.js"],"text":"Title: Import SQL dump within Node environment\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'd like a npm script to create/configure/etc. and finally import a SQL dump. The entire creation, configuring, etc. is all working, however, I cannot get the import to work. The data never is inserted. Here's what I have (nevermind the nested callback as they'll be turned into promises):\n\n```\nconnection.query(`DROP DATABASE IF EXISTS ${config.database};`, err => {\n connection.query(`CREATE DATABASE IF NOT EXISTS ${config.database};`, err => {\n connection.query('use DATABASENAME', err => {\n const sqlDumpPath = path.join(__dirname, 'sql-dump/sql-dump.sql');\n connection.query(`SOURCE ${sqlDumpPath}`, err => {\n connection.end(err => resolve());\n });\n })\n });\n});\n```\n\nI also tried the following with Sequelize (ORM):\n\n```\nreturn new Promise(resolve => {\n const sqlDumpPath = path.join(__dirname, 'sql-dump/sql-dump.sql');\n fs.readFile('./sql/dump.sql', 'utf-8', (err, data) => {\n sequelize\n .query(data)\n .then(resolve)\n .catch(console.error);\n });\n});\n```\n\n========================================\n\nTop Answer:\nBased loosely on Max Gordon's answer, here's my code to run a MySQL Dump file from NodeJs/Sequelize: \n\n```\n\"use strict\";\n\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\n/**\n * Start off with a MySQL Dump file, import that, and then migrate to the latest version.\n *\n * @param dbName {string} the name of the database\n * @param mysqlDumpFile {string} The full path to the file to import as a starting point\n */\nmodule.exports.migrateFromFile = function(dbName, mysqlDumpFile) {\n let sequelize = createSequelize(dbName);\n console.log(\"Importing from \" + mysqlDumpFile + \"...\");\n let queries = fs.readFileSync(mysqlDumpFile, {encoding: \"UTF-8\"}).split(\";\\n\");\n\n console.log(\"Importing dump file...\");\n\n // Setup the DB to import data in bulk.\n let promise = sequelize.query(\"set FOREIGN_KEY_CHECKS=0\"\n ).then(() => {\n return sequelize.query(\"set UNIQUE_CHECKS=0\");\n }).then(() => {\n return sequelize.query(\"set SQL_MODE='NO_AUTO_VALUE_ON_ZERO'\");\n }).then(() => {\n return sequelize.query(\"set SQL_NOTES=0\");\n });\n\n console.time(\"Importing mysql dump\");\n for (let query of queries) {\n query = query.trim();\n if (query.length !== 0 && !query.match(/\\/\\*/)) {\n promise = promise.then(() => {\n console.log(\"Executing: \" + query.substring(0, 100));\n return sequelize.query(query, {raw: true});\n })\n }\n }\n\n return promise.then(() => {\n console.timeEnd(\"Importing mysql dump\");\n\n console.log(\"Migrating the rest of the way...\");\n console.time(\"Migrating after importing mysql dump\");\n return exports.migrateUp(dbName); // Run the rest of your migrations\n }).then(() => {\n console.timeEnd(\"Migrating after importing mysql dump\");\n });\n\n};\n```\n\n========================================\n\nCode:\n```text\nconnection.query(`DROP DATABASE IF EXISTS ${config.database};`, err => {\n  connection.query(`CREATE DATABASE IF NOT EXISTS ${config.database};`, err => {\n    connection.query('use DATABASENAME', err => {\n      const sqlDumpPath = path.join(__dirname, 'sql-dump/sql-dump.sql');\n      connection.query(`SOURCE ${sqlDumpPath}`, err => {\n        connection.end(err => resolve());\n      });\n    })\n  });\n});\n```\n\n```text\nreturn new Promise(resolve => {\n  const sqlDumpPath = path.join(__dirname, 'sql-dump/sql-dump.sql');\n  fs.readFile('./sql/dump.sql', 'utf-8', (err, data) => {\n    sequelize\n      .query(data)\n      .then(resolve)\n      .catch(console.error);\n  });\n});\n```\n\n```sh\nsequelize migration:create\n```\n\n```sh\nsequelize db:migrate\n```\n\n```js\n\"use strict\";\nconst promise = require(\"bluebird\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst assert = require(\"assert\");\nconst db = require(\"../api/models\"); // To be able to run raw queries\nconst debug = require(\"debug\")(\"my_new_api\");\n\n// I needed this in order to get some encoding issues straight\nconst Aring = new RegExp(String.fromCharCode(65533) +\n  \"\\\\\" + String.fromCharCode(46) + \"{1,3}\", \"g\");\nconst Auml = new RegExp(String.fromCharCode(65533) +\n  String.fromCharCode(44) + \"{1,3}\", \"g\");\nconst Ouml = new RegExp(String.fromCharCode(65533) +\n  String.fromCharCode(45) + \"{1,3}\", \"g\");\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    // The following section allows me to have multiple sql-files and only use the last dump\n    var last_sql;\n    for (let fn of fs.readdirSync(__dirname)){\n      if (fn.match(/\\.sql$/)){\n        fn = path.join(__dirname, fn);\n        var stats = fs.statSync(fn);\n        if (typeof last_sql === \"undefined\" ||\n            last_sql.stats.mtime < stats.mtime){\n          last_sql = {\n            filename: fn,\n            stats: stats\n          };\n        }\n      }\n    }\n    assert(typeof last_sql !== \"undefined\", \"Could not find any valid sql files in \" + __dirname);\n\n    // Split file into queries\n    var queries = fs.readFileSync(last_sql.filename).toString().split(/;\\n/);\n\n    var actions = [{\n      query: \"Running the down section\",\n      exec: this.down\n    }]; // Clean database by calling the down first\n\n    for (let i in queries){\n      // Skip empty queries and the character set information in the 40101 section\n      //   as this would most likely require a multi-query set-up\n      if (queries[i].trim().length == 0 ||\n          queries[i].match(new RegExp(\"/\\\\*!40101 .+ \\\\*/\"))){\n        continue;\n      }\n\n      // The manual fixing of encoding\n      let clean_query = queries[i]\n        .replace(Aring, \"Å\")\n        .replace(Ouml, \"Ö\")\n        .replace(Auml, \"Ä\");\n\n      actions.push({\n        query: clean_query.substring(0, 200), // We save a short section of the query only for debugging purposes\n        exec: () => db.sequelize.query(clean_query)\n      });\n    }\n\n    // The Series is important as the order isn't retained with just map\n    return promise.mapSeries(actions, function(item) {\n      debug(item.query);\n\n      return item.exec();\n    }, { concurrency: 1 });\n  },\n\n  down: function (queryInterface, Sequelize) {\n    var tables_2_drop = [\n      \"items\",\n      \"users\",\n      \"usertypes\"\n    ];\n    var actions = [];\n    for (let tbl of tables_2_drop){\n      actions.push({\n        // The created should be created_at\n        exec: () => db.sequelize.query(\"DROP TABLE IF EXISTS `\" + tbl +\"`\")\n      });\n    }\n\n    return promise.map(actions, function(item) {\n      return item.exec();\n    }, { concurrency: 1 });/**/\n  }\n};\n```\n\n```text\nfs\n```\n\n```text\nthis.down\n```\n\n```text\nmapSeries\n```\n\n```text\nmap\n```\n\n```text\nsequelize-cli\n```\n\n```text\n\"use strict\";\n\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\n/**\n * Start off with a MySQL Dump file, import that, and then migrate to the latest version.\n *\n * @param dbName {string} the name of the database\n * @param mysqlDumpFile {string} The full path to the file to import as a starting point\n */\nmodule.exports.migrateFromFile = function(dbName, mysqlDumpFile) {\n  let sequelize = createSequelize(dbName);\n  console.log(\"Importing from \" + mysqlDumpFile + \"...\");\n  let queries = fs.readFileSync(mysqlDumpFile, {encoding: \"UTF-8\"}).split(\";\\n\");\n\n  console.log(\"Importing dump file...\");\n\n  // Setup the DB to import data in bulk.\n  let promise = sequelize.query(\"set FOREIGN_KEY_CHECKS=0\"\n  ).then(() => {\n    return sequelize.query(\"set UNIQUE_CHECKS=0\");\n  }).then(() => {\n    return sequelize.query(\"set SQL_MODE='NO_AUTO_VALUE_ON_ZERO'\");\n  }).then(() => {\n    return sequelize.query(\"set SQL_NOTES=0\");\n  });\n\n  console.time(\"Importing mysql dump\");\n  for (let query of queries) {\n    query = query.trim();\n    if (query.length !== 0 && !query.match(/\\/\\*/)) {\n      promise = promise.then(() => {\n        console.log(\"Executing: \" + query.substring(0, 100));\n        return sequelize.query(query, {raw: true});\n      })\n    }\n  }\n\n  return promise.then(() => {\n    console.timeEnd(\"Importing mysql dump\");\n\n    console.log(\"Migrating the rest of the way...\");\n    console.time(\"Migrating after importing mysql dump\");\n    return exports.migrateUp(dbName); // Run the rest of your migrations\n  }).then(() => {\n    console.timeEnd(\"Migrating after importing mysql dump\");\n  });\n\n};\n```\n\n========================================\n\nComments:\n- This was useful for me, although that you're replacing characters in queries tells me that you're using the wrong encoding when reading your dump file. Change `fs.readFileSync(last_sql.filename)` to something like `fs.readFileSync(last_sql.filename, , {encoding: \"UTF-8\"})`","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":298,"estimatedTokens":2121}}559{"id":"stack-50589429","source":"stackoverflow","questionId":50589429,"title":"How to test Sequelize migrations?","tags":["testing","migration","sequelize.js"],"text":"Title: How to test Sequelize migrations?\nTags: testing, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it necessary to cover `Sequelize` migrations with unit tests, or even functional tests to check how they affect DB structure? If so, how to do it?\n\n========================================\n\nTop Answer:\nI found myself with a similar problem.\n\nIn my case I was making changes in a migration that didn't match my models and this was affecting the code in production (could not `save` model because `created_at` was actually `createdAt` or something stupid like that.) and our unit test were not catching this issue because we used `await sequelize.sync();` in our `setup.js`.\n\nWhat worked for us was:\n\n```\nimport { up as createUsersMigration } from '../database/migrations/20220426100249-create_users.js';\n// Repeat for each migration...\nexport const performDatabaseMigrations = async (sequelize, Sequelize) => {\n await createUsersMigration(sequelize.getQueryInterface(), Sequelize);\n // Repeat for each migration...\n};\n```\n\n... and invoking this function in our `setup.js` instead of syncing the models.\n\nThis allows us to test that the migrations work, but just like @simon.ro said we don't *test the migrations*, just that the *models match the database*.\n\nUPDATE: Eventually we settled on the following:\n\n```\nexport const performDatabaseMigrations = async (sequelize, Sequelize) => {\n const files = readdirSync('database/migrations');\n\n for (const file of files) {\n if (file === 'package.json') continue;\n const migration = await import(`database/migrations/${file}`);\n await migration.up(sequelize.getQueryInterface(), Sequelize);\n }\n};\n```\n\n========================================\n\nCode:\n```text\nSequelize\n```\n\n```js\nimport { up as createUsersMigration } from '../database/migrations/20220426100249-create_users.js';\n// Repeat for each migration...\nexport const performDatabaseMigrations = async (sequelize, Sequelize) => {\n  await createUsersMigration(sequelize.getQueryInterface(), Sequelize);\n  // Repeat for each migration...\n};\n```\n\n```js\nexport const performDatabaseMigrations = async (sequelize, Sequelize) => {\n  const files = readdirSync('database/migrations');\n\n  for (const file of files) {\n    if (file === 'package.json') continue;\n    const migration = await import(`database/migrations/${file}`);\n    await migration.up(sequelize.getQueryInterface(), Sequelize);\n  }\n};\n```\n\n```text\nsave\n```\n\n```text\ncreated_at\n```\n\n```text\ncreatedAt\n```\n\n```text\nawait sequelize.sync();\n```\n\n```text\nsetup.js\n```\n\n```text\nsetup.js\n```\n\n========================================\n\nComments:\n- But what if you made a mistake, especially with data migration.. isn't it a good approach to run the migration and then check if the changes are applied to the target DB?\n- Of course it's a good idea to check wether your migration does what it should do. Especially its a good idea to check it before you run it in production. Just like any other config change. But its probably not something you want periodically re-check in an automated test suite.\n- I just wonder why not? because it's very sensitive part in the application that no one really checks - just manually, so thought maybe there is some techniques to do it.\n- Because I don't consider it as \"part of the application\". It's a part of the history how your application evolved. But if your keen to test migrations, write a test that runs your migrations step by step and after each add some assertions that check your database schema.","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":102,"estimatedTokens":877}}560{"id":"stack-53123172","source":"stackoverflow","questionId":53123172,"title":"Sequelize is setting PSQL to VARCHAR(255) regardless if I tell it TEXT(2048) or any other length","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize is setting PSQL to VARCHAR(255) regardless if I tell it TEXT(2048) or any other length\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen I the instructions on how to create a larger field in psql through sequelize, it still always pushes `VARCHAR(255)` when it creates the table. Sequelize Data Types\n\nHere's my sequelize model:\n\n```\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n const Message = sequelize.define(\n 'Message',\n {\n message: {\n type: DataTypes.STRING(2048),\n allowNull: false,\n validate: {\n notEmpty: true\n }\n }\n },\n {}\n );\n Message.associate = function(models) {\n // associations can be defined here\n };\n return Message;\n};\n```\n\n`DataTypes.TEXT` has the same result.\n\nHere's the SQL that it outputs:\n\n```\nCREATE TABLE IF NOT EXISTS \"Messages\" (\"id\" SERIAL , \"message\" VARCHAR(255) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL, \"updatedAt\" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY (\"id\"));\n```\n\nWhen I try to insert a large string (more than 255 characters) into this field, it gives me the following error:\n\n`error: value too long for type character varying(255)`\n\nI've tried the following github issues on the project, but they don't seem to work for me. Relevant github issues.\n\nThank you for any help.\n\n**Specs:**\n\npsql (PostgreSQL) `10.5`\n\nnode `v10.4.0`.\n\n```\n\"dependencies\": {\n \"pg\": \"^7.5.0\",\n \"pg-hstore\": \"^2.3.2\",\n \"sequelize\": \"^4.39.0\",\n \"sequelize-cli\": \"^5.2.0\"\n }\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n  const Message = sequelize.define(\n    'Message',\n    {\n      message: {\n        type: DataTypes.STRING(2048),\n        allowNull: false,\n        validate: {\n          notEmpty: true\n        }\n      }\n    },\n    {}\n  );\n  Message.associate = function(models) {\n    // associations can be defined here\n  };\n  return Message;\n};\n```\n\n```text\nCREATE TABLE IF NOT EXISTS \"Messages\" (\"id\" SERIAL , \"message\" VARCHAR(255) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL, \"updatedAt\" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY (\"id\"));\n```\n\n```text\n\"dependencies\": {\n    \"pg\": \"^7.5.0\",\n    \"pg-hstore\": \"^2.3.2\",\n    \"sequelize\": \"^4.39.0\",\n    \"sequelize-cli\": \"^5.2.0\"\n  }\n```\n\n```text\nVARCHAR(255)\n```\n\n```text\nDataTypes.TEXT\n```\n\n```text\nerror: value too long for type character varying(255)\n```\n\n```text\n10.5\n```\n\n```text\nv10.4.0\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":123,"estimatedTokens":610}}561{"id":"stack-51401814","source":"stackoverflow","questionId":51401814,"title":"sequelize.js belongsToMany on non-primary key","tags":["node.js","sequelize.js"],"text":"Title: sequelize.js belongsToMany on non-primary key\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI made API server with Node.js.\n\nAlso I use sequelize(version 4) for communicate with MySQL.\n\nMy database structure is simple system.\n\n[model.js]\n\n```\nexport const User = sequelize.define('user', {\n no: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n userid: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: true\n },\n userpw: {\n type: Sequelize.STRING,\n allowNull: false\n }\n}, {\n freezeTableName: true,\n underscored: true\n})\n```\n\nI heard that if there is no option about `targetKey`, Primary key will be refered automatically.\n\nBut if `targetKey` exist, refer that column.\n\nSo I defined association like this.\n\n```\nUser.belongsToMany(User, { as: 'follower', through: '', foreignKey: 'follower_id', targetKey: 'userid'});\nUser.belongsToMany(User, { as: 'following', through: '', foreignKey: 'following_id', targetKey: 'userid'});\n```\n\nI want to refer User's `userid`. But after I run it, it still refer `no(PK)`.\n\nExecuted query in console is here.\n\n```\nCREATE TABLE IF NOT EXISTS `` (`created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, `follower_id` INTEGER , `following_id` INTEGER , PRIMARY KEY (`follower_id`, `following_id`), FOREIGN KEY (`follower_id`) REFERENCES `user` (`no`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`following_id`) REFERENCES `user` (`no`) ONDELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;\n```\n\nWhy still refer user's no column?\n\nHow can I solve this issue?\n\nThanks.\n\n========================================\n\nTop Answer:\nAs of 5.15.0, support has been added for `sourceKey` and `targetKey` for many-to-many relationships. This page in the docs provides examples for this use case (at the bottom of the page).\n\nCheck my answer here for more details.\n\n========================================\n\nCode:\n```text\nexport const User = sequelize.define('user', {\n    no: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    userid: {\n        type: Sequelize.STRING,\n        allowNull: false,\n        unique: true\n    },\n    userpw: {\n        type: Sequelize.STRING,\n        allowNull: false\n    }\n}, {\n    freezeTableName: true,\n    underscored: true\n})\n```\n\n```text\nUser.belongsToMany(User, { as: 'follower', through: 'follow', foreignKey: 'follower_id', targetKey: 'userid'});\nUser.belongsToMany(User, { as: 'following', through: 'follow', foreignKey: 'following_id', targetKey: 'userid'});\n```\n\n```text\nCREATE TABLE IF NOT EXISTS `follow` (`created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, `follower_id` INTEGER , `following_id` INTEGER , PRIMARY KEY (`follower_id`, `following_id`), FOREIGN KEY (`follower_id`) REFERENCES `user` (`no`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`following_id`) REFERENCES `user` (`no`) ONDELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;\n```\n\n```text\ntargetKey\n```\n\n```text\ntargetKey\n```\n\n```text\nuserid\n```\n\n```text\nno(PK)\n```\n\n```text\nUser.belongsToMany(User, { as: 'follower', through: 'follow', foreignKey: 'follower_id', otherKey: 'userid'});\nUser.belongsToMany(User, { as: 'following', through: 'follow', foreignKey: 'following_id', otherKey: 'userid'});\n```\n\n```text\ntargetKey\n```\n\n```text\nbelongsTo()\n```\n\n```text\nbelongsToMany()\n```\n\n```text\notherKey\n```\n\n```text\ntargetKey\n```\n\n```text\nsourceKey\n```\n\n```text\ntargetKey\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":149,"estimatedTokens":856}}562{"id":"stack-45235521","source":"stackoverflow","questionId":45235521,"title":"Sequelize.INTEGER vs DataTypes.INTEGER","tags":["javascript","node.js","orm","sequelize.js","sequelize-cli"],"text":"Title: Sequelize.INTEGER vs DataTypes.INTEGER\nTags: javascript, node.js, orm, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nIn code from 2016 using sequelize ORM, I see model types defined with this pattern:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n const Tasks = sequelize.define(\"Tasks\", { id: {\n type: DataTypes.INTEGER,\n [ ...etc.]\n```\n\nHowever in the current sequelize docs you see most prominently documented: `Sequelize.INTEGER` (or other type then integer).\nAt the same time in the current docs I find also `DataTypes` still `documented/used`: here.\n\nOn same page the `Sequelize.INTEGER` is used..., is that only for deferrables or something?\n\nI tried to find whether this altered over time or something but could not find it.\n\nWhen `Sequelize.INTEGER` is 'current solution' could I just alter above code into:\n\n```\nmodule.exports = function(sequelize, Sequelize) {\n const Tasks = sequelize.define(\"Tasks\", { id: {\n type: Sequelize.INTEGER,\n [ ...etc.]\n```\n\nOr would using `Sequelize` as argument somehow make this fail?\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n     const Tasks = sequelize.define(\"Tasks\", {  id: {\n       type: DataTypes.INTEGER,\n       [ ...etc.]\n```\n\n```text\nmodule.exports = function(sequelize, Sequelize) {\n  const Tasks = sequelize.define(\"Tasks\", {  id: {\n    type: Sequelize.INTEGER,\n    [ ...etc.]\n```\n\n```text\nSequelize.INTEGER\n```\n\n```text\nDataTypes\n```\n\n```text\ndocumented/used\n```\n\n```text\nSequelize.INTEGER\n```\n\n```text\nSequelize.INTEGER\n```\n\n```text\nSequelize\n```\n\n```text\nconst Sequelize = require('sequelize');\n```\n\n```text\nconst model = require(path.join(__dirname, file))(sequelize, Sequelize);\n```\n\n```text\nmodule.exports = (sequelize, abc) => {\n  const Driver = sequelize.define('Driver', {\n  firstName: {\n       type: abc.STRING(),\n       allowNull: false\n  },\n  last_name: {\n       type: abc.TEXT,\n       allowNull: true\n  },\n  email: {\n      type: abc.TEXT,\n      allowNull: false\n  },\n  password: {\n      type: abc.TEXT,\n      allowNull: true\n  }\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize\n```\n\n```text\nabc\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":113,"estimatedTokens":540}}563{"id":"stack-53877066","source":"stackoverflow","questionId":53877066,"title":"Does Sequelize.js escape input for SQL injection by default?","tags":["node.js","sequelize.js"],"text":"Title: Does Sequelize.js escape input for SQL injection by default?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIf I try to use Sequelize.js like this:\n\n```\nmodel.user.create\n(\n {\n username : user_name,\n password : hashed_password\n },\n {\n attribute : ['id'],\n raw : true\n }\n);\n```\n\nWill Sequelize.js ensure user_name will not cause any SQL injection or should I make sure to escape it before handing it off to Sequelize.js ? (in model, both username and password are just `type : Sequelize.TEXT`)\n\n========================================\n\nCode:\n```text\nmodel.user.create\n(\n    {\n        username : user_name,\n        password : hashed_password\n    },\n    {\n        attribute : ['id'],\n        raw : true\n    }\n);\n```\n\n```text\ntype : Sequelize.TEXT\n```\n\n```text\ninsertQuery()\n```\n\n```text\nescape()\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":51,"estimatedTokens":205}}564{"id":"stack-42077987","source":"stackoverflow","questionId":42077987,"title":"Sequelize Many to Many failing with 'is not associated to' when trying to associate entries?","tags":["node.js","sequelize.js"],"text":"Title: Sequelize Many to Many failing with 'is not associated to' when trying to associate entries?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am having a problem with my many to many configuration with Sequelize, where it complains that `site_article_keyword is not associated to article_keyword`. The code below represents a minimal test case to try to understand what I am doing wrong (I hoped to provide something smaller, but this is what I have). I am using bluebird for the Promise API.\n\n```\nconst Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize(undefined, undefined, undefined, {\n dialect: 'sqlite',\n storage: './mydatabase',\n});\n\nconst SiteArticle = sequelize.define('site_article', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n ownerId: {\n type: Sequelize.INTEGER,\n field: 'owner_id'\n },\n title: Sequelize.STRING\n // other fields omitted\n}, {\n timestamps: true\n});\n\nconst ArticleKeyword = sequelize.define('article_keyword', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n name: Sequelize.STRING,\n language: Sequelize.STRING\n // other fields omitted\n}, {\n timestamps: true\n});\n\nconst SiteArticleKeyword = sequelize.define('site_article_keyword', {\n siteArticleId: {\n type: Sequelize.INTEGER,\n field: 'site_article_id',\n references: {\n model: SiteArticle,\n key: 'id'\n }\n },\n articleKeywordId: {\n type: Sequelize.INTEGER,\n field: 'article_keyword_id',\n references: {\n model: ArticleKeyword,\n key: 'id'\n }\n }\n // other fields omitted\n}, {\n timestamps: true\n});\n\n(ArticleKeyword).belongsToMany(\n SiteArticle, { through: SiteArticleKeyword });\n\n(SiteArticle).belongsToMany(\n ArticleKeyword, { through: SiteArticleKeyword });\n```\n\nThat's the model defined, now for trying to create the source and destination entries, that I then want to associate. The failure happens on the line where I call `ArticleKeyword.findAll()`:\n\n```\nsequelize.sync({}).then(function() {\n\n // populate some data here\n\n let siteArticle;\n\n SiteArticle.create({\n ownerId: 1,\n title: 'hello world'\n }).then(function(entry) {\n siteArticle = entry;\n console.log('site article: ', JSON.stringify(entry, undefined, 2));\n\n return ArticleKeyword.findOrCreate({\n where: {\n name: 'keyword1',\n language: 'en'\n }\n });\n }).spread(function(entry, success) {\n console.log('article keyword: ', JSON.stringify(entry, undefined, 2));\n return siteArticle.addArticle_keyword(entry);\n }).spread(function(entry, success) {\n console.log('site article keyword: ', JSON.stringify(entry, undefined, 2));\n\n const siteArticleId = 1;\n const language = 'en';\n\n return ArticleKeyword.findAll({\n where: {\n language: language,\n },\n include: [{\n model: SiteArticleKeyword,\n where: {\n siteArticleId: siteArticleId\n }\n }]\n });\n }).then(function(articleKeywords) {\n if (articleKeywords) {\n console.log('entries: ', JSON.stringify(articleKeywords, undefined, 2));\n } else {\n console.log('entries: ', 'none');\n }\n }).catch(function(error) {\n console.log('ERROR: ', error);\n }.bind(this));\n\n}).catch(function(error) {\n console.log(error);\n});\n```\n\nI am basing my code on the 'Mixin BelongsToMany' example in the Sequelize documentation.\n\nCan anyone suggest what I am doing wrong?\n\n========================================\n\nTop Answer:\nThe issue turns out that the reason `site_article_keyword` is not associated is because it is the association! With that in mind the code becomes:\n\n```\nreturn ArticleKeyword.findAll({\n where: {\n language: language,\n },\n include: [{\n model: SiteArticle,\n as: 'SiteArticle',\n siteArticleId: siteArticleId\n }]\n });\n```\n\nBTW one minor tweak to my code, is in the inclusion of 'as' to the belongsToMany:\n\n```\nArticleKeyword.belongsToMany(\n SiteArticle,\n { through: SiteArticleKeyword, as: 'SiteArticle' }\n);\n\nSiteArticle.belongsToMany(\n ArticleKeyword,\n { through: SiteArticleKeyword, as: 'ArticleKeyword' }\n);\n```\n\nThis allows for `addArticleKeyword()` instead of `addArticle_Keyword()`.\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\n\nvar sequelize = new Sequelize(undefined, undefined, undefined, {\n    dialect: 'sqlite',\n    storage: './mydatabase',\n});\n\nconst SiteArticle = sequelize.define('site_article', {\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    ownerId: {\n        type: Sequelize.INTEGER,\n        field: 'owner_id'\n    },\n    title: Sequelize.STRING\n        // other fields omitted\n}, {\n    timestamps: true\n});\n\nconst ArticleKeyword = sequelize.define('article_keyword', {\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    name: Sequelize.STRING,\n    language: Sequelize.STRING\n        // other fields omitted\n}, {\n    timestamps: true\n});\n\nconst SiteArticleKeyword = sequelize.define('site_article_keyword', {\n    siteArticleId: {\n        type: Sequelize.INTEGER,\n        field: 'site_article_id',\n        references: {\n            model: SiteArticle,\n            key: 'id'\n        }\n    },\n    articleKeywordId: {\n        type: Sequelize.INTEGER,\n        field: 'article_keyword_id',\n        references: {\n            model: ArticleKeyword,\n            key: 'id'\n        }\n    }\n    // other fields omitted\n}, {\n    timestamps: true\n});\n\n(ArticleKeyword).belongsToMany(\n    SiteArticle, { through: SiteArticleKeyword });\n\n(SiteArticle).belongsToMany(\n    ArticleKeyword, { through: SiteArticleKeyword });\n```\n\n```text\nsequelize.sync({}).then(function() {\n\n    // populate some data here\n\n    let siteArticle;\n\n    SiteArticle.create({\n        ownerId: 1,\n        title: 'hello world'\n    }).then(function(entry) {\n        siteArticle = entry;\n        console.log('site article: ', JSON.stringify(entry, undefined, 2));\n\n        return ArticleKeyword.findOrCreate({\n            where: {\n                name: 'keyword1',\n                language: 'en'\n            }\n        });\n    }).spread(function(entry, success) {\n        console.log('article keyword: ', JSON.stringify(entry, undefined, 2));\n        return siteArticle.addArticle_keyword(entry);\n    }).spread(function(entry, success) {\n        console.log('site article keyword: ', JSON.stringify(entry, undefined, 2));\n\n        const siteArticleId = 1;\n        const language = 'en';\n\n        return ArticleKeyword.findAll({\n            where: {\n                language: language,\n            },\n            include: [{\n                model: SiteArticleKeyword,\n                where: {\n                    siteArticleId: siteArticleId\n                }\n            }]\n        });\n    }).then(function(articleKeywords) {\n        if (articleKeywords) {\n            console.log('entries: ', JSON.stringify(articleKeywords, undefined, 2));\n        } else {\n            console.log('entries: ', 'none');\n        }\n    }).catch(function(error) {\n        console.log('ERROR: ', error);\n    }.bind(this));\n\n}).catch(function(error) {\n    console.log(error);\n});\n```\n\n```text\nsite_article_keyword is not associated to article_keyword\n```\n\n```text\nArticleKeyword.findAll()\n```\n\n```js\nArticleKeyword.findAll({\n    include: [{\n        model: SiteArticle,\n        through: {\n            attributes: ['createdAt', 'startedAt', 'finishedAt'],\n            where: {\n                siteArticleId: siteArticleId\n            }\n        }\n    }]\n});\n```\n\n```text\nreturn ArticleKeyword.findAll({\n    where: {\n        language: language,\n    },\n    include: [{\n            model: SiteArticle,\n            as: 'SiteArticle',\n            siteArticleId: siteArticleId\n        }]\n    });\n```\n\n```text\nArticleKeyword.belongsToMany(\n    SiteArticle,\n    { through: SiteArticleKeyword, as: 'SiteArticle' }\n);\n\nSiteArticle.belongsToMany(\n    ArticleKeyword,\n    { through: SiteArticleKeyword, as: 'ArticleKeyword' }\n);\n```\n\n```text\nsite_article_keyword\n```\n\n```text\naddArticleKeyword()\n```\n\n```text\naddArticle_Keyword()\n```\n\n========================================\n\nComments:\n- this one \"site_article_keyword is not associated to article_keyword\" ?\n- Yes, thought I think I have found the answer. Will elaborate in an answer.\n- is there any way to do this *without* having to specify \"as\" both in the model, and the query? Seems redundant and now we're left with a hard-coded string in two places.","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":357,"estimatedTokens":2072}}565{"id":"stack-29539157","source":"stackoverflow","questionId":29539157,"title":"Integration testing with Sequelize","tags":["node.js","sqlite","express","sequelize.js"],"text":"Title: Integration testing with Sequelize\nTags: node.js, sqlite, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got a Express web api using sequelize that i want to do end to end testing with. I want to be able to do end to end testing with an in memory database so i can run it on whatever machine pleases me.\n\nI use mysql database for development and production, however i was thinking about using an in-memory sqlite database for testing but i'm not sure what the best way is to get test data into it.\n\nThere are several modules around like squelize-fixtures but none of them seem to be able to just fill the database with data without the need to write code around it to manipulate and insert it.\n\nAnyone here doing integration tests with sequelize and sqlite that has figured out a good way of doing it without all the boilerplate code?\n\n========================================\n\nCode:\n```text\nstorage: 'path/to/database.sqlite'\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":19,"estimatedTokens":238}}566{"id":"stack-47697859","source":"stackoverflow","questionId":47697859,"title":"My self referential Sequelize model isn't creating an extra column","tags":["sequelize.js"],"text":"Title: My self referential Sequelize model isn't creating an extra column\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\nmodule.exports = (sequelize, DataTypes) => {\n const User = sequelize.define(\n \"User\",\n {\n username: {\n type: DataTypes.STRING,\n unique: true\n },\n firstName: {\n type: DataTypes.STRING\n },\n lastName: {\n type: DataTypes.STRING\n },\n email: {\n type: DataTypes.STRING\n },\n password: {\n type: DataTypes.STRING\n },\n lastLogin: {\n type: DataTypes.DATE\n },\n active: {\n type: DataTypes.BOOLEAN\n },\n lastName: {\n type: DataTypes.STRING\n }\n }, {\n paranoid: true,\n classMethods: {\n associate: models => {\n User.hasOne(models.User, {\n as: \"createdByUser\"\n })\n\n User.hasOne(models.User, {\n as: \"updatedByUser\"\n })\n }\n }\n }\n )\n\n return User\n};\n```\n\nI would expect a field to be called `createdByUser` in the Postgres DB, but it's not there. What am I doing wrong?\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const User = sequelize.define(\n    \"User\",\n    {\n      username: {\n        type: DataTypes.STRING,\n        unique: true\n      },\n      firstName: {\n        type: DataTypes.STRING\n      },\n      lastName: {\n        type: DataTypes.STRING\n      },\n      email: {\n        type: DataTypes.STRING\n      },\n      password: {\n        type: DataTypes.STRING\n      },\n      lastLogin: {\n        type: DataTypes.DATE\n      },\n      active: {\n        type: DataTypes.BOOLEAN\n      },\n      lastName: {\n        type: DataTypes.STRING\n      }\n    }, {\n      paranoid: true,\n      classMethods: {\n        associate: models => {\n          User.hasOne(models.User, {\n            as: \"createdByUser\"\n          })\n\n          User.hasOne(models.User, {\n            as: \"updatedByUser\"\n          })\n        }\n      }\n    }\n  )\n\n  return User\n};\n```\n\n```text\ncreatedByUser\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const User = sequelize.define(\n    \"User\",\n    {\n      username: {\n        type: DataTypes.STRING,\n        unique: true\n      },\n      firstName: {\n        type: DataTypes.STRING\n      },\n      lastName: {\n        type: DataTypes.STRING\n      },\n      email: {\n        type: DataTypes.STRING\n      },\n      password: {\n        type: DataTypes.STRING\n      },\n      lastLogin: {\n        type: DataTypes.DATE\n      },\n      active: {\n        type: DataTypes.BOOLEAN\n      }\n    }, {\n      paranoid: true\n    }\n  )\n\n  User.associate = models => {\n    User.hasOne(models.User, {\n      as: \"createdByUser\"\n    })\n\n    User.hasOne(models.User, {\n      as: \"updatedByUser\"\n    })\n  }\n\n  return User\n};\n```\n\n```text\nclassMethods\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":163,"estimatedTokens":655}}567{"id":"stack-38145702","source":"stackoverflow","questionId":38145702,"title":"Create a composite index with associated data?","tags":["node.js","sequelize.js"],"text":"Title: Create a composite index with associated data?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a User-table and a userAttributes table. Every user can only have one instance of each userAttribute, so I would like to create a composite unique index for the columns name and userId(That is created by userAttributes.belongsTo.) How can this be done?\n\n```\nUserAttribute = sequelize.define('userAttributes', {\n name: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: 'nameIndex',\n validate: {\n isIn: [['phone', 'name','driverRequest']],\n }\n },\n value: {\n type: Sequelize.STRING,\n allowNull: false\n },\n});\n\nUser.hasMany(userAttributes, {unique: 'nameIndex'});\nuserAttributes.belongsTo(User, {unique: 'nameIndex'});\n```\n\nI tride adding the unique nameIndex with no success, it seems to only apply to the name-column.\n\n========================================\n\nCode:\n```text\nUserAttribute = sequelize.define('userAttributes', {\n    name: {\n        type:       Sequelize.STRING,\n        allowNull:  false,\n        unique: 'nameIndex',\n        validate: {\n            isIn: [['phone', 'name','driverRequest']],\n        }\n    },\n    value: {\n        type:       Sequelize.STRING,\n        allowNull:  false\n    },\n});\n\n\nUser.hasMany(userAttributes, {unique: 'nameIndex'});\nuserAttributes.belongsTo(User, {unique: 'nameIndex'});\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('<yourDatabaseName>', '<yourUserName>', '<yourPassword', {\n  host: '<ip>'\n});\n\nvar User = sequelize.define('user', {\n  id: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    primaryKey: true\n  },\n});\nvar UserAttribute = sequelize.define('userattribute', {\n  userId: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    unique: 'compositeIndex',\n    references: {\n      model: User,\n      key: \"id\"\n    }\n  },\n  name: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    unique: 'compositeIndex'\n  }\n});\n\nUser.hasOne(UserAttribute, {\n  as: \"UserAttribute\"\n})\n\nUserAttribute.belongsTo(User, {\n  foreignKey: \"userId\",\n  as: 'UserId'\n})\n\n\nsequelize.sync({\n  // use force to delete tables before generating them\n  force: true\n}).then(function() {\n  console.log('tables have been created');\n  return User.create({\n    id: 'randomId1'\n  });\n})\n  .then(function() {\n    console.log('tables have been created');\n    return User.create({\n      id: 'randomId2'\n    });\n  })\n  .then(function() {\n    return UserAttribute.create({\n      userId: 'randomId1',\n      name: 'name1'\n    });\n  })\n  .then(function() {\n    return UserAttribute.create({\n      userId: 'randomId2',\n      name: 'name1'\n    });\n  })\n  // // generates Validation Error\n  // .then(function() {\n  //   return UserAttribute.create({\n  //     userId: 'randomId1',\n  //     name: 'name1'\n  //   });\n  // })\n```\n\n========================================\n\nComments:\n- I've modified the below example to use the composite index, I think it should work, let me know if it doesn't\n- Is what you did to manually add in useId in the data-model? I'm missing the value-attribute aswell?\n- I can't really understand some things. You wrote: \"Every user can only have one instance of each userAttribute, so I would like to create a composite unique index for the columns name and userId\". I believe that those 2 indexes(userId and name) are saved in userAttribute, correct me if I'm wrong. In the following code that you provide I can see that new field 'value', I'm not sure what it is meant for, can you provide more info about it? or explain where am I missing the problem context ?","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":135,"estimatedTokens":893}}568{"id":"stack-36947904","source":"stackoverflow","questionId":36947904,"title":"Building, seeding and destroying PostgreSQL with Sequelize for testing","tags":["node.js","postgresql","testing","mocha.js","sequelize.js"],"text":"Title: Building, seeding and destroying PostgreSQL with Sequelize for testing\nTags: node.js, postgresql, testing, mocha.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to automate my database being built, seeded and destroyed for each test. I am using PostgreSQL, Mocha and Sequelize.\n\nI found a library: sequelize-fixtures that has got me part way there, but ultimately it's very inconsistent and occasionally will throw constraint errors: `Unhandled rejection SequelizeUniqueConstraintError: Validation error` even though I do not have any validation on the model.\n\nHere's how I am doing the tests\n\n```\nconst sequelize = new Sequelize('test_db', 'db', null, {\n logging: false,\n host: 'localhost',\n port: '5432',\n dialect: 'postgres',\n protocol: 'postgres'\n})\n\ndescribe('/auth/whoami', () => {\n beforeEach((done) => {\n Fixtures.loadFile('test/fixtures/data.json', models)\n .then(function(){\n done()\n })\n })\n\n afterEach((done) => {\n sequelize.sync({\n force: true\n }).then(() => {\n done()\n })\n })\n\n it('should connect to the DB', (done) => {\n sequelize.authenticate()\n .then((err) => {\n expect(err).toBe(undefined)\n done()\n })\n })\n\n it('should test getting a user', (done) => {\n models.User.findAll({\n attributes: ['username'],\n }).then((users) => {\n users.forEach((user) => {\n console.log(user.password)\n })\n done()\n })\n })\n})\n```\n\nMy model is defined like so:\n\n```\nvar Sequelize = require('sequelize'),\n db = require('./../utils/db')\n\nvar User = db.define('User', {\n username: {\n type: Sequelize.STRING(20),\n allowNull: false,\n notEmpty: true\n },\n password: {\n type: Sequelize.STRING(60),\n allowNull: false,\n notEmpty: true\n }\n})\n\nmodule.exports = User\n```\n\nThe error logs:\n\n```\nFixtures: reading file test/fixtures/data.json...\nExecuting (default): CREATE TABLE IF NOT EXISTS \"Users\" (\"id\" SERIAL , \"username\" VARCHAR(20) NOT NULL, \"password\" VARCHAR(60) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL, \"updatedAt\" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT \"id\", \"username\", \"password\", \"createdAt\", \"updatedAt\" FROM \"Users\" AS \"User\" WHERE \"User\".\"id\" = 1 AND \"User\".\"username\" = 'Test User 1' AND \"User\".\"password\" = 'testpassword';\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'Users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): INSERT INTO \"Users\" (\"id\",\"username\",\"password\",\"createdAt\",\"updatedAt\") VALUES (1,'Test User 1','testpassword','2016-04-29 23:15:08.828 +00:00','2016-04-29 23:15:08.828 +00:00') RETURNING *;\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n```\n\nThis worked once, then never again. Is there a more robust way for me to, before every test, start with a completely clean DB for me to fill with test data to operate on?\n\nThis is the closest I have come to finding any kind of discussion/answer. \n\nAdditionally, if anyone also knows why I still get `console.logs()` even though I have `logging: false` on, that would be appreciated.\n\n========================================\n\nCode:\n```text\nconst sequelize = new Sequelize('test_db', 'db', null, {\n  logging: false,\n  host: 'localhost',\n  port: '5432',\n  dialect: 'postgres',\n  protocol: 'postgres'\n})\n\ndescribe('/auth/whoami', () => {\n  beforeEach((done) => {\n    Fixtures.loadFile('test/fixtures/data.json', models)\n      .then(function(){\n         done()\n      })\n  })\n\n  afterEach((done) => {\n    sequelize.sync({\n      force: true\n    }).then(() => {\n      done()\n    })\n  })\n\n  it('should connect to the DB', (done) => {\n    sequelize.authenticate()\n      .then((err) => {\n        expect(err).toBe(undefined)\n        done()\n      })\n  })\n\n  it('should test getting a user', (done) => {\n    models.User.findAll({\n      attributes: ['username'],\n    }).then((users) => {\n      users.forEach((user) => {\n        console.log(user.password)\n      })\n      done()\n    })\n  })\n})\n```\n\n```text\nvar Sequelize = require('sequelize'),\n    db = require('./../utils/db')\n\nvar User = db.define('User', {\n  username: {\n    type: Sequelize.STRING(20),\n    allowNull: false,\n    notEmpty: true\n  },\n  password: {\n    type: Sequelize.STRING(60),\n    allowNull: false,\n    notEmpty: true\n  }\n})\n\nmodule.exports = User\n```\n\n```text\nFixtures: reading file test/fixtures/data.json...\nExecuting (default): CREATE TABLE IF NOT EXISTS \"Users\" (\"id\"   SERIAL , \"username\" VARCHAR(20) NOT NULL, \"password\" VARCHAR(60) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL, \"updatedAt\" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT \"id\", \"username\", \"password\", \"createdAt\", \"updatedAt\" FROM \"Users\" AS \"User\" WHERE \"User\".\"id\" = 1 AND \"User\".\"username\" = 'Test User 1' AND \"User\".\"password\" = 'testpassword';\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'Users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): INSERT INTO \"Users\" (\"id\",\"username\",\"password\",\"createdAt\",\"updatedAt\") VALUES (1,'Test User 1','testpassword','2016-04-29 23:15:08.828 +00:00','2016-04-29 23:15:08.828 +00:00') RETURNING *;\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n```\n\n```text\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n```\n\n```text\nconsole.logs()\n```\n\n```text\nlogging: false\n```\n\n```text\nfunction cleanup() {\n    return User.destroy({ truncate: true, cascade: true });\n}\n```\n\n```text\nfunction create() {\n    var users = require('./fixtures/user.json');\n    return User.bulkCreate(users);\n}\n```\n\n```text\nit('should connect to the DB', () => {\n   return sequelize.authenticate()\n })\n```\n\n```text\nid\n```\n\n```text\nsequelize.sync({force: true})\n```\n\n```text\nbeforeEach\n```\n\n```text\ncreate\n```\n\n```text\nsequelize-fixtures\n```\n\n```text\ndone\n```\n\n```text\nthis\n```\n\n```text\nthis.timeout(1000);\n```\n\n========================================\n\nComments:\n- How is your model defined? logging false means Sequelize will not print the SQL to console. In your case, you should enable log to get all the information about your problem you can.\n- @denisazevedo I have updated my post with my model definition and the logs. I tried to disable logging but for some reason it still produces the logs so I am still seeing them.","metadata":{"transformedAt":"2026-08-18T18:33:34.386Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":242,"estimatedTokens":1751}}569{"id":"stack-61126561","source":"stackoverflow","questionId":61126561,"title":"What is the references field for in sequelize?","tags":["javascript","graphql","sequelize.js","sequelize-auto"],"text":"Title: What is the references field for in sequelize?\nTags: javascript, graphql, sequelize.js, sequelize-auto\nSource: Stack Overflow\n\nQuestion:\nI have a user table that has a foreign key column to a roles table. \n\nI defined all relationships in mysql and using `sequelize-auto` I generated my models. \n\nThe generated model for user was this: \n\n```\nconst user = sequelize.define('user', {\n Id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n Email: {\n type: DataTypes.STRING(45),\n allowNull: false,\n unique: true,\n },\n RoleId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'roles',\n key: 'Id',\n },\n },\n });\n```\n\nI thought that my reference was set so that when I did the following in my resolver: \n\n```\nusers: async () => {\n const users = await db.user.findAll({\n include: [\n {\n model: db.roles,\n },\n ],\n });\n\nreturn users\n```\n\nI should have gotten back a list of user roles with the following query in the playground: \n\n```\n{users\n {roles\n {Name, Id}\n }\n}\n```\n\ninstead I got \n\n roles is not associated to user!\n\nWhat I later figured out is that I needed to make an association: \n\n```\nuser.associate = models => {\n user.hasMany(models.roles, {\n foreignKey: 'Id',\n sourceKey: 'RoleId',\n onDelete: 'cascade',\n });\n };\n```\n\nThen it worked. \n\nWhat I still dont understand is what is this for in the user-model?: \n\n```\nreferences: {\n model: 'roles',\n key: 'Id',\n },\n```\n\nI thought that it was my \"association\" with the roles table but without me explicitly adding an association this simply did nothing. Can someone please explain the meaning of `references` field?\n\n========================================\n\nTop Answer:\nThe given answer is correct but I realized later on that the reason for this question was that I assumed I could create assosiations via code so that I did not have to modify every model manualy by default. \n\nFor those of you looking to do the same I found a solution here. \n\nWhich is basically: \n\n1) inside of your models folder create an index.js file and add the following code\n\n```\nimport Sequelize from 'sequelize';\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst basename = path.basename(__filename);\n\nconst db = {};\n\n// @ts-ignore\nconst sequelize = new Sequelize('dbname', 'dbUser', 'password', {\n host: '127.0.0.1',\n port: 'PORT',\n dialect: 'mysql',\n define: {\n freezeTableName: true,\n timestamps: false,\n },\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000,\n },\n // \n operatorsAliases: false,\n});\n\nconst tableModel = {};\n\nfs.readdirSync(__dirname)\n .filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')\n .forEach(file => {\n const model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n tableModel[model.name] = model;\n });\n\nObject.getOwnPropertyNames(db).forEach(modelName => {\n const currentModel = db[modelName];\n Object.getOwnPropertyNames(currentModel.rawAttributes).forEach(attributeName => {\n if (\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName],\n 'references'\n ) &&\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName].references,\n 'model'\n ) &&\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName].references,\n 'key'\n )\n ) {\n if (\n !(\n currentModel.rawAttributes[attributeName].references.model &&\n currentModel.rawAttributes[attributeName].references.key\n )\n ) {\n console.log(\n `*SKIPPED* ${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n );\n return;\n }\n\n console.log(\n `${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n );\n const referencedTable =\n tableModel[currentModel.rawAttributes[attributeName].references.model];\n\n currentModel.belongsTo(referencedTable, { foreignKey: attributeName });\n referencedTable.hasMany(currentModel, { foreignKey: attributeName });\n\n }\n });\n});\n\n// @ts-ignore\ndb.sequelize = sequelize;\n// @ts-ignore\ndb.Sequelize = Sequelize;\n\n// eslint-disable-next-line eol-last\nmodule.exports = db;\n```\n\n2) inside of your resolver just reference the above: \n\n```\nconst db = require('../assets/models/index');\n```\n\n========================================\n\nCode:\n```text\nconst user = sequelize.define('user', {\n    Id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true,\n    },\n    Email: {\n      type: DataTypes.STRING(45),\n      allowNull: false,\n      unique: true,\n    },\n    RoleId: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      references: {\n        model: 'roles',\n        key: 'Id',\n      },\n    },\n  });\n```\n\n```text\nusers: async () => {\n  const users = await db.user.findAll({\n    include: [\n      {\n        model: db.roles,\n      },\n    ],\n  });\n\nreturn users\n```\n\n```text\n{users\n  {roles\n   {Name, Id}\n  }\n}\n```\n\n```text\nuser.associate = models => {\n    user.hasMany(models.roles, {\n      foreignKey: 'Id',\n      sourceKey: 'RoleId',\n      onDelete: 'cascade',\n    });\n  };\n```\n\n```text\nreferences: {\n    model: 'roles',\n    key: 'Id',\n  },\n```\n\n```text\nsequelize-auto\n```\n\n```text\nreferences\n```\n\n```text\nimport Sequelize from 'sequelize';\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst basename = path.basename(__filename);\n\nconst db = {};\n\n// @ts-ignore\nconst sequelize = new Sequelize('dbname', 'dbUser', 'password', {\n  host: '127.0.0.1',\n  port: 'PORT',\n  dialect: 'mysql',\n  define: {\n    freezeTableName: true,\n    timestamps: false,\n  },\n  pool: {\n    max: 5,\n    min: 0,\n    acquire: 30000,\n    idle: 10000,\n  },\n  // <http://docs.sequelizejs.com/manual/tutorial/querying.html#operators>\n  operatorsAliases: false,\n});\n\nconst tableModel = {};\n\nfs.readdirSync(__dirname)\n  .filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')\n  .forEach(file => {\n    const model = sequelize.import(path.join(__dirname, file));\n    db[model.name] = model;\n    tableModel[model.name] = model;\n  });\n\nObject.getOwnPropertyNames(db).forEach(modelName => {\n  const currentModel = db[modelName];\n  Object.getOwnPropertyNames(currentModel.rawAttributes).forEach(attributeName => {\n    if (\n      Object.prototype.hasOwnProperty.call(\n        currentModel.rawAttributes[attributeName],\n        'references'\n      ) &&\n      Object.prototype.hasOwnProperty.call(\n        currentModel.rawAttributes[attributeName].references,\n        'model'\n      ) &&\n      Object.prototype.hasOwnProperty.call(\n        currentModel.rawAttributes[attributeName].references,\n        'key'\n      )\n    ) {\n      if (\n        !(\n          currentModel.rawAttributes[attributeName].references.model &&\n          currentModel.rawAttributes[attributeName].references.key\n        )\n      ) {\n        console.log(\n          `*SKIPPED* ${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n        );\n        return;\n      }\n\n      console.log(\n        `${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n      );\n      const referencedTable =\n        tableModel[currentModel.rawAttributes[attributeName].references.model];\n\n      currentModel.belongsTo(referencedTable, { foreignKey: attributeName });\n      referencedTable.hasMany(currentModel, { foreignKey: attributeName });\n\n    }\n  });\n});\n\n// @ts-ignore\ndb.sequelize = sequelize;\n// @ts-ignore\ndb.Sequelize = Sequelize;\n\n// eslint-disable-next-line eol-last\nmodule.exports = db;\n```\n\n```text\nconst db = require('../assets/models/index');\n```\n\n========================================\n\nComments:\n- So it&#168;s a deskription but if Im focusing on being practical only in my backend enviorment and creating all relationships in the mysql workbench then this field is useless for me? If I however want to create tables from my backend to my mysql enviorment then this is of use?\n- If you will use migrations to create and modify your DB structure then you won't need 'references' in the models at all. All these references will be in migrations to help sequelize CLI to create foreign keys.\n- Current version 0.7.5 of `sequelize-auto` generates the associations automatically.","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":369,"estimatedTokens":2141}}570{"id":"stack-28434300","source":"stackoverflow","questionId":28434300,"title":"How to create assocations in Sequelize migrations?","tags":["node.js","migration","sequelize.js"],"text":"Title: How to create assocations in Sequelize migrations?\nTags: node.js, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using migrations to create entities. Naturally, some have relations between them. Until now, by using `sync(true)`, I enjoyed the benefit of Sequelize implementing the relations for me at the database level. \n\nHow do I express new relations in a migration?\n\n- One-to-many: Should I be taking care of the foreign key columns?\n\n- Many-to-many: Should I be creating the intermediate table and setting foreign keys on each entity's table?\n\nOr: Am I supposed to run the migration and then `sync(false)`?\nWhat about relations that are no longer relevant?\n\n========================================\n\nCode:\n```text\nsync(true)\n```\n\n```text\nsync(false)\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var User = sequelize.define(\"User\", {\n        \"fname\": {\n            \"type\": DataTypes.STRING,\n            \"unique\": false,\n            \"allowNull\": false\n        },\n        \"lname\": {\n            \"type\": DataTypes.STRING,\n            \"allowNull\": false\n        }\n    }, {\n        \"tableName\": \"Users\",\n        \"classMethods\": {\n            \"associate\": function (models) {\n                Locale.hasMany(models.Permissions);\n            }\n        }\n    });\n\n    return User;\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":51,"estimatedTokens":332}}571{"id":"stack-53255911","source":"stackoverflow","questionId":53255911,"title":"Sequelize Hooks- Previous data values for afterBulkUpdate","tags":["sequelize.js"],"text":"Title: Sequelize Hooks- Previous data values for afterBulkUpdate\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a hook `beforeBulkUpdate` and get new and previous values of a field. I tried using `.reload()` on the model and `_previousDataValues` but they only work on instances and not bulk create and update (I'm using bulk update). Is there a way to get the previous value of field using the `beforeBulkUpdate` hook?\n\n```\nbeforeBulkUpdate: (person) => {\n console.log(person.name) // 'John' (new name)\n Person.findOne({ where: { id: input.id } }).then(person => {\n person.reload().then(() => {\n console.log(person.name) // 'John' (expected old name, but returns new name)\n })\n })\n}\n```\n\n========================================\n\nCode:\n```text\nbeforeBulkUpdate: (person) => {\n  console.log(person.name) // 'John' (new name)\n  Person.findOne({ where: { id: input.id } }).then(person => {\n  person.reload().then(() => {\n    console.log(person.name) // 'John' (expected old name, but returns new name)\n    })\n  })\n}\n```\n\n```text\nbeforeBulkUpdate\n```\n\n```text\n.reload()\n```\n\n```text\n_previousDataValues\n```\n\n```text\nbeforeBulkUpdate\n```\n\n```text\nModel.update({id: input.id}, { individualHooks: true});\n```\n\n```text\nhooks: {\n      beforeUpdate: (instance, options) => {\n        console.log(instance.dataValues); // new values\n        console.log(instance._previousDataValues); // current values\n      }\n    }\n```\n\n```text\nindividualHooks:true\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":64,"estimatedTokens":368}}572{"id":"stack-48358408","source":"stackoverflow","questionId":48358408,"title":"sequelize beforeSave hook not firing","tags":["node.js","postgresql","sequelize.js","postgis"],"text":"Title: sequelize beforeSave hook not firing\nTags: node.js, postgresql, sequelize.js, postgis\nSource: Stack Overflow\n\nQuestion:\nI've generated models with sequelize-auto, and need to use a beforeSave hook (see here). The hook isn't firing as far as I can tell. sequelize version ^4.20.1, sequelize-auto version ^0.4.29, express version ~4.15.5. Can anyone help?\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('trad', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n geom: {\n type: DataTypes.GEOMETRY('POINT', 4326),\n allowNull: true\n },\n ...\n }, {\n hooks: {\n beforeSave: (instance, options) => {\n console.log('Saving geom: ' + instance.geom);\n if (instance.geom && !instance.geom.crs) {\n instance.geom.crs = {\n type: 'name',\n properties: {\n name: 'EPSG:4326'\n }\n };\n }\n }\n },\n tableName: 'trad',\n timestamps: false,\n });\n};\n```\n\nHere's the code from the PUT request:\n\n```\n// Update (PUT)\nrouter.put('/table/:table/:id', function(req, res, next) {\n db.resolveTableName( req )\n .then( table => {\n const primaryKey = table.primaryKeyAttributes[0];\n var where = {};\n where[primaryKey] = req.params.id;\n console.log('Put - pkey: ' + primaryKey);\n\n auth.authMethodTable( req )\n .then( function() {\n table.update( req.body, {\n where: where,\n returning: true,\n plain: true\n })\n .then( data => {\n res.status(200).json( data[1].dataValues );\n })\n .catch( function (error ) {\n res.status(500).json( error );\n });\n })\n .catch( function( error ) {\n res.status(401).json('Unauthorized');\n });\n })\n .catch( function(e) {\n res.status(400).json('Bad request');\n });\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('trad', {\n    id: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    geom: {\n      type: DataTypes.GEOMETRY('POINT', 4326),\n      allowNull: true\n    },\n    ...\n  }, {\n    hooks: {\n      beforeSave: (instance, options) => {\n        console.log('Saving geom: ' + instance.geom);\n        if (instance.geom && !instance.geom.crs) {\n          instance.geom.crs = {\n            type: 'name',\n            properties: {\n              name: 'EPSG:4326'\n            }\n          };\n        }\n      }\n    },\n    tableName: 'trad',\n    timestamps: false,\n  });\n};\n```\n\n```text\n// Update (PUT)\nrouter.put('/table/:table/:id', function(req, res, next) {\n  db.resolveTableName( req )\n  .then( table => {\n    const primaryKey = table.primaryKeyAttributes[0];\n    var where = {};\n    where[primaryKey] =  req.params.id;\n    console.log('Put - pkey: ' + primaryKey);\n\n    auth.authMethodTable( req )\n    .then( function() {\n      table.update( req.body, {\n        where: where,\n        returning: true,\n        plain: true\n      })\n      .then( data => {\n        res.status(200).json( data[1].dataValues );\n      })\n      .catch( function (error ) {\n        res.status(500).json( error );\n      });\n    })\n    .catch( function( error ) {\n      res.status(401).json('Unauthorized');\n    });\n  })\n  .catch( function(e) {\n    res.status(400).json('Bad request');\n  });\n});\n```\n\n```text\ntable.update( req.body, {\n  where: where,\n  returning: true,\n  individualHooks: true\n  plain: true\n})\n```\n\n```text\ntable.findById(req.params.id)\n  .then(function(instance) {\n    instance.update(req.body, {\n      returning: true\n      plain: true\n    })\n  })\n```\n\n```text\nbeforeSave\n```\n\n```text\nindividualHooks\n```\n\n========================================\n\nComments:\n- could you the code where you are trying to save a model instance?\n- Good idea @mcranston18. Done!\n- Thanks @mcranston18. I used option 2 as this seems a much cleaner way to update individual records. The hook is now firing. It appears also that with option 2 sequelize only saves the changed attributes - plus the geometry now that I've added the hook.","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":181,"estimatedTokens":982}}573{"id":"stack-45501856","source":"stackoverflow","questionId":45501856,"title":"Associate different models using sequelize?","tags":["node.js","express","associations","sequelize.js"],"text":"Title: Associate different models using sequelize?\nTags: node.js, express, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHi I am trying to associate my User model with login model and Question_details models.But if i am using the Question_details association then i am geeting eagerLodingError :user is not associated to login but if i am commenting it then it works fine so how can i associate it ? \n\nBut if i am associating with \n\n```\nUser Model\n\n module.exports = (sequelize, DataTypes) => {\n var Users = sequelize.define('users', {\n name: {\n type: DataTypes.STRING(100)\n }\n phone: {\n type: DataTypes.BIGINT,\n unique: true\n }\n }, { freezeTableName: true });\n\n Users.associate = function(models) {\n Users.hasOne(models.login, {\n foreignKey: 'user_id',\n as: 'loginDetails'\n });\n };\n\n Users.associate = function(models) {\n Users.hasMany(models.customer_query, {\n foreignKey: 'user_id',\n as: 'queryDetails'\n });\n };\n\n return Users;\n };\n```\n\nLOGIN MODEL\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n var Login = sequelize.define('login', {\n user_id: {\n type: DataTypes.INTEGER\n },\n user_name: {\n type: DataTypes.STRING(500),\n isEmail: true\n },\n password: {\n type: DataTypes.STRING(500)\n },\n role_id: {\n type: DataTypes.INTEGER\n }\n }, {\n underscored: true,\n freezeTableName: true\n });\n\n Login.associate = function(models) {\n Login.belongsTo(models.users, {\n foreignKey: 'user_id',\n onDelete: 'CASCADE'\n });\n };\n Login.associate = function(models) {\n Login.belongsTo(models.roles, {\n foreignKey: 'role_id',\n onDelete: 'CASCADE'\n });\n };\n return Login;\n```\n\n};\n\nquestionDetails Model\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var questionDetails = sequelize.define('question_details', {\n query_id: {\n type: DataTypes.INTEGER\n },\n ques_type_id: {\n type: DataTypes.INTEGER\n },\n created_by: {\n type: DataTypes.INTEGER\n },\n question: {\n type: DataTypes.TEXT\n },\n\n }, { freezeTableName: true });\n\n questionDetails.associate = function(models) {\n questionDetails.belongsTo(models.users, {\n foreignKey: 'created_by',\n onDelete: 'CASCADE'\n });\n };\n\n return questionDetails;\n };\n```\n\n========================================\n\nCode:\n```text\nUser Model\n\n    module.exports = (sequelize, DataTypes) => {\n        var Users = sequelize.define('users', {\n            name: {\n                type: DataTypes.STRING(100)\n             }\n            phone: {\n                type: DataTypes.BIGINT,\n                unique: true\n            }\n        }, { freezeTableName: true });\n\n        Users.associate = function(models) {\n            Users.hasOne(models.login, {\n                foreignKey: 'user_id',\n                as: 'loginDetails'\n            });\n        };\n\n        Users.associate = function(models) {\n            Users.hasMany(models.customer_query, {\n                foreignKey: 'user_id',\n                as: 'queryDetails'\n            });\n        };\n\n        return Users;\n    };\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    var Login = sequelize.define('login', {\n        user_id: {\n            type: DataTypes.INTEGER\n        },\n        user_name: {\n            type: DataTypes.STRING(500),\n            isEmail: true\n        },\n        password: {\n            type: DataTypes.STRING(500)\n        },\n        role_id: {\n            type: DataTypes.INTEGER\n        }\n    }, {\n        underscored: true,\n        freezeTableName: true\n    });\n\n    Login.associate = function(models) {\n        Login.belongsTo(models.users, {\n            foreignKey: 'user_id',\n            onDelete: 'CASCADE'\n        });\n    };\n    Login.associate = function(models) {\n        Login.belongsTo(models.roles, {\n            foreignKey: 'role_id',\n            onDelete: 'CASCADE'\n        });\n    };\n    return Login;\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n        var questionDetails = sequelize.define('question_details', {\n            query_id: {\n                type: DataTypes.INTEGER\n            },\n            ques_type_id: {\n                type: DataTypes.INTEGER\n            },\n            created_by: {\n                type: DataTypes.INTEGER\n            },\n            question: {\n                type: DataTypes.TEXT\n            },\n\n        }, { freezeTableName: true });\n\n questionDetails.associate = function(models) {\n            questionDetails.belongsTo(models.users, {\n                foreignKey: 'created_by',\n                onDelete: 'CASCADE'\n            });\n        };\n\n        return questionDetails;\n    };\n```\n\n```text\nUsers.associate = function(models) {\n      Users.hasOne(models.login, {\n        foreignKey: 'user_id',\n        as: 'loginDetails'\n      });\n\n      Users.hasMany(models.customer_query, {\n        foreignKey: 'user_id',\n        as: 'queryDetails'\n      });\n    };\n```\n\n```text\nUser\n```\n\n```text\nassociate\n```\n\n========================================\n\nComments:\n- I cannot find association function or any syntax like Model.associate = function(models) { any where in the sequelize docs. Can any one please help me to find details about association function in docs or anywhere.\n- @AbhishekKumar `Users.associate` is a custom function that we created to add these relationships to the model. We had to do it that way because we need to call the `associate` function after all of the models have been imported into Sequelize. See github.com/sequelize/express-example/blob/master/models/&hellip; for an example.\n- my question almost same, but little nested, jsfiddle.net/j74rt9y1/1 the second assosiation didn't works and no error,, anyone can helps ?\n- @DylanAspden How to create a login record for a user?\n- here is the complete explaination how its done codebysamgan.com/&hellip;\n- Here in 2023 and there is still no documentation for the association function","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":243,"estimatedTokens":1437}}574{"id":"stack-42159779","source":"stackoverflow","questionId":42159779,"title":"How to make sequelize.sync() omit some models?","tags":["mysql","node.js","database","sequelize.js"],"text":"Title: How to make sequelize.sync() omit some models?\nTags: mysql, node.js, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI use tables and views in my DB (mysql), so for dev/test environment I want to use sync(), but it crashes on views.\n\nCan I somehow omit these models?\n\n========================================\n\nTop Answer:\nI use a method quite similar to Crusader's answer when I want to create and use Views with Sequelize. In this case I do not want to have Sequelize try and sync the view as it results in a table being created. To do this I add the following to a Sequelize model: \n\n```\nvar MyView = sequelize.define(\"MyView\", {\n status: { type: DataTypes.TEXT },\n},\n{\n doNotSync: true,\n tableName: \"myDatabaseView\", // The actual view name in database\n classMethods: {\n createView: function(models) {\n return sequelize.query(\"CREATE OR REPLACE VIEW myDatabaseView ...;\");\n }\n});\n```\n\nNow I have that setup I need to make sure the views are not included when I create the database and that the `createView` method is called on each of the views.\n\n```\nvar tables = [];\nsequelize.modelManager.forEachModel(m => {\n if (m.options.doNotSync !== true) {\n tables.push(m);\n } \n});\n\nreturn Sequelize.Promise.each(tables, t => {\n\n return t.sync({force: true});\n\n}).then(_ => {\n\n var views = [];\n sequelize.modelManager.forEachModel(m => {\n if (m.options.doNotSync && m.createView) {\n views.push(m);\n } \n });\n\n return Sequelize.Promise.each(views, v => {\n\n return v.createView(sequelize.models);\n\n });\n\n});\n```\n\nAlso, just to be on the safe side I add hooks to prevent using any of the create/update/delete operations on the views.\n\n```\nhooks: {\n beforeBulkCreate: throwNotAllowedError,\n beforeBulkDestroy: throwNotAllowedError,\n beforeBulkUpdate: throwNotAllowedError,\n beforeCreate: throwNotAllowedError,\n beforeDestroy: throwNotAllowedError,\n beforeUpdate: throwNotAllowedError\n}\n```\n\nWhere `throwNotAllowedError` is a simple function\n\n```\nfunction throwNotAllowedError() {\n throw new Error(\"Operation not allowed on a view\");\n}\n```\n\nHope that helps. Getting views into Sequelize has given us a massive increate in productivity on the project.\n\nAnd you can still create relationships and associations from the views allowing you to use the `include:[]` notation to bring additional tables into your view query.\n\n========================================\n\nCode:\n```text\nconst MyView = sequelize.define('myView', {\n  ids: {\n    type: DataTypes.ARRAY(DataTypes.INTEGER)\n  },\n  volumeSum: {\n    type: DataTypes.INTEGER\n  }\n});\n\n// To avoid table creation\nMyView.sync = () => Promise.resolve();\n```\n\n```text\nsequelize.sync();\n```\n\n```text\nif (config.sync && config.sync != 'false') {\n  let models = [];\n  sequelize.modelManager.forEachModel(function(model) {\n    if (model && model.options.sync !== false) {\n      models.push(model);\n    } else {\n      // DB should throw an SQL error if referencing inexistant table\n    }\n  });\n  return Sequelize.Promise.each(models, function(model) {\n    return model.sync(config.sync);\n  });\n}\n```\n\n```text\nvar MyView = sequelize.define(\"MyView\", {\n  status: { type: DataTypes.TEXT },\n},\n{\n  doNotSync: true,\n  tableName: \"myDatabaseView\", // The actual view name in database\n  classMethods: {\n    createView: function(models) {\n      return sequelize.query(\"CREATE OR REPLACE VIEW myDatabaseView ...;\");\n    }\n});\n```\n\n```text\nvar tables = [];\nsequelize.modelManager.forEachModel(m => {\n    if (m.options.doNotSync !== true) {\n      tables.push(m);\n    }              \n});\n\nreturn Sequelize.Promise.each(tables, t => {\n\n  return t.sync({force: true});\n\n}).then(_ => {\n\n  var views = [];\n  sequelize.modelManager.forEachModel(m => {\n      if (m.options.doNotSync && m.createView) {\n        views.push(m);\n      }              \n  });\n\n  return Sequelize.Promise.each(views, v => {\n\n    return v.createView(sequelize.models);\n\n  });\n\n});\n```\n\n```text\nhooks: {\n  beforeBulkCreate: throwNotAllowedError,\n  beforeBulkDestroy: throwNotAllowedError,\n  beforeBulkUpdate: throwNotAllowedError,\n  beforeCreate: throwNotAllowedError,\n  beforeDestroy: throwNotAllowedError,\n  beforeUpdate: throwNotAllowedError\n}\n```\n\n```text\nfunction throwNotAllowedError() {\n  throw new Error(\"Operation not allowed on a view\");\n}\n```\n\n```text\ncreateView\n```\n\n```text\nthrowNotAllowedError\n```\n\n```text\ninclude:[]\n```\n\n========================================\n\nComments:\n- Thorough answer. This should be part of the official sequelize documentation. It is very good. Thank you for this. Now we can use views with sequelize as well.\n- When using sequelize-typescript it gives an error saying doNotSync does not exist and it also doesnt detect Sequelize.Promise\n- Great tip, thanks! The benefit of this approach is that you can still rely on Sequelize to manage the order of syncing your models correctly, with respect to **foreign keys**. If you try to manually call `model.sync()` on each of your models as @gary-johnson suggested, you are responsible for ensuring they are ordered correctly.","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":201,"estimatedTokens":1252}}575{"id":"stack-40987364","source":"stackoverflow","questionId":40987364,"title":"Sequelize Nested Association with Two Tables","tags":["node.js","associations","sequelize.js"],"text":"Title: Sequelize Nested Association with Two Tables\nTags: node.js, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a scenario where I am trying to query a parent table (document) with two associated tables (reference & user) that do not have a relationship to each other, but do have a relationship with the parent table. In SQL, this query would look like such and correctly outputs the data I am looking for:\n\n```\nselect *\nfrom `document`\nleft join `user`\non `document`.`user_id` = `user`.`user_id`\nleft join `reference`\non `document`.`reference_id` = `reference`.`reference_id`\nwhere `user`.`organization_id` = 1;\n```\n\nHowever, associations that are nested have to relate in hierarchical order in order for the query to work. Since the nested associations are not related to each other I get an association error. How can I avoid this error? Would `required: false` have any influence on this?\n\n```\nmodels.Document.findAll({\n order: 'documentDate DESC',\n include: [{\n model: models.User,\n where: { organizationId: req.user.organizationId },\n include: [{\n model: models.Reference,\n }]\n }],\n})\n```\n\n**Error**: \n\n Unhandled rejection Error: reference is not associated to user!\n\n**Associations**:\n\n**`Document`**:\n\n```\nassociate: function(db) {\n Document.belongsTo(db.User, {foreignKey: 'user_id'}),\n Document.belongsTo(db.Reference, { foreignKey: 'reference_id'});;\n}\n```\n\n**`Reference`**:\n\n```\nassociate: function(db){\n Reference.hasMany(db.Document, { foreignKey: 'reference_id' });\n}\n```\n\nShould I just chain queries instead?\n\n========================================\n\nTop Answer:\nThe error is indicating that the `User` model is not associated to the `Reference` model, but there are only definitions for the `Document` and `Reference` models in your description. You are joining these tables in your query with the `include` option, so you have to make sure they are associated. You don't technically need the `foreignKey` here either, you are specifying the default values.\n\n**Add `Reference->User` association**\n\n```\nassociate: function(db) {\n // belongsTo()? maybe another relationship depending on your data model\n Reference.belongsTo(db.User, {foreignKey: 'user_id'});\n\n Reference.hasMany(db.Document, { foreignKey: 'reference_id' });\n}\n```\n\nIt also looks like you probably set `underscored: true` in your model definitions, so your query should reflect this. Additionally if you want to perform a `LEFT JOIN` you need to specify `required: false` on the `include`, otherwise it is a regular `JOIN` and you will only get back rows with matches in the `include`d model. You are also using the wrong `order` format, it should be an array of values, and to sort by `model.document_date DESC` you should use `order: [['document_date', 'DESC']]`.\n\n**Proper query arguments**\n\n```\nmodels.Document.findAll({\n order: [['document_date', 'DESC']], // If you are still having trouble, try enabling logging by setting `logging: console.log` in your Sequelize connection, that will show you all the queries it is running in your console.\n\n========================================\n\nCode:\n```sql\nselect *\nfrom `document`\nleft join `user`\non `document`.`user_id` = `user`.`user_id`\nleft join `reference`\non `document`.`reference_id` = `reference`.`reference_id`\nwhere `user`.`organization_id` = 1;\n```\n\n```js\nmodels.Document.findAll({\n  order: 'documentDate DESC',\n  include: [{\n    model: models.User,\n    where: { organizationId: req.user.organizationId },\n    include: [{\n      model: models.Reference,\n    }]\n  }],\n})\n```\n\n```js\nassociate: function(db) {\n  Document.belongsTo(db.User, {foreignKey: 'user_id'}),\n    Document.belongsTo(db.Reference, { foreignKey: 'reference_id'});;\n}\n```\n\n```js\nassociate: function(db){\n  Reference.hasMany(db.Document, { foreignKey: 'reference_id' });\n}\n```\n\n```text\nrequired: false\n```\n\n```text\nDocument\n```\n\n```text\nReference\n```\n\n```js\nmodels.Document.findAll({\n  // this is an array of includes, don't nest them\n  include: [{\n    model: models.User,\n    where: { organization_id: req.user.organization_id }, // <-- underscored HERE\n    required: true, // <-- JOIN to only return Documents where there is a matching User\n  },\n  {\n    model: models.Reference,\n    required: false, // <-- LEFT JOIN, return rows even if there is no match\n  }],\n  order: [['document_date', 'DESC']], // <-- underscored HERE, plus use correct format\n});\n```\n\n```text\nwhere\n```\n\n```text\ninclude\n```\n\n```text\nDocument.user_id\n```\n\n```text\nUser.organization_id\n```\n\n```text\nDocument\n```\n\n```text\nUser.organization_id\n```\n\n```text\nrequired: true\n```\n\n```text\nUser <- Document -> Reference\n```\n\n```js\nassociate: function(db) {\n  // belongsTo()? maybe another relationship depending on your data model\n  Reference.belongsTo(db.User, {foreignKey: 'user_id'});\n\n  Reference.hasMany(db.Document, { foreignKey: 'reference_id' });\n}\n```\n\n```js\nmodels.Document.findAll({\n  order: [['document_date', 'DESC']], // <-- underscored HERE, plus use correct format\n  include: [{\n    model: models.User,\n    where: { organization_id: req.user.organization_id }, // <-- underscored HERE\n    required: false, // <-- LEFT JOIN\n    include: [{\n      model: models.Reference,\n      required: false, // <-- LEFT JOIN\n    }]\n  }],\n});\n```\n\n```text\nUser\n```\n\n```text\nReference\n```\n\n```text\nDocument\n```\n\n```text\nReference\n```\n\n```text\ninclude\n```\n\n```text\nforeignKey\n```\n\n```text\nReference->User\n```\n\n```text\nunderscored: true\n```\n\n```text\nLEFT JOIN\n```\n\n```text\nrequired: false\n```\n\n```text\ninclude\n```\n\n```text\nJOIN\n```\n\n```text\ninclude\n```\n\n```text\norder\n```\n\n```text\nmodel.document_date DESC\n```\n\n```text\norder: [['document_date', 'DESC']]\n```\n\n```text\nlogging: console.log\n```\n\n```text\nassociate: function(db) {\n  Document.belongsTo(db.User, {foreignKey: 'user_id'}),  //key in documents\n  Document.belongsTo(db.Reference, { foreignKey: 'reference_id'}); //key in documents\n}\n```\n\n```text\nassociate: function(db) {\n  User.belongsTo(db.Document, {\n    foreignKey: 'id',    //Key in User\n    targetKey: 'user_id' //Key in Documents\n  }),\n}\n```\n\n```text\nassociate: function(db) {\n  Reference.belongsTo(db.Document, {\n      foreignKey: 'id',         //Key in reference\n      targetKey: 'reference_id' //Key in Documents\n  }),\n}\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n    logging: console.log\n    logging: function (str) {\n        // do your own logging\n    }\n});\n```\n\n========================================\n\nComments:\n- It looks like you specify `underscored: true` but are using cameCase names: `organization_id` vs `organizationId` for example.\n- I appreciate the detailed comment and noticed that I never added detail about the User model. The reason why I left it out outside of the brief reference is because there is no association on that model that is related to the two other tables mentioned (Document and Reference). My question is doesn't associating tables without a foreign key defeat the purpose of what an association should be? A relationship between tables with an FK? Would a raw query be the a better route since Reference isn't directly related to User?\n- Your query reflects that the association is `Document->User->Reference`.\n- Do you mean to query `Document->User` and `Document->Reference`?\n- `Document -> User` and `Document -> Reference` is the correct way to put together the relationships. Document is linked to both tables, but they aren't linked to each other. I believe this also mimics the double left join in the SQL query in the question.\n- I posted a different answer based on your original query and that information. Not knowing your requirements my guess is that you need to make the user include required since you probably want to exclude documents for users in the wrong organization...?\n- this is exactly what I was looking for! I have been trying to figure out how to join multiple tables that are associated to a parent table, but not together and this solved the issue. How did you know to nest both within the include array rather than nest another include within the first? I don't believe I have ever found this in documentation or within any community answers.\n- It depends on your data model. Like I mentioned before (and why my first answer was incorrect) when you nest them you change the type of relationship to `Document->User->Reference`, when really you wanted `Document->User` + `Document->Reference`.\n- You don't really need `required: true` when you are using the `where` clause.\n- @keshavAggarwal that's correct, `required: true` is the default value, I just included it to make it explicit.","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":319,"estimatedTokens":2151}}576{"id":"stack-31983885","source":"stackoverflow","questionId":31983885,"title":"Create multiple INNER JOINS with Sequelize ORM","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Create multiple INNER JOINS with Sequelize ORM\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize ORM with Node.js and I can't get my head around on how to build the following query with it.\n\n```\nSELECT service.*, serviceCollection.*, client.companyName, client.idclient \nFROM service \nINNER JOIN serviceCollection \nON service.serviceCollection_idserviceCollection = serviceCollection.idserviceCollection \nINNER JOIN client \nON serviceCollection.client_idclient = client.idclient\n```\n\nThis query works and runs fine when I try it on phpMyAdmin.\nThe complication is that the Client model has no direct relation with Service, so when trying to do this : \n\n```\nService.findAll({include : [ServiceCollection, Client]}).then(function(service){\n if(service) {\n res.status(200).json(service);\n }\n});\n```\n\nI get the following error : \n\n```\nUnhandled rejection Error: client is not associated to service!\n```\n\nHow could I prepare the query in a way that would get the client information from the foreignkey in ***serviceCollection*** and not the original model - ***service***.\nI can't just use `include` on ***client*** because it will give me the error, I need to associate it to this query some other way and I can't seem to find the solution in the documentation.\n\n========================================\n\nCode:\n```text\nSELECT service.*, serviceCollection.*, client.companyName, client.idclient \nFROM service \nINNER JOIN serviceCollection \nON service.serviceCollection_idserviceCollection = serviceCollection.idserviceCollection \nINNER JOIN client \nON serviceCollection.client_idclient = client.idclient\n```\n\n```text\nService.findAll({include : [ServiceCollection, Client]}).then(function(service){\n    if(service) {\n        res.status(200).json(service);\n    }\n});\n```\n\n```text\nUnhandled rejection Error: client is not associated to service!\n```\n\n```text\ninclude\n```\n\n```text\nService.findAll({\n  include : [\n    { \n      model: ServiceCollection, \n      required: true,\n      include: [{model: Client, required: true }]}\n  ]\n});\n```\n\n```text\nrequired: true\n```\n\n========================================\n\nComments:\n- possible duplicate of How to make join querys using sequelize in nodejs","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":560}}577{"id":"stack-51941168","source":"stackoverflow","questionId":51941168,"title":"Error cannot find module 'sequelize'","tags":["node.js","npm","sequelize.js"],"text":"Title: Error cannot find module 'sequelize'\nTags: node.js, npm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've install (fresh install) using nodejs and npm, then install sequelize-cli and module as per instruction on tutorial of sequelize http://docs.sequelizejs.com/manual/tutorial/migrations.html#installing-cli\n\nBut when wan't to do anything with sequelize, it return an error like below :\n\n```\nme@u64:~/project/manztihagi$ sequelize\ninternal/modules/cjs/loader.js:583\n throw err;\n ^\n\nError: Cannot find module 'sequelize'\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)\n at Function.Module._load (internal/modules/cjs/loader.js:507:25)\n at Module.require (internal/modules/cjs/loader.js:637:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at Object. (/usr/lib/node_modules/sequelize-cli/lib/helpers/model-helper.js:7:18)\n at Module._compile (internal/modules/cjs/loader.js:689:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n at Module.load (internal/modules/cjs/loader.js:599:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n at Function.Module._load (internal/modules/cjs/loader.js:530:3)\n at Module.require (internal/modules/cjs/loader.js:637:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at /usr/lib/node_modules/sequelize-cli/lib/helpers/index.js:18:52\n at Array.forEach ()\n at Object. (/usr/lib/node_modules/sequelize-cli/lib/helpers/index.js:17:4)\n at Module._compile (internal/modules/cjs/loader.js:689:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n at Module.load (internal/modules/cjs/loader.js:599:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n at Function.Module._load (internal/modules/cjs/loader.js:530:3)\n at Module.require (internal/modules/cjs/loader.js:637:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at Object. (/usr/lib/node_modules/sequelize-cli/lib/commands/init.js:7:16)\n at Module._compile (internal/modules/cjs/loader.js:689:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n at Module.load (internal/modules/cjs/loader.js:599:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n at Function.Module._load (internal/modules/cjs/loader.js:530:3)\nme@u64:~/project/manztihagi$\n```\n\nSearch another solution until reinstall the packages still not luck.\n\nHow to resolve this error ?\n\n```\nme@u64:~/project/manztihagi$ ng -v\n\n _ _ ____ _ ___\n / \\ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|\n / △ \\ | '_ \\ / _` | | | | |/ _` | '__| | | | | | |\n / ___ \\| | | | (_| | |_| | | (_| | | | |___| |___ | |\n /_/ \\_\\_| |_|\\__, |\\__,_|_|\\__,_|_| \\____|_____|___|\n |___/\n\nAngular CLI: 6.1.3\nNode: 10.9.0\nOS: linux x64\nAngular: undefined\n... \n\nPackage Version\n------------------------------------------------------\n@angular-devkit/architect 0.7.3 (cli-only)\n@angular-devkit/core 0.7.3 (cli-only)\n@angular-devkit/schematics 0.7.3 (cli-only)\n@schematics/angular 0.7.3 (cli-only)\n@schematics/update 0.7.3 (cli-only)\nrxjs 6.2.2\n\nme@u64:~/project/manztihagi$ node -v\nv10.9.0\nme@u64:~/project/manztihagi$ npm -v\n6.2.0\nme@u64:~/project/manztihagi$\n```\n\n========================================\n\nTop Answer:\n```\nError: Cannot find module 'sequelize'\n```\n\nI had the same problem, but it was caused by wrong name of module.\n\n- **correct form is: require('sequelize')**\n\n- wrong is: require('**S**equelize')\n\nI was working on windows and trying to run code on better system ;)\n\nhope this might be helpfull, GL\n\n========================================\n\nCode:\n```text\nme@u64:~/project/manztihagi$ sequelize\ninternal/modules/cjs/loader.js:583\n    throw err;\n    ^\n\nError: Cannot find module 'sequelize'\n    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)\n    at Function.Module._load (internal/modules/cjs/loader.js:507:25)\n    at Module.require (internal/modules/cjs/loader.js:637:17)\n    at require (internal/modules/cjs/helpers.js:20:18)\n    at Object.<anonymous> (/usr/lib/node_modules/sequelize-cli/lib/helpers/model-helper.js:7:18)\n    at Module._compile (internal/modules/cjs/loader.js:689:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n    at Module.load (internal/modules/cjs/loader.js:599:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:530:3)\n    at Module.require (internal/modules/cjs/loader.js:637:17)\n    at require (internal/modules/cjs/helpers.js:20:18)\n    at /usr/lib/node_modules/sequelize-cli/lib/helpers/index.js:18:52\n    at Array.forEach (<anonymous>)\n    at Object.<anonymous> (/usr/lib/node_modules/sequelize-cli/lib/helpers/index.js:17:4)\n    at Module._compile (internal/modules/cjs/loader.js:689:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n    at Module.load (internal/modules/cjs/loader.js:599:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:530:3)\n    at Module.require (internal/modules/cjs/loader.js:637:17)\n    at require (internal/modules/cjs/helpers.js:20:18)\n    at Object.<anonymous> (/usr/lib/node_modules/sequelize-cli/lib/commands/init.js:7:16)\n    at Module._compile (internal/modules/cjs/loader.js:689:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n    at Module.load (internal/modules/cjs/loader.js:599:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:530:3)\nme@u64:~/project/manztihagi$\n```\n\n```text\nme@u64:~/project/manztihagi$ ng -v\n\n     _                      _                 ____ _     ___\n    / \\   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|\n   / △ \\ | '_ \\ / _` | | | | |/ _` | '__|   | |   | |    | |\n  / ___ \\| | | | (_| | |_| | | (_| | |      | |___| |___ | |\n /_/   \\_\\_| |_|\\__, |\\__,_|_|\\__,_|_|       \\____|_____|___|\n                |___/\n\n\nAngular CLI: 6.1.3\nNode: 10.9.0\nOS: linux x64\nAngular: undefined\n... \n\nPackage                      Version\n------------------------------------------------------\n@angular-devkit/architect    0.7.3 (cli-only)\n@angular-devkit/core         0.7.3 (cli-only)\n@angular-devkit/schematics   0.7.3 (cli-only)\n@schematics/angular          0.7.3 (cli-only)\n@schematics/update           0.7.3 (cli-only)\nrxjs                         6.2.2\n\nme@u64:~/project/manztihagi$ node -v\nv10.9.0\nme@u64:~/project/manztihagi$ npm -v\n6.2.0\nme@u64:~/project/manztihagi$\n```\n\n```text\nnpm install -g sequelize-cli\nnpm install -g sequelize\n```\n\n```text\nnpm install --save sequelize-cli\nnpm install --save sequelize\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize-cli\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize-cli\n```\n\n```text\nnpm install -g sequelize-cli\nnpm install -g sequelize\n```\n\n```text\nError: Cannot find module 'sequelize'\n```\n\n```text\nError: Cannot find module 'sequelize/types/lib/operators'\n```\n\n```text\nconst { substring } = require(\"sequelize/types/lib/operators\");\n```\n\n```text\nimports\n```\n\n```text\nenumSingular = enumPlural.substring(0, enumPlural.length - 1);\n```\n\n```text\nsubstring\n```\n\n========================================\n\nComments:\n- I'm already try your solution and solve my issue, but the other hand, from the other tutorial that guide the sequelize-cli shall install as global module and sequelize as local module but the error appear. I'm trying on other machine, sequelize-cli as global and sequelize as local both of sequelize can run well ... Not sure what happened on my this machines error\n- Yes you were right! VS code was the culprit. It has added an import to something which i accidently typed and deleted. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":234,"estimatedTokens":1924}}578{"id":"stack-18640627","source":"stackoverflow","questionId":18640627,"title":"Node.js multiple Sequelize raw sql query sub queries","tags":["javascript","node.js","sequelize.js"],"text":"Title: Node.js multiple Sequelize raw sql query sub queries\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe title sounds complicated. I have a users table, and each user can have multiple interests. These interests are linked to the user via a lookup table. In PHP I queried the users table, then for each one did a query to find interests. How can I do this in Node.js/Sequelize? How can I set up some sort of promises too? For example:\n\n```\nsequelize.query(\"SELECT * FROM users\").success(function(users) {\n for (var u in users) {\n sequelize.query(\"SELECT interests.id, interests.title FROM interests, user_interests WHERE interests.id = user_interests.interest_id AND user_interests.user_id = \" + users[u].id).success(function(interests) {\n if (interests.length > 0) {\n users[u].interests = interests;\n }\n });\n }\n return users;\n});\n```\n\n========================================\n\nCode:\n```text\nsequelize.query(\"SELECT * FROM users\").success(function(users) {\n    for (var u in users) {\n       sequelize.query(\"SELECT interests.id, interests.title FROM interests, user_interests WHERE interests.id = user_interests.interest_id AND user_interests.user_id = \" + users[u].id).success(function(interests) {\n       if (interests.length > 0) {\n         users[u].interests = interests;\n       }\n    });\n  }\n  return users;\n});\n```\n\n```text\nsequelize.query(\"SELECT * FROM users\").success(function(users) {\n    done = _.after(users.length, function () {\n        callback(users)\n    })\n\n    for (var u in users) {\n        sequelize.query(\"SELECT interests.id, interests.title FROM interests, user_interests WHERE interests.id = user_interests.interest_id AND user_interests.user_id = \" + users[u].id).success(function(interests) {\n            if (interests.length > 0) {\n             users[u].interests = interests;\n            }\n            done();\n        });\n    }\n});\n```\n\n```text\nsequelize.query(\"SELECT * FROM users\").then(function(users) {\n  return sequelize.Promise.map(users, function (u) {\n    return sequelize.query(\"SELECT interests.id, interests.title FROM interests, user_interests WHERE interests.id = user_interests.interest_id AND user_interests.user_id = \" + users[u].id).then(function(interests) {\n      if (interests.length > 0) {\n        user.interests = interests;\n      }\n    });\n  });\n});\n```\n\n```text\n_\n```\n\n========================================\n\nComments:\n- Just remember that you have to include underscore module\n- _ is already used in sequelize, and exposed via `Sequelize.Utils._`\n- Hi Jan I was blocked on the same issue for many hours. I tried using Promise.all without any luck. I'm new to node.js and all the async stuff so likely I've been confused but I was wondering if you had a working example using Promise.all ? thanks In any case your answer works and helped me a lot.\n- @Etienne I've added an example using promises\n- @Jan. \" Any reason why you are not using the SQL driver directly?\" Can you please explain SQL driver. I am connecting postres and express using sequelize and only executing raw queries / raw multiple queries","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":773}}579{"id":"stack-48757188","source":"stackoverflow","questionId":48757188,"title":"Sequelize Complex And/OR","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize Complex And/OR\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to do a statement like this in Sequelize.\n\n```\nSelect * from table WHERE completed = 0 AND tracking = 1 AND ((FromNumber = +15625554444 AND ToNumber = +17145554444) OR (FromNumber = +17145554444 AND ToNumber = +15625554444))\n```\n\nHow would I do this query in Sequelize? I looked in the documentation but am very confused and keep running into weird queries in my attempts thus far.\n\nMy actual code attempt thus far while experimenting is this, but it doesn't mean anything since it doesn't work right now. **I am not sure what the syntax should look like for this type of AND/Or Scenario.**\n\n```\nvar setNumberData = await models[\"texts\"].findOne({\n where: {\n completed: 0,\n agentNumber: agentData.number,\n trackingNumber: obj.To,\n [Op.and]: [\n {to: realTo},\n {[Op.or] : [{from: agentData.number}]}\n ],\n // [Op.and]: [{to: obj.To}],\n // [Op.or]: [{from: obj.To}],\n // [Op.and]: [{to: obj.From}]\n }\n });\n```\n\n========================================\n\nCode:\n```text\nSelect * from table WHERE completed = 0 AND tracking = 1 AND ((FromNumber = +15625554444 AND ToNumber = +17145554444) OR (FromNumber = +17145554444 AND ToNumber = +15625554444))\n```\n\n```text\nvar setNumberData = await models[\"texts\"].findOne({\n    where: {\n      completed: 0,\n      agentNumber: agentData.number,\n      trackingNumber: obj.To,\n      [Op.and]: [\n        {to: realTo},\n        {[Op.or] : [{from: agentData.number}]}\n      ],\n      // [Op.and]: [{to: obj.To}],\n      // [Op.or]: [{from: obj.To}],\n      // [Op.and]: [{to: obj.From}]\n    }\n  });\n```\n\n```text\nvar setNumberData = await models[\"texts\"].findOne({\n    where: {\n      completed: 0,\n      agentNumber: agentData.number,\n      trackingNumber: obj.To,\n      [Op.or]: [\n        {[Op.and] : [\n          {from: obj.From},\n          {to: realTo}\n        ]},\n        {[Op.and] : [\n          {from: realTo},\n          {to: obj.From}\n        ]}\n      ]\n    }\n  });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":75,"estimatedTokens":502}}580{"id":"stack-54687518","source":"stackoverflow","questionId":54687518,"title":"How to use paranoid in sequelize?","tags":["sequelize.js"],"text":"Title: How to use paranoid in sequelize?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am a newbie to Sequelize if I want to delete an entry I will not delete directly I have a separate field to make it active and inactive. So I want to have a deteledAT field to update automatically while deleting an entry. Is there any way I can do with paranoid.\n\n========================================\n\nCode:\n```text\nparanoid: true,\n  timestamps: true,\n```\n\n```text\nsequelize.define(\n    'example',\n    {\n      id: {\n        type: DataTypes.UUID,\n        allowNull: false,\n        primaryKey: true,\n        unique: true,\n        defaultValue: sequelize.literal('uuid_generate_v1()'),\n      }\n    },\n    {\n      tableName: 'example',\n      createdAt: 'created_at',\n      updatedAt: 'updated_at',\n      deletedAt: 'deletedAt',\n      paranoid: true,\n      timestamps: true,\n    },\n  );\n```\n\n```text\nexample\n```\n\n```text\ndestroy\n```\n\n```text\ndeletedAt\n```\n\n========================================\n\nComments:\n- Thank you so much. This is really helpful\n- It does not work for me. I don't have `deteledAT` column created for me by sequelize.\n- OP may have typo'd 'deletedAt' as 'deteledAT'. It caused me to look again\n- not work , i dunno why ,version : \"sequelize\": \"^6.6.5\"","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":57,"estimatedTokens":318}}581{"id":"stack-49242772","source":"stackoverflow","questionId":49242772,"title":"How to create prepared statements in Sequelize?","tags":["javascript","sequelize.js"],"text":"Title: How to create prepared statements in Sequelize?\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nFirst is it possible, I think it should be as they're safer than raw queries and prevent sql injection.\n\nBut there is literally nothing I can find in documentation.\n\n`sequelize.prepare` `sequelize.query` <- exists\n\n========================================\n\nCode:\n```text\nsequelize.prepare\n```\n\n```text\nsequelize.query\n```\n\n```text\nsequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',\n  { replacements: { search_name: 'ben%'  }, type: sequelize.QueryTypes.SELECT }\n).then(projects => {\n  console.log(projects)\n})\n```\n\n```text\nsequelize.query\n```\n\n```text\nreplacements\n```\n\n========================================\n\nComments:\n- Did you ever get an answer to this?\n- It's so built-in you hardly notice it's there.\n- But is this really about prepared statements, like sending a `PREPARE` command to the server and then sending only the parameter values? This seems more simply about having placeholders in a query that will be parsed repeatedly by the server if sumbitted again with different parameters.\n- That's right, but remember sequelize is an ORM and not a DB driver.\n- How do you make replacements in sequelize literal?","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":46,"estimatedTokens":315}}582{"id":"stack-48514254","source":"stackoverflow","questionId":48514254,"title":"Sequelize: find latest record per group of id","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize: find latest record per group of id\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to accomplish the same query on the link below but got no luck here:\n\nhttps://dzone.com/articles/get-last-record-in-each-mysql-group\n\nCan you suggest the proper way of converting the raw query on the link above into sequelize ORM format?\n\n========================================\n\nTop Answer:\nHere's what I did base on Nguyen's idea with some tweaks:\n\n```\nlet conversationIds = conversations.map(conversation => {\n return conversation.conversation_id;\n });\n\n models.conversationDetails.findAll({\n attributes: [\n [models.sequelize.fn(\"max\", models.sequelize.col('id')), 'id']\n ],\n where: {\n conversation_id: conversationIds\n },\n group: ['conversation_id']\n })\n .then(function(results) {\n let ids = results.map(result => {\n return result.id;\n });\n\n models.conversationDetails.findAll({\n include: [\n {\n model: models.conversationMeta,\n as: 'conversationMeta'\n }\n ],\n where: {\n id: {\n [Op.in]: ids\n }\n }\n })\n .then(function(conversationList) {\n callback(false, conversationList);\n })\n .catch(function(error) {\n console.log(error);\n callback(true, 'Internal Server Error');\n });\n })\n .catch(function(error) {\n console.log(error);\n callback(true, 'Internal Server Error');\n });\n```\n\n========================================\n\nCode:\n```text\nPosts.findAll({\n    attributes: [sequelize.fn(\"max\", sequelize.col('id'))],\n    group: [\"category_id\"]\n}).then(function(maxIds){\n    return Posts.findAll({\n        where: {\n            id: {\n                [Op.in]: maxIds\n            }\n        }\n    })\n}).then(function(result){\n    return Promise.resolve(result);\n});\n```\n\n```text\nlet conversationIds = conversations.map(conversation => {\n    return conversation.conversation_id;\n  });\n\n  models.conversationDetails.findAll({\n    attributes: [\n      [models.sequelize.fn(\"max\", models.sequelize.col('id')), 'id']\n    ],\n    where: {\n      conversation_id: conversationIds\n    },\n    group: ['conversation_id']\n  })\n  .then(function(results) {\n    let ids = results.map(result => {\n      return result.id;\n    });\n\n    models.conversationDetails.findAll({\n      include: [\n        {\n          model: models.conversationMeta,\n          as: 'conversationMeta'\n        }\n      ],\n      where: {\n        id: {\n            [Op.in]: ids\n        }\n      }\n    })\n    .then(function(conversationList) {\n      callback(false, conversationList);\n    })\n    .catch(function(error) {\n      console.log(error);\n      callback(true, 'Internal Server Error');\n    });\n  })\n  .catch(function(error) {\n    console.log(error);\n    callback(true, 'Internal Server Error');\n  });\n```\n\n========================================\n\nComments:\n- Thanks for the idea, it looks like this solves my issue. I'll post what I did with some tweaks. Thanks again\n- I'm glad it helps. :)\n- Is there any way to accomplish this without touching the database twice? This solution works, but it seems unoptimized\n- Hi @TheHanna, if you really want to touch the db once. I would suggest you passing the raw query directly to `sequelize.query`. Please consider the performance vs maintainability before you do any micro optimization.\n- That was what I looking for. Thaks @MyNguyen","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":136,"estimatedTokens":817}}583{"id":"stack-56468951","source":"stackoverflow","questionId":56468951,"title":"\"dataValues\" is not allowed by JOI.validate()","tags":["node.js","sequelize.js","joi"],"text":"Title: \"dataValues\" is not allowed by JOI.validate()\nTags: node.js, sequelize.js, joi\nSource: Stack Overflow\n\nQuestion:\nHere is code for `User` model with JOI (14.3) validation. The code used to be working when creating new user but it seems got flu recently and throws out error of `xxx not allowed`:\n\n```\nrequire('dotenv').config({path: process.cwd() +'\\\\config\\\\.env'});\nconst jwt = require('jsonwebtoken');\nconst moment = require('moment');\nconst Joi = require('joi');\nconst Sql = require('sequelize');\nconst db = require(\"../startup/db\");\n\nconst User = db.define('user', {\n name: {type: Sql.STRING,\n allowNull: false,\n min: 2,\n max: 50,\n },\n email: {type: Sql.STRING,\n isEmail: true\n }, \n cell: {type: Sql.STRING,\n allowNull: false,\n min: 10,\n max: 20,\n },\n cell_country_code: {type: Sql.STRING,\n allowNull: false\n },\n comp_name: {type: Sql.STRING\n },\n status: {type: Sql.STRING,\n allowNull: false,\n isIn: ['active', 'blocked', 'inactive', 'pending', 'unverified']\n },\n role: {type: Sql.STRING,\n allowNull: false\n },\n device_id: {type: Sql.STRING, //maybe empty when the user is initially created.\n },\n user_data: {type: Sql.JSONB\n },\n last_updated_by_id: {type: Sql.INTEGER},\n fort_token: {type: Sql.STRING,\n allowNull: false,\n min: 20 //64 for production\n },\n createdAt: Sql.DATE,\n updatedAt: Sql.DATE\n }, {\n\n indexes: [\n { \n //For same fort_token, name to be unique\n unique: true,\n fields: ['name', 'fort_token']\n }, {\n //unique cell\n //unique: true,\n fields: ['cell_country_code', 'cell', 'status']\n }, {\n fields: ['cell_country_code', 'cell']\n }, {\n //email\n fields: ['email']\n }, {\n fields: ['device_id']\n }, {\n fields: ['status']\n }, {\n fields: ['fort_token']\n }\n ] \n\n });\n\nfunction validateUser(user) {\n const schema = {\n name: Joi.string()\n .min(2)\n .max(50)\n .required()\n .trim(),\n cell: Joi.string()\n .min(10)\n .max(20)\n .trim()\n .required()\n .error(new Error('该手机号有误!')),\n cell_country_code: Joi.string()\n .trim()\n .required(),\n role: Joi.string()\n .required()\n .trim(),\n email: Joi.string()\n .email()\n .allow(\"\")\n .optional()\n };\n\n return Joi.validate(user, schema);\n};\n```\n\nHere is the error:\n\n```\nnew user data : { _device_id: '8c9c25711c7d0262',\n cell: '8008006414 ',\n cell_country_code: '1',\n name: 'ss9',\n corp_name: '',\n role: 'eventer',\n email: '',\n user_data: { avatar: '' } }\nerror in user validate : { ValidationError: \"dataValues\" is not allowed. \"_previousDataValues\" is not allowed. \"_changed\" is not allowed. \"_modelOptions\" is not allowed. \"_options\" is not allowed. \"isNewRecord\" is not allowed\n at Object.exports.process (C:\\d\\code\\js\\emps_bbone\\node_modules\\joi\\lib\\errors.js:203:19)\n at internals.Object._validateWithOptions (C:\\d\\code\\js\\emps_bbone\\node_modules\\joi\\lib\\types\\any\\index.js:764:31)\n at module.exports.internals.Any.root.validate (C:\\d\\code\\js\\emps_bbone\\node_modules\\joi\\lib\\index.js:147:23)\n at validateUser (C:\\d\\code\\js\\emps_bbone\\models\\user.js:106:16)\n at router.post (C:\\d\\code\\js\\emps_bbone\\routes\\users.js:217:27)\n at newFn (C:\\d\\code\\js\\emps_bbone\\node_modules\\express-async-errors\\index.js:16:20)\n at Layer.handle [as handle_request] (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at next (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\route.js:137:13)\n at C:\\d\\code\\js\\emps_bbone\\middleware\\auth_role.js:7:7\n at newFn (C:\\d\\code\\js\\emps_bbone\\node_modules\\express-async-errors\\index.js:16:20)\n at Layer.handle [as handle_request] (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at next (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\route.js:137:13)\n at module.exports (C:\\d\\code\\js\\emps_bbone\\middleware\\auth_userinfo.js:106:13)\n isJoi: true,\n name: 'ValidationError',\n details:\n [ { message: '\"dataValues\" is not allowed',\n path: [Array],\n type: 'object.allowUnknown',\n context: [Object] },\n { message: '\"_previousDataValues\" is not allowed',\n path: [Array],\n type: 'object.allowUnknown',\n context: [Object] },\n { message: '\"_changed\" is not allowed',\n path: [Array],\n type: 'object.allowUnknown',\n context: [Object] },\n { message: '\"_modelOptions\" is not allowed',\n path: [Array],\n type: 'object.allowUnknown',\n context: [Object] },\n { message: '\"_options\" is not allowed',\n path: [Array],\n type: 'object.allowUnknown',\n context: [Object] },\n { message: '\"isNewRecord\" is not allowed',\n path: [Array],\n type: 'object.allowUnknown',\n context: [Object] } ],\n _object:\n user {\n dataValues:\n { id: null,\n name: 'ss9',\n cell: '8008006414',\n cell_country_code: '1',\n email: '',\n role: 'eventer' },\n _previousDataValues:\n { name: undefined,\n cell: '8008006414 ',\n cell_country_code: undefined,\n email: undefined,\n role: undefined },\n _changed:\n { name: true,\n cell: true,\n cell_country_code: true,\n email: true,\n role: true },\n _modelOptions:\n { timestamps: true,\n validate: {},\n freezeTableName: false,\n underscored: false,\n paranoid: false,\n rejectOnEmpty: false,\n whereCollection: [Object],\n schema: null,\n schemaDelimiter: '',\n defaultScope: {},\n scopes: {},\n indexes: [Array],\n name: [Object],\n omitNull: false,\n sequelize: [Sequelize],\n hooks: {} },\n _options: { isNewRecord: true, _schema: null, _schemaDelimiter: '' },\n isNewRecord: true },\n annotate: [Function] }\nerror in new user\n```\n\nHere is the code for creating new user:\n\n```\ntry {\n user = new User(_.pick(req.body, [\"name\", \"cell\", \"cell_country_code\", \"email\", \"role\" ]));\n const { error } = validateUser(user); //I have no clue what the validation error is about.\n\n========================================\n\nCode:\n```text\nrequire('dotenv').config({path: process.cwd() +'\\\\config\\\\.env'});\nconst jwt = require('jsonwebtoken');\nconst moment = require('moment');\nconst Joi = require('joi');\nconst Sql = require('sequelize');\nconst db = require(\"../startup/db\");\n\nconst User = db.define('user', {\n    name: {type: Sql.STRING,\n           allowNull: false,\n           min: 2,\n           max: 50,\n    },\n    email: {type: Sql.STRING,\n            isEmail: true\n    },      \n    cell: {type: Sql.STRING,\n            allowNull: false,\n            min: 10,\n            max: 20,\n    },\n    cell_country_code: {type: Sql.STRING,\n                        allowNull: false\n    },\n    comp_name: {type: Sql.STRING\n    },\n    status: {type: Sql.STRING,\n             allowNull: false,\n             isIn: ['active', 'blocked', 'inactive', 'pending', 'unverified']\n    },\n    role: {type: Sql.STRING,\n           allowNull: false\n    },\n    device_id: {type: Sql.STRING,   //maybe empty when the user is initially created.\n    },\n    user_data: {type: Sql.JSONB\n    },\n    last_updated_by_id: {type: Sql.INTEGER},\n    fort_token: {type: Sql.STRING,\n                 allowNull: false,\n                 min: 20  //64 for production\n    },\n    createdAt: Sql.DATE,\n    updatedAt: Sql.DATE\n  }, {\n\n    indexes: [\n      { \n        //For same fort_token, name to be unique\n        unique: true,\n        fields: ['name', 'fort_token']\n      }, {\n        //unique cell\n        //unique: true,\n        fields: ['cell_country_code', 'cell', 'status']\n      }, {\n        fields: ['cell_country_code', 'cell']\n      }, {\n        //email\n        fields: ['email']\n      }, {\n        fields: ['device_id']\n      }, {\n        fields: ['status']\n      }, {\n        fields: ['fort_token']\n      }\n    ]   \n\n  });\n\nfunction validateUser(user) {\n    const schema = {\n        name: Joi.string()\n        .min(2)\n        .max(50)\n        .required()\n        .trim(),\n    cell: Joi.string()\n        .min(10)\n        .max(20)\n        .trim()\n        .required()\n        .error(new Error('该手机号有误!')),\n    cell_country_code: Joi.string()\n        .trim()\n        .required(),\n    role: Joi.string()\n        .required()\n        .trim(),\n    email: Joi.string()\n        .email()\n        .allow(\"\")\n        .optional()\n    };\n\n    return Joi.validate(user, schema);\n};\n```\n\n```text\nnew user data :  { _device_id: '8c9c25711c7d0262',\n  cell: '8008006414 ',\n  cell_country_code: '1',\n  name: 'ss9',\n  corp_name: '',\n  role: 'eventer',\n  email: '',\n  user_data: { avatar: '' } }\nerror in user validate :  { ValidationError: \"dataValues\" is not allowed. \"_previousDataValues\" is not allowed. \"_changed\" is not allowed. \"_modelOptions\" is not allowed. \"_options\" is not allowed. \"isNewRecord\" is not allowed\n    at Object.exports.process (C:\\d\\code\\js\\emps_bbone\\node_modules\\joi\\lib\\errors.js:203:19)\n    at internals.Object._validateWithOptions (C:\\d\\code\\js\\emps_bbone\\node_modules\\joi\\lib\\types\\any\\index.js:764:31)\n    at module.exports.internals.Any.root.validate (C:\\d\\code\\js\\emps_bbone\\node_modules\\joi\\lib\\index.js:147:23)\n    at validateUser (C:\\d\\code\\js\\emps_bbone\\models\\user.js:106:16)\n    at router.post (C:\\d\\code\\js\\emps_bbone\\routes\\users.js:217:27)\n    at newFn (C:\\d\\code\\js\\emps_bbone\\node_modules\\express-async-errors\\index.js:16:20)\n    at Layer.handle [as handle_request] (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\layer.js:95:5)\n    at next (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\route.js:137:13)\n    at C:\\d\\code\\js\\emps_bbone\\middleware\\auth_role.js:7:7\n    at newFn (C:\\d\\code\\js\\emps_bbone\\node_modules\\express-async-errors\\index.js:16:20)\n    at Layer.handle [as handle_request] (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\layer.js:95:5)\n    at next (C:\\d\\code\\js\\emps_bbone\\node_modules\\express\\lib\\router\\route.js:137:13)\n    at module.exports (C:\\d\\code\\js\\emps_bbone\\middleware\\auth_userinfo.js:106:13)\n  isJoi: true,\n  name: 'ValidationError',\n  details:\n   [ { message: '\"dataValues\" is not allowed',\n       path: [Array],\n       type: 'object.allowUnknown',\n       context: [Object] },\n     { message: '\"_previousDataValues\" is not allowed',\n       path: [Array],\n       type: 'object.allowUnknown',\n       context: [Object] },\n     { message: '\"_changed\" is not allowed',\n       path: [Array],\n       type: 'object.allowUnknown',\n       context: [Object] },\n     { message: '\"_modelOptions\" is not allowed',\n       path: [Array],\n       type: 'object.allowUnknown',\n       context: [Object] },\n     { message: '\"_options\" is not allowed',\n       path: [Array],\n       type: 'object.allowUnknown',\n       context: [Object] },\n     { message: '\"isNewRecord\" is not allowed',\n       path: [Array],\n       type: 'object.allowUnknown',\n       context: [Object] } ],\n  _object:\n   user {\n     dataValues:\n      { id: null,\n        name: 'ss9',\n        cell: '8008006414',\n        cell_country_code: '1',\n        email: '',\n        role: 'eventer' },\n     _previousDataValues:\n      { name: undefined,\n        cell: '8008006414 ',\n        cell_country_code: undefined,\n        email: undefined,\n        role: undefined },\n     _changed:\n      { name: true,\n        cell: true,\n        cell_country_code: true,\n        email: true,\n        role: true },\n     _modelOptions:\n      { timestamps: true,\n        validate: {},\n        freezeTableName: false,\n        underscored: false,\n        paranoid: false,\n        rejectOnEmpty: false,\n        whereCollection: [Object],\n        schema: null,\n        schemaDelimiter: '',\n        defaultScope: {},\n        scopes: {},\n        indexes: [Array],\n        name: [Object],\n        omitNull: false,\n        sequelize: [Sequelize],\n        hooks: {} },\n     _options: { isNewRecord: true, _schema: null, _schemaDelimiter: '' },\n     isNewRecord: true },\n  annotate: [Function] }\nerror in new user\n```\n\n```text\ntry {\n        user = new User(_.pick(req.body, [\"name\", \"cell\", \"cell_country_code\", \"email\", \"role\" ]));\n        const { error } = validateUser(user);  //<<====== throws error with JOI.validate()\n        console.log(\"error in user validate : \", error);\n        if (error) {console.log(\"error in new user \"); return res.status(400).send(error.details[0].message)};\n```\n\n```text\nUser\n```\n\n```text\nxxx not allowed\n```\n\n========================================\n\nComments:\n- That negates the use of schema, doesn't it?","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":429,"estimatedTokens":2972}}584{"id":"stack-45151194","source":"stackoverflow","questionId":45151194,"title":"Sequelize 4.3.2 n:m (many-to-many) association: Unhandled rejection SequelizeEagerLoadingError","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize 4.3.2 n:m (many-to-many) association: Unhandled rejection SequelizeEagerLoadingError\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 3 models: User, Project, UserProject:\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n var User = sequelize.define('User', {\n title: DataTypes.STRING,\n description: DataTypes.STRING\n}, {\n classMethods: {\n associate: function (models) {\n User.belongsToMany(models.Project, { \n through: 'UserProject',\n foreignKey: 'userId'\n })\n }\n },\n freezeTableName: true\n})\n return User\n}\n\nmodule.exports = function (sequelize, DataTypes) {\n var Project = sequelize.define('Project', {\n title: DataTypes.STRING,\n description: DataTypes.STRING\n }, {\n classMethods: {\n associate: function (models) {\n Project.belongsToMany(models.User, { \n through: 'UserProject',\n foreignKey: 'projectId'\n })\n }\n },\n freezeTableName: true\n})\n return Project\n}\n\nmodule.exports = function (sequelize, DataTypes) {\n var UserProject = sequelize.define('UserProject', {\n userId: DataTypes.INTEGER,\n projectId: DataTypes.INTEGER,\n }, {\n classMethods: {\n },\n freezeTableName: true\n })\n return UserProject\n}\n```\n\nThe code above worked perfectly with some old version of Sequelize. Now I updated to Sequelize 4.3.2 and I get the following error when trying to use these models:\n\n*Unhandled rejection SequelizeEagerLoadingError: Project is not associated to User!*\n\nWhat is wrong with this? I'm trying to do many-to-many association here, and get Users included when findAll Projects and vice versa. I'm using MySQL as a database.\n\nHere is the findAll-part:\n\n```\nfunction getUsersWithProjects (request, response, next) {\n models.User.findAll({\n include: [{\n model: models.Project,\n }]\n });\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function (sequelize, DataTypes) {\n  var User = sequelize.define('User', {\n  title: DataTypes.STRING,\n  description: DataTypes.STRING\n}, {\n  classMethods: {\n    associate: function (models) {\n      User.belongsToMany(models.Project, { \n        through: 'UserProject',\n        foreignKey: 'userId'\n      })\n    }\n  },\n  freezeTableName: true\n})\n  return User\n}\n\n\nmodule.exports = function (sequelize, DataTypes) {\n  var Project = sequelize.define('Project', {\n  title: DataTypes.STRING,\n  description: DataTypes.STRING\n  }, {\n  classMethods: {\n    associate: function (models) {\n      Project.belongsToMany(models.User, { \n        through: 'UserProject',\n        foreignKey: 'projectId'\n      })\n    }\n  },\n  freezeTableName: true\n})\n  return Project\n}\n\n\nmodule.exports = function (sequelize, DataTypes) {\n var UserProject = sequelize.define('UserProject', {\n  userId: DataTypes.INTEGER,\n  projectId: DataTypes.INTEGER,\n }, {\n  classMethods: {\n },\n  freezeTableName: true\n })\n  return UserProject\n}\n```\n\n```text\nfunction getUsersWithProjects (request, response, next) {\n  models.User.findAll({\n    include: [{\n      model: models.Project,\n    }]\n  });\n}\n```\n\n```text\nmodule.exports = function (sequelize, DataTypes) {\n  var User = sequelize.define('User', {\n    title: DataTypes.STRING,\n    description: DataTypes.STRING\n  }, {\n   freezeTableName: true\n  })\n  User.associate = function (models) {\n   User.belongsToMany(models.Project, { \n    through: 'UserProject',\n    foreignKey: 'userId'\n   })\n };\n return User\n}\n```\n\n```text\nclassMethods\n```\n\n```text\ninstanceMethods\n```\n\n========================================\n\nComments:\n- yes, it seems like they changed in 4.x, after modifying like these worked.","metadata":{"transformedAt":"2026-08-18T18:33:34.387Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":170,"estimatedTokens":882}}585{"id":"stack-33798994","source":"stackoverflow","questionId":33798994,"title":"Sequelize include - Don't include (remove) pivot data","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize include - Don't include (remove) pivot data\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using the Sequelize package for node. I have a typical include on man to many relationship.\n\n```\nItem.findAll({\n include: {model: Blah: as 'blahs'}\n});\n```\n\nAll works well but it returns the set with the pivot data on each sub item. I don't need it. Is there any way to disable it or to specify the pivot fields needed?\n\n========================================\n\nTop Answer:\nIt is not very clear what you are looking for but can you try adding raw:true\n\n```\nItem.findAll({\n include: {model: Blah, raw: true}\n});\n```\n\ncan you post the result you got vs result you want\n\n========================================\n\nCode:\n```text\nItem.findAll({\n    include: {model: Blah: as 'blahs'}\n});\n```\n\n```text\n{model: Model, as: 'model', through: {attributes: []}}\n```\n\n```text\nItem.findAll({\n    include: {model: Blah, raw: true}\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":46,"estimatedTokens":241}}586{"id":"stack-55452441","source":"stackoverflow","questionId":55452441,"title":"FOR and FOR UPDATE statements in Sequelize","tags":["javascript","mysql","sql","sequelize.js"],"text":"Title: FOR and FOR UPDATE statements in Sequelize\nTags: javascript, mysql, sql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nRegular SQL queries can contain ‘SELECT FOR ’ and ‘SELECT FOR UPDATE’ statements when we use transactions.\n\nIs there a way to set up the same statements with Sequelize? I have not found those options. May be there are some tricks?\n\nWhat it’s required for, you can read here https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html#locking-read-examples\n\n========================================\n\nCode:\n```text\nUser.findAll({\n   lock: transaction.LOCK.UPDATE // or SHARE, KEY_SHARE, NO_KEY_UPDATE\n})\n```\n\n```text\nKEY_SHARE\n```\n\n```text\nNO_KEY_UPDATE\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":27,"estimatedTokens":172}}587{"id":"stack-47092292","source":"stackoverflow","questionId":47092292,"title":"Sequelize create model with object type","tags":["javascript","postgresql","sequelize.js"],"text":"Title: Sequelize create model with object type\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs this possible to create model with sequelize to look like: \n\n```\nvar User = sequelize.define('User', {\n username: DataTypes.STRING,\n email: DataTypes.STRING,\n password: DataTypes.STRING,\n facebook: {\n id: DataTypes.STRING,\n token: DataTypes.STRING,\n email: DataTypes.STRING,\n name: DataTypes.STRING\n },\n})\n```\n\nIdea is: When i will get user data from DB i would like to see \nUser: {\n facebook: {\n id,\n token,\n ...\n }\n}\n\n========================================\n\nTop Answer:\nColumn dataType - TEXT save as JSON format\nafter find table - return json patse text\n\n\r\n\r\n\n```\nPodPodMaterial.afterFind(async (material) => {\n if(material.length) {\n for(let mat in material) {\n try {\n material[mat].ez_kolvo = JSON.parse(material[mat].ez_kolvo)\n } catch(e) {console.error(e)}\n }\n } else {\n try {\n material.ez_kolvo = JSON.stringify(material.ez_kolvo)\n }catch(e) {console.error(e)}\n }\n\n return material\n})\n```\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {\n    username: DataTypes.STRING,\n    email: DataTypes.STRING,\n    password: DataTypes.STRING,\n    facebook: {\n      id: DataTypes.STRING,\n      token: DataTypes.STRING,\n      email: DataTypes.STRING,\n      name: DataTypes.STRING\n    },\n})\n```\n\n```text\nUser.facebook\n```\n\n```text\nDataType.JSON\n```\n\n```js\nPodPodMaterial.afterFind(async (material) => {\n  if(material.length) {\n    for(let mat in material) {\n      try {\n          material[mat].ez_kolvo = JSON.parse(material[mat].ez_kolvo)\n      } catch(e) {console.error(e)}\n    }\n  } else {\n    try {\n        material.ez_kolvo = JSON.stringify(material.ez_kolvo)\n    }catch(e) {console.error(e)}\n  }\n\n  return material\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":99,"estimatedTokens":449}}588{"id":"stack-29835154","source":"stackoverflow","questionId":29835154,"title":"sequelize association key is uppercased in response","tags":["sequelize.js"],"text":"Title: sequelize association key is uppercased in response\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I make `Music` to be `music? \n\n```\n{\n id: 4\n name: \"playlist 1\"\n created_at: \"2015-04-21T21:43:07.000Z\"\n updated_at: \"2015-04-23T20:44:50.000Z\"\n Music: [\n {\n id: 12\n name: \"Deorro - Five Hours (Static Video) [LE7ELS]\"\n video_id: \"K_yBUfMGvzc\"\n thumbnail: \"https://i.ytimg.com/vi/K_yBUfMGvzc/default.jpg\"\n created_at: \"2015-04-22T21:46:21.000Z\"\n updated_at: \"2015-04-22T21:46:21.000Z\"\n playlist_id: 4\n }\n ]\n}\n```\n\nMy query looks something like:\n\n```\n.get(function (req, res) {\n db.Playlist.findAll({\n include: [db.Music]\n }).then(function (playlists) {\n if(!playlists) {\n res.status(404).json({message: 'No playlist found!'});\n return;\n }\n\n res.json(playlists)\n })\n })\n```\n\nPlaylist model: \n\n```\nmodule.exports = function(sequelize, DataType) {\n var Playlist = sequelize.define('Playlist', {\n name: DataType.STRING\n }, {\n classMethods: {\n associate: function(models) {\n Playlist.hasMany(models.Music, { foreignKey: 'playlist_id' });\n }\n },\n tableName: 'playlists',\n underscored: true\n });\n\n return Playlist;\n};\n```\n\nMusic model:\n\n```\nmodule.exports = function(sequelize, DataType) {\n var Music = sequelize.define('Music', {\n name: DataType.STRING,\n video_id: DataType.STRING,\n thumbnail: DataType.STRING\n }, {\n classMethods: {\n associate: function(models) {\n Music.belongsTo(models.Playlist);\n }\n },\n tableName: 'musics',\n underscored: true\n });\n\n return Music;\n}\n```\n\n========================================\n\nTop Answer:\n**The working code for easier reference:**\n\nPlaylist model:\n\n```\nmodule.exports = function(sequelize, DataType) {\n var Playlist = sequelize.define('Playlist', {\n name: DataType.STRING\n }, {\n classMethods: {\n associate: function(models) {\n Playlist.hasMany(models.Music, { as: 'music', foreignKey: 'playlist_id' });\n }\n },\n tableName: 'playlists',\n underscored: true\n });\n\n return Playlist;\n};\n```\n\nMusic model: unchanged\n\nQuery:\n\n```\ncontroller.route('/playlist')\n .get(function (req, res) {\n db.Playlist.findAll({\n include: [{ model: db.Music, as: 'music' }]\n }).then(function (playlists) {\n if(!playlists) {\n res.status(404).json({message: 'No playlist found!'});\n return;\n }\n\n res.json(playlists)\n })\n })\n```\n\n========================================\n\nCode:\n```text\n{\n  id: 4\n  name: \"playlist 1\"\n  created_at: \"2015-04-21T21:43:07.000Z\"\n  updated_at: \"2015-04-23T20:44:50.000Z\"\n  Music: [\n    {\n      id: 12\n      name: \"Deorro - Five Hours (Static Video) [LE7ELS]\"\n      video_id: \"K_yBUfMGvzc\"\n      thumbnail: \"https://i.ytimg.com/vi/K_yBUfMGvzc/default.jpg\"\n      created_at: \"2015-04-22T21:46:21.000Z\"\n      updated_at: \"2015-04-22T21:46:21.000Z\"\n      playlist_id: 4\n    }\n  ]\n}\n```\n\n```text\n.get(function (req, res) {\n    db.Playlist.findAll({\n      include: [db.Music]\n    }).then(function (playlists) {\n      if(!playlists) {\n        res.status(404).json({message: 'No playlist found!'});\n        return;\n      }\n\n      res.json(playlists)\n    })\n  })\n```\n\n```text\nmodule.exports = function(sequelize, DataType) {\n  var Playlist = sequelize.define('Playlist', {\n    name: DataType.STRING\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Playlist.hasMany(models.Music, { foreignKey: 'playlist_id' });\n      }\n    },\n    tableName:   'playlists',\n    underscored: true\n  });\n\n  return Playlist;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataType) {\n  var Music = sequelize.define('Music', {\n    name: DataType.STRING,\n    video_id:  DataType.STRING,\n    thumbnail:  DataType.STRING\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Music.belongsTo(models.Playlist);\n      }\n    },\n    tableName:   'musics',\n    underscored: true\n  });\n\n  return Music;\n}\n```\n\n```text\nMusic\n```\n\n```text\nsequelize.define('music', ...)\n```\n\n```text\nPlaylist.hasMany(Music, { as: 'music' })\n```\n\n```text\nas\n```\n\n```text\nmodule.exports = function(sequelize, DataType) {\n  var Playlist = sequelize.define('Playlist', {\n    name: DataType.STRING\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Playlist.hasMany(models.Music, { as: 'music', foreignKey: 'playlist_id' });\n      }\n    },\n    tableName:   'playlists',\n    underscored: true\n  });\n\n  return Playlist;\n};\n```\n\n```text\ncontroller.route('/playlist')\n  .get(function (req, res) {\n    db.Playlist.findAll({\n      include: [{ model: db.Music, as: 'music' }]\n    }).then(function (playlists) {\n      if(!playlists) {\n        res.status(404).json({message: 'No playlist found!'});\n        return;\n      }\n\n      res.json(playlists)\n    })\n  })\n```\n\n```text\nname: {\n  singular: 'report',\n  plural: 'reports'\n}\n```\n\n========================================\n\nComments:\n- Yep I've tried those, for the first one I get: `Error: Playlist.hasMany called with something that's not an instance of Sequelize.Model` For the alias I get: `Possibly unhandled Error: Music is not associated to Playlist!` Note: I included my model structure in my question so you can take a look, maybe i messed up something.\n- 1st error: you probably need to use `models.music` in your assocation - the model is stored under its name, so you need to use the lower case version. 2nd: add `as: 'music'` to the include as well. Or save the return value from the `hasMany` call and used that instead","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":269,"estimatedTokens":1332}}589{"id":"stack-48869975","source":"stackoverflow","questionId":48869975,"title":"TypeError: s.replace is not a function","tags":["postgresql","sequelize.js","sequelize-cli"],"text":"Title: TypeError: s.replace is not a function\nTags: postgresql, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\n**Env:**\n\n- Postgres: 10.2\n\n- Node: 6.11.0\n\n- CLI: 2.4.0\n\n- ORM: 2.1.3\n\n**Model:**\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var test = sequelize.define('test', {\n id: DataTypes.UUID,\n type: DataTypes.STRING,\n data: DataTypes.JSON,\n }, {\n 'createdAt': {\n type: Sequelize.DATE(3),\n defaultValue: Sequelize.literal('CURRENT_TIMESTAMP(3)'),\n },\n 'updatedAt': {\n type: Sequelize.DATE(3),\n defaultValue: Sequelize.literal('CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)'),\n },\n classMethods: {\n associate: function(models) {\n // associations can be defined here\n }\n }\n });\n return test;\n}\n```\n\n**Migration:**\n\n```\n'use strict';\nmodule.exports = {\n up: function(queryInterface, Sequelize) {\n return queryInterface.addColumn('test', {\n test_col: {\n type: Sequelize.JSONB\n }\n });\n },\n down: function(queryInterface, Sequelize) {\n return queryInterface.removeColumn('test', 'test_col');\n }\n};\n```\n\n**Error:**\n\n```\nTypeError: s.replace is not a function\n at Object.removeTicks (/node_modules/sequelize/lib/utils.js:329:14)\n at Object.addTicks (/node_modules/sequelize/lib/utils.js:325:29)\n at Object.quoteIdentifier (/node_modules/sequelize/lib/dialects/postgres/query-generator.js:835:22)\n at Object.addColumnQuery (/node_modules/sequelize/lib/dialects/postgres/query-generator.js:182:19)\n at QueryInterface.module.exports.QueryInterface.addColumn\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n    var test = sequelize.define('test', {\n        id: DataTypes.UUID,\n        type: DataTypes.STRING,\n        data: DataTypes.JSON,\n    }, {\n        'createdAt': {\n            type: Sequelize.DATE(3),\n            defaultValue: Sequelize.literal('CURRENT_TIMESTAMP(3)'),\n        },\n        'updatedAt': {\n            type: Sequelize.DATE(3),\n            defaultValue: Sequelize.literal('CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)'),\n        },\n        classMethods: {\n            associate: function(models) {\n                // associations can be defined here\n            }\n        }\n    });\n    return test;\n}\n```\n\n```text\n'use strict';\nmodule.exports = {\n    up: function(queryInterface, Sequelize) {\n        return queryInterface.addColumn('test', {\n            test_col: {\n                type: Sequelize.JSONB\n            }\n        });\n    },\n    down: function(queryInterface, Sequelize) {\n        return queryInterface.removeColumn('test', 'test_col');\n    }\n};\n```\n\n```text\nTypeError: s.replace is not a function\n    at Object.removeTicks (/node_modules/sequelize/lib/utils.js:329:14)\n    at Object.addTicks (/node_modules/sequelize/lib/utils.js:325:29)\n    at Object.quoteIdentifier (/node_modules/sequelize/lib/dialects/postgres/query-generator.js:835:22)\n    at Object.addColumnQuery (/node_modules/sequelize/lib/dialects/postgres/query-generator.js:182:19)\n    at QueryInterface.module.exports.QueryInterface.addColumn\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n    return queryInterface.addColumn(\n          'pages',\n          'group',\n          Sequelize.JSONB\n      );\n  },\n  down: function(queryInterface, Sequelize) {\n    return queryInterface.removeColumn('pages', 'group');\n  }\n};\n```\n\n```text\npublic addColumn(table: String, key: String, attribute: Object, options: Object): Promise\n```\n\n```text\ns.replace\n```\n\n```text\nqueryInterface.addColumn\n```\n\n```text\nString\n```\n\n========================================\n\nComments:\n- Probably because `s` is null\n- @AlexanderMP but y is `s` is null ? Any idea ?\n- If I knew, I wouldn't have written it in a comment :)\n- Thank you for the note on `s.replace`. For me, I had a poorly formatted `where:{}` definition on a `Model.findAll` method call.","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":165,"estimatedTokens":972}}590{"id":"stack-43015323","source":"stackoverflow","questionId":43015323,"title":"Sequelize - Associate table column value in where condition","tags":["mysql","node.js","express","associations","sequelize.js"],"text":"Title: Sequelize - Associate table column value in where condition\nTags: mysql, node.js, express, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSequelize - Associate table column in where condition\n\nI want to perform this query in sequelize models:\n\n```\nSELECT * FROM `model_game` AS `Game` INNER JOIN `model_activity` AS `Activity` ON `Game`.`ActivityId` = `Activity`.`id` WHERE `Game`.`startAt` > ('2017-03-25 07:37:36'-`Activity.duration`) AND `Game`.`status` = 'NotStarted';\n```\n\nI tried using sequelize.col() function, But still cannot poulate the value. My code is below\n\n```\nMy Game model . table name model_game\n\nvar Game = sequelize.define(\"Game\", {\n startAt: DataTypes.DATE,\n status: DataTypes.ENUM('NotStarted','Completed')\n }, {\nclassMethods: {\n associate: function(models) {\n Activity.belongsTo(models.Activity);\n }\n}\n});\n```\n\nMy Activity model, table name model_activity\n\n```\nvar Activity = sequelize.define(\"Activity\", {\n title: DataTypes.STRING,\n duration: DataTypes.INTEGER\n },{\nclassMethods: {\n associate: function(models) {\n Activity.hasMany(models.Game);\n }\n}\n});\n```\n\nFind Query, which now returns value but sequelize.col(\"Activity.duration\") has no effect at all\n\n```\nvar currentTime = moment();\nmodels.Game.findAndCountAll({\n where: { status: 'NotStarted', \n startAt: {gt: currentTime.subtract(moment.duration(sequelize.col(\"Activity.duration\"), 'minutes'))}, \n },\n include: [{\n model: models.Activity \n }]\n }).then(function(result) {\n //Success\n});\n```\n\nBut the above code does not populate \"Activity.duration\" duration value. And there is no error, What should be done to rectify this. Thanks in Advance\n\n========================================\n\nCode:\n```text\nSELECT * FROM `model_game` AS `Game` INNER JOIN `model_activity` AS `Activity` ON `Game`.`ActivityId` = `Activity`.`id`  WHERE `Game`.`startAt` > ('2017-03-25 07:37:36'-`Activity.duration`) AND `Game`.`status` = 'NotStarted';\n```\n\n```text\nMy Game model . table name model_game\n\nvar Game = sequelize.define(\"Game\", {\n    startAt: DataTypes.DATE,\n    status: DataTypes.ENUM('NotStarted','Completed')\n  }, {\nclassMethods: {\n      associate: function(models) {\n        Activity.belongsTo(models.Activity);\n      }\n}\n});\n```\n\n```text\nvar Activity = sequelize.define(\"Activity\", {\n    title: DataTypes.STRING,\n    duration: DataTypes.INTEGER\n  },{\nclassMethods: {\n      associate: function(models) {\n        Activity.hasMany(models.Game);\n      }\n}\n});\n```\n\n```text\nvar currentTime = moment();\nmodels.Game.findAndCountAll({\n            where: { status: 'NotStarted',   \n            startAt: {gt: currentTime.subtract(moment.duration(sequelize.col(\"Activity.duration\"), 'minutes'))}, \n            },\n            include: [{\n                model: models.Activity             \n            }]\n        }).then(function(result) {\n     //Success\n});\n```\n\n```text\nmodels.Game.findAndCountAll({\n    where: {\n        status: 'NotStarted',\n        startAt: {\n            $gt: models.sequelize.fn(\n                'DATE_SUB',\n                models.sequelize.literal('NOW()'),\n                models.sequelize.literal('INTERVAL Activity.duration MINUTE')\n            )\n        }\n    },\n    include: [models.Activity]\n}).then(result => {\n    // result...\n});\n```\n\n```sql\nSELECT * FROM games INNER JOIN activities\nON games.activityId = activities.id\nWHERE games.status = 'NotStarted'\nAND games.startAt > DATE_SUB(NOW(), INTERVAL activities.duration MINUTE);\n```\n\n```text\nDATE_SUB()\n```\n\n```text\nsequelize.literal\n```\n\n```text\nNOW()\n```\n\n```text\nActivity.duration\n```\n\n```text\nMINUTE\n```\n\n```text\nActivity.duration\n```\n\n========================================\n\nComments:\n- Thanks for the answer. But I am getting this Error. Error: ER_BAD_FIELD_ERROR: Unknown column 'Activity.duration' in 'where clause'\n- Try doing `INTERVAL \"Activity\".\"duration\" MINUTE`, or, if it does not help, look at the sql being generated and replace `Activity` with proper alias of the activity table.\n- Thanks, Adding required:true in Activity model solved the problem :)","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":167,"estimatedTokens":1008}}591{"id":"stack-21518970","source":"stackoverflow","questionId":21518970,"title":"sequelize DB clears out after restarting node app","tags":["node.js","sequelize.js"],"text":"Title: sequelize DB clears out after restarting node app\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni am new to node and in my app i am using sequelize for my DB. \nWhenever i restart my node app, the DB data get cleared out. \nAny idea how to fix this?\n\nI am not sure what to do\n\n========================================\n\nCode:\n```text\nsequelize.sync({force:true})\n```\n\n```text\n{force:true}\n```\n\n========================================\n\nComments:\n- What you should do is show us your code!","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":26,"estimatedTokens":127}}592{"id":"stack-48374032","source":"stackoverflow","questionId":48374032,"title":"Sequelize model getters in TypeScript","tags":["typescript","sequelize.js"],"text":"Title: Sequelize model getters in TypeScript\nTags: typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the correct way of using `this.getDataValue` in a getter function for a Sequelize model when using TypeScript?\n\nThis is the error I'm getting:\n\n Property 'getDataValue' does not exist on type 'string | DataTypeAbstract | DefineAttributeColumnOptions'.\n\n \n Property 'getDataValue' does not exist on type 'string'.\n\nMy model definition:\n\n```\nimport * as Sequelize from 'sequelize';\nimport sequelize from '../db-connection';\n\nexport interface IUserAttributes {\n date_of_birth: Date;\n name: string;\n}\n\nexport interface IUserInstance extends Sequelize.Instance {\n date_of_birth: Date;\n name: string;\n}\n\nconst User = sequelize.define('user', {\n name: {\n type: Sequelize.STRING,\n validate: {\n notEmpty: true,\n },\n },\n date_of_birth: {\n get(): Date {\n return new Date(this.getDataValue('date_of_birth'));\n },\n type: Sequelize.DATEONLY,\n validate: {\n isDate: true,\n notEmpty: true,\n },\n },\n});\n\nexport default User;\n```\n\n========================================\n\nTop Answer:\nFor `\"sequelize\": \"^5.21.3\"`, `\"typescript\": \"^3.7.5\"` and define the sequelize model using TypeScript class based style.\n\n`index.ts`:\n\n```\nimport { sequelize } from '../../db';\nimport Sequelize, { Model } from 'sequelize';\n\nclass User extends Model {\n public date_of_birth!: Date;\n public name!: string;\n}\nUser.init(\n {\n name: {\n type: Sequelize.STRING,\n validate: {\n notEmpty: true,\n },\n },\n date_of_birth: {\n get(this: User): Date {\n return new Date(this.getDataValue('date_of_birth'));\n },\n type: Sequelize.DATEONLY,\n validate: {\n isDate: true,\n notEmpty: true,\n },\n },\n },\n { sequelize, modelName: 'user' },\n);\n```\n\nCast `this` type to `User` class will get rid of the error. Don't forget to declare the properties in the `User` class.\n\n========================================\n\nCode:\n```text\nimport * as Sequelize from 'sequelize';\nimport sequelize from '../db-connection';\n\nexport interface IUserAttributes {\n    date_of_birth: Date;\n    name: string;\n}\n\nexport interface IUserInstance extends Sequelize.Instance<IUserAttributes> {\n    date_of_birth: Date;\n    name: string;\n}\n\nconst User = sequelize.define<IUserAttributes, IUserInstance>('user', {\n    name: {\n        type: Sequelize.STRING,\n        validate: {\n            notEmpty: true,\n        },\n    },\n    date_of_birth: {\n        get(): Date {\n            return new Date(this.getDataValue('date_of_birth'));\n        },\n        type: Sequelize.DATEONLY,\n        validate: {\n            isDate: true,\n            notEmpty: true,\n        },\n    },\n});\n\nexport default User;\n```\n\n```text\nthis.getDataValue\n```\n\n```text\nconst User = sequelize.define<IUserAttributes, IUserInstance>('user', {\n  name: {\n      type: Sequelize.STRING,\n      validate: {\n          notEmpty: true,\n      },\n  },\n  date_of_birth: {\n      get(this: IUserInstance): Date {\n          return new Date(this.getDataValue('date_of_birth'));\n      },\n      type: Sequelize.DATEONLY,\n      validate: {\n          isDate: true,\n          notEmpty: true,\n      },\n  },\n});\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n```text\nimport {DataTypes, Model, Sequelize} from 'sequelize';\n\nexport class Book extends Model {\n    public id!: number; \n    public name!: string;\n    public payload!: any;\n    private data!: string;\n}\n\nexport const initBook = (sequelize: Sequelize) => {\n    Book.init(\n        {\n            id: {\n                type: DataTypes.INTEGER,\n                primaryKey: true\n            },\n            name: {\n                type: DataTypes.STRING(100),\n                primaryKey: false\n            },\n            data: {\n                type: DataTypes.TEXT,\n                primaryKey: false\n            },               \n            payload: {\n                type: DataTypes.JSONB,\n                allowNull: false,\n                field: 'data',\n                get(this: any) {\n                    const j = this.getDataValue('payload');\n                    return JSON.parse(j);\n                }\n            }               \n        },\n        {\n            tableName: 'book',\n            sequelize // this bit is important\n        }\n    );\n};\n\nexport default {Book, initBook};\n```\n\n```js\nimport { sequelize } from '../../db';\nimport Sequelize, { Model } from 'sequelize';\n\nclass User extends Model {\n  public date_of_birth!: Date;\n  public name!: string;\n}\nUser.init(\n  {\n    name: {\n      type: Sequelize.STRING,\n      validate: {\n        notEmpty: true,\n      },\n    },\n    date_of_birth: {\n      get(this: User): Date {\n        return new Date(this.getDataValue('date_of_birth'));\n      },\n      type: Sequelize.DATEONLY,\n      validate: {\n        isDate: true,\n        notEmpty: true,\n      },\n    },\n  },\n  { sequelize, modelName: 'user' },\n);\n```\n\n```text\n\"sequelize\": \"^5.21.3\"\n```\n\n```text\n\"typescript\": \"^3.7.5\"\n```\n\n```text\nindex.ts\n```\n\n```text\nthis\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- Thank you! Is there any documentation on this? (no pun intended) All I can find is discussion on this issue: github.com/Microsoft/TypeScript/issues/3694\n- @rink.attendant.6 Nope .. that is the extent of the documentation I know of :(\n- Any idea how you'd go about setters? I thought of adding the type annotation of this as a second argument but TS wouldn't stand for that.","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":270,"estimatedTokens":1341}}593{"id":"stack-41790321","source":"stackoverflow","questionId":41790321,"title":"Sequelize error: Unhandled rejection TypeError: Cannot read property '_pseudo of undefined","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize error: Unhandled rejection TypeError: Cannot read property '_pseudo of undefined\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am cloned this app https://github.com/sequelize/express-example which appears to be the official sequelize express example but I get this error when I try to run it\n\n`Unhandled rejection TypeError: Cannot read property '_pseudo' of undefined\n at conformInclude (/Users/wasswasam/express-example-master/node_modules/sequelize/lib/model.js:277:14)`\n\nI am not sure what's going on.\n\n========================================\n\nTop Answer:\nI get this error when the object in the `include` array is undefined. Usually caused by a dependency loop or a misspelled import.\n\n========================================\n\nCode:\n```text\nUnhandled rejection TypeError: Cannot read property '_pseudo' of undefined\n at conformInclude (/Users/wasswasam/express-example-master/node_modules/sequelize/lib/model.js:277:14)\n```\n\n```text\nmodels.User.findAll({\n    include: [ models.Task ]\n  })\n```\n\n```text\nmodels.User.findAll()\n```\n\n```text\ninclude\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":38,"estimatedTokens":275}}594{"id":"stack-47701890","source":"stackoverflow","questionId":47701890,"title":"sequelize foreign key target vs source","tags":["sequelize.js"],"text":"Title: sequelize foreign key target vs source\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have been using sequelize for a little bit, but never bother to really understand how `foreignKey` actually works. In their doc they state:\n\n The target key is the column on the target model that the foreign key column on the source model points to.\n\nSo in the following cases, which is the target?\n\n```\nRoute.belongsTo(models.Subarea, {\n foreignKey: 'subareaId',\n as: 'subarea',\n });\n\n Route.belongsToMany(models.Book, {\n through: models.BookRoute,\n foreignKey: 'routeId',\n as: 'books',\n });\n```\n\nMy confusion is on why in first case I put foreignKey on SubareaId, but for second case I put it as routeId. Should it not be routeId for both cases, if foreignKey should be the sourceId?\n\n========================================\n\nCode:\n```text\nRoute.belongsTo(models.Subarea, {\n      foreignKey: 'subareaId',\n      as: 'subarea',\n    });\n\n    Route.belongsToMany(models.Book, {\n      through: models.BookRoute,\n      foreignKey: 'routeId',\n      as: 'books',\n    });\n```\n\n```text\nforeignKey\n```\n\n```text\nhasOne\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsToMany\n```\n\n```text\nhasOne\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsToMany\n```\n\n```text\notherKey:\n```\n\n```text\nbelongsToMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nbelongsToMany\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":93,"estimatedTokens":344}}595{"id":"stack-27951337","source":"stackoverflow","questionId":27951337,"title":"Get raw query generated by sequelize.js","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: Get raw query generated by sequelize.js\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nGood afternoon everyone. I am developing a node.js/express system using sequelize.js (postgresql). \n\nMy problem is: I need to store the raw queries generated by sequelize in a log history, but I can't find a function that returns the generated query. Does anyone know if sequelize provides a function that returns the generated SQL query, or if there's any other way to achieve this?\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize('db', 'username', 'pwd', {\n\n  // you can either write to console\n  logging: console.log\n\n  // or write your own custom logging function\n  logging: function (str) {\n    // do stuff with the sql str\n  }\n});\n```\n\n========================================\n\nComments:\n- what if I want to print specific query only and not all queries?\n- You can use {logging: true} with the particular query. Check the params of the FindAll\n- What if we only want to get a query not to execute?","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":31,"estimatedTokens":268}}596{"id":"stack-54876680","source":"stackoverflow","questionId":54876680,"title":"How do I get the top X number of users with the most Y in Sequelize ORM?","tags":["sequelize.js"],"text":"Title: How do I get the top X number of users with the most Y in Sequelize ORM?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to get the top 10 users with the highest follower count. How do I do this using the Sequelize ORM? Seems as though you would be using `SELECT TOP number|percent column_name(s)` with vanilla SQL, but can't seem to find the same func with Sequelize.\n\n========================================\n\nTop Answer:\nSELECT TOP doesn't work in every database vendor (maybe only Microsoft SQL Server?). The sequelize doc describes \"LIMIT\" (used by MySql), which might work for your database. Here's an example: \n\n```\n/*Find the 5 most relevant answers:*/\nAnswers.findAll({\n order: [[Sequelize.col(relevance_index),'DESC']],\n limit: 5\n })\n```\n\n========================================\n\nCode:\n```text\nSELECT TOP number|percent column_name(s)\n```\n\n```text\nUser.findAll({ \n    limit: 10 ,\n    order: 'follower DESC'\n})\n```\n\n```text\n/*Find the 5 most relevant answers:*/\nAnswers.findAll({\n  order: [[Sequelize.col(relevance_index),'DESC']],\n  limit: 5\n  })\n```\n\n```js\nUser.findAll({ \n    limit: 10 ,\n    order: [['follower', 'DESC']]\n})\n```\n\n========================================\n\nComments:\n- You can use SubQuery in Attributes to get the follower count along with user info and then order desc for that value.\n- Im looking at the documentation for sequelize, and for some reason this only returns the very TOP result, not a set of data... can you think of any reason why that is?\n- I figured it out, My problem laid in the fact that i was doing `const [results, metadata] = ....` this set the `results` variable equal to the first object, when in reality i wanted it to return the array of results. so i just cut out that in lieu of `const data = ....` and returned the data object. now it returns the the correct SQL query","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":55,"estimatedTokens":462}}597{"id":"stack-24440565","source":"stackoverflow","questionId":24440565,"title":"Sequelize findall for every findall is possible?","tags":["node.js","sequelize.js"],"text":"Title: Sequelize findall for every findall is possible?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have this tables. Clients have Projects and Users works in Projects\n\n```\nClients\n- id\n- name\n\nProjects\n- id\n- name\n- client_id\n\nUsers\n- id\n- name\n\nUserProject\n- user_id\n- project_id\n```\n\nI try to return all users of the every project of client for example id=1\nFinally result, something like this JSON:\n\n```\n[{\n id:1\n name:\"Project1\"\n users:[{\n id:23\n name:\"Robert Stark\"\n },{\n id:67\n name: \"John Snow\"\n }]\n }, {\n id:2\n name:\"Project2\"\n users:[{\n id:1\n name:\"Aria Stark\"\n }]\n}]\n```\n\nIf I find projects it works fine\n\n```\nreq.tables.Project.findAll({\n where: {\n client_id:1\n }\n }).success(function(projects) {\n ...\n```\n\nIf I find Users of a project it works fine\n\n```\nreq.tables.UserProject.findAll({\n where: {\n project_id:1\n },\n include: [\n { model: req.tables.User, as: 'User' }\n ]\n}).success(function(UsersProject) {\n ...\n```\n\nBut, how can I combine both finAlls to return all users in every project? Something like the next code, but that works well. How can I do it?\nI found this: Node.js multiple Sequelize raw sql query sub queries but It doesn't work for me or I do not know how to use it, because I have 2 loops not only one. I have projects loop and users loop\n\n```\nreq.tables.Project.findAll({\n where: {\n client_id:1\n }\n}).success(function(projects) {\n\n var ret_projects=[];\n\n projects.forEach(function (project) {\n\n var ret_project={\n id:project.id,\n name:project.name,\n data:project.created,\n users:[]\n });\n\n req.tables.UserProject.findAll({\n where: {\n project_id:project.id\n },\n include: [\n { model: req.tables.User, as: 'User' }\n ]\n }).success(function(UsersProject) {\n\n var ret_users=[];\n\n UsersProject.forEach(function (UserProject) {\n ret_users.push({\n id:UserProject.user.id,\n name:UserProject.user.name,\n email:UserProject.user.email\n });\n });\n ret_project.users=ret_users;\n ret_project.push(ret_project)\n });\n });\n\n res.json(projects);\n});\n```\n\n========================================\n\nTop Answer:\nSounds like you already have a solution, but I came across the same issue and came up with this solution. \n\nVery similar to what cvng said, just using nested include. So use:\n\n```\nProject.belongsTo(Client);\nProject.hasMany(User);\nUser.hasMany(Project);\n```\n\nThen:\n\n```\nreq.tables.Client.find({\n where: { id:req.params.id },\n include: [{model: req.tables.Project, include : [req.tables.User]}]\n }).success(function(clientProjectUsers) {\n // Do something with clientProjectUsers.\n // Which has the client, its projects, and its users.\n });\n}\n```\n\nThe ability to 'Load further nested related models' is described through the param 'option.include[].include' here: Sequelize API Reference Model.\n\nMaybe this will be useful to someone else in the future. \n\nCheers!\n\n========================================\n\nCode:\n```text\nClients\n- id\n- name\n\nProjects\n- id\n- name\n- client_id\n\nUsers\n- id\n- name\n\nUserProject\n- user_id\n- project_id\n```\n\n```text\n[{\n   id:1\n   name:\"Project1\"\n   users:[{\n            id:23\n            name:\"Robert Stark\"\n          },{\n            id:67\n            name: \"John Snow\"\n          }]\n }, {\n   id:2\n   name:\"Project2\"\n   users:[{\n            id:1\n            name:\"Aria Stark\"\n          }]\n}]\n```\n\n```text\nreq.tables.Project.findAll({\n    where: {\n        client_id:1\n    }\n }).success(function(projects) {\n          ...\n```\n\n```text\nreq.tables.UserProject.findAll({\n   where: {\n       project_id:1\n   },\n   include: [\n       { model: req.tables.User, as: 'User' }\n   ]\n}).success(function(UsersProject) {\n     ...\n```\n\n```text\nreq.tables.Project.findAll({\n    where: {\n        client_id:1\n    }\n}).success(function(projects) {\n\n    var ret_projects=[];\n\n    projects.forEach(function (project) {\n\n         var ret_project={\n             id:project.id,\n             name:project.name,\n             data:project.created,\n             users:[]\n         });\n\n         req.tables.UserProject.findAll({\n             where: {\n                 project_id:project.id\n             },\n             include: [\n                 { model: req.tables.User, as: 'User' }\n             ]\n         }).success(function(UsersProject) {\n\n             var ret_users=[];\n\n             UsersProject.forEach(function (UserProject) {\n                 ret_users.push({\n                     id:UserProject.user.id,\n                     name:UserProject.user.name,\n                     email:UserProject.user.email\n                  });\n             });\n             ret_project.users=ret_users;\n             ret_project.push(ret_project)\n         });\n     });\n\n     res.json(projects);\n});\n```\n\n```text\nreq.tables.Client.find({\n            where: { id:req.params.id },\n            include: [{ model: req.tables.Project, as: 'Projects' }]\n        }).success(function(client) {\n\n            var ret ={\n                    id:client.id,\n                    name:client.name,\n                    projects:[]\n                };\n\n            done = _.after(client.projects.length, function () {\n                res.json(ret);\n            });\n\n            client.projects.forEach(function (project) {\n                project.getUsers().success(function(users) {\n\n                    var u=[]\n                    users.forEach(function (user) {\n                        u.push({\n                            id:user.id,\n                            name:user.name,\n                        });\n                    });\n\n                    ret.projects.push({\n                        id:project.id,\n                        name:project.name,\n                        users:u\n                    });\n                    done();\n\n                });\n\n            });\n\n        });\n```\n\n```text\nProject.belongsTo(Client);\nProject.hasMany(User, { as: 'Workers' });\nUser.hasMany(Project);\n```\n\n```text\nProject\n     .findAll({ include: [{ model: User, as: 'Workers' })\n     .success(function(users) {\n         // do success things here\n     }\n```\n\n```text\nProject.belongsTo(Client);\nProject.hasMany(User);\nUser.hasMany(Project);\n```\n\n```text\nreq.tables.Client.find({\n    where: { id:req.params.id },\n    include: [{model: req.tables.Project, include : [req.tables.User]}]\n  }).success(function(clientProjectUsers) {\n    // Do something with clientProjectUsers.\n    // Which has the client, its projects, and its users.\n  });\n}\n```\n\n========================================\n\nComments:\n- To make it bulletproof add `through: 'UserProject` to both `Project.hasMany(User)` and `User.hasMany(Project)`\n- I made a gist of it you wanna take a look! many-to-many\n- Looks like the 'Sequelize API Reference Model' link above is broken. Here's a more updated link http://docs.sequelizejs.com/en/latest/api/model/","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":342,"estimatedTokens":1678}}598{"id":"stack-31802946","source":"stackoverflow","questionId":31802946,"title":"Sequelize object is not a function","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: Sequelize object is not a function\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am working from this repo and trying to convert it over to PostgreSQL here is my error:\n\n```\n/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601\n this.importCache[path] = defineCall(this, DataTypes);\n ^\nTypeError: object is not a function\n at Sequelize.import (/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601:30)\n at db.sequelize (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:15:37)\n at Array.forEach (native)\n at Object. (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:14:6)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n at Module.require (module.js:364:17)\n at require (module.js:380:17)\n at Object. (/home/otis/Developer/Shipwrecked/Hatchway/app.js:10:12)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n at Module.require (module.js:364:17)\n at require (module.js:380:17)\n at Object. (/home/otis/Developer/Shipwrecked/Hatchway/bin/www:7:11)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n```\n\nHere is the code that is causing the error (models/index.js):\n\n```\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar Sequelize = require(\"sequelize\");\nvar env = process.env.NODE_ENV || \"development\";\nvar config = require(__dirname + '/../config.json')[env];\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\nvar db = {};\n\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n })\n .forEach(function(file) {\n var model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function(modelName) {\n if (\"associate\" in db[modelName]) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nIf I comment out the following lines the error stops:\n\n```\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n })\n .forEach(function(file) {\n var model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n });\n```\n\n`Node.js` errors are not my strong point so I am not really sure what is going, on I can also post my `config.json` if that is needed?\n\n========================================\n\nCode:\n```text\n/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601\n    this.importCache[path] = defineCall(this, DataTypes);\n                             ^\nTypeError: object is not a function\n    at Sequelize.import (/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601:30)\n    at db.sequelize (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:15:37)\n    at Array.forEach (native)\n    at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:14:6)\n    at Module._compile (module.js:456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n    at Module.require (module.js:364:17)\n    at require (module.js:380:17)\n    at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/app.js:10:12)\n    at Module._compile (module.js:456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n    at Module.require (module.js:364:17)\n    at require (module.js:380:17)\n    at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/bin/www:7:11)\n    at Module._compile (module.js:456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n```\n\n```text\nvar fs        = require(\"fs\");\nvar path      = require(\"path\");\nvar Sequelize = require(\"sequelize\");\nvar env       = process.env.NODE_ENV || \"development\";\nvar config    = require(__dirname + '/../config.json')[env];\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\nvar db        = {};\n\nfs\n    .readdirSync(__dirname)\n    .filter(function(file) {\n        return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n    })\n    .forEach(function(file) {\n        var model = sequelize.import(path.join(__dirname, file));\n        db[model.name] = model;\n    });\n\nObject.keys(db).forEach(function(modelName) {\n    if (\"associate\" in db[modelName]) {\n        db[modelName].associate(db);\n    }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nfs\n    .readdirSync(__dirname)\n    .filter(function(file) {\n        return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n    })\n    .forEach(function(file) {\n        var model = sequelize.import(path.join(__dirname, file));\n        db[model.name] = model;\n    });\n```\n\n```text\nNode.js\n```\n\n```text\nconfig.json\n```\n\n```text\nif (!this.importCache[path]) {\n    var defineCall = (arguments.length > 1 ? arguments[1] : require(path));\n    this.importCache[path] = defineCall(this, DataTypes);\n  }\n```\n\n========================================\n\nComments:\n- paste your `models&#47;index.js` file\n- The middle snippet is the index.js\n- Cheers, figured this out just before I saw your answer :)","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":181,"estimatedTokens":1429}}599{"id":"stack-39062925","source":"stackoverflow","questionId":39062925,"title":"Sequelize: Or-condition over multiple tables","tags":["mysql","sequelize.js"],"text":"Title: Sequelize: Or-condition over multiple tables\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to add an or condition over multiple tables with sequelizejs.\nMy problem is that I don't know how to use the or operators ($or and Sequelize.or) over more than one table.\n\nLet's say I want to implement the following sql-query:\n\n```\nselect * from A as a, B as b, C as c where (A.b_id = b.id and b.x = 7) or (A.c_id = C.id and c.z = \"test\")\n```\n\nI would implement only the first condition with sequelize like this:\n\n```\nA.findAll({\n include: [{ model: B, where: { x: 7 } }]\n})\n```\n\nAnd only the second condition like this:\n\n```\nA.findAll({\n include: [{ model: C, where: { z: \"test\" } }]\n})\n```\n\nBut how do I combine both queries into the one I want?\n\n========================================\n\nCode:\n```text\nselect * from A as a, B as b, C as c where (A.b_id = b.id and b.x = 7) or (A.c_id = C.id and c.z = \"test\")\n```\n\n```text\nA.findAll({\n   include: [{ model: B, where: { x: 7 } }]\n})\n```\n\n```text\nA.findAll({\n   include: [{ model: C, where: { z: \"test\" } }]\n})\n```\n\n```text\nA.findAll({\n   include: [{model: B},{model: C}], \n   where: {\n     '$or':{\n        '$b.x$': 7, \n        '$c.z$': \"test\"\n     }\n   });\n```\n\n========================================\n\nComments:\n- Thanks for accepted answer and glad to hear, up vote if you like answer\n- @SaravananNandhan :)\n- This doesn't work, as adding multiple tables causes an issue with SQL query. I am not sure of the exact reason other than how the joins function changes when there is more than 1 include. I have tried this with more than 1 table and have receive the error that the table name is missing in the clause","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":421}}600{"id":"stack-53903699","source":"stackoverflow","questionId":53903699,"title":"How to handle the sequelize unique constraint error?","tags":["node.js","sequelize.js"],"text":"Title: How to handle the sequelize unique constraint error?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to javascript and I need to handle constraint error in sequelize. I searched related to this topic everywhere, but still, I couldn't get a proper workable answer. My attempt it as follows.\n\n```\napp.post('/api/users', (req, res) => {\n try {\n console.log(req.body);\n User.create(req.body)\n .then(user=> res.json(user));\n } catch (error) {\n console.log(\"Error: \"+error);\n }});\n```\n\nHere couldn't catch the exception yet. For a valid user input it is able to post the request. So I just need to know a way to handle the exception.\n\n========================================\n\nTop Answer:\nWas looking around for an answer for this, but was not really satisfied with the two given. If you are looking to return a correct response such as a 403 this is the solution I have came up with.\n\n```\napp.post('/api/users', async (req, res) => {\n try {\n console.log(req.body);\n var user = await User.create(req.body)\n return res.status(200).json({ status: 'success', result: res.json(user) })\n } catch (error) {\n if (error.name === 'SequelizeUniqueConstraintError') {\n res.status(403)\n res.send({ status: 'error', message: \"User already exists\"});\n } else {\n res.status(500)\n res.send({ status: 'error', message: \"Something went wrong\"});\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\napp.post('/api/users', (req, res) => {\n  try {\n    console.log(req.body);\n    User.create(req.body)\n        .then(user=> res.json(user));\n  } catch (error) {\n    console.log(\"Error: \"+error);\n  }});\n```\n\n```text\napp.post('/api/users', (req, res) => {\n    console.log(req.body);\n    User.create(req.body)\n        .then(user=> res.json(user))\n        .catch(err => console.log(err))\n});\n```\n\n```text\napp.post('/api/users', async (req, res) => {\n    try {\n      console.log(req.body);\n      const user = await User.create(req.body);\n      res.json(user);\n    } catch (error) {\n      console.log(\"Error: \"+error);\n    }\n});\n```\n\n```text\nPromise\n```\n\n```text\n.then().catch()\n```\n\n```text\nasync/await\n```\n\n```text\ntry/catch\n```\n\n```text\nPromise\n```\n\n```text\nasync/await\n```\n\n```text\napp.post('/api/users', (req, res) => {\n  console.log(req.body)\n  User.create(req.body)\n    .then(user => res.json(user))\n    .catch(error => console.log('Error: ' + error))\n})\n```\n\n```text\napp.post('/api/users', async (req, res) => {\n  console.log(req.body)\n  try {\n    const user = await User.create(req.body)\n    res.json(user)\n  }\n  catch (error) { console.log('Error: ' + error) }\n})\n```\n\n```text\nthen()\n```\n\n```text\nawait\n```\n\n```text\nasync\n```\n\n```text\nasync (req, res)\n```\n\n```text\nthen()\n```\n\n```js\napp.post('/api/users', async (req, res) => {\n    try {\n        console.log(req.body);\n        var user = await User.create(req.body)\n        return res.status(200).json({ status: 'success', result: res.json(user) })\n    } catch (error) {\n        if (error.name === 'SequelizeUniqueConstraintError') {\n            res.status(403)\n            res.send({ status: 'error', message: \"User already exists\"});\n        } else {\n            res.status(500)\n            res.send({ status: 'error', message: \"Something went wrong\"});\n        }\n    }\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":159,"estimatedTokens":814}}601{"id":"stack-27569523","source":"stackoverflow","questionId":27569523,"title":"Sequelize store date part only in (mysql) table","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize store date part only in (mysql) table\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy application wants to store only date part in one of tables. In Sequelize there is only one data type, `Sequelize.DATE`, that can be used. On MySQL table it creates `DATETIME` column.\n\nHow can I have a column in database table to store only date, without time. part?\nMySQL is having separate `DATE` and `DATETIME` datatypes, but could not find a way to tell that in Sequelize.\n\nOr can we make to ignore time part while running queries using Date object?\n(I know we can use getters and setters with properties. No idea whether it will work while running queries having conditions for the date field.)\n\n========================================\n\nTop Answer:\nSomething of note... DATEONLY type in Sequelize v3 is NOT working as would be expected. It returns a Datetime with timezone, so if you are doing date comparisons they will not work as you expect unless your server timezone GMT. In my case, I'm working with holidays across timezones, so this was a headache for me. They do have a fix as of 2016-11-01 on the master branch, but it has not made it's way into v3 and there is no v4 yet. To work around the issue for now, you can do this in your model definition, which I found on that same link:\n\n```\nregDate: {\n type: DataTypes.DATEONLY,\n get: function() {\n return moment.utc(this.getDataValue('regDate')).format('YYYY-MM-DD');\n }\n}\n```\n\n========================================\n\nCode:\n```text\nSequelize.DATE\n```\n\n```text\nDATETIME\n```\n\n```text\nDATE\n```\n\n```text\nDATETIME\n```\n\n```text\nsequelize ^3.7.1\n```\n\n```text\nDATEONLY\n```\n\n```text\nregDate: {\n  type: DataTypes.DATEONLY,\n  get: function() {\n    return moment.utc(this.getDataValue('regDate')).format('YYYY-MM-DD');\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":62,"estimatedTokens":452}}602{"id":"stack-68122497","source":"stackoverflow","questionId":68122497,"title":"Sequelize Op.or within Op.and for nested operations","tags":["node.js","database","sequelize.js"],"text":"Title: Sequelize Op.or within Op.and for nested operations\nTags: node.js, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to make the condition\n\n(A AND B) And (C Or D Or E Or F)\n\nWhen I try to do\n\n```\nwhere: {\n [Op.and]: [{\n A,\n B,\n [Op.or]: [{\n C,\n D,\n E,\n F\n }]\n }]\n}\n```\n\nThis operation will just return A And B AND C AND D AND E AND F, for some reason Op.or just fails within Op.and. Maybe there is a better way to do the logical operation, would anyone know what do?\n\n========================================\n\nTop Answer:\nI fixed this problem by getting rid of the arrays, for some reason they were interfering in the interpretation. I guess you're not allowed to wrap Op.or with Op.and\n\n```\n[Op.and]: {\n A',\n B,\n [Op.or]: {\n C,\n D,\n E,\n F\n },\n }\n```\n\n========================================\n\nCode:\n```text\nwhere: {\n  [Op.and]: [{\n    A,\n    B,\n    [Op.or]: [{\n        C,\n        D,\n        E,\n        F\n     }]\n  }]\n}\n```\n\n```text\nwhere: {\n  [Op.and]: [\n    {\n      A\n    },\n    {\n      B\n    },\n    {\n      [Op.or]: [{\n        C,\n        D,\n        E,\n        F\n     }]\n    }\n  ]\n}\n```\n\n```text\n[Op.and]\n```\n\n```text\n[Op.and]: {\n                A',\n                B,\n                [Op.or]: {\n                    C,\n                    D,\n                    E,\n                    F\n                },\n            }\n```\n\n========================================\n\nComments:\n- Each condition will go within separate object. You are passing all the condition in one object.\n- I figured out a solution shortly after posting, I'm sure your method works though so I'll give you the check. Thanks for helping!","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":408}}603{"id":"stack-67477656","source":"stackoverflow","questionId":67477656,"title":"Is there a difference between findOne and findByPk in Sequelize?","tags":["sequelize.js"],"text":"Title: Is there a difference between findOne and findByPk in Sequelize?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nProvided that you're looking for something based on its primary key and don't want to include any additional options, does it matter whether you use findOne or findByPk? Would the performance be the same?\n\n========================================\n\nTop Answer:\nUnder the hood, there is no difference between passing a pk to `findOne` or using `findByPk`, i.e the performance is the same.\n\nIt's just an abstraction that sequelize gives in order to get a much readable code.\n\n========================================\n\nCode:\n```text\nModel.findByPk()\n```\n\n```text\nModel.findOne()\n```\n\n```text\nModel.findAll()\n```\n\n```text\nwhere\n```\n\n```text\nModel.findByPk(1)\n```\n\n```text\nModel.findOne({primaryKey: 1})\n```\n\n```text\nfindOne\n```\n\n```text\nfindByPk\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":48,"estimatedTokens":218}}604{"id":"stack-64057493","source":"stackoverflow","questionId":64057493,"title":"Sequelize function on where","tags":["node.js","orm","sequelize.js"],"text":"Title: Sequelize function on where\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI using sequelize 5.21.2 on Node 12.\n\nI want to get like this:\n\n```\nSELECT `id`\nFROM `order`\nWHERE (substr(`order`.`code`,1,8) >= '20200101'\nAND substr(`order`.`code`,1,8) So I wrote it like this:\n\n```\nreturn Model.order.findAll({\n attributes: [\n 'id',\n ],\n where: {\n [sequelize.fn('substr', Model.sequelize.col('code'), 1, 8)]: {\n [Op.gte]: params.start_date,\n [Op.lte]: params.end_date,\n },\n },\n});\n```\n\nBut It returns:\n\n```\nSELECT `order`.`id`\nFROM `order`\nWHERE (`order`.`[object Object]` >= '20200101'\nAND `order`.`[object Object]` I tried\n\n```\n[sequelize.literal('STR_TO_DATE(substr(code,1,8),\\'%Y %m %d\\')'), 'order_date']\n[sequelize.literal('STR_TO_DATE(substr(code,1,8),\\'%Y %m %d\\')')]\n[sequelize.fn('substr', Model.sequelize.col('code'), 1, 8)]\n```\n\nbut they work fine when I `SELECT`, but not `WHERE`.\n\nHow do I get the results I want? I couldn't find any relevant information in the official manual.. (https://sequelize.org/v5/manual/querying.html#where)\n\n========================================\n\nCode:\n```text\nSELECT `id`\nFROM `order`\nWHERE (substr(`order`.`code`,1,8) >= '20200101'\nAND substr(`order`.`code`,1,8) <= '20201230')\n```\n\n```text\nreturn Model.order.findAll({\n  attributes: [\n    'id',\n  ],\n  where: {\n    [sequelize.fn('substr', Model.sequelize.col('code'), 1, 8)]: {\n      [Op.gte]: params.start_date,\n      [Op.lte]: params.end_date,\n    },\n  },\n});\n```\n\n```text\nSELECT `order`.`id`\nFROM `order`\nWHERE (`order`.`[object Object]` >= '20200101'\nAND `order`.`[object Object]` <= '20201230')\n```\n\n```text\n[sequelize.literal('STR_TO_DATE(substr(code,1,8),\\'%Y %m %d\\')'), 'order_date']\n[sequelize.literal('STR_TO_DATE(substr(code,1,8),\\'%Y %m %d\\')')]\n[sequelize.fn('substr', Model.sequelize.col('code'), 1, 8)]\n```\n\n```text\nSELECT\n```\n\n```text\nWHERE\n```\n\n```text\nconst { sequelize, order } = Model;\nreturn order.findAll({\n  attributes: [\n    'id',\n  ],\n  where: {\n    [Op.and]: [\n      sequelize.where(sequelize.fn('substr', sequelize.col('code'), 1, 8), {\n        [Op.gte]: params.start_date,\n      }),\n      sequelize.where(sequelize.fn('substr', sequelize.col('code'), 1, 8), {\n        [Op.lte]: params.end_date,\n      }),\n    ],\n  },\n});\n```\n\n```text\nsequelize.where\n```\n\n```text\nOp.and\n```\n\n========================================\n\nComments:\n- The first code working nicely! But the second one is occurring syntax error(`SyntaxError: Unexpected token '.'`)...\n- @Centell - thanks i will remove that part of the answer. Was pretty sure just the first would work but found some documentation suggesting the second would but... nope. :)","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":124,"estimatedTokens":667}}605{"id":"stack-74837366","source":"stackoverflow","questionId":74837366,"title":"Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect [as oncomplete]","tags":["node.js","postgresql","sequelize.js","backend","production-environment"],"text":"Title: Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect [as oncomplete]\nTags: node.js, postgresql, sequelize.js, backend, production-environment\nSource: Stack Overflow\n\nQuestion:\nI have a simple node application with postgres database that is running perfectly on my local Machin ,\ni used to deploy backend application on Heroku,Since it has no more free services i tried many different alternative Like {Cyclic ,RailWay} , for now i couldn't deploy the server correctly with this Error :\n\n```\noriginal: Error: connect ECONNREFUSED 127.0.0.1:5432\nat TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {\nerrno: -111,\ncode: 'ECONNREFUSED',\nsyscall: 'connect',\naddress: '127.0.0.1',\nport: 5432\n}\n}\n```\n\nthis is my code :\n\n```\n\"use strict\";\nrequire('dotenv').config();\nconst Collection = require(\"./collection\");\n\nconst Users = require(\"./user.model\");\nconst Records =require('./records')\n\nconst POSTGRES_URI = process.env.NODE_ENV === 'test' ? 'sqlite:memory:' : process.env.DATABASE_URL;\nconst {\nSequelize,\nDataTypes\n} = require(\"sequelize\");\n\nlet sequelizeOptions =process.env.NODE_ENV === \"production\" ?\n{\ndialect: 'postgres',\nprotocol: 'postgres',\n\n } : {};\n\nlet sequelize = new Sequelize(POSTGRES_URI,sequelizeOptions);\nconst users = Users(sequelize, DataTypes);\nconst records = Records(sequelize, DataTypes);\n\n// Users.hasMany(Records)\nusers.hasMany(records, {\nforeignKey: \"userId\",\nsourceKey: \"id\",\nonDelete:'cascade'\n});\n\nrecords.belongsTo(users, {\nforeignKey: \"userId\",\ntargetKey: \"id\",\n});\n\nmodule.exports = {\ndb: sequelize,\nrecords: new Collection(records),\nusers:users,\n};\n```\n\nthis is `.env` file\n\n```\nDATABASE_URL=postgres://mohammadsh:0000@localhost:5432/covid\nPORT=3000\nSECRET=secretstring\nNODE_ENV=production\n```\n\nthis my package.json\n\n```\n\"scripts\": {\n \"start\": \"NODE_ENV=production node index.js\",\n \"dev\": \"NODE_ENV=development node index.js\"\n \n\n \n \"dependencies\": {\n \"axios\": \"^1.2.1\",\n \"base-64\": \"^1.0.0\",\n \"bcrypt\": \"^5.1.0\",\n \"cors\": \"^2.8.5\",\n \"dotenv\": \"^16.0.3\",\n \"express\": \"^4.18.2\",\n \"jsonwebtoken\": \"^8.5.1\",\n \"pg\": \"^8.8.0\",\n \"sequelize\": \"^6.27.0\",\n \"sequelize-cli\": \"^6.5.2\",\n \"sqlite3\": \"^5.1.4\"\n }\n```\n\ni set the .env variables with the deployment on{Cyclic and RailWay} as they are in my .env file\n\n- when this error happen on my local machin i just run the postgres server by this command\n\n```\npg_ctl -D /home/linuxbrew/.linuxbrew/var/postgresql@14 start\n```\n\nhow to do this on Cyclic ? or any other application\n\ni tried punch of code by playing with connection options\n*aslo i tried to change the IP address to be 0.0.0.0 and i got the same error\n\n```\noriginal: Error: connect ECONNREFUSED 127.0.0.1:5432\nat TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {\nerrno: -111,\ncode: 'ECONNREFUSED',\nsyscall: 'connect',\naddress: '127.0.0.1',\nport: 5432\n}\n}\n```\n\n`any help ???`\n\n========================================\n\nCode:\n```text\noriginal: Error: connect ECONNREFUSED 127.0.0.1:5432\nat TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {\nerrno: -111,\ncode: 'ECONNREFUSED',\nsyscall: 'connect',\naddress: '127.0.0.1',\nport: 5432\n}\n}\n```\n\n```text\n\"use strict\";\nrequire('dotenv').config();\nconst Collection = require(\"./collection\");\n\nconst Users = require(\"./user.model\");\nconst Records =require('./records')\n\nconst POSTGRES_URI = process.env.NODE_ENV === 'test' ? 'sqlite:memory:' : process.env.DATABASE_URL;\nconst {\nSequelize,\nDataTypes\n} = require(\"sequelize\");\n\nlet sequelizeOptions =process.env.NODE_ENV === \"production\" ?\n{\ndialect: 'postgres',\nprotocol: 'postgres',\n\n    } : {};\n\nlet sequelize = new Sequelize(POSTGRES_URI,sequelizeOptions);\nconst users = Users(sequelize, DataTypes);\nconst records = Records(sequelize, DataTypes);\n\n// Users.hasMany(Records)\nusers.hasMany(records, {\nforeignKey: \"userId\",\nsourceKey: \"id\",\nonDelete:'cascade'\n});\n\nrecords.belongsTo(users, {\nforeignKey: \"userId\",\ntargetKey: \"id\",\n});\n\nmodule.exports = {\ndb: sequelize,\nrecords: new Collection(records),\nusers:users,\n};\n```\n\n```text\nDATABASE_URL=postgres://mohammadsh:0000@localhost:5432/covid\nPORT=3000\nSECRET=secretstring\nNODE_ENV=production\n```\n\n```text\n\"scripts\": {\n    \"start\": \"NODE_ENV=production node index.js\",\n    \"dev\": \"NODE_ENV=development node index.js\"\n    \n\n  \n  \"dependencies\": {\n    \"axios\": \"^1.2.1\",\n    \"base-64\": \"^1.0.0\",\n    \"bcrypt\": \"^5.1.0\",\n    \"cors\": \"^2.8.5\",\n    \"dotenv\": \"^16.0.3\",\n    \"express\": \"^4.18.2\",\n    \"jsonwebtoken\": \"^8.5.1\",\n    \"pg\": \"^8.8.0\",\n    \"sequelize\": \"^6.27.0\",\n    \"sequelize-cli\": \"^6.5.2\",\n    \"sqlite3\": \"^5.1.4\"\n  }\n```\n\n```text\npg_ctl -D /home/linuxbrew/.linuxbrew/var/postgresql@14 start\n```\n\n```text\noriginal: Error: connect ECONNREFUSED 127.0.0.1:5432\nat TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {\nerrno: -111,\ncode: 'ECONNREFUSED',\nsyscall: 'connect',\naddress: '127.0.0.1',\nport: 5432\n}\n}\n```\n\n```text\n.env\n```\n\n```text\nany help ???\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.388Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":237,"estimatedTokens":1228}}606{"id":"stack-42610767","source":"stackoverflow","questionId":42610767,"title":"Sequelizejs belongsToMany relation with otherKey","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelizejs belongsToMany relation with otherKey\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am creating an application about songs and artists, following is the database schema:\n\nSong has many Artists, and Artist has many Songs, this is a many to many relations, so I define a join table `SongArtist`:\n\nSongArtist Model:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var SongArtist = sequelize.define('SongArtist', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n songId: {\n type: DataTypes.INTEGER,\n allowNull: false,\n\n },\n artistId: {\n type: DataTypes.INTEGER,\n allowNull: false,\n\n }\n }, {\n tableName: 'SongArtist',\n });\n return SongArtist;\n};\n```\n\nThe default behavior is `SongArtist` use `Songs` and `Artists` primary key('id') to query, but I wanna use `neteaseId` column in Songs and Artists to many to many query, so I am using `otherKey` in following:\n\nSongs Model:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var Songs = sequelize.define('Songs', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: DataTypes.STRING,\n allowNull: true\n },\n neteaseId: {\n type: DataTypes.INTEGER,\n allowNull: false,\n unque: true\n }\n }, {\n tableName: 'Songs',\n classMethods: {\n associate: (models) => {\n Songs.belongsToMany(models.Artists,{\n through: 'SongArtist',\n foreignKey: 'songId',\n otherKey: 'neteaseId'\n })\n }\n }\n });\n\n return Songs;\n};\n```\n\nArtists Model:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var Artists = sequelize.define('Artists', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: DataTypes.STRING,\n allowNull: true\n },\n neteaseId: {\n type: DataTypes.INTEGER,\n allowNull: false,\n unque: true\n }\n }, {\n tableName: 'Artists',\n classMethods: {\n associate: (models) => {\n Artists.belongsToMany(models.Songs,{\n through: 'SongArtist',\n foreignKey: 'artistId',\n otherKey: 'neteaseId'\n })\n }\n }\n });\n\n return Artists;\n};\n```\n\nBut when I execute query with following code it throws error to me:\n\n```\nmodels.Songs.findAll({include: [models.Artists, models.Album]})\n\n> SequelizeDatabaseError: column Artists.SongArtist.neteaseId does not exist\n```\n\nSo how to change default query column in many to many query, and should generate following sql:\n\n```\nLEFT OUTER JOIN (\"SongArtist\" AS \"Artists.SongArtist\"\nINNER JOIN \"Artists\" AS \"Artists\" ON \"Artists\".\"neteaseId\" = \"Artists.SongArtist\".\"artistId\") \nON \"Songs\".\"id\" = \"Artists.songId\".\"songId\"\n```\n\ninstead of \n\n```\nLEFT OUTER JOIN (\"SongArtist\" AS \"Artists.SongArtist\"\nINNER JOIN \"Artists\" AS \"Artists\" ON \"Artists\".\"id\" = \"Artists.SongArtist\".\"artistId\") \nON \"Songs\".\"id\" = \"Artists.SongArtist\".\"songId\"\n```\n\n========================================\n\nTop Answer:\nSupport for `targetKey` and `sourceKey` for many-to-many relations was added in Sequelize 5.15.0 as pointed out in this PR.\n\nQuoting the docs here.\n\nThere are four cases to consider:\n\nWe might want a many-to-many relationship using the default primary\nkeys for both Foo and Bar:\n\n```\nFoo.belongsToMany(Bar, { through: 'foo_bar' }); // This creates a junction table `foo_bar` with fields `fooId` and `barId`\n```\n\nWe might want a many-to-many relationship using the default primary key > for Foo but a different field for Bar:\n\n```\nFoo.belongsToMany(Bar, { through: 'foo_bar', targetKey: 'title' }); // This creates a junction table `foo_bar` with fields `fooId` and `barTitle`\n```\n\nWe might want a many-to-many relationship using the a different field for Foo and the default primary key for Bar:\n\n```\nFoo.belongsToMany(Bar, { through: 'foo_bar', sourceKey: 'name' }); // This creates a junction table `foo_bar` with fields `fooName` and `barId`\n```\n\nWe might want a many-to-many relationship using different fields for both Foo and Bar:\n\n```\nFoo.belongsToMany(Bar, { through: 'foo_bar', sourceKey: 'name', targetKey: 'title' }); // This creates a junction table `foo_bar` with fields `fooName` and `barTitle`\n```\n\nCode example shown in this commit. Pasting here for quick reference.\n\n```\nconst User = this.sequelize.define('User', {\n id: {\n type: DataTypes.UUID,\n allowNull: false,\n primaryKey: true,\n defaultValue: DataTypes.UUIDV4,\n field: 'user_id'\n },\n userSecondId: {\n type: DataTypes.UUID,\n allowNull: false,\n defaultValue: DataTypes.UUIDV4,\n field: 'user_second_id'\n }\n}, {\n tableName: 'tbl_user',\n indexes: [\n {\n unique: true,\n fields: ['user_second_id']\n }\n ]\n});\nconst Group = this.sequelize.define('Group', {\n id: {\n type: DataTypes.UUID,\n allowNull: false,\n primaryKey: true,\n defaultValue: DataTypes.UUIDV4,\n field: 'group_id'\n },\n groupSecondId: {\n type: DataTypes.UUID,\n allowNull: false,\n defaultValue: DataTypes.UUIDV4,\n field: 'group_second_id'\n }\n}, {\n tableName: 'tbl_group',\n indexes: [\n {\n unique: true,\n fields: ['group_second_id']\n }\n ]\n});\nUser.belongsToMany(Group, {\n through: 'usergroups',\n sourceKey: 'userSecondId'\n});\nGroup.belongsToMany(User, {\n through: 'usergroups',\n sourceKey: 'groupSecondId'\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var SongArtist = sequelize.define('SongArtist', {\n    id: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    songId: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n\n    },\n    artistId: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n\n    }\n  }, {\n    tableName: 'SongArtist',\n  });\n  return SongArtist;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var Songs = sequelize.define('Songs', {\n    id: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: true\n    },\n    neteaseId: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      unque: true\n    }\n  }, {\n    tableName: 'Songs',\n    classMethods: {\n      associate: (models) => {\n        Songs.belongsToMany(models.Artists,{\n          through: 'SongArtist',\n          foreignKey: 'songId',\n          otherKey: 'neteaseId'\n        })\n      }\n    }\n  });\n\n  return Songs;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var Artists = sequelize.define('Artists', {\n    id: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: true\n    },\n    neteaseId: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      unque: true\n    }\n  }, {\n    tableName: 'Artists',\n    classMethods: {\n      associate: (models) => {\n        Artists.belongsToMany(models.Songs,{\n          through: 'SongArtist',\n          foreignKey: 'artistId',\n          otherKey: 'neteaseId'\n        })\n      }\n    }\n  });\n\n  return Artists;\n};\n```\n\n```text\nmodels.Songs.findAll({include: [models.Artists, models.Album]})\n\n> SequelizeDatabaseError: column Artists.SongArtist.neteaseId does not exist\n```\n\n```text\nLEFT OUTER JOIN (\"SongArtist\" AS \"Artists.SongArtist\"\nINNER JOIN \"Artists\" AS \"Artists\" ON \"Artists\".\"neteaseId\" =    \"Artists.SongArtist\".\"artistId\") \nON \"Songs\".\"id\" = \"Artists.songId\".\"songId\"\n```\n\n```text\nLEFT OUTER JOIN (\"SongArtist\" AS \"Artists.SongArtist\"\nINNER JOIN \"Artists\" AS \"Artists\" ON \"Artists\".\"id\" =   \"Artists.SongArtist\".\"artistId\") \nON \"Songs\".\"id\" = \"Artists.SongArtist\".\"songId\"\n```\n\n```text\nSongArtist\n```\n\n```text\nSongArtist\n```\n\n```text\nSongs\n```\n\n```text\nArtists\n```\n\n```text\nneteaseId\n```\n\n```text\notherKey\n```\n\n```text\nconst sourceKey = this.source.rawAttributes[this.source.primaryKeyAttribute];\n```\n\n```text\notherKey\n```\n\n```text\notherKey\n```\n\n```text\nbelongsToMany\n```\n\n```text\nthis.source\n```\n\n```text\nSong\n```\n\n```text\nArtist\n```\n\n```text\nprimaryKeyAttribute\n```\n\n```text\nid\n```\n\n```text\nFoo.belongsToMany(Bar, { through: 'foo_bar' }); // This creates a junction table `foo_bar` with fields `fooId` and `barId`\n```\n\n```text\nFoo.belongsToMany(Bar, { through: 'foo_bar', targetKey: 'title' }); // This creates a junction table `foo_bar` with fields `fooId` and `barTitle`\n```\n\n```text\nFoo.belongsToMany(Bar, { through: 'foo_bar', sourceKey: 'name' }); // This creates a junction table `foo_bar` with fields `fooName` and `barId`\n```\n\n```text\nFoo.belongsToMany(Bar, { through: 'foo_bar', sourceKey: 'name', targetKey: 'title' }); // This creates a junction table `foo_bar` with fields `fooName` and `barTitle`\n```\n\n```text\nconst User = this.sequelize.define('User', {\n  id: {\n    type: DataTypes.UUID,\n    allowNull: false,\n    primaryKey: true,\n    defaultValue: DataTypes.UUIDV4,\n    field: 'user_id'\n  },\n  userSecondId: {\n    type: DataTypes.UUID,\n    allowNull: false,\n    defaultValue: DataTypes.UUIDV4,\n    field: 'user_second_id'\n  }\n}, {\n  tableName: 'tbl_user',\n  indexes: [\n    {\n      unique: true,\n      fields: ['user_second_id']\n    }\n  ]\n});\nconst Group = this.sequelize.define('Group', {\n  id: {\n    type: DataTypes.UUID,\n    allowNull: false,\n    primaryKey: true,\n    defaultValue: DataTypes.UUIDV4,\n    field: 'group_id'\n  },\n  groupSecondId: {\n    type: DataTypes.UUID,\n    allowNull: false,\n    defaultValue: DataTypes.UUIDV4,\n    field: 'group_second_id'\n  }\n}, {\n  tableName: 'tbl_group',\n  indexes: [\n    {\n      unique: true,\n      fields: ['group_second_id']\n    }\n  ]\n});\nUser.belongsToMany(Group, {\n  through: 'usergroups',\n  sourceKey: 'userSecondId'\n});\nGroup.belongsToMany(User, {\n  through: 'usergroups',\n  sourceKey: 'groupSecondId'\n});\n```\n\n```text\ntargetKey\n```\n\n```text\nsourceKey\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":487,"estimatedTokens":2417}}607{"id":"stack-69727991","source":"stackoverflow","questionId":69727991,"title":"Postgres jsonb query for dynamic values","tags":["sql","node.js","postgresql","sequelize.js","typeorm"],"text":"Title: Postgres jsonb query for dynamic values\nTags: sql, node.js, postgresql, sequelize.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn the users table I have a jsob column `experience` with following json structure:\n\n```\n[\n {\n \"field\": \"devops\",\n \"years\": 9\n },\n {\n \"field\": \"backend dev\",\n \"years\": 7\n } \n... // could be N number of objects with different values\n]\n```\n\n**Business requirement**\n\nClient can request for people with experience in any field and with their respective years experience in each\n\n**This is an example query**\n\n```\nSELECT * FROM users\nWHERE\njsonb_path_exists(experience, '$[*] ? (@.field == \"devops\" && @.years > 5)') and\njsonb_path_exists(experience, '$[*] ? (@.field == \"backend dev\" && @.years > 5)')\nLIMIT 3;\n```\n\n### Issue\n\nLets say if I get a request for\n\n```\n[\n { field: \"devops\", years: 5 }, \n { field: \"java\", years: 6 }, \n { field: \"ui/ux\", years: 2 }] // and so on\n```\n\nHow do I dynamically create a query without worrying about sql injection?\n\n### Techstack\n\n- Nodejs\n\n- Typescript\n\n- TypeORM\n\n- Postgres\n\n========================================\n\nTop Answer:\nThis is a parameterized query so more or less injection safe. `qualifies` scalar subquery calculates whether `experience` satisfies all request items. The parameters are `$1` (the jsonb array of request parameters) and `$2` (the limit value). You may need to change their syntax depending on the flavour of your environment.\n\n```\nselect t.* from \n(\n select u.*,\n (\n select count(*) = jsonb_array_length($1)\n from jsonb_array_elements(u.experience) ej -- jsonb list of experiences \n inner join jsonb_array_elements($1) rj -- jsonb list of request items\n on ej ->> 'field' = rj ->> 'field'\n and (ej ->> 'years')::numeric >= (rj ->> 'years')::numeric\n ) as qualifies\n from users as u\n) as t\nwhere t.qualifies\nlimit $2;\n```\n\n**Some explanation**\n\nThe logic of the `qualifies` subquery is this: first 'normalize' the `experience` and request jsonb arrays into 'tables', then inner join them on the target condition (which is `field_a = field_b and years_a >= years_b` in this case) and count how many of them match. If the count is equal to the number of request items (i.e. `count(*) = jsonb_array_length($1)`) then all of them are satisfied and so `experience` qualifies.\n\nThus no dynamic SQL is necessary. I think that this approach may be reusable too.\n\n========================================\n\nCode:\n```json\n[\n    {\n        \"field\": \"devops\",\n        \"years\": 9\n    },\n    {\n        \"field\": \"backend dev\",\n        \"years\": 7\n    } \n... // could be N number of objects with different values\n]\n```\n\n```sql\nSELECT * FROM users\nWHERE\njsonb_path_exists(experience, '$[*] ? (@.field == \"devops\" && @.years > 5)') and\njsonb_path_exists(experience, '$[*] ? (@.field == \"backend dev\" && @.years > 5)')\nLIMIT 3;\n```\n\n```text\n[\n  { field: \"devops\", years: 5 }, \n  { field: \"java\", years: 6 }, \n  { field: \"ui/ux\", years: 2 }] // and so on\n```\n\n```text\nexperience\n```\n\n```text\nCREATE INDEX users_experience_gin_idx ON users USING gin (experience jsonb_path_ops);\n```\n\n```sql\nSELECT *\nFROM   users\nWHERE  experience @? '$[*] ? (@.field == \"devops\" && @.years > 5 )'\nAND    experience @? '$[*] ? (@.field == \"backend dev\" && @.years > 5)'\nLIMIT  3;\n```\n\n```sql\nSELECT 'SELECT * FROM users\nWHERE  experience @? '\n       || string_agg(quote_nullable(format('$[*] ? (@.field == %s && @.years > %s)'\n                                         , f->'field'\n                                         , f->'years')) || '::jsonpath'\n                   , E'\\nAND    experience @? ')\n       || E'\\nLIMIT  3'\nFROM   jsonb_array_elements('[{\"field\": \"devops\", \"years\": 5 }, \n                              {\"field\": \"java\", \"years\": 6 }, \n                              {\"field\": \"ui/ux\", \"years\": 2 }]') f;\n```\n\n```sql\nSELECT * FROM users\nWHERE  experience @? '$[*] ? (@.field == \"devops\" && @.years > 5)'::jsonpath\nAND    experience @? '$[*] ? (@.field == \"java\" && @.years > 6)'::jsonpath\nAND    experience @? '$[*] ? (@.field == \"ui/ux\" && @.years > 2)'::jsonpath\nLIMIT  3;\n```\n\n```sql\nCREATE OR REPLACE FUNCTION f_users_with_experience(_filter_arr jsonb, _limit int = 3)\n  RETURNS SETOF users\n  LANGUAGE plpgsql PARALLEL SAFE STABLE STRICT AS\n$func$\nDECLARE\n   _sql text;\nBEGIN\n   -- assert (you may want to be stricter?)\n   IF jsonb_path_exists (_filter_arr, '$[*] ? (!exists(@.field) || !exists(@.years))') THEN\n      RAISE EXCEPTION 'Parameter $2 (_filter_arr) must be a JSON array with keys \"field\" and \"years\" in every object. Invalid input was: >>%<<', _filter_arr;\n   END IF;\n\n   -- generate query string\n   SELECT INTO _sql\n'SELECT * FROM users\nWHERE  experience @? '\n       || string_agg(quote_nullable(format('$[*] ? (@.field == %s && @.years > %s)'\n                                         , f->'field'\n                                         , f->'years'))\n                   , E'\\nAND    experience @? ')\n       || E'\\nLIMIT   ' || _limit\n   FROM   jsonb_array_elements(_filter_arr) f;\n\n   -- execute\n   IF _sql IS NULL THEN\n      RAISE EXCEPTION 'SQL statement is NULL. Should not occur!';\n   ELSE\n   -- RAISE NOTICE '%', _sql;     -- debug first if in doubt\n      RETURN QUERY EXECUTE _sql;\n   END IF;\nEND\n$func$;\n```\n\n```text\nSELECT * FROM f_users_with_experience('[{\"field\": \"devops\", \"years\": 5 }, \n                                      , {\"field\": \"backend dev\", \"years\": 6}]');\n```\n\n```text\nSELECT * FROM f_users_with_experience('[{\"field\": \"devops\", \"years\": 5 }]', 123);\n```\n\n```text\njsonb_path_exists (_filter_arr, '$[*] ? (!exists(@.field) || !exists(@.years))')\n```\n\n```text\njsonb_path_ops\n```\n\n```text\n@?\n```\n\n```text\njsonb_path_exists()\n```\n\n```text\nLIMIT\n```\n\n```text\njsonpath\n```\n\n```text\nquote_nullable()\n```\n\n```text\nfield\n```\n\n```text\nyears\n```\n\n```sql\nselect t.* from \n(\n  select u.*,\n    (\n      select count(*) = jsonb_array_length($1)\n      from jsonb_array_elements(u.experience) ej -- jsonb list of experiences \n      inner join jsonb_array_elements($1) rj     -- jsonb list of request items\n         on ej ->> 'field' =  rj ->> 'field'\n        and (ej ->> 'years')::numeric >= (rj ->> 'years')::numeric\n    ) as qualifies\n from users as u\n) as t\nwhere t.qualifies\nlimit $2;\n```\n\n```text\nqualifies\n```\n\n```text\nexperience\n```\n\n```text\n$1\n```\n\n```text\n$2\n```\n\n```text\nqualifies\n```\n\n```text\nexperience\n```\n\n```text\nfield_a = field_b and years_a >= years_b\n```\n\n```text\ncount(*) = jsonb_array_length($1)\n```\n\n```text\nexperience\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":287,"estimatedTokens":1612}}608{"id":"stack-40728509","source":"stackoverflow","questionId":40728509,"title":"Nodejs use JOIN for two tables on sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: Nodejs use JOIN for two tables on sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implementing this mysql command on sequelize, but as far as i'm newbie to use this library i can't implementing that\n\ni want to make this sql command:\n\n```\nSELECT * FROM users \njoin users_contacts_lists on users_contacts_lists.mobile_number = users.mobile_number \nWHERE users_contacts_lists.user_id = 1\n```\n\nMy models to create database schema:\n\n```\n'use strict';\nvar config = require('../config');\n\nvar User = config.sequelize.define('users', {\n id: {\n type: config.Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n password: {\n type: config.Sequelize.STRING\n },\n username: {\n type: config.Sequelize.STRING\n },\n mobileNumber: {\n type: config.Sequelize.STRING,\n field: 'mobile_number'\n },\n status: {\n type: config.Sequelize.STRING\n },\n}, {freezeTableName: true});\n\nvar UsersContactsLists = config.sequelize.define('users_contacts_lists', {\n id: {\n type: config.Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n userId: {\n type: config.Sequelize.INTEGER,\n field: 'user_id'\n },\n mobileNumber: {\n type: config.Sequelize.STRING,\n field: 'mobile_number', defaultValue: 0\n }\n}, {freezeTableName: true});\n\nUsersContactsLists.belongsTo(ChannelsTypes, {foreignKey: 'user_id'});\nUser.hasMany(Channels, {foreignKey: 'id'});\n\nUser.sync();\nUsersContactsLists.sync();\n\nmodule.exports =\n{\n users: User,\n usersContactsLists: UsersContactsLists\n};\n```\n\nhow can i resolve this problem? Thanks in advance\n\n========================================\n\nTop Answer:\nFiddled around a bit, does this statement do what you want?\n\n```\nUser.findAll({\n include: [{\n model: UsersContactsLists,\n where: {\n userId: 1\n }\n }]\n```\n\n========================================\n\nCode:\n```text\nSELECT * FROM users \njoin users_contacts_lists on users_contacts_lists.mobile_number = users.mobile_number \nWHERE users_contacts_lists.user_id = 1\n```\n\n```text\n'use strict';\nvar config = require('../config');\n\nvar User = config.sequelize.define('users', {\n    id: {\n        type: config.Sequelize.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    password: {\n        type: config.Sequelize.STRING\n    },\n    username: {\n        type: config.Sequelize.STRING\n    },\n    mobileNumber: {\n        type: config.Sequelize.STRING,\n        field: 'mobile_number'\n    },\n    status: {\n        type: config.Sequelize.STRING\n    },\n}, {freezeTableName: true});\n\nvar UsersContactsLists = config.sequelize.define('users_contacts_lists', {\n    id: {\n        type: config.Sequelize.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    userId: {\n        type: config.Sequelize.INTEGER,\n        field: 'user_id'\n    },\n    mobileNumber: {\n        type: config.Sequelize.STRING,\n        field: 'mobile_number', defaultValue: 0\n    }\n}, {freezeTableName: true});\n\nUsersContactsLists.belongsTo(ChannelsTypes, {foreignKey: 'user_id'});\nUser.hasMany(Channels, {foreignKey: 'id'});\n\nUser.sync();\nUsersContactsLists.sync();\n\nmodule.exports =\n{\n    users: User,\n    usersContactsLists: UsersContactsLists\n};\n```\n\n```text\nUser.belongsTo(UsersContactsLists, {targetKey:'mobileNumber',foreignKey: 'mobileNumber'});\n```\n\n```text\nUser.findAll({\n    include: [{\n        model: UsersContactsLists,\n        where: {\n            userId: 1\n        }\n    }]\n})\n```\n\n```text\nUser.findAll({\n    include: [{\n        model: UsersContactsLists,\n        where: {\n            userId: 1\n        }\n    }]\n```\n\n========================================\n\nComments:\n- Thanks man, unfortunately i get this error `TypeError: Cannot read property 'field' of undefined at new BelongsTo (&#47;Volumes&#47;Home&#47;Projects&#47;Web&#47;test&#47;node_modules&#47;sequelize&#47;lib&#47;&zwnj;&#8203;associations&#47;belongs&zwnj;&#8203;-to.js:64:66)`\n- Thanks, how can i choose some fields from `Users` and `UsersContactsLists` models? for example `id` from `User` and `updated_at` from `UsersContactsLists`?\n- the targetkey refers to target model that here is UsersContactsLists so targetKey will be `updated_at` and another is foriegnKey of current model that here is `id`\n- its wasn't my mean, create join `sql` command and select some fields from two tables\n- use something like this : `User.findAll({ include: [{ model: UsersContactsLists, where: { userId: 1 }, attributes: {'updated_at'} }], attributes: {'id'} })`\n- Let us continue this discussion in chat.\n- User.findAll( { include: [ { model: UsersContactsLists, where: { userId: 1 }, attributes: ['updated_at'] }] , attributes: ['id'] } )","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":186,"estimatedTokens":1151}}609{"id":"stack-33138603","source":"stackoverflow","questionId":33138603,"title":"ExpressJS - Sequelize - Unrecognized Data Type","tags":["node.js","express","sequelize.js"],"text":"Title: ExpressJS - Sequelize - Unrecognized Data Type\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI manually created a sql database and am now trying to set up my sequelize models to match the columns in my sql tables, but I've run into an issue with my model related to an unrecognized field type. I can't seem to pinpoint the error and if it is related to not matching the data type for a field in my database or that the sequelize does not recognize some of my code. \n\nHere is my error: \n\n```\n/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/model.js:90\n throw new Error('Unrecognized data type for field ' + name);\n ^\nError: Unrecognized data type for field pattern\n at null. (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/model.js:90:13)\n at /Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:2874:23\n at /Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:3395:24\n at /Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:3073:15\n at baseForOwn (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:2046:14)\n at Function.mapValues (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:3394:9)\n at new Model (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/model.js:74:50)\n at Sequelize.define (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/sequelize.js:577:15)\n at Object. (/Users/user/Desktop/Projects/node/assistant/app/models/imagesModel.js:9:24)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n at Module.require (module.js:364:17)\n at require (module.js:380:17)\n at Object. (/Users/user/Desktop/Projects/node/assistant/app/routes.js:4:14)\n at Module._compile (module.js:456:26)\n at Object.Module._extensions..js (module.js:474:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n at Module.require (module.js:364:17)\n at require (module.js:380:17)\n```\n\nHere is my model:\n\n```\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('db', 'admin', 'pwd', {\n host: 'database-host',\n port: 3306,\n dialect: 'mysql'\n});\n\nvar Images = sequelize.define('images', {\n pattern: {\n type: sequelize.STRING,\n field: 'pattern'\n },\n color: {\n type: sequelize.STRING,\n field: 'color'\n },\n imageUrl: {\n type: sequelize.STRING,\n field: 'imageUrl'\n },\n imageSource: {\n type: sequelize.STRING,\n field: 'imageSource'\n },\n description_id: {\n type: sequelize.INTEGER,\n field: 'description_id'\n }\n});\n\nmodule.exports = Images;\n```\n\n========================================\n\nTop Answer:\nYou use your sequelize constructor to define your table with the `sequelize.define()` method, while you use the object `Sequelize` in which your sequelize package was assigned to, to carry out functions on each of your values in your nested object. \nFor example, \n\n```\ncolor: {\n type: Sequelize.STRING,\n field: 'color'\n}\n```\n\nand not, \n\n```\ncolor: {\n type: sequelize.STRING,\n field: 'color'\n}\n```\n\n========================================\n\nCode:\n```text\n/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/model.js:90\n      throw new Error('Unrecognized data type for field ' + name);\n            ^\nError: Unrecognized data type for field pattern\n    at null.<anonymous> (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/model.js:90:13)\n    at /Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:2874:23\n    at /Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:3395:24\n    at /Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:3073:15\n    at baseForOwn (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:2046:14)\n    at Function.mapValues (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/node_modules/lodash/index.js:3394:9)\n    at new Model (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/model.js:74:50)\n    at Sequelize.define (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/sequelize.js:577:15)\n    at Object.<anonymous> (/Users/user/Desktop/Projects/node/assistant/app/models/imagesModel.js:9:24)\n    at Module._compile (module.js:456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n    at Module.require (module.js:364:17)\n    at require (module.js:380:17)\n    at Object.<anonymous> (/Users/user/Desktop/Projects/node/assistant/app/routes.js:4:14)\n    at Module._compile (module.js:456:26)\n    at Object.Module._extensions..js (module.js:474:10)\n    at Module.load (module.js:356:32)\n    at Function.Module._load (module.js:312:12)\n    at Module.require (module.js:364:17)\n    at require (module.js:380:17)\n```\n\n```text\nvar Sequelize      = require('sequelize');\nvar sequelize = new Sequelize('db', 'admin', 'pwd', {\n    host: 'database-host',\n    port: 3306,\n    dialect: 'mysql'\n});\n\n\nvar Images = sequelize.define('images', {\n    pattern: {\n        type: sequelize.STRING,\n        field: 'pattern'\n    },\n    color: {\n        type: sequelize.STRING,\n        field: 'color'\n    },\n    imageUrl: {\n        type: sequelize.STRING,\n        field: 'imageUrl'\n    },\n    imageSource: {\n        type: sequelize.STRING,\n        field: 'imageSource'\n    },\n    description_id: {\n        type: sequelize.INTEGER,\n        field: 'description_id'\n    }\n});\n\nmodule.exports = Images;\n```\n\n```text\nvar Sequelize      = require('sequelize');\nvar sequelize = new Sequelize('db', 'admin', 'pwd', {\n    host: 'database-host',\n    port: 3306,\n    dialect: 'mysql'\n});\n\n\nvar Images = sequelize.define('images', {\n    pattern: {\n        type: Sequelize.STRING,\n        field: 'pattern'\n    },\n    color: {\n        type: Sequelize.STRING,\n        field: 'color'\n    },\n    imageUrl: {\n        type: Sequelize.STRING,\n        field: 'imageUrl'\n    },\n    imageSource: {\n        type: Sequelize.STRING,\n        field: 'imageSource'\n    },\n    description_id: {\n        type: Sequelize.INTEGER,\n        field: 'description_id'\n    }\n});\n\nmodule.exports = Images;\n```\n\n```text\ncolor: {\n    type: Sequelize.STRING,\n    field: 'color'\n}\n```\n\n```text\ncolor: {\n  type: sequelize.STRING,\n  field: 'color'\n}\n```\n\n```text\nsequelize.define()\n```\n\n```text\nSequelize\n```\n\n========================================\n\nComments:\n- This doc page shows the type as `Sequelize.STRING` not `sequelize.STRING`. Note the leading capital S.\n- Don't see it that way here: docs.sequelizejs.com/en/latest/docs/getting-started/&hellip;\n- Did you read: docs.sequelizejs.com/en/latest/docs/models-definition, I just change `sequelize` to `Sequelize`. It works for you?","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":226,"estimatedTokens":1773}}610{"id":"stack-61432426","source":"stackoverflow","questionId":61432426,"title":"how to configure the __dirname to point to project directory in node?","tags":["node.js","sequelize.js"],"text":"Title: how to configure the __dirname to point to project directory in node?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am adding a sequelize to my node project, it adds the following index.js file as a part of the setup, but when I run the project the __dirname resolves to my C: directory instead of the project root folder \nC:\\workspace\\myapp. How do I configure it so that it resolves to my project root directory? \n\nindex.js file \n\n```\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(__dirname + '/../config.json')[env];\nconst db = {};\n\nlet sequelize;\nif (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs.readdirSync(__dirname)\n .filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n .forEach(file => {\n const model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\npackage.json\n\n```\n{\n \"name\": \"my-app-model\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"next dev\",\n \"build\": \"next build\",\n \"format\": \"prettier --write \\\"src/**/*.{js,jsx,ts,tsx}\\\"\",\n \"start\": \"next start\",\n \"type-check\": \"tsc\"\n },\n \"dependencies\": {\n \"@material-ui/core\": \"^4.8.3\",\n \"@material-ui/lab\": \"4.0.0-alpha.39\",\n \"mysql\": \"^2.18.1\",\n \"mysql2\": \"^2.1.0\",\n \"next\": \"9.1.7\",\n \"prettier\": \"^1.19.1\",\n \"react\": \"16.12.0\",\n \"react-dom\": \"16.12.0\",\n \"sequelize\": \"^5.21.7\",\n \"sequelize-cli\": \"^5.5.1\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^13.1.6\",\n \"@types/react\": \"^16.9.17\",\n \"@types/react-dom\": \"^16.9.4\",\n \"typescript\": \"^3.7.4\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nI've had success using `rootrequire` (archived in favor of ES6 modules): https://github.com/ericelliott/rootrequire\n\n```\nconst root = require('rootrequire'); // project root path\n const myLib = require(`${root}/path/to/lib.js`);\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(__dirname + '/../config.json')[env];\nconst db = {};\n\nlet sequelize;\nif (config.use_env_variable) {\n  sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n  sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs.readdirSync(__dirname)\n  .filter(file => {\n    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n  })\n  .forEach(file => {\n    const model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(modelName => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n{\n  \"name\": \"my-app-model\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next build\",\n    \"format\": \"prettier --write \\\"src/**/*.{js,jsx,ts,tsx}\\\"\",\n    \"start\": \"next start\",\n    \"type-check\": \"tsc\"\n  },\n  \"dependencies\": {\n    \"@material-ui/core\": \"^4.8.3\",\n    \"@material-ui/lab\": \"4.0.0-alpha.39\",\n    \"mysql\": \"^2.18.1\",\n    \"mysql2\": \"^2.1.0\",\n    \"next\": \"9.1.7\",\n    \"prettier\": \"^1.19.1\",\n    \"react\": \"16.12.0\",\n    \"react-dom\": \"16.12.0\",\n    \"sequelize\": \"^5.21.7\",\n    \"sequelize-cli\": \"^5.5.1\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^13.1.6\",\n    \"@types/react\": \"^16.9.17\",\n    \"@types/react-dom\": \"^16.9.4\",\n    \"typescript\": \"^3.7.4\"\n  }\n}\n```\n\n```text\nconst modelsDir = path.resolve(process.cwd(), 'path/to/models')\nfs.readdirSync(modelsDir)\n  .filter(....\n```\n\n```text\nError: Cannot find module '/Applications'\nRequire stack:\n- /Users/username/src/mariner-next/node_modules/sequelize/lib/sequelize.js\n- /Users/username/src/mariner-next/node_modules/sequelize/index.js\n- /Users/username/src/mariner-next/.next/server/static/development/pages/api/graphql.js\n- /Users/username/src/mariner-next/node_modules/next/dist/next-server/server/next-server.js\n- /Users/username/src/mariner-next/node_modules/next/dist/server/next.js\n- /Users/username/src/mariner-next/node_modules/next/dist/server/lib/start-server.js\n- /Users/username/src/mariner-next/node_modules/next/dist/cli/next-dev.js\n- /Users/username/src/mariner-next/node_modules/next/dist/bin/next\n    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:981:15)\n    at Function.Module._load (internal/modules/cjs/loader.js:863:27)\n    at Module.require (internal/modules/cjs/loader.js:1043:19)\n    at require (internal/modules/cjs/helpers.js:77:18)\n    at Sequelize.import (/Users/username/src/mariner-next/node_modules/sequelize/lib/sequelize.js:481:62)\n    at eval (webpack-internal:///./tnr/lib/models/index.js:60:36)\n    at Array.forEach (<anonymous>)\n    at Module.eval (webpack-internal:///./tnr/lib/models/index.js:58:4)\n```\n\n```text\n__dirname\n```\n\n```text\n__dirname\n```\n\n```text\nmodels/index.js\n```\n\n```text\n__dirname\n```\n\n```text\n\"/\"\n```\n\n```text\nfs.readdrSync(__dirname)\n```\n\n```text\nconst root = require('rootrequire'); // project root path\n  const myLib = require(`${root}/path/to/lib.js`);\n```\n\n```text\nrootrequire\n```\n\n========================================\n\nComments:\n- Depends on how you run the project.\n- @Anatoly - thanks. so how should i run it?\n- __dirname is a path of a script you run as an entry point. Check how you run it and from where\n- Ok. show your \"run\" command from package.json\n- maybe 'next' is running with c:\\ as working directory?\n- Stop. How do you run your backend server?\n- I don't run the backend server separetely. I have one next.js project.","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":239,"estimatedTokens":1554}}611{"id":"stack-52937747","source":"stackoverflow","questionId":52937747,"title":"How to add an instance method in Sequelize model","tags":["node.js","sequelize.js"],"text":"Title: How to add an instance method in Sequelize model\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI would like to add an instance method to `Sequelize` `User` model with `postgres`. `User` model is defined as below:\n\n```\nconst Sql = require('sequelize');\nconst db = require(\"../startup/db\");\n\nconst User = db.define('user', {\n id: {type: Sql.INTEGER,\n primaryKey:true,\n min: 1},\n name: {type: Sql.STRING,\n allowNull: false,\n min: 2,\n max: 50\n },\n email: {type: Sql.STRING,\n isEmail: true}, \n encrypted_password: {type: Sql.STRING,\n min: 8},\n createdAt: Sql.DATE,\n updatedAt: Sql.DATE\n});\n```\n\nI am looking for something like this in model `User`:\n\n```\nUser.instanceMethods.create(someMethod => function() {\n //method code here\n });\n```\n\nThe instance method can be access like this:\n\n```\nlet user = new User();\nuser.someMethod();\n```\n\nThere is `Instance` for model in `Sequelize` but it was not for the instance method. What is the right way to add instance method in `Sequelize` model?\n\n========================================\n\nTop Answer:\n```\nconst User = db.define('user', {\n id: {type: Sql.INTEGER,\n primaryKey:true,\n min: 1},\n name: {type: Sql.STRING,\n allowNull: false,\n min: 2,\n max: 50\n },\n email: {type: Sql.STRING,\n isEmail: true}, \n encrypted_password: {type: Sql.STRING, min: 8},\n createdAt: Sql.DATE,\n updatedAt: Sql.DATE\n});\n\n// This is an hook function\nUser.beforeSave((user, options) => {\n // Do something\n});\n\n// This is a class method\nUser.classMethod = function (params) {\n // Do something with params\n}\n\n// This is an instance method\nUser.prototype.instanceMethod = function (params) {\n // Do something with params\n}\n```\n\n========================================\n\nCode:\n```text\nconst Sql = require('sequelize');\nconst db = require(\"../startup/db\");\n\nconst User = db.define('user', {\n    id: {type: Sql.INTEGER,\n         primaryKey:true,\n         min: 1},\n    name: {type: Sql.STRING,\n           allowNull: false,\n           min: 2,\n           max: 50\n        },\n    email: {type: Sql.STRING,\n            isEmail: true},       \n    encrypted_password: {type: Sql.STRING,\n                         min: 8},\n    createdAt: Sql.DATE,\n    updatedAt: Sql.DATE\n});\n```\n\n```text\nUser.instanceMethods.create(someMethod => function() {\n   //method code here\n   });\n```\n\n```text\nlet user = new User();\nuser.someMethod();\n```\n\n```text\nSequelize\n```\n\n```text\nUser\n```\n\n```text\npostgres\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nInstance\n```\n\n```text\nSequelize\n```\n\n```text\nSequelize\n```\n\n```text\nMariano\n```\n\n```text\nconst User = db.define('user', {\n    id: {type: Sql.INTEGER,\n         primaryKey:true,\n         min: 1},\n    name: {type: Sql.STRING,\n           allowNull: false,\n           min: 2,\n           max: 50\n        },\n    email: {type: Sql.STRING,\n            isEmail: true},       \n    encrypted_password: {type: Sql.STRING, min: 8},\n    createdAt: Sql.DATE,\n    updatedAt: Sql.DATE\n});\n\n\n// This is an hook function\nUser.beforeSave((user, options) => {\n   // Do something\n});\n\n// This is a class method\nUser.classMethod = function (params) {\n    // Do something with params\n}\n\n// This is an instance method\nUser.prototype.instanceMethod = function (params) {\n    // Do something with params\n}\n```\n\n========================================\n\nComments:\n- So the user user938363 posts a question. And then he adds a simple link as an \"answer\". And then he decides that his link is the proper answer, despite the fact that another user (Ugo Giordano) posted an actual answer with useful working code below. Uhmm, interesting!\n- This should be selected as the real answer of the question. And not the link posted by the owner of the question.","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":193,"estimatedTokens":921}}612{"id":"stack-60942051","source":"stackoverflow","questionId":60942051,"title":"Sequelize with asynchronous configuration in nodejs","tags":["javascript","node.js","amazon-web-services","asynchronous","sequelize.js"],"text":"Title: Sequelize with asynchronous configuration in nodejs\nTags: javascript, node.js, amazon-web-services, asynchronous, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have been bashing my head for days as I cannot find a valid example of async configuration in Sequelize \n\nSo as you may know, you can simply config a Sequelize instance like that \n\n```\nconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname')\n```\n\nand then declare your Model\n\n```\nconst User = sequelize.define('User', {\n // Model attributes are defined here\n firstName: {\n type: DataTypes.STRING,\n allowNull: false\n },\n lastName: {\n type: DataTypes.STRING\n // allowNull defaults to true\n }\n}, {\n // Other model options go here\n});\n```\n\nHowever what happens when the db credentials comes from an external service? \n\n```\nconst credentials = await getDbCredentials();\nconst sequelize = new Sequelize({credentials})\n```\n\nsince sequelize models creation are coupled with the instance creation (unlike many others ORMs) this becomes a big problem.\n\nMy current solution is the following:\n\n```\nconst Sequelize = require(\"sequelize\");\n\n// Models\nconst { User } = require(\"./User\");\n\nconst env = process.env.NODE_ENV || \"development\";\nconst db = {};\n\nlet sequelize = null;\n\nconst initSequelize = async () => {\n if (!sequelize) {\n let configWithCredentials = {};\n\n if (env === \"production\") {\n const credentials = await getDbCredentials();\n const { password, username, dbname, engine, host, port } = credentials;\n configWithCredentials = {\n username,\n password,\n database: dbname,\n host,\n port,\n dialect: engine,\n operatorsAliases: 0\n };\n }\n\n const config = {\n development: {\n // Dev config \n },\n production: configWithCredentials,\n };\n\n sequelize = new Sequelize(config[env]);\n\n sequelize.authenticate().then(() => {\n console.log(\"db authenticated\")\n });\n });\n }\n\n db.User = User;\n\n db.sequelize = sequelize;\n db.Sequelize = Sequelize;\n};\n\ninitSequelize().then(() => {\n console.log(\"done\");\n});\n\nmodule.exports = db;\n```\n\nHowever I feel that this is not a good approach because of the asynchronous nature of the initialization and sometimes the `db` is undefined.\nIs there a better way to approach this thing?\nThanks\n\n========================================\n\nTop Answer:\nI think your db is sometimes undefined, because in your async function you're not \"waiting\" for the resolution of sequelize.authenticate(). Change this:\n\n```\nsequelize.authenticate().then(() => {\n console.log(\"db authenticated\")\n });\n```\n\nTo this:\n\n```\nawait sequelize.authenticate()\n\n console.log(\"db authenticated\")\n```\n\nWhat was happening, is that your initSequelize async function would resolve, before sequelize.authenticate promise would. This is a common pitfall in JS. I think this adjustment will solve your problem. Regarding \"the best approach\", i don't see much that can be done here, but of course i don't have the entire picture.\n\n========================================\n\nCode:\n```text\nconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname')\n```\n\n```text\nconst User = sequelize.define('User', {\n  // Model attributes are defined here\n  firstName: {\n    type: DataTypes.STRING,\n    allowNull: false\n  },\n  lastName: {\n    type: DataTypes.STRING\n    // allowNull defaults to true\n  }\n}, {\n  // Other model options go here\n});\n```\n\n```js\nconst credentials = await getDbCredentials();\nconst sequelize = new Sequelize({credentials})\n```\n\n```js\nconst Sequelize = require(\"sequelize\");\n\n// Models\nconst { User } = require(\"./User\");\n\nconst env = process.env.NODE_ENV || \"development\";\nconst db = {};\n\nlet sequelize = null;\n\nconst initSequelize = async () => {\n  if (!sequelize) {\n      let configWithCredentials = {};\n\n      if (env === \"production\") {\n        const credentials = await getDbCredentials();\n        const { password, username, dbname, engine, host, port } = credentials;\n        configWithCredentials = {\n          username,\n          password,\n          database: dbname,\n          host,\n          port,\n          dialect: engine,\n          operatorsAliases: 0\n        };\n      }\n\n      const config = {\n        development: {\n          // Dev config \n        },\n        production: configWithCredentials,\n      };\n\n      sequelize = new Sequelize(config[env]);\n\n      sequelize.authenticate().then(() => {\n         console.log(\"db authenticated\")\n        });\n      });\n  }\n\n  db.User = User;\n\n  db.sequelize = sequelize;\n  db.Sequelize = Sequelize;\n};\n\ninitSequelize().then(() => {\n  console.log(\"done\");\n});\n\nmodule.exports = db;\n```\n\n```text\ndb\n```\n\n```text\nsequelize = new Sequelize(config.database, '', '', config);\nsequelize.beforeConnect(async (config) => {\n    config.username = await getSecretUsername();\n    config.password = await getSecretPassword();\n});\n```\n\n```text\nsequelize.authenticate().then(() => {\n         console.log(\"db authenticated\")\n        });\n```\n\n```text\nawait sequelize.authenticate()\n\n console.log(\"db authenticated\")\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst { Model } = Sequelize\n\nclass User extends Model {\n  static get modelFields(){\n    return {\n      id: {\n        type: Sequelize.UUID,\n        primaryKey: true,\n        defaultValue: Sequelize.UUIDV4,\n      },\n      name: {\n        type: Sequelize.STRING,\n        allowNull: false,\n        unique: true,\n      }\n    }\n  }\n  static get modelOptions(){\n    return {\n      version: true,\n    }\n  }\n  static init(sequelize){\n    const options = { ...this.modelOptions, sequelize }\n    return super.init(this.modelFields, options)\n  }\n  static associate(models) {\n    this.hasMany(models.Task)\n  }\n}\n\nmodule.exports = User\n```\n\n```text\nconst User = require('./User')\n\nclass Database {\n   async static setup(){\n     const credentials = await getCredentials()\n     this.sequelize = new Sequelize(credentials)\n     User.init(this.sequelize)\n     this.User = User\n     // When you have multiple models to associate add:\n     this.User.associate(this)\n   }\n}\n\nmodule.exports = Database\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize.define\n```\n\n```text\nModel.init\n```\n\n```text\n.listen()\n```\n\n```text\nDatabase.setup()\n```\n\n```text\n./getEnv exec -- node index.js\n```\n\n```js\nconst { Sequelize } = require('sequelize');\nconst asyncFetch = require('../util/async-fetch');\n\nconst sequelize = new Sequelize({\n  dialect: 'mysql',\n  database: 'db_name',\n  host: '127.0.0.1'\n});\n\nsequelize.beforeConnect(async (config) => {\n  const [username, password] = await Promise.all([\n    asyncFetch('username'),\n    asyncFetch('password')\n  ]);\n  config.username = username;\n  config.password = password;\n});\n\nmodule.exports = sequelize;\n```\n\n========================================\n\nComments:\n- But the async function keeps running\n- Oh i see what your getting at... `.authenticate()` isn't required to setup a sequelize connection.\n- It does initiate a connection to test it, but an app will be able to use the DB without it.\n- Wait..but was i right or wrong about the \"then\" issue? Let's put aside the sequelize stuff, there is a very fundamental thing here which i have to understand :D You have a very high score and i trust you :D\n- What you pointed out is correct, sorry! :) The async function wasn't waiting for that promise to complete. It just happens not to impact anything in this instance.\n- actually the databse gets authenticated correctly, is the db object and the entities that do not get populated.\n- But will I need to run that `setup()` method every time I need to access the db object?\n- I have the slight sensation that I would need to pass it down via app context\n- `Database.sequelize` or `User` can be used once the connection is setup.\n- I have this problem too. I wish sequelize had allowed us to pass in async way to write configurations. Knex allows this.\n- i think this should be the accepted answer now. the documentation explicitly says this \"These hooks can be useful if you need to asynchronously obtain database credentials, or need to directly access the low-level database connection after it has been created.\"","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":346,"estimatedTokens":2007}}613{"id":"stack-59016613","source":"stackoverflow","questionId":59016613,"title":"Sequelize find all where currentUserEditor is not null","tags":["node.js","sequelize.js"],"text":"Title: Sequelize find all where currentUserEditor is not null\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow i find all from table where currentUserEditor !== null ?\n\nI need to check if currentUserEditor and if it null other user can edit things but if there is a user that not null other user can edit.\n\n========================================\n\nTop Answer:\nOther way is:\n\n```\nconst Op = require('sequelize').Op;\n\n Model.findAll({\n where: {\n currentUserEditor: {[Op.not]: null}\n }\n })\n```\n\nBecause it generate a query similar with this:\n\n```\nSELECT * FROM \"Model\" AS \"Model\" WHERE \"Model\".\"currentUserEditor\" IS NOT NULL\n```\n\n========================================\n\nCode:\n```text\nconst Op = require('sequelize').Op;\n\n    Model.findAll({\n      where: {\n         currentUserEditor: {[Op.ne]: null}\n      }\n    })\n```\n\n```text\nconst Op = require('sequelize').Op;\n\n    Model.findAll({\n      where: {\n         currentUserEditor: {[Op.not]: null}\n      }\n    })\n```\n\n```text\nSELECT * FROM \"Model\" AS \"Model\" WHERE \"Model\".\"currentUserEditor\" IS NOT NULL\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":56,"estimatedTokens":269}}614{"id":"stack-63611772","source":"stackoverflow","questionId":63611772,"title":"sequelize does not creating a table shows this result : \"Executing (default): SELECT 1+1 AS result\"","tags":["javascript","mysql","sequelize.js"],"text":"Title: sequelize does not creating a table shows this result : \"Executing (default): SELECT 1+1 AS result\"\nTags: javascript, mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI try to create a table using sequelize it goes fine with no error but instead of creating a table is show this message as a result\n\n```\nExecuting (default): SELECT 1+1 AS result\n```\n\nhere my config file:\n\n```\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('*******', '******', '*******', {\n dialect: 'mysql',\n host: 'localhost',\n});\n\nmodule.exports = sequelize;\n```\n\nhere my user.js file:\n\n```\nconst Sequelize = require('sequelize');\n\nconst sequelize = require('../db/mysql/config');\n\nconst User = sequelize.define('user', {\n id: {\n type: Sequelize.INREGER,\n autoIncrement: true,\n allowNull: false,\n primaryKey: true\n },\n userName: {\n type: Sequelize.STRING,\n allowNull: false\n },\n email: {\n type: Sequelize.STRING,\n allowNull: false\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false\n }\n\n});\n\nmodule.exports = User;\n```\n\nand this is my test.js file i run it with node commend:\n\n```\nconst sequelize = require('./db/mysql/config')\n\nsequelize\n .sync()\n .then(result => {\n console.log(result);\n })\n .catch(err => {\n console.log(err);\n })\n```\n\nif I copy user.js code inside config file it works fine\n\n========================================\n\nTop Answer:\nBecause you are not exporting the Tables you have created.\n\n- In your file you have created user.js, so you have to export it and make sure you are hitting(synchronizing) that table, either you can sync a particular table, or you can sync all the tables(models) at once.\n\nHow you can sync a Particular table (model)?\n\n- In your root file(which starts the application), you import the user.js\n\n**import user.js from ('your path to the file')**\n\nNow write\n**modelName.sync();**\n\nHow you can hit(sync) all the tables at once?\n\n- After you created all the models, you have to export it\n\n- Then in your root file, write the following\n\n\r\n\r\n\n```\nsequelize.sync()\n```\n\n========================================\n\nCode:\n```text\nExecuting (default): SELECT 1+1 AS result\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('*******', '******', '*******', {\n    dialect: 'mysql',\n    host: 'localhost',\n});\n\nmodule.exports = sequelize;\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = require('../db/mysql/config');\n\nconst User = sequelize.define('user', {\n    id: {\n        type: Sequelize.INREGER,\n        autoIncrement: true,\n        allowNull: false,\n        primaryKey: true\n    },\n    userName: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    email: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING,\n        allowNull: false\n    }\n\n});\n\n\nmodule.exports = User;\n```\n\n```text\nconst sequelize = require('./db/mysql/config')\n\nsequelize\n    .sync()\n    .then(result => {\n        console.log(result);\n    })\n    .catch(err => {\n        console.log(err);\n    })\n```\n\n```text\nconst User = require('enter your path here for user.js')\n\n     User.sync();\n```\n\n```js\nsequelize.sync()\n```\n\n```text\nconst {DataTypes, Model} = require('sequelize');\n\n// on importe la connexion\nconst sequelize = require('./../database');\n\nclass User extends Model {\n}\n\nUser.init({\n        username: {\n            type: DataTypes.STRING,\n            allowNull: false\n        },\n        email: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            unique: true\n        },\n        password: {\n            type: DataTypes.STRING,\n            allowNull: false\n        },\n        roles: {\n            type: DataTypes.JSON,\n            defaultValue: {\"roles\":[{\n                    \"role_name\":\"ROLE_USER\",\n                }\n            ]},\n        },\n        status: {\n            type: DataTypes.BOOLEAN,\n            defaultValue: false\n        },\n        birthday: {\n            type: DataTypes.DATE,\n            allowNull: false\n        },\n        filename: DataTypes.STRING,\n        activation_token: DataTypes.STRING,\n\n    },\n    {\n        underscored: true,\n        sequelize, //connexion a l'instance\n        timestamps: true,\n        tableName: 'user'\n    }\n);\n\nUser.sync({ alter: true });\nconsole.log(\"==> The table for the User model was just (re)created!\");\n\nmodule.exports = User;\n```\n\n```text\nconst {Sequelize} = require('sequelize');\n\nconst sequelize = new Sequelize(process.env.PG_URL, {});\n\nmodule.exports = sequelize;\n```\n\n```text\nconst User      = require('./user');\nconst Category  = require('./category');\n    ...\nmodule.exports = { User, Category };\n```\n\n```text\nconst models = require('./app/models'); //By default load index.js inside /app/models\nconst sequelize = require('./app/database');\n\nconst init_BDD = async () => {\n    try {\n        await sequelize.authenticate();\n        console.log('Connection has been established successfully.');\n        const created =  sequelize.sync({force: true});\n\n        if(created) {\n            console.log(\"==> TABLE DONE !\");\n        }\n\n    } catch (error) {\n        console.error('Unable to connect to the database:', error);\n    }\n} \ninit_BDD();\n```\n\n```text\n/app/models\n```\n\n```text\n/app/database.js\n```\n\n```text\n/app/models\n```\n\n```text\nindex.js\n```\n\n```text\ninit_models_db.js\n```\n\n```text\nnode init_models_db.js\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('*******', '******', '*******', {\n    dialect: 'mysql',\n    host: 'localhost',\n    logging: false\n\n});\n\nmodule.exports = sequelize;\n```\n\n```text\n'logging: false'\n```\n\n```text\nconst User = require('models/user');\n```\n\n```text\nconst sequelize = require('./db/mysql/config')\n\nsequelize\n    .sync()\n    .then(result => {\n        console.log(result);\n    })\n    .catch(err => {\n        console.log(err);\n    })\n```\n\n```text\nconst sequelize = require('./models/user')\n```\n\n========================================\n\nComments:\n- I tried that its give this error message: TypeError: sequelize.define is not a function\n- In your test.js file replace const sequelize as `const Sequelize = require('sequelize');`","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":333,"estimatedTokens":1540}}615{"id":"stack-53269920","source":"stackoverflow","questionId":53269920,"title":"JavaScript: Promise.All() and Async / Await and Map()","tags":["javascript","asynchronous","promise","async-await","sequelize.js"],"text":"Title: JavaScript: Promise.All() and Async / Await and Map()\nTags: javascript, asynchronous, promise, async-await, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to understand why the following two code blocks yield different results.\n\nCode Block one works as expected and returns an array of the providers looked up from the database. On the other hand, Code Block two returns an array of functions. I feel like I'm missing something simple here in my understanding of Promise.all() and async / await.\n\nThe differences in the code blocks are:\n\nBlock 1: Array of promise functions is created and then wrapped in async functions using the map operator.\n\nBlock 2: Array of promises functions are created as async functions. Therefore, the map operator isn't called.\n\nIn case you aren't familiar with the Sequelize library, the findOne() method that gets called returns a promise.\n\nAlso worth mentioning, I know that I could use a single find query with and \"name in\" where clause to get the same results without creating an array of promises for multiple select queries. I'm doing this simply as a learning exercise on async / await and Promise.all(). \n\n**CODE BLOCK 1: Using map() inside Promise.all()**\n\n```\nprivate async createProfilePromises(profiles){\n\n let profileProviderFindPromises = [];\n\n //Build the Profile Providers Promises Array.\n profiles.forEach(profile => {\n profileProviderFindPromises.push(\n () => {\n return BaseRoute.db.models.ProfileProvider.findOne({\n where: {\n name: {[BaseRoute.Op.eq]: profile.profileProvider}\n }\n })}\n );\n });\n\n //Map and Execute the Promises\n let providers = await Promise.all(profileProviderFindPromises.map(async (myPromise) =>{\n try{\n return await myPromise();\n }catch(err){\n return err.toString();\n }\n }));\n\n //Log the Results\n console.log(providers);\n}\n```\n\n**CODE BLOCK 2: Adding the async function without the use of map()**\n\n```\nprivate async createProfilePromises(profiles){\n\n let profileProviderFindPromises = [];\n\n //Build the Profile Providers Promises Array.\n profiles.forEach(profile => {\n profileProviderFindPromises.push(\n async () => {\n try{\n return await BaseRoute.db.models.ProfileProvider.findOne({\n where: {\n name: {[BaseRoute.Op.eq]: profile.profileProvider}\n }\n });\n }catch(e){\n return e.toString();\n }\n }\n );\n });\n\n //Execute the Promises\n let providers = await Promise.all(profileProviderFindPromises);\n\n //Log the Results\n console.log(providers);\n}\n```\n\n========================================\n\nCode:\n```text\nprivate async createProfilePromises(profiles){\n\n    let profileProviderFindPromises = [];\n\n    //Build the Profile Providers Promises Array.\n    profiles.forEach(profile => {\n        profileProviderFindPromises.push(\n            () => {\n                return BaseRoute.db.models.ProfileProvider.findOne({\n                    where: {\n                        name: {[BaseRoute.Op.eq]: profile.profileProvider}\n                    }\n                })}\n        );\n    });\n\n    //Map and Execute the Promises\n    let providers = await Promise.all(profileProviderFindPromises.map(async (myPromise) =>{\n        try{\n            return await myPromise();\n        }catch(err){\n            return err.toString();\n        }\n    }));\n\n    //Log the Results\n    console.log(providers);\n}\n```\n\n```text\nprivate async createProfilePromises(profiles){\n\n    let profileProviderFindPromises = [];\n\n    //Build the Profile Providers Promises Array.\n    profiles.forEach(profile => {\n        profileProviderFindPromises.push(\n            async () => {\n                try{\n                    return await BaseRoute.db.models.ProfileProvider.findOne({\n                        where: {\n                            name: {[BaseRoute.Op.eq]: profile.profileProvider}\n                        }\n                    });\n                }catch(e){\n                    return e.toString();\n                }\n            }\n        );\n    });\n\n    //Execute the Promises\n    let providers = await Promise.all(profileProviderFindPromises);\n\n    //Log the Results\n    console.log(providers);\n}\n```\n\n```text\nconst array = [1, 2, 3];\n\n  function fn() { return 1; }\n\n  array.map(fn); // [1, 1, 1]\n\n  array.push(fn);\n  console.log(array); // [1, 2, 3, fn]\n```\n\n```text\narray.push(fn());\n```\n\n```text\narray.push((async () => { /*...*/ })());\n```\n\n```text\nreturn Promise.all(profiles.map(async profile => {\n   try{\n     return await BaseRoute.db.models.ProfileProvider.findOne({\n       where: {\n         name: { [BaseRoute.Op.eq]: profile.profileProvider }\n       }\n     });\n  } catch(e) {\n    // seriously: does that make sense? :\n    return e.toString();\n  }\n}));\n```\n\n```text\nasync\n```\n\n========================================\n\nComments:\n- Uh, just don't build an array of functions. Both your `profileProviderFindPromises` arrays actually contain functions, not promises.","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":190,"estimatedTokens":1208}}616{"id":"stack-60220308","source":"stackoverflow","questionId":60220308,"title":"Sequelize: create is not a function when model is generated from migration","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize: create is not a function when model is generated from migration\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI created this model from sequelize CLI \n\n**models/society.js**\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const Society = sequelize.define('Society', {\n code: DataTypes.STRING,\n name: DataTypes.STRING,\n description: DataTypes.STRING\n }, {});\n Society.associate = function(models) {\n // associations can be defined here\n };\n return Society;\n};\n```\n\nThen this is my **index.js** file for configurations\n\n```\n'use strict'\n\nconst express = require('express')\nconst bodyParser = require('body-parser')\nconst app = express()\nconst api = require('./routes')\n\napp.use(bodyParser.urlencoded({extended: false}))\napp.use(bodyParser.json())\napp.use('/api', api)\n\nconst port = process.env.PORT || 3000\n\napp.listen(port, ()=>{\n console.log(`API REST running on http://localhost:${port}`)\n})\n```\n\nThe part of routes is this\n\n**routes/index.js**\n\n```\n'use strict'\n\nconst express = require('express')\nconst api = express.Router()\n\nconst SocietyCtrl = require('../controllers/society')\napi.post('/society', SocietyCtrl.createSociety)\n\nmodule.exports = api\n```\n\nAnd finally it's just the controller\n**controllers/society.js**\n\n```\n'use strict'\n\nconst Society = require('../models/society')\n\nfunction createSociety(req, res){\n console.log('POST /api/society/')\n Society.create(req.body).then(created =>{\n res.status(200).send({society: created})\n })\n}\n\nmodule.exports = {\n createSociety\n}\n```\n\nThe problem comes when I try to make POST, I get this following error:\n\n*Society.create is not a function*\n\nCan you tell me what I'm doing wrong?\n\n========================================\n\nTop Answer:\nThis problem is not related to migration, however to solve this problem you have to do two steps:\n\n**1)** Add new file in `models` directory called `index.js` which contain the following code\n\n **NOTE:** make sure to edit sequelize config (with your environment) which starts in line `9` and ends in line `13` in file below (`models/index.js`)\n\n```\n'use strict';\n\nconst Sequelize = require('sequelize');\nconst fs = require('fs');\nconst path = require('path');\nconst basename = path.basename(__filename);\n\nconst db = {};\n\nconst sequelize = new Sequelize('database', 'username', 'password', {\n host: 'localhost',\n port: 3066,\n dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */\n});\n\nfs.readdirSync(__dirname).filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n}).forEach(file => {\n const model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n});\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\nmodule.exports = db;\n```\n\n**2)** in `controllers/society.js` file do the following\n\n- replace `const Society = require('../models/society');` with `const db = require('../models/index');` or `const db = require('../models');`\n\n- replace `Society.create` with `db.Society.create`\n\nlike this:\n\n```\n'use strict'\n\nconst db = require('../models');\n\nfunction createSociety(req, res){\n console.log('POST /api/society/');\n db.Society.create(req.body).then(created =>{\n res.status(200).send({society: created})\n });\n}\n\nmodule.exports = {\n createSociety\n}\n```\n\nTo learn more I recommend you to check a github repository called express-example which developed by official sequelize team\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n  const Society = sequelize.define('Society', {\n    code: DataTypes.STRING,\n    name: DataTypes.STRING,\n    description: DataTypes.STRING\n  }, {});\n  Society.associate = function(models) {\n    // associations can be defined here\n  };\n  return Society;\n};\n```\n\n```text\n'use strict'\n\nconst express = require('express')\nconst bodyParser = require('body-parser')\nconst app = express()\nconst api = require('./routes')\n\napp.use(bodyParser.urlencoded({extended: false}))\napp.use(bodyParser.json())\napp.use('/api', api)\n\nconst port = process.env.PORT || 3000\n\n\napp.listen(port, ()=>{\n    console.log(`API REST running on http://localhost:${port}`)\n})\n```\n\n```text\n'use strict'\n\nconst express = require('express')\nconst api = express.Router()\n\nconst SocietyCtrl = require('../controllers/society')\napi.post('/society', SocietyCtrl.createSociety)\n\nmodule.exports = api\n```\n\n```text\n'use strict'\n\nconst Society = require('../models/society')\n\nfunction createSociety(req, res){\n    console.log('POST /api/society/')\n    Society.create(req.body).then(created =>{\n        res.status(200).send({society: created})\n    })\n}\n\nmodule.exports = {\n    createSociety\n}\n```\n\n```text\n'use strict'\n\nconst db = require('../models/index')\nconst Society = db.Society\n```\n\n```text\nmodels\n```\n\n```text\n'use strict';\n\nconst Sequelize = require('sequelize');\nconst fs = require('fs');\nconst path = require('path');\nconst basename = path.basename(__filename);\n\nconst db = {};\n\nconst sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  port: 3066,\n  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */\n});\n\nfs.readdirSync(__dirname).filter(file => {\n  return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n}).forEach(file => {\n  const model = sequelize['import'](path.join(__dirname, file));\n  db[model.name] = model;\n});\n\nObject.keys(db).forEach(modelName => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\nmodule.exports = db;\n```\n\n```text\n'use strict'\n\nconst db = require('../models');\n\nfunction createSociety(req, res){\n    console.log('POST /api/society/');\n    db.Society.create(req.body).then(created =>{\n        res.status(200).send({society: created})\n    });\n}\n\nmodule.exports = {\n    createSociety\n}\n```\n\n```text\nmodels\n```\n\n```text\nindex.js\n```\n\n```text\n9\n```\n\n```text\n13\n```\n\n```text\nmodels/index.js\n```\n\n```text\ncontrollers/society.js\n```\n\n```text\nconst Society = require('../models/society');\n```\n\n```text\nconst db = require('../models/index');\n```\n\n```text\nconst db = require('../models');\n```\n\n```text\nSociety.create\n```\n\n```text\ndb.Society.create\n```\n\n========================================\n\nComments:\n- have you tried Society.Society.create() ?\n- You can use `console.log(Society.create)` to check what it is. Make sure your models are organized correctly.\n- Because **models/society.js** return a function\n- Does this answer your question? sequelize .create is not a function error","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":333,"estimatedTokens":1644}}617{"id":"stack-57092309","source":"stackoverflow","questionId":57092309,"title":"How to use like in where condition in sequelize, node js","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: How to use like in where condition in sequelize, node js\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to filter the data from table in which i want to use multiple condition. when i apply like in query it show application error.\nhow to do the same?\n\nI am using nodejs framework, express, sequelize and mysql. \n\n```\nrouter.get('/booking-information', function (req, res) {\n // Get orders\n Promise.all([Order.findAll({\n /*where: {\n endDate: null,\n },*/\n order: [\n ['id', 'DESC'],\n ]\n }),\n Professional.findAll({where: {status : '1'}})\n ])\n .then(([orders, professionals]) => {\n orders.map((order) => {\n let professionalsInSameArea = professionals.filter((professional) => {\n return (professional.service === order.service || professional.secondary_service LIKE '%' + order.service + '%') && (professional.area === order.area || order.area === professional.secondary_area);\n });\n order.professionals = [...professionalsInSameArea]\n return order;\n });\n res.render('booking-information', {title: 'Technician', orders: orders, user: req.user});\n })\n .catch((err) => {\n console.error(err);\n });\n});\n```\n\nI want to filter out the professionals in same area and same service for which a order placed.\n\n========================================\n\nTop Answer:\n```\nyou can use Op operator in query\nlike :-\n\nconst Op = Sequelize.Op\n\n{\n [Op.or]: [\n {\n fieldName: {\n [Op.like]: 'abc%'\n }\n },\n {\n fieldName: {\n [Op.like]: '%abc%'\n }\n }\n ]\n}\n```\n\n========================================\n\nCode:\n```text\nrouter.get('/booking-information', function (req, res) {\n  // Get orders\n  Promise.all([Order.findAll({\n    /*where: {\n      endDate: null,\n    },*/\n    order: [\n    ['id', 'DESC'],\n    ]\n    }),\n    Professional.findAll({where: {status : '1'}})\n  ])\n    .then(([orders, professionals]) => {\n      orders.map((order) => {\n        let professionalsInSameArea = professionals.filter((professional) => {\n          return (professional.service === order.service || professional.secondary_service LIKE '%' + order.service + '%') && (professional.area === order.area || order.area === professional.secondary_area);\n        });\n        order.professionals = [...professionalsInSameArea]\n        return order;\n      });\n      res.render('booking-information', {title: 'Technician', orders: orders, user: req.user});\n    })\n      .catch((err) => {\n        console.error(err);\n      });\n});\n```\n\n```text\nrouter.get('/booking-information', function (req, res) {\n  // Get orders\n  Promise.all([\n    Order.findAll({\n      /*where: {\n        endDate: null,\n      },*/\n      order: [\n        ['id', 'DESC'],\n      ]\n    }),\n    Professional.findAll({\n      where: {\n        status: '1'\n      }\n    })\n  ])\n    .then(([orders, professionals]) => {\n      orders.map((order) => {\n        let professionalsInSameArea = professionals.filter((professional) => {\n          return (professional.service === order.service \n                 || (professional.secondary_service || '').toLowerCase().indexOf((order.service || '').toLowerCase()) > -1) \n            && (professional.area === order.area \n                || order.area === professional.secondary_area);\n        });\n        order.professionals = professionalsInSameArea; //you don't need to spread, then make an array\n        return order;\n      });\n      res.render('booking-information', { title: 'Technician', orders: orders, user: req.user });\n    })\n    .catch((err) => {\n      console.error(err);\n    });\n});\n```\n\n```text\nString.indexOf\n```\n\n```text\nString LIKE %word%\n```\n\n```text\nString\n```\n\n```text\nword\n```\n\n```text\nyou can use Op operator in query\nlike :-\n\nconst Op = Sequelize.Op\n\n{\n  [Op.or]: [\n    {\n      fieldName: {\n        [Op.like]: 'abc%'\n      }\n    },\n    {\n      fieldName: {\n        [Op.like]: '%abc%'\n      }\n    }\n  ]\n}\n```\n\n========================================\n\nComments:\n- Do you want to query the model? what is `orders`, is it the result? Please post a minimal, complete, verifiable exaple.\n- I have added complete code\n- Can any one please help me from this issue: How i can apply in this line: return (professional.service === order.service || professional.secondary_service LIKE '%' + order.service + '%') && (professional.area === order.area || order.area === professional.secondary_area); Is it true or false\n- How i can apply in this line: return (professional.service === order.service || professional.secondary_service LIKE '%' + order.service + '%') && (professional.area === order.area || order.area === professional.secondary_area);\n- Thank you for your response, But it show error: TypeError: Cannot read property 'toLowerCase' of null @Aritra\n- Yes you have to handle nulls as well, depending on the data. I just showed you how can you do this in optimal situation.\n- Handled the nulls for now.","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":183,"estimatedTokens":1203}}618{"id":"stack-57129544","source":"stackoverflow","questionId":57129544,"title":"TypeScript & Sequelize: Pass in generic Model","tags":["typescript","sequelize.js","typescript-generics"],"text":"Title: TypeScript & Sequelize: Pass in generic Model\nTags: typescript, sequelize.js, typescript-generics\nSource: Stack Overflow\n\nQuestion:\nI have this code\n\n```\nimport { Model, DataTypes, Sequelize } from \"sequelize\";\n\nclass User extends Model {\n public id!: number;\n public firstName!: string;\n public readonly createdAt!: Date;\n public readonly updatedAt!: Date;\n}\n\nfunction async InitAndDefineModel(model: Model): void {\n const sequelize = new Sequelize({\n dialect: \"sqlite\",\n storage: \":memory:\",\n });\n model.init{\n firstName: {\n allowNull: false,\n type: DataTypes.STRING,\n },\n },\n {\n sequelize,\n });\n const tables = await sequelize.showAllSchemas({});\n console.log(tables);\n}\n\nInitAndDefineModel(User);\n```\n\nThe console.log statement returns:\n\n```\n// [ { name: 'Users' } ]\n```\n\nSo I know the code works, however, TypeScript complains that:\n\n```\nProperty 'init' is a static member of type 'Model'ts(2576)\n```\n\non the `model.init(...)` call.\n\nI think TS thinks I'm passing in a Model object directory. I guess I need to tell it it's a type of Model, or the object passed in was extended from it.\nHow do I tell TypeScript that the argument `model: Model` is valid? I tried to use `model: Model` and `model: T any other variations, but to no avail.\n\n========================================\n\nCode:\n```js\nimport { Model, DataTypes, Sequelize } from \"sequelize\";\n\nclass User extends Model {\n    public id!: number;\n    public firstName!: string;\n    public readonly createdAt!: Date;\n    public readonly updatedAt!: Date;\n}\n\nfunction async InitAndDefineModel(model: Model): void {\n    const sequelize = new Sequelize({\n        dialect: \"sqlite\",\n        storage: \":memory:\",\n    });\n    model.init{\n        firstName: {\n            allowNull: false,\n            type: DataTypes.STRING,\n        },\n    },\n    {\n        sequelize,\n    });\n    const tables = await sequelize.showAllSchemas({});\n    console.log(tables);\n}\n\nInitAndDefineModel(User);\n```\n\n```text\n// [ { name: 'Users' } ]\n```\n\n```text\nProperty 'init' is a static member of type 'Model<any, any>'ts(2576)\n```\n\n```text\nmodel.init(...)\n```\n\n```text\nmodel: Model\n```\n\n```text\nmodel: Model<T>\n```\n\n```js\ntype ModelStatic = typeof Model & {\n  new(values?: object, options?: Sequelize.BuildOptions): Model;\n}\n```\n\n```js\nfunction async InitAndDefineModel(model: ModelStatic): void\n```\n\n```text\nInitAndDefineModel\n```\n\n```text\nmodel\n```\n\n```text\nSequelize.Model\n```\n\n========================================\n\nComments:\n- I had to tweak your type definition slightly to satisfy TS lint rules to: `type ModelStatic = typeof Model & (new(values?: object, options?: BuildOptions) => Model);`. Aside from that, it worked. Thank you.\n- `export abstract class EntityService { readonly entity; async findById(id: number): Promise { const model = await this.entity.findByPk(id) if (model) return model throw new NotFoundException() } }` Hi, can you help with the above? How would I set types for the property `entity` in `EntityService` class so that I can get intellisense functionality in the findById function?","metadata":{"transformedAt":"2026-08-18T18:33:34.389Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":136,"estimatedTokens":764}}619{"id":"stack-52610961","source":"stackoverflow","questionId":52610961,"title":"Sequelizejs \"isAfter\" validation with other field","tags":["node.js","validation","sequelize.js"],"text":"Title: Sequelizejs \"isAfter\" validation with other field\nTags: node.js, validation, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn the Sequelize's docs, they have mention following way to restrict a date field value to after a certain date.\n\n```\nvalidate: {\n isAfter: '2018-10-02'\n}\n```\n\nBut I want to perform this validation against another date field from `req.body`\n\nLike\n\n```\nvalidate: {\n isAfter: anotherFieldName // fieldname instead of static value\n}\n```\n\n========================================\n\nCode:\n```text\nvalidate: {\n    isAfter: '2018-10-02'\n}\n```\n\n```text\nvalidate: {\n    isAfter: anotherFieldName    // fieldname instead of static value\n}\n```\n\n```text\nreq.body\n```\n\n```text\nconst SomeModel = db.define(\n  'some_model',\n  {\n    start_date: {\n      type: Sequelize.DATEONLY,\n      validate: {\n        isDate: true\n      }\n    },\n    end_date: {\n      type: Sequelize.DATEONLY,\n      validate: {\n        isDate: true\n      }\n    },\n  },\n  {\n    validate: {\n      startDateAfterEndDate() {\n        if (this.start_date.isAfter(this.end_date)) {\n          throw new Error('Start date must be before the end date.');\n        }\n      }\n    }\n  }\n);\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":70,"estimatedTokens":291}}620{"id":"stack-55297499","source":"stackoverflow","questionId":55297499,"title":"in Sequelize after create add in response \"val\": \"CURRENT_TIMESTAMP\" instance of time(2019-03-22 09:56:38)","tags":["sequelize.js"],"text":"Title: in Sequelize after create add in response \"val\": \"CURRENT_TIMESTAMP\" instance of time(2019-03-22 09:56:38)\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn Sequelize after create add in response `\"val\": \"CURRENT_TIMESTAMP\"` instance of **time(2019-03-22 09:56:38)**\nwhat define in code is described below\n\n**model:**\n\n```\ncreated_at: {\n type: DataTypes.DATE,\n allowNull: false,\n defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),\n },\n```\n\n**controller:**\n\n```\nMessage.create(\n {\n col: body.col\n },\n ).then((\n const MessageResponse = response.get({\n plain: true,\n });\n res.send(apiSuccessHandler({}, { MessageResponse, message: 'Your request submitted successfully.' }, 200));\n }).catch((err) => {\n console.log(err);\n res.status(403).send(apiFailureHandler({ message: \"We couldn't save your request, please try again.\" }, {}, 403));\n });\n```\n\n**response:**\n\n```\n{\n \"resultState\": {\n \"status\": 200,\n \"message\": \"Success\"\n },\n \"MessageResponse\": {\n //what i get\n \"created_at\": {\n \"val\": \"CURRENT_TIMESTAMP\"\n },\n //my requirement \n \"created_at\": 2019-03-22 09:56:38,\n \"id\": 60,\n\n },\n \"message\": \"Your request submitted successfully.\"\n}\n```\n\n========================================\n\nTop Answer:\nYou can try this\n\n```\nMessage.create(\n {\n col: body.col,\n created_at: moment(), // add this line\n },\n ).then((\n const MessageResponse = response.get({\n plain: true,\n });\n res.send(apiSuccessHandler({}, { MessageResponse, message: 'Your request submitted successfully.' }, 200));\n}).catch((err) => {\n console.log(err);\n res.status(403).send(apiFailureHandler({ message: \"We couldn't save your request, please try again.\" }, {}, 403));\n});\n```\n\n========================================\n\nCode:\n```text\ncreated_at: {\n              type: DataTypes.DATE,\n              allowNull: false,\n              defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),\n            },\n```\n\n```text\nMessage.create(\n          {\n            col: body.col\n          },\n        ).then((\n          const MessageResponse = response.get({\n            plain: true,\n          });\n       res.send(apiSuccessHandler({}, { MessageResponse, message: 'Your request submitted successfully.' }, 200));\n    }).catch((err) => {\n      console.log(err);\n      res.status(403).send(apiFailureHandler({ message: \"We couldn't save your request, please try again.\" }, {}, 403));\n    });\n```\n\n```text\n{\n    \"resultState\": {\n        \"status\": 200,\n        \"message\": \"Success\"\n    },\n    \"MessageResponse\": {\n        //what i get\n         \"created_at\": {\n            \"val\": \"CURRENT_TIMESTAMP\"\n        },\n        //my requirement \n        \"created_at\": 2019-03-22 09:56:38,\n        \"id\": 60,\n\n    },\n    \"message\": \"Your request submitted successfully.\"\n}\n```\n\n```text\n\"val\": \"CURRENT_TIMESTAMP\"\n```\n\n```text\ncreatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),\n}\n```\n\n```text\ncreated_at: {\n              type: DataTypes.DATE,\n              allowNull: false,\n              defaultValue: moment().format('YYYY-MM-DDTHH:mm:s:ss') + '.000Z',\n            },\n```\n\n```text\ndefaultValue: sequelize.literal('CURRENT_TIMESTAMP')\n```\n\n```text\nsequelize.literal('CURRENT_TIMESTAMP')\n```\n\n```text\n{val: 'CURRENT_TIMESTAMP'}\n```\n\n```text\nMessage.create(\n      {\n        col: body.col,\n        created_at: moment(), // add this line\n      },\n    ).then((\n      const MessageResponse = response.get({\n        plain: true,\n      });\n   res.send(apiSuccessHandler({}, { MessageResponse, message: 'Your request submitted successfully.' }, 200));\n}).catch((err) => {\n  console.log(err);\n  res.status(403).send(apiFailureHandler({ message: \"We couldn't save your request, please try again.\" }, {}, 403));\n});\n```\n\n```text\ncreatedDateTime: {\n    type: DataTypes.DATE,\n    allowNull: false,\n    defaultValue: DataTypes.NOW\n},\n```\n\n```text\ncreatedDateTime: {\n    type: DataTypes.DATE,\n    allowNull: false,\n    defaultValue: moment()\n},\n```\n\n========================================\n\nComments:\n- did you fix this?\n- Kinda defeats the purpose of having a `defaultValue` option...\n- This will determine the default value at interpretation time which means if you're running in a Node server, every defaultValue will just be the time you last restarted the server.","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":198,"estimatedTokens":1069}}621{"id":"stack-67754660","source":"stackoverflow","questionId":67754660,"title":"display attributes without nesting objects using include in (Sequelize)","tags":["node.js","sequelize.js","associations"],"text":"Title: display attributes without nesting objects using include in (Sequelize)\nTags: node.js, sequelize.js, associations\nSource: Stack Overflow\n\nQuestion:\nI have a model SKUValue and it is associated with two other models **VariantOptions** and **ProductVariant**.\nI created a sequelize query that *\"left-joins\"* **SKUValue** value with **VariantOptions** and **ProductVariant**, and brings brings result.\n\n**Sequelize query**\n\n```\nawait SKUValue.findAll({\n where: {\n productId: '7bde8a1d-5f6c-4349-bfda-428399c88291'\n },\n include: [\n {\n model: VariantOption,\n attributes: ['name']\n },\n {\n model: ProductVariant,\n attributes: ['name']\n }\n ],\n attributes: ['SKUId']\n });\n```\n\nThe query result returns an array where the attributes **VariantOption** and **ProductVariant** are a nested object and has only one field.\n\n```\n[\n {\n \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n \"VariantOption\": {\n \"name\": \"Large\"\n },\n \"ProductVariant\": {\n \"name\": \"Size\"\n }\n },\n {\n \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n \"VariantOption\": {\n \"name\": \"Red\"\n },\n \"ProductVariant\": {\n \"name\": \"color\"\n }\n }\n]\n```\n\nHow do I query the attributes in such a way the result of **VariantOption** and **ProductVariant** does not return a nested object but only a stirng.\n\nIn general I want the result to be something like this\n\n```\n[\n {\n \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n \"VariantOption.name\": \"Large\",\n \"ProductVariant.name\": \"Size\"\n },\n {\n \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n \"VariantOption.name\": \"Red\",\n \"ProductVariant.name\": \"Color\"\n }\n]\n```\n\n========================================\n\nCode:\n```text\nawait SKUValue.findAll({\n            where: {\n                productId: '7bde8a1d-5f6c-4349-bfda-428399c88291'\n            },\n            include: [\n                {\n                    model: VariantOption,\n                    attributes: ['name']\n                },\n                {\n                    model: ProductVariant,\n                    attributes: ['name']\n                }\n            ],\n            attributes: ['SKUId']\n        });\n```\n\n```text\n[\n    {\n        \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n        \"VariantOption\": {\n            \"name\": \"Large\"\n        },\n        \"ProductVariant\": {\n            \"name\": \"Size\"\n        }\n    },\n    {\n        \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n        \"VariantOption\": {\n            \"name\": \"Red\"\n        },\n        \"ProductVariant\": {\n            \"name\": \"color\"\n        }\n    }\n]\n```\n\n```text\n[\n    {\n        \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n        \"VariantOption.name\": \"Large\",\n        \"ProductVariant.name\": \"Size\"\n    },\n    {\n        \"SKUId\": \"72edd3ca-fa12-4234-ba8c-dd008eb416d5\",\n        \"VariantOption.name\": \"Red\",\n        \"ProductVariant.name\": \"Color\"\n    }\n]\n```\n\n```text\nreturn await SKUValue.findAll({\n            where: {\n                productId: '7bde8a1d-5f6c-4349-bfda-428399c88291'\n            },\n            include: [\n                {\n                    model: VariantOption,\n                    attributes: []\n                },\n                {\n                    model: ProductVariant,\n                    attributes: []\n                }\n            ],\n            attributes: [\n                'SKUId',\n                [Sequelize.literal('\"ProductVariant\".\"name\"'), 'productVariant'],\n                [Sequelize.literal('\"VariantOption\".\"name\"'), 'variantOption']\n            ]\n        });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":155,"estimatedTokens":862}}622{"id":"stack-46759668","source":"stackoverflow","questionId":46759668,"title":"Automated Testing with Databases","tags":["node.js","postgresql","testing","sequelize.js","jestjs"],"text":"Title: Automated Testing with Databases\nTags: node.js, postgresql, testing, sequelize.js, jestjs\nSource: Stack Overflow\n\nQuestion:\nI'm fairly new to automated testing and was wondering how I should go about writing tests for the database. The project I'm working on right now is running PostgreSQL with Sequelize as the ORM on a Node.JS environment. If it matters, I'm also using Jest as the testing library right now.\n\n========================================\n\nTop Answer:\nIf you're not doing anything particularly complicated on the DB side, take a look at pg-mem:\n\n- https://swizec.com/blog/pg-mem-and-jest-for-smooth-integration-testing/\n\n- https://github.com/oguimbal/pg-mem\n\nIt's really cool in that it tests actual PG syntax and can pick up a bunch of errors that using a different DB or mock DB won't pick up. However, it's not a perfect implementation and missing a bunch of features (e.g. triggers, decent \"not exists\" handling, lots of functions) some of which are easy to work around with the hooks provided and some aren't.\n\nFor me, having the test DB initialized with the same schema initialization scripts as the real DB is a big win.\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n  database: {\n    name: 'dbname',\n    user: 'user',\n    password: 'password',\n    host: 'host',\n    // Use \"sqlite\" for \"test\", the connection settings above are ignored\n    dialect: process.env.APP_ENV === 'test' ? 'sqlite' : 'mysql',\n  },\n};\n```\n\n```js\n// get our config\n  const config = require('../config');\n  \n  // ... code\n\n  const instance = new Sequelize(\n      config.database.name,\n      config.database.user,\n      config.database.password,\n      {\n        host: config.database.host,\n        // set the dialect, will be \"sqlite\" for \"test\"\n        dialect: config.database.dialect,\n      }\n  );\n```\n\n```js\nconst TestUtils = require('./lib/test-utils');\n    \ndescribe('Some Tests', () => {\n  let app = null;\n\n  // run before the tests start\n  before((done) => {\n    // Mock up our services\n    TestUtils.mock();\n\n    // these are instantiated after the mocking\n    app = require('../server');\n\n    // Populate redis data\n    TestUtils.populateRedis(() => {\n      // Populate db data\n      TestUtils.syncAndPopulateDatabase('test-data', () => {\n        done();\n      });\n    });\n  });\n\n  // run code after tests have completed\n  after(() => {\n    TestUtils.unMock();\n  });\n\n  describe('/my/route', () => {\n    it('should do something', (done) => {\n      return done();\n    });\n  });\n});\n```\n\n```text\nconfig\n```\n\n```text\nprocess.env.APP_ENV\n```\n\n```text\ntest\n```\n\n```text\ndialect\n```\n\n```text\nsqlite\n```\n\n```text\nyarn add -D sqlite3\n```\n\n```text\nnpm i -D sqlite3\n```\n\n```text\nAPP_ENV=test ./node_modules/.bin/mocha\n```\n\n========================================\n\nComments:\n- You shouldn't \"write tests for the database\" so to speak. You should write tests for your own code. Then, that code may interact with that database. You'd have a separate test database that your code connects to when you're in test mode, so that your tests don't change the data in your development database.\n- FWIW - when writing tests for code that uses sequelize I usually sub in sqlite for my \"real\" database. I can give an example for Mocha if that is useful.\n- Thanks for the info guys! @doublesharp an example would be really helpful and much appreciated! So if I'm reading this right, I should have a \"mock\" database that I run my functions for read/write/update/delete requests to and test the response from that. Is there an easy way to point my automated tests to my \"mock\" database?\n- Mocking is a bit different - you still want to use `sequelize` but swap out `sqlite` as an in memory implementation. Mocking means that you are swapping out one module for another - for example I use `ioredis` to access Redis in production but `fakeredis` for testing. I mock `ioredis` so that when you `require()` it you get `fakeredis` instead.\n- You shouldn't use different DB backends between your test and other environments. As then you are not doing a true test of what your production environment might be.\n- @coler-j it depends on what you are testing. our ci/cd tools run docker and mimic a production environment to run tests before deployments, but there are cases where you might want to test isolated unrelated functionality (this is less true if you are able to use docker or similar though)","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":131,"estimatedTokens":1103}}623{"id":"stack-59506149","source":"stackoverflow","questionId":59506149,"title":"Use ENUM with Sequelize and Typescript","tags":["node.js","typescript","enums","sequelize.js"],"text":"Title: Use ENUM with Sequelize and Typescript\nTags: node.js, typescript, enums, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a API with a USER class that can have more then one way of authenticating itself with the API.\n\nI have managed to get it working with 1 user only having 1 credential but when trying to expand to allow multiple credentials then I got error:\n`UnhandledPromiseRejectionWarning: SequelizeDatabaseError: (conn=498, no: 1265, SQLState: 01000) Data truncated for column 'type' at row 1`\n\nWhat I currently have is this:\n\n```\nUser.hasMany(Credential, { foreignKey: 'id', sourceKey: 'id' });\n```\n\nAnd this:\n\n```\n//Credential.ts\nexport function CredentialInit(sequelize: Sequelize) {\n let cred = Object.keys(CredentialType);\n let credArr: string[] = [];\n for(let i = 0; i Also have this Model to remove these stuff from all my other models.\n\n```\n//BaseModel.ts\nexport class BaseModel extends Model {\n public id?: number;\n public readonly createdAt?: Date;\n public readonly updatedAt?: Date;\n}\n```\n\nAny clue why I get this message?\nI have written it like this because I do not want to have to declare the content of the enum twice.. If changed I want it to change everywhere....\n\n========================================\n\nTop Answer:\nSince an `enum` in TypeScript is a value, you can spread the `enum` values into the `DataTypes.ENUM` of Sequelize, like this:\n\n```\nenum CredentialType {\n EMAIL,\n TOKEN\n}\n\nCredential.init({\n // ...\n type: {\n type: DataTypes.ENUM(...Object.values(CredentialType)),\n allowNull: false\n }\n}, {\n sequelize: sequelize,\n tableName: 'credentials'\n});\n```\n\nOr with the sequelize-typescript library, like this:\n\n```\nimport { Column, DataType, Model, Table } from \"sequelize-typescript\";\n\nenum CredentialType {\n EMAIL = \"EMAIL\",\n TOKEN = \"TOKEN\",\n}\n\n@Table\nclass Credential extends Model {\n @Column({\n defaultValue: CredentialType.EMAIL,\n type: DataType.ENUM(...Object.values(CredentialType)),\n })\n type!: CredentialType;\n}\n```\n\nNote, the default values for an `enum` in TypeScript are indexed, but can be overridden with your own values , like this:\n\n```\nenum CredentialType {\n EMAIL = \"EMAIL\",\n TOKEN = \"TOKEN\"\n}\n```\n\n========================================\n\nCode:\n```text\nUser.hasMany(Credential, { foreignKey: 'id', sourceKey: 'id' });\n```\n\n```text\n//Credential.ts\nexport function CredentialInit(sequelize: Sequelize) {\n    let cred = Object.keys(CredentialType);\n    let credArr: string[] = [];\n    for(let i = 0; i < cred.length/2; i++) {\n        credArr.push(`${i}`);\n    };\n    Credential.init({\n        email: {\n            type: DataTypes.STRING,\n            allowNull: true\n        },\n        password: {\n            type: DataTypes.STRING,\n            allowNull: true\n        },\n        token: {\n            type: DataTypes.STRING,\n            allowNull: true\n        },\n        type: {\n            type: DataTypes.ENUM,\n            values: credArr,\n            allowNull: false\n        }\n    }, {\n        sequelize: sequelize,\n        tableName: 'credentials'\n    });\n}\n\nexport enum CredentialType {\n    EMAIL,\n    TOKEN\n}\n\nexport class Credential extends BaseModel {\n    public type!: CredentialType;\n    public token?: string;\n    public email?: string;\n    public password?: string;\n}\n```\n\n```text\n//BaseModel.ts\nexport class BaseModel extends Model {\n    public id?: number;\n    public readonly createdAt?: Date;\n    public readonly updatedAt?: Date;\n}\n```\n\n```text\nUnhandledPromiseRejectionWarning: SequelizeDatabaseError: (conn=498, no: 1265, SQLState: 01000) Data truncated for column 'type' at row 1\n```\n\n```text\nCredential.init({\n    email: {\n        type: DataTypes.STRING,\n        allowNull: true\n    },\n    password: {\n        type: DataTypes.STRING,\n        allowNull: true\n    },\n    token: {\n        type: DataTypes.STRING,\n        allowNull: true\n    },\n    type: {\n        type: DataTypes.INTEGER,\n        allowNull: false\n    }\n}, {\n    sequelize: sequelize,\n    tableName: 'credentials'\n});\n```\n\n```js\nenum CredentialType {\n  EMAIL,\n  TOKEN\n}\n\nCredential.init({\n  // ...\n  type: {\n    type: DataTypes.ENUM(...Object.values(CredentialType)),\n    allowNull: false\n  }\n}, {\n  sequelize: sequelize,\n  tableName: 'credentials'\n});\n```\n\n```js\nimport { Column, DataType, Model, Table } from \"sequelize-typescript\";\n\nenum CredentialType {\n  EMAIL = \"EMAIL\",\n  TOKEN = \"TOKEN\",\n}\n\n@Table\nclass Credential extends Model {\n  @Column({\n    defaultValue: CredentialType.EMAIL,\n    type: DataType.ENUM(...Object.values(CredentialType)),\n  })\n  type!: CredentialType;\n}\n```\n\n```js\nenum CredentialType {\n  EMAIL = \"EMAIL\",\n  TOKEN = \"TOKEN\"\n}\n```\n\n```text\nenum\n```\n\n```text\nenum\n```\n\n```text\nDataTypes.ENUM\n```\n\n```text\nenum\n```\n\n========================================\n\nComments:\n- why are looping over only ~half of the enum keys?\n- The first half is the index of the elements, or the assigned value ('0' ,'1' ) and the second half is the elements string representation('EMAIL', 'TOKEN')\n- Realised now that I could have done Object.keys(CredentialType).slice(0,Object.keys(CredentialTy&zwnj;&#8203;pe)/2) and skipped the for-loop.. Anyway... XD\n- Or you can use string instead of the number `export enum CredentialType { EMAIL = \"EMAIL\", TOKEN = \"TOKEN\" }`","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":244,"estimatedTokens":1309}}624{"id":"stack-45845764","source":"stackoverflow","questionId":45845764,"title":"Sequelize TypeError: phone.setUser is not a Function","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize TypeError: phone.setUser is not a Function\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm a little lost and would appreciate any help with this. I have a M:M association between my users table and phones table through my `userPhones` table. \n\n**user.js**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Users = sequelize.define('Users', {\n givenName: {\n type: DataTypes.STRING\n },\n sn: {\n type: DataTypes.STRING\n },\n mail: {\n type: DataTypes.STRING\n },\n title: {\n type: DataTypes.STRING\n },\n department: {\n type: DataTypes.STRING\n },\n sAMAccountName: {\n type: DataTypes.STRING,\n primaryKey: true\n },\n displayName: {\n type: DataTypes.STRING\n },\n }, {\n freezeTableName: true,\n timestamps: false\n\n });\n return Users; \n };\n```\n\n**phone.js** \n\n```\nmodule.exports = (sequelize, DataTypes) => { \n const Phones = sequelize.define('Phones', {\n full_number: {\n type: DataTypes.STRING\n },\n telephone: {\n type: DataTypes.STRING\n },\n division_id: {\n type: DataTypes.FLOAT\n },\n }, {\n freezeTableName: true,\n timestamps: false\n\n });\n\n return Phones; \n };\n```\n\n**db.js**\n\n```\nconst Sequelize = require ('sequelize');\n\nconst sequelize = new Sequelize('db', 'user', 'password', {\n host: '127.0.0.1',\n dialect: 'mssql',\n pool: {\n max: 9,\n min: 0,\n idle: 10000\n }\n});\n\nconst db = {};\n\ndb.Sequelize = Sequelize; \ndb.sequelize = sequelize; \n\n//Gets models\n\ndb.users = require('./models/users.js')(sequelize,Sequelize);\ndb.phones = require('./models/phones.js')(sequelize,Sequelize);\ndb.userPhones = sequelize.define('userPhones')\n\n//Sequelize Associations\n\ndb.users.belongsToMany(db.phones, {through: 'userPhones'});\ndb.phones.belongsToMany(db.users, {as: 'owners', through: 'userPhones'});\n\n// Sync SQL with Sequelize Models USE CAUTION\nsequelize.sync({alter:true});\n\nmodule.exports = db;\n```\n\n**phone post route for assigning a user to a phone**\n\n```\nconst express = require('express'),\n router = express.Router(),\n db = require('../db')\n ;\n\nPhones = db.phones;\nUserPhones = db.UserPhones;\n\n// Single Phone User Assignment POST route\n\nrouter.route('/:id/users')\n .post((req, res) => {\n let users = req.body.UserSAMAccountName;\n\n Phones.findById(req.params.id)\n .then(function (phone) {\n if (!phone) {\n res.status(404).json({ message: 'record not found!' })\n }\n phone.setUsers([users])\n .then(associatedUsers => {\n res.status(200).json({ message: `${associatedUsers} added!`});\n })\n\n })\n .catch(function (err) {\n res.status(500).json({ error: `${err}`});\n })\n\n });\n\nmodule.exports = router;\n```\n\nI've previously been able to set assign phones to users and vice versa. I'm not exactly sure what has happened but the other day it just stopped working, and when I post to the API I am now getting:\n\n TypeError: phone.setUsers is not a function\n\nI've tried running `sequelize.sync({force:true});` just to test and see if re-initializing everything would fix things but I haven't seem to get things back on track. \n\nI've read about checking `Phones.instance.prototypes` but I'm not quite clear on how to go about finding that. \n\nUpdate: I failed to mention that there isn't any issue running this from my user route to assign a phone to a user. \n\n**user POST route for assigning a phone to a user**\n\n```\nconst express = require('express'),\n router = express.Router(),\n db = require('../db')\n ;\n\n Users = db.users;\n UserPhones = db.UserPhones;\n\n// Single User->Phone Assignment POST route\n\nrouter.route('/:id/phones')\n .post((req, res) => {\n let phones = req.body.phoneID;\n\n Users.findById(req.params.id)\n .then(function (user) {\n if (!user) {\n res.status(404).json({ message: 'record not found!' })\n }\n user.setPhones([phones])\n .then(associatedPhones => {\n res.status(200).json({ message: `${associatedPhones} added!`});\n })\n\n })\n .catch(function (err) {\n res.status(500).json(err);\n })\n\n });\n\n module.exports = router;\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Users = sequelize.define('Users', {\n    givenName: {\n      type: DataTypes.STRING\n    },\n    sn: {\n      type: DataTypes.STRING\n    },\n    mail: {\n      type: DataTypes.STRING\n    },\n    title: {\n      type: DataTypes.STRING\n    },\n    department: {\n      type: DataTypes.STRING\n    },\n    sAMAccountName: {\n      type: DataTypes.STRING,\n      primaryKey: true\n    },\n    displayName: {\n      type: DataTypes.STRING\n    },\n  }, {\n    freezeTableName: true,\n    timestamps: false\n\n  });\n  return Users; \n  };\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {  \n  const Phones = sequelize.define('Phones', {\n    full_number: {\n      type: DataTypes.STRING\n    },\n    telephone: {\n      type: DataTypes.STRING\n    },\n    division_id: {\n      type: DataTypes.FLOAT\n   },\n  }, {\n    freezeTableName: true,\n    timestamps: false\n\n  });\n\n  return Phones; \n  };\n```\n\n```text\nconst Sequelize = require ('sequelize');\n\nconst sequelize = new Sequelize('db', 'user', 'password', {\n    host: '127.0.0.1',\n    dialect: 'mssql',\n    pool: {\n        max: 9,\n        min: 0,\n        idle: 10000\n    }\n});\n\nconst db = {};\n\ndb.Sequelize = Sequelize; \ndb.sequelize = sequelize; \n\n//Gets models\n\ndb.users = require('./models/users.js')(sequelize,Sequelize);\ndb.phones = require('./models/phones.js')(sequelize,Sequelize);\ndb.userPhones = sequelize.define('userPhones')\n\n//Sequelize Associations\n\ndb.users.belongsToMany(db.phones, {through: 'userPhones'});\ndb.phones.belongsToMany(db.users, {as: 'owners', through: 'userPhones'});\n\n// Sync SQL with Sequelize Models USE CAUTION\nsequelize.sync({alter:true});\n\nmodule.exports = db;\n```\n\n```text\nconst express = require('express'),\n  router = express.Router(),\n  db = require('../db')\n  ;\n\n\nPhones = db.phones;\nUserPhones = db.UserPhones;\n\n// Single Phone User Assignment POST route\n\nrouter.route('/:id/users')\n  .post((req, res) => {\n    let users = req.body.UserSAMAccountName;\n\n    Phones.findById(req.params.id)\n      .then(function (phone) {\n        if (!phone) {\n          res.status(404).json({ message: 'record not found!' })\n        }\n        phone.setUsers([users])\n        .then(associatedUsers => {\n          res.status(200).json({ message: `${associatedUsers} added!`});\n        })\n\n      })\n      .catch(function (err) {\n        res.status(500).json({ error: `${err}`});\n      })\n\n  });\n\n\nmodule.exports = router;\n```\n\n```text\nconst express = require('express'),\n  router = express.Router(),\n  db = require('../db')\n  ;\n\n  Users = db.users;\n  UserPhones = db.UserPhones;\n\n// Single User->Phone Assignment POST route\n\nrouter.route('/:id/phones')\n  .post((req, res) => {\n    let phones = req.body.phoneID;\n\n    Users.findById(req.params.id)\n      .then(function (user) {\n        if (!user) {\n          res.status(404).json({ message: 'record not found!' })\n        }\n        user.setPhones([phones])\n        .then(associatedPhones => {\n          res.status(200).json({ message: `${associatedPhones} added!`});\n        })\n\n      })\n      .catch(function (err) {\n        res.status(500).json(err);\n      })\n\n  });\n\n  module.exports = router;\n```\n\n```text\nuserPhones\n```\n\n```text\nsequelize.sync({force:true});\n```\n\n```text\nPhones.instance.prototypes\n```\n\n```text\nphone.setOwners\n```\n\n```text\nphone.setowners\n```\n\n========================================\n\nComments:\n- Did you try doing a `console.log(phone)` before the `phone.setUsers([users])` to see what you've got there?\n- check with userPhones.setUsers\n- @ivo Yeah it's spitting out a bunch of queries so I'm in the process of getting that to a log file so i can inspect it further\n- Ahhhhh.. I didn't realize that changes the naming for those calls. Thank you so much!\n- I have no experience in this, lol, but I was guessing based on reading docs.sequelizejs.com/manual/tutorial/&hellip; please let me know if that actually fixes it :)\n- it did. I'm not sure how i missed that in their documentation, but at the same time I'm not surprised because they're documentation is a little confusing at times","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":383,"estimatedTokens":1992}}625{"id":"stack-38726793","source":"stackoverflow","questionId":38726793,"title":"Sequelize: Include model of through.attribute","tags":["javascript","sequelize.js"],"text":"Title: Sequelize: Include model of through.attribute\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to include a model for an attribute of a many-to-many relation via `through`?\n\nLet's say I'm having the following Models:\n\n```\nUser = sequelize.define('user', {/* attributes */});\nQuestion = sequelize.define('question', {/* attributes */});\nAnswer = sequelize.define('answer', {/* attributes */});\n\n/* Where */\nQuestion.hasMany(Answer);\nAnswer.belongsTo(Question);\n```\n\nI'd like to save for every user which answer he gave to a question. So I added the following relation:\n\n```\nUserQuestionAnswerRel = sequelize.define('usersAnwers', {\n user: {/**/},\n question: {/**/},\n answer: {/**/}\n});\n\nUser.hasMany(Question, { through: UserQuestionAnswerRel });\n```\n\nNow I'd like to query a user receiving all questions he answered *and the answer he gave*. But how does that work? Unfortunately this doesn't work:\n\n```\nUser.findAll({\n include: {\n model: Question,\n through: { include: model.Answer }\n }\n}).then /* */\n```\n\n**Please note:** All this Q&A stuff is just an example. It won't be possible for me to not use a `through` relation.\n\n========================================\n\nTop Answer:\nI think the way to look at this question is:\n\n```\nUser.hasMany(Question); //this gives every question a userId\n Question.belongsTo(User);\n User.hasMany(Answer); //this gives every answer a userId\n Answer.belongsTo(User);\n Question.hasMany(Answer); //this gives every answer a questionId\n Answer.beongsTo(Question);\n```\n\nSo, a query to get a user receiving all questions he answered and the answer he gave would go like this:\n\n```\nUser.findAll({\n where: {\n id: userId\n },\n include: [\n { model: Answer },\n include: [\n { model: Question }\n ]\n ]\n });\n```\n\nThis query is selecting a user with a supplier ID (userId) from the users table, and including all answers belong to that user, and also including all questions belonging to each of the answers included.\n\nLet me know when you try this\n\n========================================\n\nCode:\n```text\nUser = sequelize.define('user', {/* attributes */});\nQuestion = sequelize.define('question', {/* attributes */});\nAnswer = sequelize.define('answer', {/* attributes */});\n\n/* Where */\nQuestion.hasMany(Answer);\nAnswer.belongsTo(Question);\n```\n\n```text\nUserQuestionAnswerRel = sequelize.define('usersAnwers', {\n  user: {/**/},\n  question: {/**/},\n  answer: {/**/}\n});\n\nUser.hasMany(Question, { through: UserQuestionAnswerRel });\n```\n\n```text\nUser.findAll({\n  include: {\n    model: Question,\n    through: { include: model.Answer }\n  }\n}).then /* */\n```\n\n```text\nthrough\n```\n\n```text\nthrough\n```\n\n```text\nUser.findAll({\n  include: {\n    model: UserQuestionAnswerRel,\n    include: [\n      { model: Question },\n      { model: Answer }\n    ]\n  }\n}).then...\n```\n\n```text\nUser.hasMany(Question); //this gives every question a userId\n     Question.belongsTo(User);\n     User.hasMany(Answer); //this gives every answer a userId\n     Answer.belongsTo(User);\n     Question.hasMany(Answer); //this gives every answer a questionId\n     Answer.beongsTo(Question);\n```\n\n```text\nUser.findAll({\n      where: {\n         id: userId\n       },\n       include: [\n        { model: Answer },\n           include: [\n           { model: Question }\n           ]\n         ]\n        });\n```\n\n========================================\n\nComments:\n- interesting. sorry i have no answer as yet. but wonder if its similar to my question. stackoverflow.com/questions/38714624/&hellip; i essentually want to access the 'through' model and filter on records left out of an 'inner' join\n- Can you explain why you have to use a `through`? This should be pretty straight forward to do with Nested eager loading...","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":158,"estimatedTokens":933}}626{"id":"stack-38702543","source":"stackoverflow","questionId":38702543,"title":"Sequelize - Bulk create from array","tags":["javascript","node.js","express","promise","sequelize.js"],"text":"Title: Sequelize - Bulk create from array\nTags: javascript, node.js, express, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an array of items and need to create them to DB.\n\nI need to check each insert if it success so insert to new array (results) the item + success = true as a json.\n\nIf not succeed to create - insert to the same array before (results) the item + success = false.\n\nHere's the code:\n\n```\ncreate_cards: function (filter_id, is_filter, cards) {\n var result = [];\n var curr_card = null;\n for (var card in cards) {\n curr_card = this.create( {\n filter_id: filter_id,\n template: card.template,\n state: card.state,\n question_id: card.question_id || -1,\n answers: card.answers || -1,\n description: card.description || -1,\n correct_answer: card.correct_answer || -1\n }).then(function(card) {\n result.push({card: JSON.stringify(card.dataValues), success: true})\n },function(err) {\n result.push({card: card.dataValues, success: false})\n });\n }\n return results;\n}\n```\n\nNow, 2 questions:\n\nThere is 'return result' after the loop is over, but i get empty array..\nHow should i do bulk create AND after each create, to make sure if the creation succeed?\n\nHow should i get the card in the error function? i get only 'err' as variable to the reject function.\n\nThanks!\n\n========================================\n\nCode:\n```text\ncreate_cards: function (filter_id, is_filter, cards) {\n    var result = [];\n    var curr_card = null;\n    for (var card in cards) {\n        curr_card = this.create( {\n            filter_id: filter_id,\n            template: card.template,\n            state: card.state,\n            question_id: card.question_id || -1,\n            answers: card.answers || -1,\n            description: card.description || -1,\n            correct_answer: card.correct_answer || -1\n        }).then(function(card) {\n            result.push({card: JSON.stringify(card.dataValues), success: true})\n        },function(err) {\n            result.push({card: card.dataValues, success: false})\n        });\n    }\n    return results;\n}\n```\n\n```js\ncreate_cards: function(filter_id, is_filter, cards) {\n  var result = [];\n\n  var promises = cards.map(function(card) {\n    return this.create({\n        filter_id: filter_id,\n        template: card.template,\n        state: card.state,\n        question_id: card.question_id || -1,\n        answers: card.answers || -1,\n        description: card.description || -1,\n        correct_answer: card.correct_answer || -1\n      })\n      .then(function() {\n        result.push({\n          card: card,\n          success: true\n        });\n      })\n      .catch(function(err) {\n        result.push({\n          card: card,\n          success: false\n        });\n        return Promise.resolve();\n      });\n  });\n\n  return Promise.all(promises)\n    .then(function() {\n      return Promise.resolve(result);\n    });\n}\n```\n\n========================================\n\nComments:\n- You need to practice a little more with promises, `results` is empty because no promises where resolved before `return results` is called\n- @AramilRey I know this, but i didn't know how to manage all the promises and the returns. Anyway, Thanks!\n- @Zvi thanks, it helped me a lot","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":113,"estimatedTokens":799}}627{"id":"stack-29259135","source":"stackoverflow","questionId":29259135,"title":"sequelize remote database access","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: sequelize remote database access\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a database that i have previously been accessing (using php) remotely now i am trying to setup sequelize to connect to the same remote servers database:\n\nfor this i have the following `json` (database.json):\n\n```\n{\n \"dev\": {\n \"server\": \"serverip\",\n \"driver\": \"mysql\",\n \"user\": \"username\",\n \"port\": \"3306\",\n \"database\": \"databasename\",\n \"password\": \"password\"\n }\n}\n```\n\n(ive excluded sensitive data)\n\nNow the way i connect to the database from my `server.js` is:\n\n```\nvar env = app.get('env') == 'development' ? 'dev' : app.get('env');\nvar port = process.env.PORT || 8080;\n\nvar Sequelize = require('sequelize');\n\n// db config\nvar env = \"dev\";\nvar config = require('./database.json')[env];\nvar password = config.password ? config.password : null;\n\n// initialize database connection\nvar sequelize = new Sequelize(\n config.server,\n config.database,\n config.user,\n config.port,\n config.password,\n {\n logging: console.log,\n define: {\n timestamps: false\n }\n }\n);\n```\n\nThe \"sad\" thing about this is that i does not throw any errors but i know it is not connected because it does not collect any data from the database.\n\nSo what am i doing wrong?\n\n========================================\n\nCode:\n```text\n{\n  \"dev\": {\n    \"server\": \"serverip\",\n    \"driver\": \"mysql\",\n    \"user\": \"username\",\n    \"port\": \"3306\",\n    \"database\": \"databasename\",\n    \"password\": \"password\"\n  }\n}\n```\n\n```text\nvar env = app.get('env') == 'development' ? 'dev' : app.get('env');\nvar port = process.env.PORT || 8080;\n\nvar Sequelize = require('sequelize');\n\n// db config\nvar env = \"dev\";\nvar config = require('./database.json')[env];\nvar password = config.password ? config.password : null;\n\n// initialize database connection\nvar sequelize = new Sequelize(\n    config.server,\n    config.database,\n    config.user,\n    config.port,\n    config.password,\n    {\n        logging: console.log,\n        define: {\n            timestamps: false\n        }\n    }\n);\n```\n\n```text\njson\n```\n\n```text\nserver.js\n```\n\n```text\nvar sequelize = new Sequelize(\n    config.database,\n    config.user,\n    config.password,\n    {\n        port: config.port,\n        host: config.server,\n        logging: console.log,\n        define: {\n            timestamps: false\n        }    \n    }\n);\n```\n\n========================================\n\nComments:\n- Hey again @Jan ive passed the variables you suggest however it still does not connect\n- What happens when you try to run a query then? You must be getting some kind of error message?\n- No error messages all i get it \"something is happening\"\n- What do you mean you get \"something is happening\" - is that message printed to the console? That does not come from sequelize code, I can asure you.\n- Yeah i noticed but it doesnt give me any errors while connecting nor trying to access any of the models :s its kinda odd\n- Well, sequelize does actually connect to the DB before you make a query - what happens if you call `find` on your of your models. Either the query succeeds, or it throws an error :). Also, we are getting into a long comment discussion again - Try to join the #sequelizejs IRC channel on freenode and ask your question there instead\n- i found an error message which is kinda odd ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'109.56.7.58' (using password: YES) the problem is that the ip is not the one i instered into the server variable???\n- How can you get the model's instance of a table that is already in a remote database. Im able to connect to a remote db. But instead of directly using query method to write extensive sql queries, can I use the ORM like functionality to query data from an existing table without defining the model in my node app?","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":135,"estimatedTokens":949}}628{"id":"stack-56241834","source":"stackoverflow","questionId":56241834,"title":"Sequelize automatically sets a default value for NOT NULL columns","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize automatically sets a default value for NOT NULL columns\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am currently running Sequelize.js code on my MySQL database, that is created using migrations. I have a table with persons that is defined like this:\n\n```\nreturn queryInterface.createTable('Persons', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n unique: true,\n type: Sequelize.INTEGER\n },\n email: {\n allowNull: false,\n unique: true,\n type: Sequelize.STRING\n },\n firstName: {\n type: Sequelize.STRING\n },\n lastName: {\n type: Sequelize.STRING\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n```\n\nand the resulting table looks like this:\n\n```\n`Persons` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `email` varchar(255) NOT NULL,\n `firstName` varchar(255) DEFAULT NULL,\n `lastName` varchar(255) DEFAULT NULL,\n `createdAt` datetime NOT NULL,\n `updatedAt` datetime NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `id` (`id`),\n UNIQUE KEY `email` (`email`)\n)\n```\n\nWhen I add an entry to the database using Model.create({}) (with nothing between the brackets), the following object is added to the database:\n\n```\nid email firstName lastName createdAt updatedAt\n1 '' NULL NULL 2019-05-21 15:33:13 2019-05-21 15:33:13\n```\n\nEvery NOT NULL column I have in my database gets a default value (empty string for varchar, false for boolean, NOW() for datetime).\n\nThe Sequelize.js docs state the following:\n\n setting allowNull to false will add NOT NULL to the column, which means an error will be thrown from the DB when the query is executed if the column is null. If you want to check that a value is not null before querying the DB, look at the validations section below.\n\n \n title: { type: Sequelize.STRING, allowNull: false },\n\nI want to receive the error as stated in the official docs but have no clue what I'm doing wrong.\n\n========================================\n\nTop Answer:\nThis can happen in two cases.\n\nFirst, if you have entered the `allowNull` later after defining the model then you need to resync the table with `sync({force: true})`.\n\nSecond, `allowNull` will work if attributes like `email` and `firstName` are not provided to `create()`. for example `create({email:'',firstName:''})` will fill empty values.But if you do `create({email:''})`,then skipping `firstName` attribute will cause validation error.\n\nIn case if you are doing `create(req.body)` as from an HTML form tag or something and body has fields `email` and `firstName` set to empty strings by default if no values were passed. then empty values will be entered. As sequelize don't consider empty string values in `req.body` object a `null` value.\n\nYou can adjust your validations to avoid such behavior by adding `notEmpty: true` to your validations as below.\n\n```\nemail: {\n allowNull: false,\n unique: true,\n type: Sequelize.STRING\n validate : {\n notEmpty: true\n }\n```\n\nor you can do the below little hack by putting the `allowNull` in a validate property like below and it will work ;)\n\n```\nemail: {\n unique: true,\n type: Sequelize.STRING\n validate : {\n allowNull: false\n }\n```\n\nHope I made myself clear :)\n\n========================================\n\nCode:\n```text\nreturn queryInterface.createTable('Persons', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        unique: true,\n        type: Sequelize.INTEGER\n      },\n      email: {\n        allowNull: false,\n        unique: true,\n        type: Sequelize.STRING\n      },\n      firstName: {\n        type: Sequelize.STRING\n      },\n      lastName: {\n        type: Sequelize.STRING\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n```\n\n```text\n`Persons` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `email` varchar(255) NOT NULL,\n  `firstName` varchar(255) DEFAULT NULL,\n  `lastName` varchar(255) DEFAULT NULL,\n  `createdAt` datetime NOT NULL,\n  `updatedAt` datetime NOT NULL,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `id` (`id`),\n  UNIQUE KEY `email` (`email`)\n)\n```\n\n```text\nid  email   firstName   lastName    createdAt   updatedAt\n1   ''      NULL        NULL        2019-05-21 15:33:13 2019-05-21 15:33:13\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Persons = sequelize.define('Persons', {\n        email: {\n            type: DataTypes.STRING(100),\n            allowNull: false\n        },\n        firstName: DataTypes.STRING(40),\n        lastName: DataTypes.STRING(40)\n    }, {});\n    return Persons;\n};\n```\n\n```text\nemail: {\n        allowNull: false,\n        unique: true,\n        defaultValue: null,\n        type: Sequelize.STRING\n      },\n```\n\n```text\nemail: {\n        allowNull: false,\n        unique: true,\n        type: Sequelize.STRING\n        validate : {\n           notEmpty: true\n        }\n```\n\n```text\nemail: {\n        unique: true,\n        type: Sequelize.STRING\n        validate : {\n           allowNull: false\n        }\n```\n\n```text\nallowNull\n```\n\n```text\nsync({force: true})\n```\n\n```text\nallowNull\n```\n\n```text\nemail\n```\n\n```text\nfirstName\n```\n\n```text\ncreate()\n```\n\n```text\ncreate({email:'',firstName:''})\n```\n\n```text\ncreate({email:''})\n```\n\n```text\nfirstName\n```\n\n```text\ncreate(req.body)\n```\n\n```text\nemail\n```\n\n```text\nfirstName\n```\n\n```text\nreq.body\n```\n\n```text\nnull\n```\n\n```text\nnotEmpty: true\n```\n\n```text\nallowNull\n```\n\n========================================\n\nComments:\n- When I do that I get an error during the migration that says \"Invalid default value for 'email'\"\n- Well then sorry that's out of my knowledge of the framework.","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":272,"estimatedTokens":1429}}629{"id":"stack-55482411","source":"stackoverflow","questionId":55482411,"title":"Sequelize - model.update vs instance.update (right way of updating)","tags":["javascript","sql","node.js","sequelize.js"],"text":"Title: Sequelize - model.update vs instance.update (right way of updating)\nTags: javascript, sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhat is the right way to update row in Sequelize.js?\nAccording to documentation I can do both `model.update` or `instance.update`.\n\n`model.update`- requires only one database call (I think), but its called as \"bulk\" update what is not good when you have for example hooks.\n\n`instance.update` - you need first find that row, then you can update, so its 2at least 2 calls. Its called as normal single update, not bulk.\n\nI have REST API with CRUD structure. Create can't be done otherwise than `mode.create` and it makes sense. But how about update. What is the RIGHT WAY for updating one row?\nOr its just about my needs and it is opinion based question?\n\n========================================\n\nCode:\n```text\nmodel.update\n```\n\n```text\ninstance.update\n```\n\n```text\nmodel.update\n```\n\n```text\ninstance.update\n```\n\n```text\nmode.create\n```\n\n```text\nparameter\n```\n\n```text\nupdate\n```\n\n```text\nfindById\n```\n\n```text\nremove\n```\n\n```text\nwhere\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":57,"estimatedTokens":273}}630{"id":"stack-38861852","source":"stackoverflow","questionId":38861852,"title":"How do I drop a foreign key using Sequelize.js?","tags":["node.js","sequelize.js"],"text":"Title: How do I drop a foreign key using Sequelize.js?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI know this can be possible by using a raw query like the one used in this question to remove a constraint, however, is there any built-in method to drop foreign keys from Sequelize.js?\n\n========================================\n\nCode:\n```text\nlet dropFKSQL = queryInterface.QueryGenerator.dropForeignKeyQuery(\"tableName\", \"foreignKey\")\nreturn queryInterface.sequelize.query(dropForeignKeySQL);\n```\n\n```text\npublic getForeignKeyName(tableName: string, columnName: string, opts: { queryInterface: QueryInterface }): Promise<string> {\n    let sqlz = opts.queryInterface.sequelize;\n    let sql = `\n        SELECT CONSTRAINT_NAME\n        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n        WHERE REFERENCED_TABLE_SCHEMA = '${dbSchema}'\n          AND TABLE_NAME = '${tableName}'\n          AND COLUMN_NAME = '${columnName}'\n    `;\n\n    return sqlz.query(sql, { type: sqlz.QueryTypes.SELECT })\n        .then((result: { CONSTRAINT_NAME: string }[]) => {\n            if (!result || !result[0] || !result[0].CONSTRAINT_NAME) {\n                return null;\n            }\n\n            return result[0].CONSTRAINT_NAME;\n        });\n}\n```\n\n```text\nQueryGenerator\n```\n\n```text\n_ibfk_{index}\n```\n\n```text\n_idx\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":48,"estimatedTokens":328}}631{"id":"stack-28546381","source":"stackoverflow","questionId":28546381,"title":"sequelize gives the wrong table name","tags":["mysql","node.js","rest","express","sequelize.js"],"text":"Title: sequelize gives the wrong table name\nTags: mysql, node.js, rest, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a database. Where i have a \"`user`\" table\n\nI am trying to create my first `REST` api using `sequelize`\n\nhowever when it executes my query i get the following in the console:\n\n```\nSELECT `id`, `username`, `password`, `name`, `organization_id`, `type_id`, `join_date` FROM `users` AS `user` WHERE `user`.`id` = '1';\n```\n\nas you can see it tries to use a table called `users` however this table does not exists.\n\nHere is some of my code:\n\nPlease do tell me if you need more i am not really sure where it goes wrong? :S\n\n```\nvar User = sequelize.define('user', {\n id: DataTypes.INTEGER,\n username: DataTypes.STRING,\n password: DataTypes.STRING,\n name: DataTypes.STRING,\n organization_id: DataTypes.INTEGER,\n type_id: DataTypes.INTEGER,\n join_date: DataTypes.STRING\n\n}, {\n instanceMethods: {\n retrieveAll: function(onSuccess, onError) {\n User.findAll({}, {raw: true})\n .ok(onSuccess).error(onError);\n },\n retrieveById: function(user_id, onSuccess, onError) {\n User.find({where: {id: user_id}}, {raw: true})\n .success(onSuccess).error(onError);\n },\n add: function(onSuccess, onError) {\n var username = this.username;\n var password = this.password;\n\n var shasum = crypto.createHash('sha1');\n shasum.update(password);\n password = shasum.digest('hex');\n\n User.build({ username: username, password: password })\n .save().ok(onSuccess).error(onError);\n },\n updateById: function(user_id, onSuccess, onError) {\n var id = user_id;\n var username = this.username;\n var password = this.password;\n\n var shasum = crypto.createHash('sha1');\n shasum.update(password);\n password = shasum.digest('hex');\n\n User.update({ username: username,password: password},{where: {id: id} })\n .success(onSuccess).error(onError);\n },\n removeById: function(user_id, onSuccess, onError) {\n User.destroy({where: {id: user_id}}).success(onSuccess).error(onError);\n }\n }\n});\n```\n\n========================================\n\nTop Answer:\nI have not used sequelize before, but reading from their documentation - may be you are missing - \n\n`User.sync({force: true}).then(function () {\n // Table created\n return User.create({\n firstName: 'John',\n lastName: 'Hancock'\n });\n});`\n\ni.e. the table creation part...\n\nThanks\n\n========================================\n\nCode:\n```text\nSELECT `id`, `username`, `password`, `name`, `organization_id`, `type_id`, `join_date` FROM `users` AS `user` WHERE `user`.`id` = '1';\n```\n\n```text\nvar User = sequelize.define('user', {\n    id: DataTypes.INTEGER,\n    username: DataTypes.STRING,\n    password: DataTypes.STRING,\n    name: DataTypes.STRING,\n    organization_id: DataTypes.INTEGER,\n    type_id: DataTypes.INTEGER,\n    join_date: DataTypes.STRING\n\n}, {\n    instanceMethods: {\n        retrieveAll: function(onSuccess, onError) {\n            User.findAll({}, {raw: true})\n                .ok(onSuccess).error(onError);\n        },\n        retrieveById: function(user_id, onSuccess, onError) {\n            User.find({where: {id: user_id}}, {raw: true})\n                .success(onSuccess).error(onError);\n        },\n        add: function(onSuccess, onError) {\n            var username = this.username;\n            var password = this.password;\n\n            var shasum = crypto.createHash('sha1');\n            shasum.update(password);\n            password = shasum.digest('hex');\n\n            User.build({ username: username, password: password })\n                .save().ok(onSuccess).error(onError);\n        },\n        updateById: function(user_id, onSuccess, onError) {\n            var id = user_id;\n            var username = this.username;\n            var password = this.password;\n\n            var shasum = crypto.createHash('sha1');\n            shasum.update(password);\n            password = shasum.digest('hex');\n\n            User.update({ username: username,password: password},{where: {id: id} })\n                .success(onSuccess).error(onError);\n        },\n        removeById: function(user_id, onSuccess, onError) {\n            User.destroy({where: {id: user_id}}).success(onSuccess).error(onError);\n        }\n    }\n});\n```\n\n```text\nuser\n```\n\n```text\nREST\n```\n\n```text\nsequelize\n```\n\n```text\nusers\n```\n\n```text\nvar User = sequelize.define('user', {\n    id: DataTypes.INTEGER,\n    username: DataTypes.STRING,\n    password: DataTypes.STRING,\n    name: DataTypes.STRING,\n    organization_id: DataTypes.INTEGER,\n    type_id: DataTypes.INTEGER,\n    join_date: DataTypes.STRING\n\n}, {\n    freezeTableName: true,\n    instanceMethods: {\n        retrieveAll: function(onSuccess, onError) {\n            User.findAll({}, {raw: true})\n                .ok(onSuccess).error(onError);\n        },\n        retrieveById: function(user_id, onSuccess, onError) {\n            User.find({where: {id: user_id}}, {raw: true})\n                .success(onSuccess).error(onError);\n        },\n        add: function(onSuccess, onError) {\n            var username = this.username;\n            var password = this.password;\n\n            var shasum = crypto.createHash('sha1');\n            shasum.update(password);\n            password = shasum.digest('hex');\n\n            User.build({ username: username, password: password })\n                .save().ok(onSuccess).error(onError);\n        },\n        updateById: function(user_id, onSuccess, onError) {\n            var id = user_id;\n            var username = this.username;\n            var password = this.password;\n\n            var shasum = crypto.createHash('sha1');\n            shasum.update(password);\n            password = shasum.digest('hex');\n\n            User.update({ username: username,password: password},{where: {id: id} })\n                .success(onSuccess).error(onError);\n        },\n        removeById: function(user_id, onSuccess, onError) {\n            User.destroy({where: {id: user_id}}).success(onSuccess).error(onError);\n        }\n    }\n});\n```\n\n```text\nUser.sync({force: true}).then(function () {\n  // Table created\n  return User.create({\n    firstName: 'John',\n    lastName: 'Hancock'\n  });\n});\n```\n\n========================================\n\nComments:\n- Just to be clear, does the \"user\" table actually already exist in your DB? And did you create it manually or did Sequelize create it?\n- @HeadCode the user table exists in my database and was created manually and already contains loads of data\n- I didn't realize this, but \"user\" looks to be a reserved keyword. I can't say this is causing you a problem, but check out this post: stackoverflow.com/questions/21114499/&hellip;\n- instead of using the table \"user\" this just creates a table called \"users\"\n- WOW ive been so close to solving this i just inserted that line in the wrong place thank you!\n- Thanks for pointing us in the right direction, but the actual syntax above is not correct: `freezeTableName = true` should be `freezeTableName: true`","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":231,"estimatedTokens":1720}}632{"id":"stack-26362965","source":"stackoverflow","questionId":26362965,"title":"Prevent junction-table data from being added to json with sequelize","tags":["json","express","has-many","sequelize.js"],"text":"Title: Prevent junction-table data from being added to json with sequelize\nTags: json, express, has-many, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got the following models associated with sequelize.\n\n```\nEvent hasMany Characters through characters_attending_boss\nBoss hasMany Characters through characters_attending_boss\nCharacters hasMany Event through characters_attending_boss\nCharacters hasMany Boss through characters_attending_boss\n```\n\nThese tables are successfully joined and I can retrieve data from them. But when I retrieve the JSON-results the name of the *through* model gets added to each object, like this:\n\n```\n{\n id: 1\n title: \"title\"\n -confirmed_for: [ //Alias for Event -> Character\n -{\n id: 2\n character_name: \"name\"\n -confirmed_for_boss: [ // Alias for Boss -> Character\n -{\n id: 9\n name: \"name\"\n -character_attending_event: { // name of through-model\n event_id: 1\n char_id: 2\n }\n }\n ]\n -character_attending_boss: { // name of through-model\n event_id: 1\n char_id: 2\n }\n}\n```\n\nSo I'm looking for a way to hide these \"character_attending_boss\" segments if possible, preferably without altering the results post-fetch.\n\nIs this possible?\n\n========================================\n\nTop Answer:\nPass `{ joinTableAttributes: [] }` to the query.\n\n========================================\n\nCode:\n```text\nEvent hasMany Characters through characters_attending_boss\nBoss hasMany Characters through characters_attending_boss\nCharacters hasMany Event through characters_attending_boss\nCharacters hasMany Boss through characters_attending_boss\n```\n\n```text\n{\n   id: 1\n   title: \"title\"\n   -confirmed_for: [ //Alias for Event -> Character\n       -{\n          id: 2\n          character_name: \"name\"\n          -confirmed_for_boss: [ // Alias for Boss -> Character\n              -{\n                   id: 9\n                   name: \"name\"\n                   -character_attending_event: { // name of through-model\n                         event_id: 1\n                         char_id: 2\n                   }\n               }\n    ]\n    -character_attending_boss: { // name of through-model\n          event_id: 1\n          char_id: 2\n    }\n}\n```\n\n```text\nthrough: {attributes: []}\n```\n\n```text\n{ joinTableAttributes: [] }\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":559}}633{"id":"stack-22932447","source":"stackoverflow","questionId":22932447,"title":"Sequelize validation throwing error","tags":["database","node.js","model","sequelize.js"],"text":"Title: Sequelize validation throwing error\nTags: database, node.js, model, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to check that a username is unique, and I gather that I'd need a custom validation for that. I've written the following code, but instead of returning the error in the array returned by `.validate()`, it just throws the error, which isn't the behaviour described in the docs and isn't what I want.\n\n```\nvar User = sequelize.define('User', {\n username: {\n type: DataTypes.STRING,\n validate: {\n isUnique: function (username) {\n User.find({ where: { username: username }})\n .done(function (err, user) {\n if (err) {\n throw err;\n }\n\n if (user) {\n throw new Error('Username already in use');\n }\n });\n }\n }\n },\n```\n\n========================================\n\nTop Answer:\nSequelize supports Promise style async operations. Specifically the Bluebird.js lib. Just change your function to specifically use the `Promise -> next()` pattern. \n\n```\nvar User = sequelize.define('User', {\n username: {\n type: DataTypes.STRING,\n validate: {\n isUnique: function (username) {\n User.find({ where: { username: username }})\n .then(function (user) {\n if (user) {\n throw new Error('Username already in use');\n }\n });\n }\n }\n},\n```\n\nThis will also handle any errors on `User.find()` for you.\nSee this example in their codebase\n\nOf course the easiest way to handle unique constraints is by setting `unique: true` on the field definition itself:\n\n```\nvar User = sequelize.define('User', {\n username: {\n type: DataTypes.STRING,\n unique: true\n },\n```\n\nBut this requires that you are either creating the table using Sequelize or already have a table with the unique constraint set.\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {\n    username: {\n        type: DataTypes.STRING,\n        validate: {\n            isUnique: function (username) {\n                User.find({ where: { username: username }})\n                    .done(function (err, user) {\n                        if (err) {\n                            throw err;\n                        }\n\n                        if (user) {\n                            throw new Error('Username already in use');\n                        }\n                    });\n            }\n        }\n    },\n```\n\n```text\n.validate()\n```\n\n```text\nvar User = sequelize.define('User', {\nusername: {\n    type: DataTypes.STRING,\n    validate: {\n        isUnique: function (username, done) {\n            User.find({ where: { username: username }})\n                .done(function (err, user) {\n                    if (err) {\n                        done(err);\n                    }\n\n                    if (user) {\n                        done(new Error('Username already in use'));\n                    }\n\n                    done();\n                });\n        }\n    }\n},\n```\n\n```text\nUser.find\n```\n\n```text\nvar User = sequelize.define('User', {\n   username: {\n    type: DataTypes.STRING,\n    validate: {\n        isUnique: function (username) {\n            User.find({ where: { username: username }})\n                .then(function (user) {\n                    if (user) {\n                        throw new Error('Username already in use');\n                    }\n                });\n        }\n    }\n},\n```\n\n```text\nvar User = sequelize.define('User', {\n  username: {\n    type: DataTypes.STRING,\n    unique: true\n  },\n```\n\n```text\nPromise -> next()\n```\n\n```text\nUser.find()\n```\n\n```text\nunique: true\n```\n\n========================================\n\nComments:\n- A little o.t but is there a reason why you aren't enforcing the username by using a unique key constraint in a dbms?\n- Don't know how, using this library.\n- The documentation is fine, I was just being stupid! I'm getting a TypeError, apparently the done function doesn't exist.\n- What version are you on, I believe async validations are only present in 2.0\n- I've updated to 2.0 now, and now the validate function returns `{fct: [Function] }` and I'm not sure what to do with it.\n- Ah, looks like I shouldn't be calling the validate function directly now. I've got it working now, thanks.","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":166,"estimatedTokens":1030}}634{"id":"stack-47628099","source":"stackoverflow","questionId":47628099,"title":"SequelizeEagerLoadingError when relationship between models has already been defined","tags":["node.js","orm","sequelize.js"],"text":"Title: SequelizeEagerLoadingError when relationship between models has already been defined\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an `exports file` that includes all the sequelize-models and then defines the relationship among the models. It looks something like:\n\n```\n// Snippet from the global init file\n\nfor (let modelFile of modelFileList) {\n // ... Some code ...\n\n // Require the file\n appliedModels[modelName] = require(`../${MODEL_DIR}/${modelFile}`).call(null, _mysql);\n }\n\n //Define the relationship between the sql models\n _defineRelationship(appliedModels);\n\nfunction _defineRelationship(models) {\n models._planAllocationModel.belongsTo(models._subscriptionModel, {\n foreignKey: 'subscription_id',\n targetKey: 'subscription_id'\n });\n}\n```\n\nBut when I try to include the model like:\n\n```\n_subscriptionModel.findAll({\n where: {\n start_date: {\n _lte: today // Get all subscriptions where start_date There is an error thrown by sequelize: `SequelizeEagerLoadingError: tbl_plan_allocation is not associated to tbl_subscription_info!` What could be the reason for this? I have already initialized the relationshipt between the 2 models.\n\n========================================\n\nCode:\n```text\n// Snippet from the global init file\n\nfor (let modelFile of modelFileList) {\n            // ... Some code ...\n\n            // Require the file\n            appliedModels[modelName] = require(`../${MODEL_DIR}/${modelFile}`).call(null, _mysql);\n }\n\n //Define the relationship between the sql models\n _defineRelationship(appliedModels);\n\n\nfunction _defineRelationship(models) {\n     models._planAllocationModel.belongsTo(models._subscriptionModel, {\n            foreignKey: 'subscription_id',\n            targetKey: 'subscription_id'\n        });\n}\n```\n\n```text\n_subscriptionModel.findAll({\n                where: {\n                    start_date: {\n                        _lte: today // Get all subscriptions where start_date <= today\n                    }\n                },\n                limit,\n                include: [\n                    {\n                        model: _planAllocationModel\n                    }\n                ]\n            });\n```\n\n```text\nexports file\n```\n\n```text\nSequelizeEagerLoadingError: tbl_plan_allocation is not associated to tbl_subscription_info!\n```\n\n```text\nbelongsTo\n```\n\n```text\nhasOne\n```\n\n```text\njoin\n```\n\n```text\nfindAll\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.390Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":100,"estimatedTokens":601}}635{"id":"stack-46373658","source":"stackoverflow","questionId":46373658,"title":"How to use query parameter as col name on sequelize query","tags":["sql","node.js","express","sequelize.js"],"text":"Title: How to use query parameter as col name on sequelize query\nTags: sql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo, I have an Express server running Sequelize ORM. Client will answer some questions with radio button options, and the answers is passed as query parameters to the URL, so I can make a GET request to server.\n\nThe thing is: my req.query values are supposed to be the column names for my database table. I want to know if it's possible to get the response from the database using Sequelize, and passing the parameters as the column name of the table.\n\n```\nasync indexAbrigo(req, res) {\n try {\n let abrigos = null\n let type = req.query.type // type = 'periodoTEMPORARIO'\n let reason = req.query.reason // reason = 'motivoRUA'\n abrigos = await Abrigos.findAll({\n attributes: ['idABRIGOS'],\n where: {\n//I want type and reason to be the parameters that I got from client\n type: 'S',\n reason: 'S'\n }\n })\n }\n res.send(abrigos)\n}\n```\n\nThis is not working, the result of the query is something like \n\n```\n(SELECT `idABRIGOS` FROM Abrigos WHERE `type` = `S` AND `reason` = `S`)\n```\n\nInstead, I need that type and reason get translated to their values, and these values will be passed to the SQL. Is it possible to do with Sequelize? Or is it even possible with any ORM for Node/Express?\n\nThanks.\n\n========================================\n\nTop Answer:\nThank you - I am passing parameters right from req.body and this worked perfectly for me so I am posting it in the event that it may save someone time.\n\n```\napp.post('/doFind', (req, res) => {\n Abrigos.findAll(\n {[req.body.field]: req.body.newVal},\n {returning: true, where: {id: req.body.id}}\n )\n .then( () => {\n res.status(200).end()\n })\n .catch(err => {\n console.log(\"Err: \" + err)\n res.status(404).send('Error attempting to update database').end()\n })\n})\n```\n\n========================================\n\nCode:\n```text\nasync indexAbrigo(req, res) {\n  try {\n    let abrigos = null\n    let type = req.query.type  // type = 'periodoTEMPORARIO'\n    let reason = req.query.reason // reason = 'motivoRUA'\n    abrigos = await Abrigos.findAll({\n      attributes: ['idABRIGOS'],\n        where: {\n//I want type and reason to be the parameters that I got from client\n          type: 'S',\n          reason: 'S'\n        }\n      })\n  }\n  res.send(abrigos)\n}\n```\n\n```text\n(SELECT `idABRIGOS` FROM Abrigos WHERE `type` = `S` AND `reason` = `S`)\n```\n\n```text\nwhere: {\n  [type]: 'S',\n  [reason]: 'S'\n}\n```\n\n```text\napp.post('/doFind', (req, res) => {\n    Abrigos.findAll(\n      {[req.body.field]: req.body.newVal},\n      {returning: true, where: {id: req.body.id}}\n    )\n    .then( () => {\n      res.status(200).end()\n    })\n    .catch(err => {\n      console.log(\"Err: \" + err)\n      res.status(404).send('Error attempting to update database').end()\n    })\n})\n```\n\n========================================\n\nComments:\n- Thank you very much, it helped a lot! I'm using ES6, tested it now and I get what I need to.","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":112,"estimatedTokens":745}}636{"id":"stack-44971151","source":"stackoverflow","questionId":44971151,"title":"sequelize.sync({ force: true }) is not working some times","tags":["node.js","gulp","sequelize.js","database-migration","sequelize-cli"],"text":"Title: sequelize.sync({ force: true }) is not working some times\nTags: node.js, gulp, sequelize.js, database-migration, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\ni am using gulp tasks for migration of database. For testing purpose i am using different database. so i need exactly same database. i am trying to do with sequelize.sync({ force: true }) but its not working.\n\ni am having my all models in portal-model. here is the code: \n\n```\nconst models = require('portal-models');\ngulp.task('migrate', ['create-database'], (done) => {\n models.sequelize.query('SET FOREIGN_KEY_CHECKS = 0')\n .then(() => models.sequelize.sync({ force: true, alter: true }))\n....\n....\n....\n)\n```\n\nWith Force: true it should work but for me i am getting error like mydatbaseName.tablename is not exists.\n\ni have created new test database. i dont want to manually create everything in testdatabase, so i am using migrations but i gusse sync is not working properly.\n\nCan anyone tell, exactly what should i ?\n\nThanks in Advance.\n\n========================================\n\nCode:\n```text\nconst models = require('portal-models');\ngulp.task('migrate', ['create-database'], (done) => {\n  models.sequelize.query('SET FOREIGN_KEY_CHECKS = 0')\n  .then(() => models.sequelize.sync({ force: true, alter: true }))\n....\n....\n....\n)\n```\n\n```text\nmodels.sequelize.sync({ force: true })\n```\n\n```text\nmodels.sequelize.sync({ force: true, logging: console.log }))\n```\n\n```text\nexport MYSQL_DATABASENAME = test_database_name\n```\n\n========================================\n\nComments:\n- Are you using sequelize-cli for migrations\n- @Shivam: No , i am not using sequelize-cli. i am using \"sequelize\": \"^3.24.3\".\n- If manually i have created tables, then it is working for insert queries. but i dont want to create tables manually. Force: true should map schema.\n- i have added models.sequelize.sync({ force: true, logging: console.log })), in console now i can see all the tables are droped and then again created. but still while insertion i am getting error ER_NO_SUCH_TABLE: Table 'DatabaseName.TableName' doesn't exist.","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":61,"estimatedTokens":521}}637{"id":"stack-42521665","source":"stackoverflow","questionId":42521665,"title":"Select from multiple tables Sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: Select from multiple tables Sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently developing a system using sequelize and I need a to do a query getting data from multiple tables like this:\n\n```\nSelect Courses.id, Rooms.DisplayLabel, Periods.DisplayName, Subjects.Name \nfrom Rooms, Periods,Subjects, Courses\nwhere Periods.id = Courses.PeriodId and Rooms.id=Courses.RoomId \nand Subjects.id = Courses.SubjectId and Courses.id = 2\n```\n\nRooms, Subjects and Periods are catalogs and course is the the table where I save all the keys. The Sequelize definition is like this:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\n var Course = sequelize.define('Course', {\n Scholarship: {\n type: DataTypes.STRING(30)\n },\n Level: {\n type: DataTypes.INTEGER(2),\n },\n CourseType: {\n type: DataTypes.STRING(30),\n },\n RecordStatus: {\n type: DataTypes.BOOLEAN,\n default: true\n },\n DeletedAt: {\n type: DataTypes.DATE\n }\n },\n {\n associate: function(models){\n Course.belongsTo(models.School, {foreignKey: {unique: true}});\n Course.belongsTo(models.Person, {foreignKey: {unique: true}});\n Course.belongsTo(models.Period, {foreignKey: {unique: true}});\n Course.belongsTo(models.Schedule, {foreignKey: {unique: true}});\n Course.belongsTo(models.Room, {foreignKey: {unique: true}});\n Course.belongsTo(models.Subject, {foreignKey: {unique: true}});\n\n Course.belongsTo(models.user, { as: 'CreatedBy' });\n Course.belongsTo(models.user, { as: 'UpdateBy' });\n Course.belongsTo(models.user, { as: 'DeleteBy' });\n }\n }\n );\n\n return Course;\n};\n```\n\nThe only query that I get so far on my controller is this:\n\n```\nexports.courseFields = function(req, res) {\n\n db.Course.find({\n where: {id: req.params.PeriodIdF},\n attributes: ['id'], \n include: [{model:db.Room, attributes:['DisplayLabel']}]})\n .then(function(courses) {\n return res.json(courses);\n })\n .catch(function(err) {\n return res.render('error', {\n error: err,\n status: 500\n });\n });\n};\n```\n\nMy question is, how do I include the other tables and fields? I confuse how sequelize works.\n\n========================================\n\nCode:\n```text\nSelect Courses.id, Rooms.DisplayLabel, Periods.DisplayName, Subjects.Name \nfrom Rooms, Periods,Subjects, Courses\nwhere Periods.id = Courses.PeriodId  and Rooms.id=Courses.RoomId \nand Subjects.id = Courses.SubjectId and Courses.id = 2\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n  var Course = sequelize.define('Course', {\n      Scholarship: {\n        type: DataTypes.STRING(30)\n      },\n      Level: {\n        type: DataTypes.INTEGER(2),\n      },\n      CourseType: {\n        type: DataTypes.STRING(30),\n      },\n      RecordStatus: {\n        type: DataTypes.BOOLEAN,\n        default: true\n      },\n      DeletedAt: {\n        type: DataTypes.DATE\n      }\n    },\n    {\n      associate: function(models){\n        Course.belongsTo(models.School, {foreignKey: {unique: true}});\n        Course.belongsTo(models.Person, {foreignKey: {unique: true}});\n        Course.belongsTo(models.Period, {foreignKey: {unique: true}});\n        Course.belongsTo(models.Schedule, {foreignKey: {unique: true}});\n        Course.belongsTo(models.Room, {foreignKey: {unique: true}});\n        Course.belongsTo(models.Subject, {foreignKey: {unique: true}});\n\n        Course.belongsTo(models.user, { as: 'CreatedBy' });\n        Course.belongsTo(models.user, { as: 'UpdateBy' });\n        Course.belongsTo(models.user, { as: 'DeleteBy' });\n      }\n    }\n  );\n\n  return Course;\n};\n```\n\n```text\nexports.courseFields = function(req, res) {\n\n    db.Course.find({\n        where: {id: req.params.PeriodIdF},\n        attributes: ['id'], \n        include: [{model:db.Room, attributes:['DisplayLabel']}]})\n    .then(function(courses) {\n            return res.json(courses);\n        })\n        .catch(function(err) {\n            return res.render('error', {\n                error: err,\n                status: 500\n            });\n        });\n};\n```\n\n```js\ninclude: [\n             {model:db.Room, attributes:['DisplayLabel']},\n             {model:db.Periods, attributes:['DisplayLabel']},\n             {model:db.Subjects, attributes:['Name']}   \n         ]\n```\n\n========================================\n\nComments:\n- thanks, that worked. Just an aditional question, How do I create a Contrain Key with the id and the foreign keys of the association. It's supposed that with the unique : true it will create, but it seems that only give the field a not duplicate restriction.","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":162,"estimatedTokens":1117}}638{"id":"stack-43486121","source":"stackoverflow","questionId":43486121,"title":"Sequelize.js still deletes table row even if paranoid is set to true","tags":["node.js","postgresql","express","sequelize.js","sequelize-cli"],"text":"Title: Sequelize.js still deletes table row even if paranoid is set to true\nTags: node.js, postgresql, express, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble getting Sequelize.js to soft delete the rows in my table. I used Sequelize cli to do all my migrations and I'm not using the sync feature to resync the database on start. I have the timestamp fields and even the deletedAt field in my migration and models (model has paranoid: true also) and no matter what it still deletes the row instead of adding a timestamp to the deletedAt field. I noticed when do any querying it doesn't add the deletedAt = NULL in the query like I've seen in some tutorials. I'm using Sequelize.js v3.29.0.\n\nModel File:\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var Collection = sequelize.define('Collection', {\n userId: {\n type: DataTypes.INTEGER,\n allowNull: false,\n validate: {\n isInt: true\n }\n },\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n description: DataTypes.TEXT,\n createdAt: {\n allowNull: false,\n type: DataTypes.DATE\n },\n updatedAt: {\n allowNull: false,\n type: DataTypes.DATE\n },\n deletedAt: {\n type: DataTypes.DATE\n }\n }, {\n classMethods: {\n associate: function(models) {\n Collection.belongsTo(models.User, { foreignKey: 'userId' })\n }\n }\n }, {\n timestamps: true,\n paranoid: true\n });\n return Collection;\n};\n```\n\nMigration File:\n\n```\n'use strict';\nmodule.exports = {\n up: function(queryInterface, Sequelize) {\n return queryInterface.createTable('Collections', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n userId: {\n allowNull: false,\n type: Sequelize.INTEGER\n },\n name: {\n allowNull: false,\n type: Sequelize.STRING\n },\n description: {\n type: Sequelize.TEXT\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n deletedAt: {\n type: Sequelize.DATE\n }\n });\n },\n down: function(queryInterface, Sequelize) {\n return queryInterface.dropTable('Collections');\n }\n};\n```\n\nHere is the code in the controller I'm using to destroy the collection object.\n\n```\nCollection.findOne({\n where: {\n id: collectionId,\n userId: user.id\n }\n }).then(function(collection){\n if (collection !== null) {\n collection.destroy().then(function(){\n res.redirect('/collection');\n }).catch(function(error){\n res.redirect('/collection/'+collectionId);\n });\n }\n });\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var Collection = sequelize.define('Collection', {\n    userId: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      validate: {\n          isInt: true\n      }\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    description: DataTypes.TEXT,\n    createdAt: {\n        allowNull: false,\n        type: DataTypes.DATE\n    },\n    updatedAt: {\n        allowNull: false,\n        type: DataTypes.DATE\n    },\n    deletedAt: {\n        type: DataTypes.DATE\n    }\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Collection.belongsTo(models.User, { foreignKey: 'userId' })\n      }\n    }\n  }, {\n    timestamps: true,\n    paranoid: true\n  });\n  return Collection;\n};\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: function(queryInterface, Sequelize) {\n    return queryInterface.createTable('Collections', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      userId: {\n        allowNull: false,\n        type: Sequelize.INTEGER\n      },\n      name: {\n        allowNull: false,\n        type: Sequelize.STRING\n      },\n      description: {\n        type: Sequelize.TEXT\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      deletedAt: {\n          type: Sequelize.DATE\n      }\n    });\n  },\n  down: function(queryInterface, Sequelize) {\n    return queryInterface.dropTable('Collections');\n  }\n};\n```\n\n```text\nCollection.findOne({\n        where: {\n            id: collectionId,\n            userId: user.id\n        }\n    }).then(function(collection){\n        if (collection !== null) {\n            collection.destroy().then(function(){\n                res.redirect('/collection');\n            }).catch(function(error){\n                res.redirect('/collection/'+collectionId);\n            });\n        }\n    });\n```\n\n```text\n..., {\nclassMethods: {\n    associate: function(models) {\n        Collection.belongsTo(models.User,{ foreignKey: 'userId' })\n      }\n  },\n    timestamps: true,\n    paranoid: true\n}\n```\n\n========================================\n\nComments:\n- Thank you so much. I didn't realize that the class level options went into the same place as the classMethods and instanceMethods in the 2nd level of the Model definition.","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":230,"estimatedTokens":1236}}639{"id":"stack-38336059","source":"stackoverflow","questionId":38336059,"title":"Sequelize query string prefix / starts with","tags":["javascript","postgresql","sequelize.js"],"text":"Title: Sequelize query string prefix / starts with\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm building an autofill function that takes a string input and returns a list of string suggestions. \n\nSequelize's `iLike:query` returns every string in which the queried string appears. I would like to favour strings for which the query is a prefix. For example when `query='sh'` then the results should return strings that start with `sh` instead of having `sh` anywhere within the string.\n\nThis is relatively simple to do after receiving the data from the DB, however I was wondering if there is a way to accomplish this via sequelize while querying the DB? If so how? \n\nThe DB size will be between 10,000 and 100,000 strings of no more than a handful of words (company names to be exact).\n\nOptional question: DB's usually have superior performance to generically written code, in this circumstance should there even be a noticeable difference? Or should I just collect all the data from the DB and apply some other filters on it after via vanilla JS. \n\n```\nlet suggestions = yield db.Company.findAll({\n limit: 7,\n where: {\n company_name: {\n $iLike: '%'+this.data.query\n }\n }\n })\n```\n\n========================================\n\nTop Answer:\n**Sequelize @6.37.3**\n\nBased on @alexei-darmin's answer\nThe code snippet below works for me\n\n```\nimport { Op } from \"sequelize\";\n\nlet suggestions = yield db.Company.findAll({\n limit: 5,\n where: { $or: [\n { stock_ticker: { [Op.iLike]: query + '%' } },\n { company_name: { [Op.iLike]: query + '%' } }\n ]},\n order: '\"volume\" DESC'\n })\n```\n\n========================================\n\nCode:\n```text\nlet suggestions = yield db.Company.findAll({\n  limit: 7,\n    where: {\n      company_name: {\n        $iLike: '%'+this.data.query\n      }\n    }\n })\n```\n\n```text\niLike:query\n```\n\n```text\nquery='sh'\n```\n\n```text\nsh\n```\n\n```text\nsh\n```\n\n```text\nlet suggestions = yield db.Company.findAll({\n    limit: 5,\n    where: { $or: [\n      { stock_ticker: { $ilike: query + '%' } },\n      { company_name: { $ilike: query + '%' } }\n    ]},\n    order: '\"volume\" DESC'\n  })\n```\n\n```text\n'%'\n```\n\n```text\n*\n```\n\n```text\nquery + '%'\n```\n\n```js\nimport { Op } from \"sequelize\";\n\nlet suggestions = yield db.Company.findAll({\n    limit: 5,\n    where: { $or: [\n      { stock_ticker: { [Op.iLike]: query + '%' } },\n      { company_name: { [Op.iLike]: query + '%' } }\n    ]},\n    order: '\"volume\" DESC'\n  })\n```\n\n========================================\n\nComments:\n- This throw `Invalid value { '$ilike': query + '%'}` error in my environment. Sequelize @6.37.3","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":117,"estimatedTokens":650}}640{"id":"stack-30202056","source":"stackoverflow","questionId":30202056,"title":"Change database connection depending on route in express.js with sequelize","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: Change database connection depending on route in express.js with sequelize\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to change the database connection in `sequelize` depending on the route? \n\nFor example, Users have access to 2 different installations in a website:\n - `example.com/foo`\n - `example.com/bar`\n\nUpon login users are redirected to `example.com/foo` \nTo get all their tasks for the `foo` site, they need to visit `example.com/foo/tasks`\n\nThe `bar` site uses a separate database and thus if they want to get all their tasks for `bar` they have to go to `example.com/bar/tasks`\n\nEvery installation has its own database, and all databases have the same schema.\n\nIs it possible to change the database connection depending on which route is visited?\n\n*login only occurs once\n\n========================================\n\nTop Answer:\nI think is better to change collections depending on the route.\nHave `foo_tasks` collection and `bar_tasks` collection in the same database. \n\nOr have the attribute `type` in the `tasks` collection that specifies if the task is a \"foo task\" or a \"bar task\".\n\n========================================\n\nCode:\n```text\nsequelize\n```\n\n```text\nexample.com/foo\n```\n\n```text\nexample.com/bar\n```\n\n```text\nexample.com/foo\n```\n\n```text\nfoo\n```\n\n```text\nexample.com/foo/tasks\n```\n\n```text\nbar\n```\n\n```text\nbar\n```\n\n```text\nexample.com/bar/tasks\n```\n\n```text\nvar router = express.Router()\n// This assumes the database is always the 2nd param, \n// otherwise you have to enumerate\nrouter.use('/:database/*', function(req, res, next){\n  req.db = req.params.database;\n  next();\n}\n```\n\n```text\nvar fooDB = new Sequelize('postgres://user:pass@example.com:5432/foo');\nvar barDB = new Sequelize('postgres://user:pass@example.com:5432/bar');\nmodule.exports = {\n  foo: fooDB,\n  bar: barDB,\n}\n```\n\n```text\nvar connection = require('connection);\n function getTasks(req, params){\n   var database = connection[req.db]; \n   //database now contains the db you wish to access based on the route.\n }\n```\n\n```text\nfoo_tasks\n```\n\n```text\nbar_tasks\n```\n\n```text\ntype\n```\n\n```text\ntasks\n```\n\n========================================\n\nComments:\n- how to do this dynamic way? for example you are hard coding the two databases in connection.js? if there are 1000 database coming dynamically how you handle?\n- consider blogging system for *.blog.dev and subdomain is database name, how many connection did you need ?\n- I have the same trouble","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":118,"estimatedTokens":626}}641{"id":"stack-16991798","source":"stackoverflow","questionId":16991798,"title":"sequelize.define error: has no method 'define' in nodejs","tags":["node.js","sequelize.js"],"text":"Title: sequelize.define error: has no method 'define' in nodejs\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThis is my managedb.js which manages all the database models:\n\n```\nvar Sequelize = require('sequelize-postgres').sequelize\nvar postgres = require('sequelize-postgres').postgres\n\n var db = new Sequelize('testdb', 'postgres', 'postgres', {\n dialect: 'postgres'\n})\n\nvar models = [\n'user'\n];\n\nmodels.forEach(function(model) {\nmodule.exports[model] = db.import(__dirname + '/' + model);\n});\n\nexports.db = db;\n```\n\nThis is my user.js\n\n```\nvar sequelize = require(\"sequelize\");\nvar seq = require(\"./managedb\");\nvar db = seq.db;\n\nvar Project = db.define('Project', {\n title: sequelize.STRING,\n description: sequelize.TEXT\n});\n```\n\nIn my app.js\n\n```\nvar seq = require('./models/managedb');\nseq.db.sync();\n```\n\nError I get is this:\n\n```\nvar Project = sequelize.define('Project', {\n ^\nTypeError: Object function (database, username, password, options) {\n var urlParts\n options = options || {}\n\n if (arguments.length === 1 || (arguments.length === 2 && typeof username === 'object')) {\n options = username || {}\n urlParts = url.parse(arguments[0])\n database = urlParts.path.replace(/^\\//, '')\n dialect = urlParts.protocol\n options.dialect = urlParts.protocol.replace(/:$/, '')\n options.host = urlParts.hostname\n\n if (urlParts.port) {\n options.port = urlParts.port\n }\n\n if (urlParts.auth) {\n username = urlParts.auth.split(':')[0]\n password = urlParts.auth.split(':')[1]\n }\n }\n\n this.options = Utils._.extend({\n dialect: 'mysql',\n host: 'localhost',\n port: 3306,\n protocol: 'tcp',\n define: {},\n query: {},\n sync: {},\n logging: console.log,\n omitNull: false,\n queue: true,\n native: false,\n replication: false,\n pool: {},\n quoteIdentifiers: true\n }, options || {})\n\n if (this.options.logging === true) {\n console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log')\n this.options.logging = console.log\n }\n\n this.config = {\n database: database,\n username: username,\n password: (( ([\"\", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),\n host : this.options.host,\n port : this.options.port,\n pool : this.options.pool,\n protocol: this.options.protocol,\n queue : this.options.queue,\n native : this.options.native,\n replication: this.options.replication,\n maxConcurrentQueries: this.options.maxConcurrentQueries\n }\n\n var ConnectorManager = require(\"./dialects/\" + this.options.dialect + \"/connector-manager\")\n\n this.daoFactoryManager = new DAOFactoryManager(this)\n this.connectorManager = new ConnectorManager(this, this.config)\n\n this.importCache = {}\n } has no method 'define'\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize-postgres').sequelize\nvar postgres  = require('sequelize-postgres').postgres\n\n var db = new Sequelize('testdb', 'postgres', 'postgres', {\n  dialect: 'postgres'\n})\n\n\nvar models = [\n'user'\n];\n\nmodels.forEach(function(model) {\nmodule.exports[model] = db.import(__dirname + '/' + model);\n});\n\n\n\nexports.db = db;\n```\n\n```text\nvar sequelize = require(\"sequelize\");\nvar seq = require(\"./managedb\");\nvar db = seq.db;\n\nvar Project = db.define('Project', {\n  title: sequelize.STRING,\n  description: sequelize.TEXT\n});\n```\n\n```text\nvar seq = require('./models/managedb');\nseq.db.sync();\n```\n\n```text\nvar Project = sequelize.define('Project', {\n                        ^\nTypeError: Object function (database, username, password, options) {\n    var urlParts\n    options = options || {}\n\n    if (arguments.length === 1 || (arguments.length === 2 && typeof username === 'object')) {\n      options = username || {}\n      urlParts = url.parse(arguments[0])\n      database = urlParts.path.replace(/^\\//,  '')\n      dialect = urlParts.protocol\n      options.dialect = urlParts.protocol.replace(/:$/, '')\n      options.host = urlParts.hostname\n\n      if (urlParts.port) {\n        options.port = urlParts.port\n      }\n\n      if (urlParts.auth) {\n        username = urlParts.auth.split(':')[0]\n        password = urlParts.auth.split(':')[1]\n      }\n    }\n\n    this.options = Utils._.extend({\n      dialect: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      protocol: 'tcp',\n      define: {},\n      query: {},\n      sync: {},\n      logging: console.log,\n      omitNull: false,\n      queue: true,\n      native: false,\n      replication: false,\n      pool: {},\n      quoteIdentifiers: true\n    }, options || {})\n\n    if (this.options.logging === true) {\n      console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log')\n      this.options.logging = console.log\n    }\n\n    this.config = {\n      database: database,\n      username: username,\n      password: (( ([\"\", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),\n      host    : this.options.host,\n      port    : this.options.port,\n      pool    : this.options.pool,\n      protocol: this.options.protocol,\n      queue   : this.options.queue,\n      native  : this.options.native,\n      replication: this.options.replication,\n      maxConcurrentQueries: this.options.maxConcurrentQueries\n    }\n\n    var ConnectorManager = require(\"./dialects/\" + this.options.dialect + \"/connector-manager\")\n\n    this.daoFactoryManager = new DAOFactoryManager(this)\n    this.connectorManager  = new ConnectorManager(this, this.config)\n\n    this.importCache = {}\n  } has no method 'define'\n```\n\n```text\nvar Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize('database', 'username');\n\nvar Project = sequelize.define('Project', {\n  title: sequelize.STRING,\n  description: sequelize.TEXT\n});\n```\n\n========================================\n\nComments:\n- Do I've to instantiate sequelize in every model then? I can just import it from the manage db, right?\n- Yes, generally you should use the same instance for your models. Edit: You can module.exports your instance and use it to define your models in other files.\n- The error still persists. I edited the question to show the change in code. Did I export/import it wrong?\n- The error that I'm currently getting it this: TypeError: Cannot call method 'define' of undefined\n- Does it works if you use module.exports.db = db instead of exports.db = db?\n- in my case, I forgot the `new` keyword before Sequelize","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":249,"estimatedTokens":1590}}642{"id":"stack-27159759","source":"stackoverflow","questionId":27159759,"title":"Sequelize, store an object along with child (associated) object","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize, store an object along with child (associated) object\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have created my models fro sequelize. I've got a User model which attached as an Address object. The links are defined as such:\n\n```\nUser.hasMany(Address);\n\nAddress.belongsTo(User);\n```\n\nThe object I am trying to store has the right structure with the child attached:\n\n```\n{\n Username: \"John\",\n Email: \"John@test.com\",\n Address: [{\n street: \"somestreet\"\n }]\n };\n```\n\nWhen I try to create the object, the parent is inserted in my database, but the app exits with a [sequelize object] does not contain method .save()\n\nI am creating as follows:\n\n```\nUser.create(user).success(function(user){\n\n});\n```\n\nI have got logging enabled on my sequelize instance and I can see the correct sql being generated for the parent object, but I am stuck on how to properly store the child (associated) object.\n\n========================================\n\nTop Answer:\nYou can also use the `include` keyword like so: \n\n```\nconst user = {\n Username: \"John\",\n Email: \"John@test.com\",\n Address: [\n {\n street: \"somestreet\"\n }\n ]\n}\n\nUser.create(user, {\n include: [models.address]\n})\n.then((createdUser) => {\n // ...\n})\n```\n\nWhere `models` is an object that holds all your Sequelize models and their associations.\n\n========================================\n\nCode:\n```text\nUser.hasMany(Address);\n\nAddress.belongsTo(User);\n```\n\n```text\n{\n      Username: \"John\",\n      Email: \"John@test.com\",\n      Address: [{\n          street: \"somestreet\"\n      }]\n  };\n```\n\n```text\nUser.create(user).success(function(user){\n\n});\n```\n\n```text\n{\n      Username: \"John\",\n      Email: \"John@test.com\",\n      Address: [{\n          street: \"somestreet\"\n      }]\n  };\n```\n\n```text\nvar user = {\n    Username: \"John\",\n    Email: \"John@test.com\"\n};\n\nUser.create(user).then(function(user) {\n    // sequelize passes the newly created object into the callback,\n    // and we named the argument \"user\".\n    // \"user\" is now a sequelize instance that has the association\n    // methods of add[AS]. So we use it.\n\n    var address = Address.build({\n        street: \"somestreet\"\n    };\n    return user.addAddress(address);\n}).then(function(address){\n    //do something with address?\n}).catch(function(err){\n    //do something with your err?\n});\n```\n\n```text\nUser.create(user).then(function(user) {\n    var address = {\n        street: \"somestreet\"\n        userId: user.userId\n    }\n    return Address.create(address);\n}).then(function(address){\n    //do something with address?\n}).catch(function(err){\n    //do something with your err?\n});\n```\n\n```text\n.then\n```\n\n```text\n.catch\n```\n\n```text\n.finally\n```\n\n```text\nuserId\n```\n\n```text\nUser\n```\n\n```text\nuserId\n```\n\n```text\nUsername\n```\n\n```text\nconst user = {\n  Username: \"John\",\n  Email: \"John@test.com\",\n  Address: [\n    {\n      street: \"somestreet\"\n    }\n  ]\n}\n\nUser.create(user, {\n    include: [models.address]\n})\n.then((createdUser) => {\n   // ...\n})\n```\n\n```text\ninclude\n```\n\n```text\nmodels\n```\n\n========================================\n\nComments:\n- Shouldn't it be `Address: [{street: \"somestreet\"}]` according to that declaration? Many, not one.\n- @JanR were you able to create child instance using the above written code??\n- Yes, make sure you pass it in as an array [ ]\n- In order for this to work for me, I had to run this: `User.Address = User.hasMany(Address);`, and use the include opt: `User.create(user, { include: [models.address] })`","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":197,"estimatedTokens":870}}643{"id":"stack-26106165","source":"stackoverflow","questionId":26106165,"title":"sequelize dynamic query params","tags":["node.js","express","sequelize.js"],"text":"Title: sequelize dynamic query params\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm sending query params as JSON format in `req.query.p` from my front-end MVC framework , the point is that this could be a dynamic key and value, for example:\n\n```\nreq.query.p = {nombre : 'juan'}\n```\n\nor\n\n```\nreq.query.p = {pais : 'chile'}\n```\n\nSo I need the key, and the value to put them in the where statement, something like this\n\n```\nexports.select = function(req, res){\n console.log('=> GET | Obtener peliculas'.bold.get);\n db.Pelicula\n .findAndCountAll({\n limit : req.query.limit,\n offset : req.query.offset,\n where : req.query.p ? [req.query.p.KEY + \" = ?\", req.query.p.VAL] : null\n })\n .success(function(resp){\n console.log(JSON.stringify(resp.rows, null, 4).bold.get);\n res.json({peliculas : resp.rows, meta : { total : resp.count}});\n });\n}\n```\n\n========================================\n\nTop Answer:\nUsually I put the entire object, so if it comes empty, it will work normally as if there is no conditional WHERE.\nYou don't need to add {} in the where, because the object that comes from req.query already has it.\n\n```\nconst filter = req.query;\nexample= await ModelExample.findAndCountAll({\n where:\n filter\n})\n```\n\n========================================\n\nCode:\n```text\nreq.query.p = {nombre : 'juan'}\n```\n\n```text\nreq.query.p = {pais : 'chile'}\n```\n\n```text\nexports.select = function(req, res){\n    console.log('=> GET | Obtener peliculas'.bold.get);\n        db.Pelicula\n            .findAndCountAll({\n                limit : req.query.limit,\n                offset : req.query.offset,\n                where : req.query.p ? [req.query.p.KEY + \" = ?\", req.query.p.VAL] : null\n            })\n            .success(function(resp){\n                console.log(JSON.stringify(resp.rows, null, 4).bold.get);\n                res.json({peliculas : resp.rows, meta : { total : resp.count}});\n            });\n}\n```\n\n```text\nreq.query.p\n```\n\n```text\nwhere: req.query.p\n```\n\n```text\nconst filter = req.query;\nexample= await ModelExample.findAndCountAll({\n               where:\n                filter\n})\n```\n\n```text\nconst { Op } = require(\"sequelize\");\n\nconst from = new Date()\n// const to = new Date().setMinutes(40)\nconst to = null\n\nlet where = {\n    timestamp: {\n        [Op.or]: {}\n    }\n}\n\nif (from) {\n    where.timestamp[Op.or][Op.gte] = new Date(from)\n}\nif (to) {\n    where.timestamp[Op.or][Op.lte] = new Date(to)\n}\nconsole.log(where);\n\nModel.find({ where })\n```\n\n========================================\n\nComments:\n- Thanks you! it works :P. Btw what about if i want to pass more than one args to my query? Which is the right way to handle this?\n- `where: { arg1: something, arg2: somethingelse }` - plain old javascript objects\n- What's the operation there? \"...where arg1 = something AND/OR? arg2 = somethingelse\"\n- Default is AND. If you want OR, use `where: sequelize.or({ arg1: something }, { arg2: somethingelse })`. I'd suggest to take a look at the guides on sequelizejs.com and the API docs at github.com/sequelize/sequelize/wiki/API-Reference","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":123,"estimatedTokens":768}}644{"id":"stack-20014593","source":"stackoverflow","questionId":20014593,"title":"Why Does Sequelize.js in Node.js always return true from a MySQL bit field?","tags":["mysql","node.js","sequelize.js"],"text":"Title: Why Does Sequelize.js in Node.js always return true from a MySQL bit field?\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a Node.Js Express application and I'm using the Sequelize.js OR/M to query a MySQL 5.6 database. I have a table called homes that contains a couple of bit fields (one of which is called isrental which I have defined as Boolean in the model. When querying the db, these fields always return true even when I have a 0 stored on the record. Here's a quick code example:\n\n```\nvar Sequelize = require('sequelize-mysql').sequelize;\nvar orm = new Sequelize('mysql://procHOAPro:password@NewMasterBedRm/HOAPro'), {\n dialect: 'mysql',\n language: 'en'\n});\nvar Home = orm.define('homes', {\n homeid : Sequelize.INTEGER,\n state : Sequelize.STRING,\n county : Sequelize.STRING,\n city : Sequelize.STRING,\n zip : DataTypes.STRING,\n isrental : {type: Sequelize.BOOLEAN, allowNull: true, defaultValue: false},\n isbuilderowned : {type: Sequelize.BOOLEAN, allowNull: true, defaultValue: false},\n mailingaddress : Sequelize.STRING\n}); \nHome.all().success(function(homes) {\n console.log(homes[0].isrental);\n console.log(homes[1].isrental);\n});\n```\n\ntable definition:\n`CREATE TABLE 'homes' (\n 'homeid' int(11) NOT NULL AUTO_INCREMENT,\n 'state' varchar(2) NOT NULL,\n 'county' varchar(100) NOT NULL,\n 'city' varchar(100) NOT NULL,\n 'zip' varchar(5) NOT NULL,\n 'section' varchar(50) NOT NULL,\n 'township' int(11) NOT NULL,\n 'townshipdir' varchar(1) NOT NULL,\n 'range' int(11) NOT NULL,\n 'rangedir' varchar(1) NOT NULL,\n 'block' int(11) NOT NULL,\n 'lot' int(11) NOT NULL,\n 'physicaladdress' varchar(255) NOT NULL,\n 'isrental' bit(1) NOT NULL DEFAULT b'0',\n 'isbuilderowned' int(1) NOT NULL DEFAULT '0',\n 'mailingaddress' varchar(255) DEFAULT NULL,\n PRIMARY KEY ('homeid'),\n UNIQUE KEY 'homeid_UNIQUE' ('homeid')\n) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;`\noutput:\n\n Executing: SELECT * FROM `homes`;\n\n true \n\nAs an fyi, I also used the node-orm OR/M and I got the exact same behavior.\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize-mysql').sequelize;\nvar orm = new Sequelize('mysql://procHOAPro:password@NewMasterBedRm/HOAPro'), {\n    dialect: 'mysql',\n    language: 'en'\n});\nvar Home = orm.define('homes', {\n    homeid : Sequelize.INTEGER,\n    state : Sequelize.STRING,\n    county : Sequelize.STRING,\n    city : Sequelize.STRING,\n    zip : DataTypes.STRING,\n    isrental : {type: Sequelize.BOOLEAN, allowNull: true, defaultValue: false},\n    isbuilderowned : {type: Sequelize.BOOLEAN, allowNull: true, defaultValue: false},\n    mailingaddress : Sequelize.STRING\n});    \nHome.all().success(function(homes) {\n    console.log(homes[0].isrental);\n    console.log(homes[1].isrental);\n});\n```\n\n```text\nCREATE TABLE 'homes' (\n  'homeid' int(11) NOT NULL AUTO_INCREMENT,\n  'state' varchar(2) NOT NULL,\n  'county' varchar(100) NOT NULL,\n  'city' varchar(100) NOT NULL,\n  'zip' varchar(5) NOT NULL,\n  'section' varchar(50) NOT NULL,\n  'township' int(11) NOT NULL,\n  'townshipdir' varchar(1) NOT NULL,\n  'range' int(11) NOT NULL,\n  'rangedir' varchar(1) NOT NULL,\n  'block' int(11) NOT NULL,\n  'lot' int(11) NOT NULL,\n  'physicaladdress' varchar(255) NOT NULL,\n  'isrental' bit(1) NOT NULL DEFAULT b'0',\n  'isbuilderowned' int(1) NOT NULL DEFAULT '0',\n  'mailingaddress' varchar(255) DEFAULT NULL,\n  PRIMARY KEY ('homeid'),\n  UNIQUE KEY 'homeid_UNIQUE' ('homeid')\n) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;\n```\n\n```text\nhomes\n```\n\n```text\n!!value\n```\n\n========================================\n\nComments:\n- I am not familiar with the package in question, so I am not putting this as a definite answer. But why are you mapping a bit field to a Boolean attribute in the model? Shouldn't the field also be Boolean? Or try mapping it to a bit (if the ORM supports that type).\n- I am mapping it to a Boolean in the model while the DB equivalent is a BIT. This is the common mapping in most OR/Ms in that a bit field on a table maps to a Boolean on the resulting object. The DB doesn't have a Boolean field type and conversely the OR/M doesn't have a bit type.\n- Sequelize defines `BOOLEAN` as `TINYINT(1)` or bit. That part is fine.\n- Can you post the table description too? Your columns might be out of order or something hinky causing sequelize to mess up.\n- Added table definition","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":122,"estimatedTokens":1092}}645{"id":"stack-40404738","source":"stackoverflow","questionId":40404738,"title":"How to set the Application Name for a Sequelize application","tags":["node.js","sequelize.js","tedious"],"text":"Title: How to set the Application Name for a Sequelize application\nTags: node.js, sequelize.js, tedious\nSource: Stack Overflow\n\nQuestion:\nI've got a nodejs application that uses Sequelize as it's ORM. I've successfully got Sequelize connected to the database, but I haven't found anything in the documentation that explains how to set the application name. To clarify I'm looking to set a unique Application Name attribute for my app's connection string. That way when a DBA is looking at traffic they can pick out my application's queries from the rest.\n\nIs this something that Sequelize can even do? Or does this need to be done at the tedious level? Failing that, is there a way in nodejs to specify connection string attributes?\n\n========================================\n\nTop Answer:\nFor those finding this when they're looking for how to set the name for Postgres, you use `application_name` in the `dialectOptions`, eg\n\n```\n{\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n database: process.env.DB_NAME,\n port: process.env.DB_PORT,\n host: DB_HOST,\n dialect: 'postgresql',\n dialectOptions: {\n application_name: 'My Node App',\n },\n},\n```\n\n========================================\n\nCode:\n```text\nvar conn = new Sequelize('my_db', 'my_user', 'my_pass', {\n  host: 'my_server',\n  dialect: 'mssql',\n\n  dialectOptions: {\n    appName: 'my_app_name'\n  }\n});\n```\n\n```text\nappName\n```\n\n```text\ndialectOptions\n```\n\n```text\n{\n    username: process.env.DB_USER,\n    password: process.env.DB_PASS,\n    database: process.env.DB_NAME,\n    port: process.env.DB_PORT,\n    host: DB_HOST,\n    dialect: 'postgresql',\n    dialectOptions: {\n        application_name: 'My Node App',\n    },\n},\n```\n\n```text\napplication_name\n```\n\n```text\ndialectOptions\n```\n\n========================================\n\nComments:\n- Thanks for the answer! In a standalone nodejs/sequelize app this works 100%. I ran into issues trying to use this in a sails application with the sails-hook-sequelize module. If I find a solution to that issue I will include it on this page.\n- Post a new question and answer it yourself if you do :)\n- stackoverflow.com/questions/40444535/&hellip; Here is the new question\n- Looks like your answer worked for sails-hook-sequelize as well. Seems like my method of capturing the application name had been wrong. Using MS SQL Profiler I was able to see the updated Application name. Seeing as how this answer covers both questions, I have deleted the question I asked above (40444535)\n- I still get Tedious as application_name, could you please take a look at my question: stackoverflow.com/questions/56903706/&hellip;\n- apologies, it’s been years since I’ve used Sequelize. Perhaps @OrwellHindenberg can help you.\n- In newer versions you must add options inside dialectOptions like: ``` var conn = new Sequelize('my_db', 'my_user', 'my_pass', { host: 'my_server', dialect: 'mssql', dialectOptions: { options: { appName: 'my_app_name' } } }); ```\n- application_name for postgres","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":746}}646{"id":"stack-34263108","source":"stackoverflow","questionId":34263108,"title":"Sequelize: Cannot set a new unique constraint message","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize: Cannot set a new unique constraint message\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup a validation message for unique constraint violation for the fields `username` and `email`. However, whenever an already taken username is entered, it shows the message defined for the `email` property, but shows the input for the `username` property and also says that this input is for the `username` property. How would I fix this? Here is my code:\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n var users = sequelize.define('users', {\n full_name: {\n type: DataTypes.STRING,\n allowNull: false,\n validate: {\n len: {\n args: [5, 50],\n msg: 'Your full name may be 5 to 50 characters only.'\n }\n }\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: {\n msg: 'This email is already taken.'\n },\n validate: {\n isEmail: {\n msg: 'Email address must be valid.'\n }\n }\n },\n username: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: {\n msg: 'This username is already taken.'\n },\n validate: {\n len: {\n args: [5, 50],\n msg: 'Your username may be 5 to 50 characters only.'\n }\n }\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false,\n validate: {\n len: {\n args: [5, 72],\n msg: 'Your password may be 5 to 72 characters only.'\n }\n }\n },\n rank: {\n type: DataTypes.INTEGER,\n allowNull: false,\n validate: {\n isInt: true\n }\n }\n }, {\n hooks: {\n beforeValidate: function (user, options) {\n if (typeof user.email === 'string') {\n user.email = user.email.toLowerCase();\n }\n\n if (typeof user.username === 'string') {\n user.username = user.username.toLowerCase();\n }\n }\n }\n });\n\n return users;\n};\n```\n\nThis is the output I get from input:\n\n```\n{\n \"name\": \"SequelizeUniqueConstraintError\",\n \"message\": \"Validation error\",\n \"errors\": [\n {\n \"message\": \"This email is already taken.\",\n \"type\": \"unique violation\",\n \"path\": \"username\",\n \"value\": \"hassan\"\n }\n ],\n \"fields\": {\n \"username\": \"hassan\"\n }\n}\n```\n\nSo as you can see, it says it is the username that is not unique, but uses the message defined for the email property.\n\n========================================\n\nTop Answer:\nThis is possible try like this\n\n```\nunique: {\n arg: true,\n msg: 'This username is already taken.'\n},\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function (sequelize, DataTypes) {\n    var users = sequelize.define('users', {\n        full_name: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            validate: {\n                len: {\n                    args: [5, 50],\n                    msg: 'Your full name may be 5 to 50 characters only.'\n                }\n            }\n        },\n        email: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            unique: {\n                msg: 'This email is already taken.'\n            },\n            validate: {\n                isEmail: {\n                    msg: 'Email address must be valid.'\n                }\n            }\n        },\n        username: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            unique: {\n                msg: 'This username is already taken.'\n            },\n            validate: {\n                len: {\n                    args: [5, 50],\n                    msg: 'Your username may be 5 to 50 characters only.'\n                }\n            }\n        },\n        password: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            validate: {\n                len: {\n                    args: [5, 72],\n                    msg: 'Your password may be 5 to 72 characters only.'\n                }\n            }\n        },\n        rank: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            validate: {\n                isInt: true\n            }\n        }\n    }, {\n        hooks: {\n            beforeValidate: function (user, options) {\n                if (typeof user.email === 'string') {\n                    user.email = user.email.toLowerCase();\n                }\n\n                if (typeof user.username === 'string') {\n                    user.username = user.username.toLowerCase();\n                }\n            }\n        }\n    });\n\n    return users;\n};\n```\n\n```text\n{\n  \"name\": \"SequelizeUniqueConstraintError\",\n  \"message\": \"Validation error\",\n  \"errors\": [\n    {\n      \"message\": \"This email is already taken.\",\n      \"type\": \"unique violation\",\n      \"path\": \"username\",\n      \"value\": \"hassan\"\n    }\n  ],\n  \"fields\": {\n    \"username\": \"hassan\"\n  }\n}\n```\n\n```text\nusername\n```\n\n```text\nemail\n```\n\n```text\nemail\n```\n\n```text\nusername\n```\n\n```text\nusername\n```\n\n```text\nvalidate: { }\n```\n\n```text\ndefaultValue: ''\n```\n\n```text\nnotNull\n```\n\n```text\nvalidate\n```\n\n```text\nallowNull\n```\n\n```text\nvalidate: {}\n```\n\n```js\nisUnique(value) {\n          \n          return User.findOne({where:{name:value}})\n            .then((name) => {\n              if (name) {\n                throw new Error('Validation error: name already exist');\n              }\n            })\n        }\n```\n\n```text\nunique: {\n    arg: true,\n    msg: 'This username is already taken.'\n},\n```\n\n========================================\n\nComments:\n- What if you define `unique` at indexes property , is the table structure created properly? docs.sequelizejs.com/en/latest/docs/models-definition/#index&zwnj;&#8203;es\n- @GeoPhoenix I gave up on this ages ago.\n- @GeoPhoenix It is not possible according to an issue I opened in GitHub.\n- Can confirm that this works\n- With typescript `arg` wasn't accepted and I had to add `name` field, to create the unique constraint","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":279,"estimatedTokens":1403}}647{"id":"stack-30308217","source":"stackoverflow","questionId":30308217,"title":"Sequelize find by association through manually-defined join table","tags":["node.js","sequelize.js"],"text":"Title: Sequelize find by association through manually-defined join table\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI know that there is a simpler case described here: \n\nUnfortunately, my case is a bit more complex than that. I have a User model which `belongsToMany` Departments (which in turn `belongsToMany` Users), but does so through `userDepartment`, a manually defined join table. **My goal is to get all the users belonging to a given department.** First let's look at `models/user.js`:\n\n```\nvar user = sequelize.define(\"user\", {\n id: {\n type: DataTypes.INTEGER,\n field: 'emplId',\n primaryKey: true,\n autoIncrement: false\n },\n firstname: {\n type: DataTypes.STRING,\n field: 'firstname_preferred',\n defaultValue: '',\n allowNull: false\n }\n ...\n ...\n ...\n\n associate: function(models) {\n user.belongsToMany(models.department, {\n foreignKey: \"emplId\",\n through: 'userDepartment'\n });\n })\n }\n ...\n return user;\n```\n\nNow, a look at `models/department.js`: \n\n```\nvar department = sequelize.define(\"department\", {\n id: {\n type: DataTypes.INTEGER,\n field: 'departmentId',\n primaryKey: true,\n autoIncrement: true\n },\n ...\n classMethods: {\n associate: function(models) {\n\n department.belongsToMany(models.user, {\n foreignKey: \"departmentId\",\n through: 'userDepartment',\n onDelete: 'cascade'\n });\n }\n\n ...\nreturn department;\n```\n\nAnd finally at `models/userDepartment.js`: \n\n```\nvar userDepartment = sequelize.define(\"userDepartment\", {\n title: {\n type: DataTypes.STRING,\n field: 'title',\n allowNull: false,\n defaultValue: ''\n }\n}, {\n tableName: 'user_departments'\n});\n\nreturn userDepartment;\n```\n\nSo far so good. However, this query: \n\n```\nmodels.user.findAll({\n where: {'departments.id': req.params.id},\n include: [{model: models.department, as: models.department.tableName}]\n\n})\n```\n\nFails with the following error:\n\n```\nSequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'user.departments.id' in 'where clause'\n```\n\nAttempting to include userDepartment model results in:\n\n```\nError: userDepartment (user_departments) is not associated to user!\n```\n\nIn short: I have two Sequelize Models with a M:M relationship. They are associated through a manually defined join table (which adds a job title to each unique relationship, i.e., User A is a \"Manager\" in Department B). Attempting to find Users by Department fails with a bad table name error.\n\nsequelize version \"^2.0.5\"\n\n========================================\n\nTop Answer:\nI had a similair problem, but in my case I couldn't switch the tables.\n\nI had to make use of the: `sequelize.literal` function.\n\nIn your case it would look like the following:\n\n```\nmodels.user.findAll({\n where: sequelize.literal(\"departments.id = \" + req.params.id),\n include: [{model: models.department, as: models.department.tableName}]\n})\n```\n\nI'm not fond of it, but it works.\n\n========================================\n\nCode:\n```text\nvar user = sequelize.define(\"user\", {\n    id: {\n        type: DataTypes.INTEGER,\n        field: 'emplId',\n        primaryKey: true,\n        autoIncrement: false\n    },\n    firstname: {\n        type: DataTypes.STRING,\n        field: 'firstname_preferred',\n        defaultValue: '',\n        allowNull: false\n    }\n    ...\n    ...\n    ...\n\n    associate: function(models) {\n            user.belongsToMany(models.department, {\n                foreignKey: \"emplId\",\n                through: 'userDepartment'\n                });\n            })\n    }\n    ...\n    return user;\n```\n\n```text\nvar department = sequelize.define(\"department\", {\n    id: {\n        type: DataTypes.INTEGER,\n        field: 'departmentId',\n        primaryKey: true,\n        autoIncrement: true\n    },\n    ...\n    classMethods: {\n        associate: function(models) {\n\n            department.belongsToMany(models.user, {\n                foreignKey: \"departmentId\",\n                through: 'userDepartment',\n                onDelete: 'cascade'\n            });\n        }\n\n    ...\nreturn department;\n```\n\n```text\nvar userDepartment = sequelize.define(\"userDepartment\", {\n    title: {\n        type: DataTypes.STRING,\n        field: 'title',\n        allowNull: false,\n        defaultValue: ''\n    }\n}, {\n    tableName: 'user_departments'\n});\n\nreturn userDepartment;\n```\n\n```text\nmodels.user.findAll({\n    where: {'departments.id': req.params.id},\n    include: [{model: models.department, as: models.department.tableName}]\n\n})\n```\n\n```text\nSequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'user.departments.id' in 'where clause'\n```\n\n```text\nError: userDepartment (user_departments) is not associated to user!\n```\n\n```text\nbelongsToMany\n```\n\n```text\nbelongsToMany\n```\n\n```text\nuserDepartment\n```\n\n```text\nmodels/user.js\n```\n\n```text\nmodels/department.js\n```\n\n```text\nmodels/userDepartment.js\n```\n\n```text\nmodels.department.find({\n    where: {id:req.params.id},\n    include: [models.user]\n```\n\n```text\nmodel_name\n```\n\n```text\nuser.departments.id\n```\n\n```text\ndepartments.id\n```\n\n```text\nmodels.user.findAll({\n    where: sequelize.literal(\"departments.id = \" + req.params.id),\n    include: [{model: models.department, as: models.department.tableName}]\n})\n```\n\n```text\nsequelize.literal\n```\n\n```js\nwhere: {\n   '$Table.column$' : value\n }\n```\n\n```text\nconst user0 = await User.create({name: 'user0'})\nconst user0Likes = await user0.getPosts({order: [['body', 'ASC']]})\nassert(user0Likes[0].body === 'post0');\nassert(user0Likes[0].UserLikesPost.score === 1);\nassert(user0Likes.length === 1);\n```\n\n```text\nconst assert = require('assert')\nconst { DataTypes, Op, Sequelize } = require('sequelize')\nconst common = require('./common')\nconst sequelize = common.sequelize(__filename, process.argv[2], { define: { timestamps: false } })\n;(async () => {\n\n// Create the tables.\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n});\nconst Post = sequelize.define('Post', {\n  body: { type: DataTypes.STRING },\n});\nconst UserLikesPost = sequelize.define('UserLikesPost', {\n  UserId: {\n    type: DataTypes.INTEGER,\n    references: {\n      model: User,\n      key: 'id'\n    }\n  },\n  PostId: {\n    type: DataTypes.INTEGER,\n    references: {\n      model: Post,\n      key: 'id'\n    }\n  },\n  score: {\n    type: DataTypes.INTEGER,\n  },\n});\nUser.belongsToMany(Post, {through: UserLikesPost});\nPost.belongsToMany(User, {through: UserLikesPost});\nawait sequelize.sync({force: true});\n\n// Create some users and likes.\n\nconst user0 = await User.create({name: 'user0'})\nconst user1 = await User.create({name: 'user1'})\nconst user2 = await User.create({name: 'user2'})\n\nconst post0 = await Post.create({body: 'post0'});\nconst post1 = await Post.create({body: 'post1'});\nconst post2 = await Post.create({body: 'post2'});\n\n// Autogenerated add* methods\n\n// Make some useres like some posts.\nawait user0.addPost(post0, {through: {score: 1}})\nawait user1.addPost(post1, {through: {score: 2}})\nawait user1.addPost(post2, {through: {score: 3}})\n\n// Find what user0 likes.\nconst user0Likes = await user0.getPosts({order: [['body', 'ASC']]})\nassert(user0Likes[0].body === 'post0');\nassert(user0Likes[0].UserLikesPost.score === 1);\nassert(user0Likes.length === 1);\n\n// Find what user1 likes.\nconst user1Likes = await user1.getPosts({order: [['body', 'ASC']]})\nassert(user1Likes[0].body === 'post1');\nassert(user1Likes[0].UserLikesPost.score === 2);\nassert(user1Likes[1].body === 'post2');\nassert(user1Likes[1].UserLikesPost.score === 3);\nassert(user1Likes.length === 2);\n\n// Where on the custom through table column.\n// Find posts that user1 likes which have score greater than 2.\n// https://stackoverflow.com/questions/38857156/how-to-query-many-to-many-relationship-sequelize\n{\n  const rows = await Post.findAll({\n    include: [\n      {\n        model: User,\n        where: {id: user1.id},\n        through: {\n          where: {score: { [Op.gt]: 2 }},\n        },\n      },\n    ],\n  })\n  assert.strictEqual(rows[0].body, 'post2');\n  // TODO how to get the score here as well?\n  //assert.strictEqual(rows[0].UserLikesPost.score, 3);\n  assert.strictEqual(rows.length, 1);\n}\n\n})().finally(() => { return sequelize.close() });\n```\n\n```text\nconst path = require('path');\n\nconst { Sequelize } = require('sequelize');\n\nfunction sequelize(filename, dialect, opts) {\n  if (dialect === undefined) {\n    dialect = 'l'\n  }\n  if (dialect === 'l') {\n    return new Sequelize(Object.assign({\n      dialect: 'sqlite',\n      storage: path.parse(filename).name + '.sqlite'\n    }, opts));\n  } else if (dialect === 'p') {\n    return new Sequelize('tmp', undefined, undefined, Object.assign({\n      dialect: 'postgres',\n      host: '/var/run/postgresql',\n    }, opts));\n  } else {\n    throw new Error('Unknown dialect')\n  }\n}\nexports.sequelize = sequelize\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.5.1\",\n    \"sqlite3\": \"5.0.2\"\n  }\n}\n```\n\n```text\ninstance.getOthers()\n```\n\n========================================\n\nComments:\n- In your query, have you tried `userDepartment.id` instead of `departments.id` ?\n- @AndrewLavers Just took a crack at it. Same bad field error.\n- There is an SQL injection attach in this code. `req.params` should never be direct input into `sequelize.literal`.","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":419,"estimatedTokens":2306}}648{"id":"stack-38942739","source":"stackoverflow","questionId":38942739,"title":"The ambiguous error occurs while using the models.sequelize.col () in the include in sequelize(node.js express)","tags":["join","include","sequelize.js","mariadb"],"text":"Title: The ambiguous error occurs while using the models.sequelize.col () in the include in sequelize(node.js express)\nTags: join, include, sequelize.js, mariadb\nSource: Stack Overflow\n\nQuestion:\nmariadb,\n\n```\nshow tables;\nBoard\nComment\n```\n\nmy code,\n\n```\nmodels.Board.findAll({\nattributes: [\n '_no', 'title', 'content', 'createdAt'\n],\ninclude: [\n {\n model: models.Comment,\n tableAlias: 'Comment',\n attributes: [\n [models.sequelize.fn('count', models.sequelize.col('_no')), 'comment']\n ]\n }\n],\ngroup: ['_no', 'title', 'content', 'createdAt'],\norder: [\n ['createdAt', 'DESC']\n],\n raw: true\n }).then(function(boards)\n\n {\n res.send(JSON.stringify(boards));\n\n });\n```\n\nWhy error occurs?\n\n```\nUnhandled rejection SequelizeDatabaseError: ER_NON_UNIQ_ERROR: Column '_no' in field list is ambiguous\n```\n\nmodels.sequelize.col('_no') -> models.sequelize.col('models.Comment._no')\nerror, too.\n\nmodels.sequelize.col ( '_ no') in the _no want to use Comment table.\n\nthanks.\n\n========================================\n\nTop Answer:\nif multiple table is there in query then you need to specify which table createdAt you want to group by because node have all table createdAt(default created)\n\n```\ngroup: [\"your_table_name_here\\\".\\\"createdAt\"]\n```\n\nif we use multiple model for get record in that case same field name in 2 or more model then you need to specify which model record you want to group by so in that case i write group: [\"**your_table_name_here**\".\"createdAt\"]\n\n========================================\n\nCode:\n```text\nshow tables;\nBoard\nComment\n```\n\n```text\nmodels.Board.findAll({\nattributes: [\n  '_no', 'title', 'content', 'createdAt'\n],\ninclude: [\n  {\n    model: models.Comment,\n    tableAlias: 'Comment',\n    attributes: [\n      [models.sequelize.fn('count', models.sequelize.col('_no')), 'comment']\n    ]\n  }\n],\ngroup: ['_no', 'title', 'content', 'createdAt'],\norder: [\n  ['createdAt', 'DESC']\n],\n    raw: true\n   }).then(function(boards)\n\n     {\n         res.send(JSON.stringify(boards));\n\n      });\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: ER_NON_UNIQ_ERROR: Column '_no' in field list is ambiguous\n```\n\n```text\n_no\n```\n\n```text\nmodels.sequelize.col('board._no'))\n```\n\n```text\ngroup: [\"your_table_name_here\\\".\\\"createdAt\"]\n```\n\n```text\nimport { Parking } from \"../database/models\";\n\nconst parking = await Parking.findAndCountAll({\n    where: {\n      \"$Parking.createdAt$\": {\n         [Op.between]: [new Date(startDate), new Date(endDate)]\n      }\n    }\n})\n```\n\n```text\ncreatedAt\n```\n\n========================================\n\nComments:\n- But how to do this on a table when you don't know from where it will be included? Any clue?\n- @Jan, can you not give me a hint?\n- Did you solve it ? We have same issue my root table have full_name column the the child table is belongsTo root table that have full_name column to ... I got ambiguitas. How to ignore them ? Without refactor the column name ..\n- Your explanation is really difficult to understand. Please try to clean it up.\n- if we use multiple model for get record in that case same field name in 2 or more model then you need to specify which model record you want to group by so in that case i write group: [\"your_table_name_here\\\".\\\"createdAt\"]","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":142,"estimatedTokens":805}}649{"id":"stack-28063394","source":"stackoverflow","questionId":28063394,"title":"Sequelize create object with associations","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: Sequelize create object with associations\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to save sequelize models with their associations. All the associations are one to one. Retrieving models with associations from the database works just fine but inserting them is another matter and the documentation is just making me more confused.\n\nHere's my insert method:\n\n```\nmodels\n .radcheck\n .create(user, {\n include: [{model: models.skraningar}, {model: models.radusergroup}, {model: models.radippool}]\n })\n .then(success, error);\n```\n\nI've seen so many ways to do this both in the documentation and here on stackoverflow and none of them make sense to me so far. Anyone care to clear things up for me?\n\n========================================\n\nCode:\n```text\nmodels\n    .radcheck\n    .create(user, {\n        include: [{model: models.skraningar}, {model: models.radusergroup}, {model: models.radippool}]\n        })\n    .then(success, error);\n```\n\n```text\nmodels.user.create({ name : 'test', usergroup_id : 1 });\n```\n\n========================================\n\nComments:\n- Are you trying to create a radcheck object, while at the same time, creating skraningar, radusergroup and radippool?\n- Thats right. Isn't that possible with sequelize?\n- No, I don't think so, it would involve multiple insert statements which would not be done with a single .create() call.\n- But doesn’t that kind of go one level of abstraction deeper than one might want to?\n- this solution also works if the 1 model is usergroup and N model is user, got it?","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":44,"estimatedTokens":394}}650{"id":"stack-31593374","source":"stackoverflow","questionId":31593374,"title":"SQL Server 2008 on Node.js with Sequelize","tags":["javascript","sql-server","node.js","sequelize.js"],"text":"Title: SQL Server 2008 on Node.js with Sequelize\nTags: javascript, sql-server, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new here !\n\nI'm trying to do a query on a MS SQL Server2008 with sequelize, but I get this error:\n\n Unhandled rejection SequelizeDatabaseError: Invalid column name 'id'.\n at Query.formatError (C:\\xampp\\htdocs\\Lavori\\Bit_Sense\\API_BS\\node_modules\\s\n equelize\\lib\\dialects\\mssql\\query.js:217:10)\n at Request.userCallback (C:\\xampp\\htdocs\\Lavori\\Bit_Sense\\API_BS\\node_module\n s\\sequelize\\lib\\dialects\\mssql\\query.js:66:25)\n at Request.callback (C:\\xampp\\htdocs\\Lavori\\Bit_Sense\\API_BS\\node_modules\\te\n dious\\lib\\request.js:30:27)\n at Connection.STATE.SENT_CLIENT_REQUEST.events.message (C:\\xampp\\htdocs\\Lavo\n ri\\Bit_Sense\\API_BS\\node_modules\\tedious\\lib\\connection.js:283:29)\n at Connection.dispatchEvent (C:\\xampp\\htdocs\\Lavori\\Bit_Sense\\API_BS\\node_mo\n dules\\tedious\\lib\\connection.js:752:59)\n at MessageIO. (C:\\xampp\\htdocs\\Lavori\\Bit_Sense\\API_BS\\node_modul\n es\\tedious\\lib\\connection.js:685:22)\n at MessageIO.emit (events.js:104:17)\n at MessageIO.eventData (C:\\xampp\\htdocs\\Lavori\\Bit_Sense\\API_BS\\node_modules\n \\tedious\\lib\\message-io.js:58:21)\n at Socket. (C:\\xampp\\htdocs\\Lavori\\Bit_Sense\\API_BS\\node_modules\\\n tedious\\lib\\message-io.js:3:59)\n at Socket.emit (events.js:107:17)\n at readableAddChunk (_stream_readable.js:163:16)\n at Socket.Readable.push (_stream_readable.js:126:10)\n at TCP.onread (net.js:538:20)\n\nI've installed this module:\n- sequelize ;\n- tedious ;\n\nI haven't problem on the connection, only with this query:\n\n\r\n\r\n\n```\ndb.KEY_ARTI.findAll({\r\n where:{\r\n CACODICE: cacodice\r\n }\r\n\t}).then(function(data) {\r\n res.send(data);\r\n\t});\n```\n\n\r\n\r\n\r\n\nWhat can I do ? I haven't ANY column called id\n\nHere is my table:\n\n\r\n\r\n\n```\nvar Sequelize = require('sequelize');\r\nvar settings = global.settings.databases.DATABASE;\r\nvar errors = global.errors;\r\nvar utilities = global.utilities; \r\n\r\nvar sequelize = new Sequelize(settings.schema, settings.username, settings.password, {\r\n dialect: settings.dialect,\r\n host: settings.host,\r\n port: settings.port, /* BISOGNA USARE LA DYNAMIC PORT */\r\n logging: function (str) {\r\n if(settings.log)\r\n console.log(\"querylog: \"+str.replace(\"Executing (default):\", \"\") );\r\n },\r\n });\r\n\r\nsequelize.authenticate().then(function(err) {\r\n if (!!err) {\r\n console.log('Database '+settings.schema+' Connection Error:', err)\r\n } \r\n else {\r\n console.log('Database '+settings.schema+' Connected')\r\n }\r\n});\r\n\r\nexports.sequelize = sequelize;\r\n\r\n/*\r\n * KEY_ARTI\r\n */\r\nexports.KEY_ARTI = sequelize.define('KEY_ARTI', {\r\n\tCACODICE: Sequelize.CHAR(20),\r\n\tCADESART: Sequelize.CHAR(40),\r\n}\n```\n\n========================================\n\nCode:\n```js\ndb.KEY_ARTI.findAll({\n  where:{\n\t      CACODICE: cacodice\n\t    }\n\t}).then(function(data) {\n\t\tres.send(data);\n\t});\n```\n\n```js\nvar Sequelize = require('sequelize');\nvar settings = global.settings.databases.DATABASE;\nvar errors = global.errors;\nvar utilities = global.utilities; \n\nvar sequelize = new Sequelize(settings.schema, settings.username, settings.password, {\n      dialect: settings.dialect,\n      host: settings.host,\n\t  port: settings.port, /* BISOGNA USARE LA DYNAMIC PORT */\n      logging: function (str) {\n          if(settings.log)\n            console.log(\"querylog: \"+str.replace(\"Executing (default):\", \"\") );\n      },\n    });\n\nsequelize.authenticate().then(function(err) {\n    if (!!err) {\n      console.log('Database '+settings.schema+' Connection Error:', err)\n    } \n    else {\n      console.log('Database '+settings.schema+' Connected')\n    }\n});\n\nexports.sequelize = sequelize;\n\n/*\n * KEY_ARTI\n */\nexports.KEY_ARTI = sequelize.define('KEY_ARTI', {\n\tCACODICE: Sequelize.CHAR(20),\n\tCADESART: Sequelize.CHAR(40),\n}\n```\n\n```text\nsequelize.define('model', {}); // Adds an id key\n\nsequelize.define('model', {\n  name: {\n    primaryKey: true\n    type: Sequelize.STRING\n  }\n}); // Doesn't add an id, because you already marked another column as primary key\n```\n\n========================================\n\nComments:\n- Can you post your initializing code as well?\n- here it's saying in Invalid column name 'id'. Can you check about this. Or post the code for review.\n- I added in the answer the code, and I'm sure that I have the Object, because if I do a console.log(db.KEY_ARTI) and isn't undefined or null\n- Yes I find it ! I added the primary key, but, as you said, you can remove the attributes","metadata":{"transformedAt":"2026-08-18T18:33:34.391Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":165,"estimatedTokens":1104}}651{"id":"stack-62042290","source":"stackoverflow","questionId":62042290,"title":"SEQUELIZE: \"Cannot read property 'length' of undefined\"","tags":["node.js","sequelize.js"],"text":"Title: SEQUELIZE: \"Cannot read property 'length' of undefined\"\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nDoes anyone know how to solve this? There is something I am not seeing. To see if the controller was working, I returned the response receiving the request in json, it worked, there was no error.\n\nThe problem seems to be with the controller, but the controller...\n\n**Edit**\n\n**Controller**\n\n```\nimport Post from '../models/Post';\nimport * as Yup from 'yup';\n\nclass PostController {\n async store(req, res) {\n\n try {\n //Checks if the fields have been filled correctly\n const schema = Yup.object().shape({\n title: Yup.string()\n .required(),\n content: Yup.string()\n .required()\n });\n\n if(!(await schema.isValid(req.body))) {\n return res.status(400).json({ error: 'Error 1' });\n }\n\n //Abstraction of fields\n const { title, content } = req.body;\n const createPost = await Post.create(title, content);\n\n if(!createPost) {\n return res.json({error: 'Error 2'})\n }\n\n //If everything is correct, the information will be registered and returned.\n return res.json({\n title,\n content,\n });\n }\n catch (err) {\n console.log(\"Error: \" + err);\n return res.status(400).json({error: 'Error 3'});\n }\n }\n}\n\nexport default new PostController();\n```\n\n**Model:**\n\n```\nimport Sequelize, { Model } from 'sequelize';\n\nclass Post extends Model {\n static init(sequelize) {\n //Fields registered by the user\n super.init({\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true\n },\n title: Sequelize.STRING,\n content: Sequelize.TEXT,\n created_at: {\n type: Sequelize.DATE,\n defaultValue: Sequelize.NOW,\n },\n updated_at: {\n type: Sequelize.DATE,\n defaultValue: Sequelize.NOW,\n },\n },\n {\n sequelize,\n tableName: 'posts'\n });\n\n return this;\n }\n}\n\nexport default Post;\n```\n\n**Migration:**\n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('posts', {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n autoIncrement: true,\n primaryKey: true\n },\n title: {\n type: Sequelize.STRING,\n allowNull: false,\n },\n content: {\n type: Sequelize.TEXT,\n allowNull: false,\n },\n created_at: {\n type: Sequelize.DATE,\n allowNull: false,\n },\n updated_at: {\n type: Sequelize.DATE,\n allowNull: false,\n }\n });\n },\n\n down: (queryInterface) => {\n return queryInterface.dropTable('posts');\n }\n};\n```\n\n**The terminal error:**\n\n```\nTypeError: Cannot read property 'length' of undefined\n```\n\n========================================\n\nTop Answer:\nI was having the same problem\n\nThe problem with my code was that I was forgetting to add the module name to my **database's index.js** file inside my **models array**\n\neg: `const **models** = [User,**Task**]`\n\nI found the answer on this post:\nhttps://github.com/sequelize/sequelize/issues/11111#issuecomment-697078832\n\n========================================\n\nCode:\n```text\nimport Post from '../models/Post';\nimport *  as Yup from 'yup';\n\nclass PostController {\n    async store(req, res) {\n\n        try {\n            //Checks if the fields have been filled correctly\n            const schema = Yup.object().shape({\n                title: Yup.string()\n                    .required(),\n                content: Yup.string()\n                    .required()\n            });\n\n\n            if(!(await schema.isValid(req.body))) {\n                return res.status(400).json({ error: 'Error 1' });\n            }\n\n            //Abstraction of fields\n            const { title, content } = req.body;\n            const createPost = await Post.create(title, content);\n\n            if(!createPost) {\n                return res.json({error: 'Error 2'})\n            }\n\n            //If everything is correct, the information will be registered and returned.\n            return res.json({\n                title,\n                content,\n            });\n        }\n        catch (err) {\n            console.log(\"Error: \" + err);\n            return res.status(400).json({error: 'Error 3'});\n        }\n    }\n}\n\nexport default new PostController();\n```\n\n```text\nimport Sequelize, { Model } from 'sequelize';\n\nclass Post extends Model {\n    static init(sequelize) {\n        //Fields registered by the user\n        super.init({\n            id: {\n                type: Sequelize.INTEGER,\n                primaryKey: true\n            },\n            title: Sequelize.STRING,\n            content: Sequelize.TEXT,\n            created_at: {\n                type: Sequelize.DATE,\n                defaultValue: Sequelize.NOW,\n            },\n            updated_at: {\n                type: Sequelize.DATE,\n                defaultValue: Sequelize.NOW,\n            },\n        },\n        {\n            sequelize,\n            tableName: 'posts'\n        });\n\n        return this;\n    }\n}\n\nexport default Post;\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('posts', {\n        id: {\n            type: Sequelize.INTEGER,\n            allowNull: false,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        title: {\n            type: Sequelize.STRING,\n            allowNull: false,\n        },\n        content: {\n            type: Sequelize.TEXT,\n            allowNull: false,\n        },\n        created_at: {\n            type: Sequelize.DATE,\n            allowNull: false,\n        },\n        updated_at: {\n            type: Sequelize.DATE,\n            allowNull: false,\n        }\n    });\n  },\n\n  down: (queryInterface) => {\n    return queryInterface.dropTable('posts');\n  }\n};\n```\n\n```text\nTypeError: Cannot read property 'length' of undefined\n```\n\n```js\nstatic init(sequelize) {\n        super.init(\n            {\n                categoryId: {\n                    type: Sequelize.INTEGER,\n                    primaryKey: true,\n                    field: 'id',\n                },\n                dateUpdated: {\n                    type: Sequelize.DATE,\n                    field: 'updated_at',\n                    defaultValue: Sequelize.NOW,\n                },\n                // ... other fields here,\n            },\n            {\n                sequelize,\n                tableName: 'categories',\n            }\n        );\n    }\n    // ... \n}\n\nexport default Category;\n```\n\n```text\nawait Post.create({ title, content });\n```\n\n```js\n// Imports here\nimport Category from '../app/models/Category';\n//...\n\nconst models = [\n    // Models that I want to use\n    Category,\n    //...\n];\n\nclass Database {\n    constructor() {\n        this.init();\n    }\n    // Load on database init\n    init() {\n        this.connection = new Sequelize(databaseConfig);\n        models.forEach(model => model.init(this.connection));\n    }\n}\n\nexport default new Database();\n```\n\n```text\nallowNull: false\n```\n\n```text\nmigration\n```\n\n```text\nModel\n```\n\n```text\nController\n```\n\n```text\ndefaultValue\n```\n\n```text\ndefaultValue: Sequelize.NOW\n```\n\n```text\ncreated_at\n```\n\n```text\nlib/model.js\n```\n\n```text\ndatabase.js\n```\n\n```text\ndatabase.js\n```\n\n```text\nconst **models** = [User,**Task**]\n```\n\n========================================\n\nComments:\n- Updated the answer, put an example that works in one of my projects. Hope to help. Check the point that I declare the `tableName`, seems to be this detail, too.\n- It gave the same error. In this project I made a user system with validation and authentication. You can create, update and delete users without problems, without errors, but now you started giving this error to categories.\n- I put a try catch and I was returned the terminal error: \"Error: TypeError: Cannot read property 'length' of undefined\"\n- I looked at the `model.js`. Check the **EDIT** on answer to see if the approach can help you.\n- Can you update your model on your answer to see if we can do more approaches?\n- Okay, I updated the information in the post. I decided to create a new entity from 0 again, but still with the same error.\n- Look at edit2, I believe we have another detail here.\n- If your yup is OK, maybe is the Model load inside your `Database` object. a new edit\n- It worked! Thank you, I really thank you. I had been programming for a long time, and with a tired mind, I started to do it in automatic and I didn't realize that I needed to instantiate the model in the Database class, just as I had instantiated the User. When you mentioned that, I remembered. Seriously, thank you very much.\n- Hi leandro, your answer is much more suitable to be a comment than a real answer to the poster question.","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":387,"estimatedTokens":2109}}652{"id":"stack-42889992","source":"stackoverflow","questionId":42889992,"title":"Sequelize CLI how to create migrations from models?","tags":["node.js","migration","sequelize.js"],"text":"Title: Sequelize CLI how to create migrations from models?\nTags: node.js, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two models with relations one to many.\n\nI don't understand how to create migration files. Does each model have its own migration file or one migration file can create several tables from models and relations between them (for example as in rails migrations)?\n\nI had a look at many examples including Sequelize docs, and there are primitive examples of models creating and its migration.\n\n```\n//User model\nmodule.exports = function (sequelize, Sequelize) {\n var User = sequelize.define('users', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n },\n email: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: true,\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n },\n });\n\n return User;\n}\n\n//Order model\nmodule.exports = function (sequelize, Sequelize) {\n var Order = sequelize.define('orders', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n },\n price: {\n type: Sequelize.INTEGER,\n allowNull: false,\n },\n totalPrice: {\n type: Sequelize.INTEGER,\n allowNull: false,\n },\n });\n\n return Order;\n}\n\n//db.js\n//Relations\ndb.orders.belongsTo(db.users);\ndb.users.hasMany(db.orders);\n```\n\nAddition\n\nI create migration for two models:\n\n```\nmodule.exports = {\n up: function (queryInterface, Sequelize, done) {\n return [\n queryInterface.createTable('users', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n },\n email: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: true,\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n },\n }),\n queryInterface.createTable('orders', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n },\n price: {\n type: Sequelize.INTEGER,\n allowNull: false,\n },\n totalPrice: {\n type: Sequelize.INTEGER,\n allowNull: false,\n },\n userId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'users',\n key: 'id'\n },\n onUpdate: 'CASCADE',\n onDelete: 'CASCADE'\n }\n }),\n done()\n ]\n },\n\n down: function (queryInterface, Sequelize, done) {\n return [\n queryInterface.dropTable('users'),\n queryInterface.dropTable('orders'),\n done()\n ]\n }\n};\n```\n\nDo I need to add into my migration file class methods for my models?\n\n```\n//for Order\nclassMethods: {\n associate: function(models) {\n Model.belongsTo(models.users, (as: 'users'));\n }\n}\n\n//for User\nclassMethods: {\n associate: function(models) {\n Model.hasMany(models.orders, (as: 'orders'));\n }\n}\n```\n\n//Addition 2\n\nhttps://i.sstatic.net/0EBV3.png\n\n========================================\n\nCode:\n```text\n//User model\nmodule.exports = function (sequelize, Sequelize) {\n    var User = sequelize.define('users', {\n        id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n            autoIncrement: true,\n        },\n        email: {\n            type: Sequelize.STRING,\n            allowNull: false,\n            unique: true,\n        },\n        password: {\n            type: Sequelize.STRING,\n            allowNull: false,\n        },\n    });\n\n    return User;\n}\n\n//Order model\nmodule.exports = function (sequelize, Sequelize) {\n    var Order = sequelize.define('orders', {\n        id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n            autoIncrement: true,\n        },\n        price: {\n            type: Sequelize.INTEGER,\n            allowNull: false,\n        },\n        totalPrice: {\n            type: Sequelize.INTEGER,\n            allowNull: false,\n        },\n    });\n\n    return Order;\n}\n\n//db.js\n//Relations\ndb.orders.belongsTo(db.users);\ndb.users.hasMany(db.orders);\n```\n\n```text\nmodule.exports = {\n    up: function (queryInterface, Sequelize, done) {\n        return [\n        queryInterface.createTable('users', {\n            id: {\n                type: Sequelize.INTEGER,\n                primaryKey: true,\n                autoIncrement: true,\n            },\n            email: {\n                type: Sequelize.STRING,\n                allowNull: false,\n                unique: true,\n            },\n            password: {\n                type: Sequelize.STRING,\n                allowNull: false,\n            },\n        }),\n        queryInterface.createTable('orders', {\n            id: {\n                type: Sequelize.INTEGER,\n                primaryKey: true,\n                autoIncrement: true,\n            },\n            price: {\n                type: Sequelize.INTEGER,\n                allowNull: false,\n            },\n            totalPrice: {\n                type: Sequelize.INTEGER,\n                allowNull: false,\n            },\n            userId: {\n                type: Sequelize.INTEGER,\n                references: {\n                    model: 'users',\n                    key: 'id'\n                },\n                onUpdate: 'CASCADE',\n                onDelete: 'CASCADE'\n            }\n        }),\n        done()\n        ]\n    },\n\n    down: function (queryInterface, Sequelize, done) {\n        return [\n        queryInterface.dropTable('users'),\n        queryInterface.dropTable('orders'),\n        done()\n        ]\n    }\n};\n```\n\n```text\n//for Order\nclassMethods: {\n    associate: function(models) {\n        Model.belongsTo(models.users, (as: 'users'));\n    }\n}\n\n//for User\nclassMethods: {\n    associate: function(models) {\n        Model.hasMany(models.orders, (as: 'orders'));\n    }\n}\n```\n\n```text\n// example column definition inside migration file\n// creates a foreign key referencing table 'users'\nuserId: {\n    type: Sequelize.INTEGER,\n    references: {\n        model: 'users',\n        key: 'id'\n    },\n    onDelete: 'CASCADE'\n}\n```\n\n```text\nreturn [queryInterface.createTable(...), queryInterface.createTable(...)];\n```\n\n```text\nsequelize migration:create\n```\n\n```text\n/migrations\n```\n\n```text\nsequelize model:create\n```\n\n```text\nsequelize-cli\n```\n\n```text\nsequelize help\n```\n\n```text\nassociate\n```\n\n```text\ncreateTable\n```\n\n```text\n.then()\n```\n\n========================================\n\nComments:\n- Thanks, I create migration file and add it to the question with a addition question.\n- I have updated the answer. In short - class methods are defined only in the model definition files, not in the migration files.\n- I chose second option: return them as an array. I did migration and got the console message: == 20170319144537-create_users_and_orders: migrating ======= == 20170319144537-create_users_and_orders: migrated (0.100s) but in the db I see only one 'users' table.\n- In your `down` function you need to swap `dropTable('users')` with `dropTable('orders')`. First you need to drop table `orders` and then you can drop `users`, because `users` is referenced in `orders` so it needs to be deleted as the second one. Try `undo` the migrations and run them once again and tell if you still have only one table in db\n- Anyway I don't get orders table. Add screen to the question.\n- Try to chain the migration functions via `then()`, maybe this will help","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":330,"estimatedTokens":1741}}653{"id":"stack-48005763","source":"stackoverflow","questionId":48005763,"title":"load items where relation is null in sequelize","tags":["node.js","sequelize.js"],"text":"Title: load items where relation is null in sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to sequelize, i'm trying to load all entries in my user table where the task relation is null. but its not working. here is what i have tried:\n\n```\nconst express = require('express');\nconst app = express();\n\nconst Sequelize = require('sequelize');\nconst sequelize = new Sequelize('sequelize', 'mazinoukah', 'solomon1', {\n host: 'localhost',\n dialect: 'postgres',\n\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000,\n },\n});\n\nconst Task = sequelize.define('Task', {\n name: Sequelize.STRING,\n completed: Sequelize.BOOLEAN,\n UserId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'Users', // Can be both a string representing the table name, or a reference to the model\n key: 'id',\n },\n },\n});\n\nconst User = sequelize.define('User', {\n firstName: Sequelize.STRING,\n lastName: Sequelize.STRING,\n email: Sequelize.STRING,\n TaskId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'Tasks', // Can be both a string representing the table name, or a reference to the model\n key: 'id',\n },\n },\n});\n\nUser.hasOne(Task);\nTask.belongsTo(User);\n\napp.get('/users', (req, res) => {\n User.findAll({\n where: {\n Task: {\n [Sequelize.Op.eq]: null,\n },\n },\n include: [\n {\n model: Task,\n },\n ],\n }).then(function(todo) {\n res.json(todo);\n });\n});\n\n app.listen(2000, () => {\n console.log('server started');\n });\n```\n\nif i have three users, and 2 of those users have a task each, i want to load just the last user without a task. is this possible in sequelize ?\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst app = express();\n\nconst Sequelize = require('sequelize');\nconst sequelize = new Sequelize('sequelize', 'mazinoukah', 'solomon1', {\n  host: 'localhost',\n  dialect: 'postgres',\n\n  pool: {\n    max: 5,\n    min: 0,\n    acquire: 30000,\n    idle: 10000,\n  },\n});\n\nconst Task = sequelize.define('Task', {\n  name: Sequelize.STRING,\n  completed: Sequelize.BOOLEAN,\n  UserId: {\n    type: Sequelize.INTEGER,\n    references: {\n      model: 'Users', // Can be both a string representing the table name, or a reference to the model\n      key: 'id',\n    },\n  },\n});\n\nconst User = sequelize.define('User', {\n  firstName: Sequelize.STRING,\n  lastName: Sequelize.STRING,\n  email: Sequelize.STRING,\n  TaskId: {\n    type: Sequelize.INTEGER,\n    references: {\n      model: 'Tasks', // Can be both a string representing the table name, or a reference to the model\n      key: 'id',\n    },\n  },\n});\n\nUser.hasOne(Task);\nTask.belongsTo(User);\n\napp.get('/users', (req, res) => {\n  User.findAll({\n    where: {\n      Task: {\n        [Sequelize.Op.eq]: null,\n      },\n    },\n    include: [\n      {\n        model: Task,\n      },\n    ],\n  }).then(function(todo) {\n    res.json(todo);\n  });\n});\n\n   app.listen(2000, () => {\n      console.log('server started');\n   });\n```\n\n```text\napp.get('/users', (req, res) => {\nUser.findAll({\n    where: {\n      '$Task$': null,\n    },\n    include: [\n      {\n        model: Task,\n        required: false,\n      },\n    ],\n  }).then(function(todo) {\n    res.json(todo);\n  });\n});\n```\n\n```text\nwhere: {\n  '$Task$': null,\n},\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":169,"estimatedTokens":800}}654{"id":"stack-47320613","source":"stackoverflow","questionId":47320613,"title":"Best practice on storing Node.js Buffer in MySQL","tags":["mysql","node.js","sequelize.js"],"text":"Title: Best practice on storing Node.js Buffer in MySQL\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow to store `Buffer` in MySQL with Node.js?\n\nOne way I know is to convert `Buffer` to *hex string* and save it as `CHAR` type in MySQL. But is it the best practice to transform *before* and *after* saving in MySQL? \n\nIs there a way that can directly save and get the `Buffer` (bytes array) in MySQL with Node.js, for example, using `BLOB` in MySQL? \n\nOr actually it doesn't matter what kind of way I use, they don't differ so much?\n\n========================================\n\nCode:\n```text\nBuffer\n```\n\n```text\nBuffer\n```\n\n```text\nCHAR\n```\n\n```text\nBuffer\n```\n\n```text\nBLOB\n```\n\n```text\nconst obj = {};\nconst zip = zlib.gzipSync(JSON.stringify(obj)).toString('base64');\n```\n\n```text\nconst originalObj = JSON.parse(zlib.unzipSync(Buffer.from(zip, 'base64')));\n```\n\n```text\nlongtext\n```\n\n```text\nBuffer.from()\n```\n\n```text\nnew Buffer()\n```\n\n```text\nlongtext\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":60,"estimatedTokens":246}}655{"id":"stack-9477404","source":"stackoverflow","questionId":9477404,"title":"sequelize for NodeJS: are these features supported?","tags":["database","node.js","sequelize.js"],"text":"Title: sequelize for NodeJS: are these features supported?\nTags: database, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHere are some questions about features supported by sequelize (sequelize project site) that I would like to clear up before deciding whether or not to use it:\n\nChaining (efficiency): when chaining multiple queries, are these collected into one request to the database (as a batch of operations), or is each one sent separately?\n\nChaining (success/error): when chaining multiple queries, when is the success event emitted and what happens on error? Is \"success\" emitted only if *all* operations succeeded? And if there was an error, does it rollback all operations (i.e. are the chained operations treated as a transaction)\n\nFiltering associations: Say a `Crowd` object has the relation `Crowd.hasMany(Person)`. You can get all the associated people by executing `crowd.getPersons()`, but is it possible to select a subset of them, like `crowd.getPersons({where: { age: 30 }})`?\n\nGetting associated objects that are related by two or more steps: Say a `Crowd` object as the relation `Crowd.hasMany(Person)` and `Person` has the relation `Person.hasMany(Pet)`. Is it possible to get all the pets of people in a crowd by executing something like `crowd.getPersons().getPets()`, and if so does this get sent as multiple request to the database, or just one request?\n\n\"Deep\" object: I want to define a person as the object:\n\n```\nsequelize.define('Person', {\n name: {\n first: ,\n last: \n }\n});\n```\n\nIs this allowed? (Note that name is not going to be a column of the database table, but first and last will be)\n\n\"Calculated\" object: Is it possible to add a field to the object that is calculated from other fields of the object? For example:\n\n```\nsequelize.define('Person', {\n name: {\n first: ,\n last: ,\n full: // So that the `name.full` field isn't actually stored in the database (which is a waste of space) but rather just calculated from the other two?\n\n========================================\n\nCode:\n```text\nsequelize.define('Person', {\n    name: {\n        first: <a string>,\n        last: <a string>\n    }\n});\n```\n\n```text\nsequelize.define('Person', {\n    name: {\n        first: <a string>,\n        last: <a string>,\n        full: <name.first + ' ' + name.last> // <-- this field\n    }\n});\n```\n\n```text\nCrowd\n```\n\n```text\nCrowd.hasMany(Person)\n```\n\n```text\ncrowd.getPersons()\n```\n\n```text\ncrowd.getPersons({where: { age: 30 }})\n```\n\n```text\nCrowd\n```\n\n```text\nCrowd.hasMany(Person)\n```\n\n```text\nPerson\n```\n\n```text\nPerson.hasMany(Pet)\n```\n\n```text\ncrowd.getPersons().getPets()\n```\n\n```text\nname.full\n```\n\n```text\ncrowd.getPeople().success(function(people) {\n  people.forEach(function(person){\n    person.getPets().success... // you have to collect them on your own\n  })\n})\n```\n\n```text\nPerson = sequelize.define('Person', {foo:Sequelize.STRING}, {\n  instanceMethods: {\n    fullname: function() {\n      return this.firstName + ' ' + this.lastName\n    }\n  }\n})\n```\n\n========================================\n\nComments:\n- So for #2, if there is an error with one of the requests, will it rollback all requests (as would happen in a transaction)? Or are the chained requests not treated as a transaction?\n- they aren't treated as a transaction but executed happily separated from each other and returning all occured errors as the result\n- It would be nice if instead of simply having the ability to add instance methods, if you could define getters and setters that were used when serializing the object.\n- About the point 3, I'm not sure if the newer version still has it, but in version 2.0.0-rc3 has.\n- @freakTheMighty I haven't tried it but I think you can. re #6 I think you can define getters in the model definition which create proper virtual fields. docs.sequelizejs.com/manual/tutorial/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":125,"estimatedTokens":958}}656{"id":"stack-50499596","source":"stackoverflow","questionId":50499596,"title":"How to update a model? .updateAttributes is not a function","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: How to update a model? .updateAttributes is not a function\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a Node Express app, with Postgres as DB and Sequelize as ORM.\n\nI have a `router.js` file:\n\n```\nrouter.route('/publish')\n .put((...args) => controller.publish(...args));\n```\n\n`controller.js` which looks like this:\n\n```\npublish(req, res, next) {\n helper.publish(req)\n .then((published) => {\n res.send({ success: true, published });\n });\n}\n```\n\nAnd a `helper.js`\n\n```\npublish(req) {\n return new Promise((resolve, reject) => {\n Article.findAll({\n where: { id: req.query.article_id },\n attributes: ['id', 'state']\n })\n .then((updateState) => {\n updateState.updateAttributes({\n state: 2\n });\n })\n .then((updateState) => {\n resolve(updateState);\n });\n });\n}\n```\n\nSo for example when I hit PUT `http://localhost:8080/api/publish?article_id=3555` I should get:\n\n```\n{\n \"success\": true,\n \"published\": [\n {\n \"id\": 3555,\n \"state\": 2\n }\n ]\n}\n```\n\nThe current state of the article is 1.\n\nHowever, I get the following error `Unhandled rejection TypeError: updateState.updateAttributes is not a function`. When I remove the `updateState.updateAttributes` part from my helper.js I get the response with the current state.\n\nHow do I update the state of the article correctly?\n\n========================================\n\nCode:\n```text\nrouter.route('/publish')\n  .put((...args) => controller.publish(...args));\n```\n\n```text\npublish(req, res, next) {\n  helper.publish(req)\n  .then((published) => {\n    res.send({ success: true, published });\n  });\n}\n```\n\n```text\npublish(req) {\n  return new Promise((resolve, reject) => {\n    Article.findAll({\n      where: { id: req.query.article_id },\n      attributes: ['id', 'state']\n    })\n    .then((updateState) => {\n      updateState.updateAttributes({\n        state: 2\n      });\n    })\n    .then((updateState) => {\n      resolve(updateState);\n    });\n  });\n}\n```\n\n```text\n{\n  \"success\": true,\n  \"published\": [\n    {\n      \"id\": 3555,\n      \"state\": 2\n    }\n  ]\n}\n```\n\n```text\nrouter.js\n```\n\n```text\ncontroller.js\n```\n\n```text\nhelper.js\n```\n\n```text\nhttp://localhost:8080/api/publish?article_id=3555\n```\n\n```text\nUnhandled rejection TypeError: updateState.updateAttributes is not a function\n```\n\n```text\nupdateState.updateAttributes\n```\n\n```text\nArticle.fineOne({  //<--------- Change here\n    where: { id: req.query.article_id },\n    attributes: ['id', 'state']\n})\n.then((updateState) => {\n    updateState.updateAttributes({state: 2}); //<------- And this will work\n})\n```\n\n```text\nArticle.findAll({\n    where: { id: req.query.article_id },\n    attributes: ['id', 'state']\n})\n.then((updateState) => {\n    // updateState will be the array of articles objects \n    updateState.forEach((article) => {\n        article.updateAttributes({ state: 2 });\n    });\n\n    //-------------- OR -----------------\n    updateState.forEach((article) => {\n        article.update({ state: 2 });\n    });\n})\n```\n\n```text\nfindAll\n```\n\n```text\nfindOne\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":173,"estimatedTokens":753}}657{"id":"stack-64441761","source":"stackoverflow","questionId":64441761,"title":"Postgress tries to return a column that does not exist in my model","tags":["node.js","postgresql","graphql","sequelize.js","database-migration"],"text":"Title: Postgress tries to return a column that does not exist in my model\nTags: node.js, postgresql, graphql, sequelize.js, database-migration\nSource: Stack Overflow\n\nQuestion:\nI use graphql API and try to insert data into Postgress table and got an error:\n\n```\n\"message\": \"column \\\"UserId\\\" does not exist\",\n```\n\nand my raw query:\n\n```\nExecuting (default): INSERT INTO \"Recipes\" \n(\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\") VALUES \n(DEFAULT,$1,$2,$3,$4,$5,$6) \n RETURNING \n\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\",\"UserId\";\n```\n\nthe problem is that a column **UserId** isn't in my model but **userId** is ! And i don't know why Postgres trying to return UserId column.\nMy Models.\nUser:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n class User extends Model {\n static associate(models) {\n User.hasMany(models.Recipe)\n }\n };\n User.init({\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'User',\n });\n return User;\n};\n```\n\nRecipe:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n class Recipe extends Model {\n static associate(models) {\n Recipe.belongsTo(models.User, { foreignKey: 'userId' })\n }\n };\n Recipe.init({\n title: {\n type: DataTypes.STRING,\n allowNull: false\n },\n ingredients: {\n type: DataTypes.STRING,\n allowNull: false\n },\n direction: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'Recipe',\n });\n return Recipe;\n};\n```\n\nmy graphql schema:\n\n```\nconst typeDefs = gql`\n type User {\n id: Int!\n name: String!\n email: String!\n recipes: [Recipe!]!\n }\n\n type Recipe {\n id: Int!\n title: String!\n ingredients: String!\n direction: String!\n user: User!\n }\n\n type Query {\n user(id: Int!): User\n allRecipes: [Recipe!]!\n recipe(id: Int!): Recipe\n }\n\n type Mutation {\n createUser(name: String!, email: String!, password: String!): User!\n createRecipe(\n userId: Int!\n title: String!\n ingredients: String!\n direction: String!\n ): Recipe!\n }\n`\n```\n\ngraphql reslover:\n\n```\nMutation: {\n async createRecipe (root, { userId, title, ingredients, direction }, { models }) {\n return models.Recipe.create({ userId, title, ingredients, direction })\n }\n }\n```\n\nand my grapql request:\n\n```\nmutation {\n createRecipe(\n userId: 1\n title: \"Sample 2\"\n ingredients: \"Salt, Pepper\"\n direction: \"Add salt, Add pepper\"\n ) {\n id\n title\n ingredients\n direction\n }\n}\n```\n\n========================================\n\nCode:\n```text\n\"message\": \"column \\\"UserId\\\" does not exist\",\n```\n\n```text\nExecuting (default): INSERT INTO \"Recipes\" \n(\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\") VALUES \n(DEFAULT,$1,$2,$3,$4,$5,$6) \n RETURNING \n\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\",\"UserId\";\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  class User extends Model {\n    static associate(models) {\n      User.hasMany(models.Recipe)\n    }\n  };\n  User.init({\n    name: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    email: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    password: {\n        type: DataTypes.STRING,\n        allowNull: false\n    }\n  }, {\n    sequelize,\n    modelName: 'User',\n  });\n  return User;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  class Recipe extends Model {\n    static associate(models) {\n      Recipe.belongsTo(models.User, { foreignKey: 'userId' })\n    }\n  };\n  Recipe.init({\n    title: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    ingredients: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    direction: {\n        type: DataTypes.STRING,\n        allowNull: false\n    }\n  }, {\n    sequelize,\n    modelName: 'Recipe',\n  });\n  return Recipe;\n};\n```\n\n```text\nconst typeDefs = gql`\n    type User {\n        id: Int!\n        name: String!\n        email: String!\n        recipes: [Recipe!]!\n      }\n\n    type Recipe {\n        id: Int!\n        title: String!\n        ingredients: String!\n        direction: String!\n        user: User!\n    }\n\n    type Query {\n        user(id: Int!): User\n        allRecipes: [Recipe!]!\n        recipe(id: Int!): Recipe\n    }\n\n    type Mutation {\n        createUser(name: String!, email: String!, password: String!): User!\n        createRecipe(\n          userId: Int!\n          title: String!\n          ingredients: String!\n          direction: String!\n        ): Recipe!\n    }\n`\n```\n\n```text\nMutation: {\n      async createRecipe (root, { userId, title, ingredients, direction }, { models }) {\n          return models.Recipe.create({ userId, title, ingredients, direction })\n      }\n  }\n```\n\n```text\nmutation {\n  createRecipe(\n    userId: 1\n    title: \"Sample 2\"\n    ingredients: \"Salt, Pepper\"\n    direction: \"Add salt, Add pepper\"\n  ) {\n    id\n    title\n    ingredients\n    direction\n  }\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n\nclass User extends Model {\n    static associate(models) {\n      User.hasMany(models.Recipe, {as: 'recipes', foreignKey:'userId'})\n    }\n  };\n  User.init({\n    name: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    email: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    password: {\n        type: DataTypes.STRING,\n        allowNull: false\n    }\n  }, {\n    sequelize,\n    modelName: 'User',\n  });\n  return User;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  class Recipe extends Model {\n    static associate(models) {\n      Recipe.belongsTo(models.User, { foreignKey: 'userId' })\n    }\n  };\n  Recipe.init({\n    title: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    ingredients: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    direction: {\n        type: DataTypes.STRING,\n        allowNull: false\n    }\n  }, {\n    sequelize,\n    modelName: 'Recipe',\n  });\n  return Recipe;\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":334,"estimatedTokens":1491}}658{"id":"stack-67438575","source":"stackoverflow","questionId":67438575,"title":"Fulltext search using Sequelize (Postgres)","tags":["node.js","postgresql","sequelize.js","full-text-search"],"text":"Title: Fulltext search using Sequelize (Postgres)\nTags: node.js, postgresql, sequelize.js, full-text-search\nSource: Stack Overflow\n\nQuestion:\nSo I've been working with `sequelize` for a while now, and after juggling with `elasticsearch`, I decided to make use of `postgres's` support for `fts`.\n\nIt looks like just at the start of this year `sequelize` added support for `TSVector` which is necessary for `FTS` implementation. Although I just can't find any documentation whatsover anywhere.\n\nThe pull request\n\nAll help is appreciated!\n\n========================================\n\nTop Answer:\n**Setting up a always up-to-date generated `TSVECTOR` column**\n\nAlthough using the built-in `DataTypes.TSVECTOR` type mentioned by Anatoly is tempting, we ideally also want to make that column be auto-generated from the column it indexes to keep it always up-to-date. I don't think there's an alternative to a raw query there so I'm using something like:\n\n```\nconst col = 'mycol'\nawait sequelize.query(`ALTER TABLE \"${MyTable.tableName}\"\n ADD COLUMN IF NOT EXISTS \"${col}_tsvector\" TSVECTOR\n GENERATED ALWAYS AS (to_tsvector('english', \"${col}\")) STORED`)\nawait sequelize.query(`CREATE INDEX \"${MyTable.tableName}_${col}_gin_idx\"\n ON \"${Strings.tableName}\" USING GIN (\"${col}_tsvector\")`)\n```\n\n**Escaping user-provided queries so `to_tsquery` doesn't blow up**\n\nAnother thing you likely will want to think about is that `to_tsquery` can lead to errors if you just give it user queries directly.\n\nSolutions and workarounds can be found on this thread: PSQLException: ERROR: syntax error in tsquery e.g. you might want to use `plainto_tsquery` instead of `to_tsquery`.\n\n**Minimal runable example with asserts**\n\nHere I put everything together:\n\nmain.js\n\n```\n#!/usr/bin/env node\n\nconst assert = require('assert')\n\nconst { DataTypes, Op, Sequelize } = require('sequelize')\n\nfunction assertEqual(rows, rowsExpect) {\n assert.strictEqual(rows.length, rowsExpect.length)\n for (let i = 0; i {\nawait sequelize.sync({ force: true })\nawait reset()\nlet rows\nif (sequelize.options.dialect === 'postgres') {\n rows = await Strings.findAll({\n //where: { mycol_tsvector: { [Op.match]: Sequelize.fn('to_tsquery', 'beetle') } },\n where: { mycol_tsvector: { [Op.match]: Sequelize.fn('plainto_tsquery', 'beetle') } },\n })\n assertEqual(rows, [\n { mycol: 'beetle rabbit' },\n { mycol: 'elephant beetle' },\n ])\n\n // Prefix search on the last term. Does not blow up for arbitrary user input I believe.\n rows = await Strings.findAll({\n where: { mycol_tsvector: { [Op.match]: sequelizePostgresqlUserQueryToTsqueryPrefixLiteral('rabbit bee') } },\n order: [['mycol', 'ASC']]\n })\n assertEqual(rows, [\n { mycol: 'beetle rabbit' },\n ])\n // Mostly to check that these cases don't blow up due to bad to_tsquery.\n rows = await Strings.findAll({\n where: { mycol_tsvector: { [Op.match]: sequelizePostgresqlUserQueryToTsqueryPrefixLiteral('') } },\n order: [['mycol', 'ASC']]\n })\n assertEqual(rows, [])\n rows = await Strings.findAll({\n where: { mycol_tsvector: { [Op.match]: sequelizePostgresqlUserQueryToTsqueryPrefixLiteral(',') } },\n order: [['mycol', 'ASC']]\n })\n assertEqual(rows, [])\n}\n})().finally(() => { return sequelize.close() })\n```\n\npackage.json\n\n```\n{\n \"name\": \"tmp\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"dependencies\": {\n \"pg\": \"8.5.1\",\n \"pg-hstore\": \"2.3.3\",\n \"sequelize\": \"6.14.0\"\n }\n}\n```\n\nTested on PostgreSQL 16.6, Node.js v20.10.0, Ubuntu 24.10.\n\n========================================\n\nCode:\n```text\nsequelize\n```\n\n```text\nelasticsearch\n```\n\n```text\npostgres's\n```\n\n```text\nfts\n```\n\n```text\nsequelize\n```\n\n```text\nTSVector\n```\n\n```text\nFTS\n```\n\n```js\n...\ntextField: {\n   type: DataTypes.TSVECTOR\n}\n...\n```\n\n```text\ntextField: {\n  [Op.match]: Sequelize.fn('to_tsquery', 'fat & rat') // match text search for strings 'fat' and 'rat' (PG only)\n}\n```\n\n```text\nOp.match\n```\n\n```text\nDateTypes.TSVECTOR\n```\n\n```text\nwhere\n```\n\n```text\nconst col = 'mycol'\nawait sequelize.query(`ALTER TABLE \"${MyTable.tableName}\"\n  ADD COLUMN IF NOT EXISTS \"${col}_tsvector\" TSVECTOR\n  GENERATED ALWAYS AS (to_tsvector('english', \"${col}\")) STORED`)\nawait sequelize.query(`CREATE INDEX \"${MyTable.tableName}_${col}_gin_idx\"\n  ON \"${Strings.tableName}\" USING GIN (\"${col}_tsvector\")`)\n```\n\n```js\n#!/usr/bin/env node\n\nconst assert = require('assert')\n\nconst { DataTypes, Op, Sequelize } = require('sequelize')\n\nfunction assertEqual(rows, rowsExpect) {\n  assert.strictEqual(rows.length, rowsExpect.length)\n  for (let i = 0; i < rows.length; i++) {\n    let row = rows[i]\n    let rowExpect = rowsExpect[i]\n    for (let key in rowExpect) {\n      assert.strictEqual(row[key], rowExpect[key])\n    }\n  }\n}\n\n/** Safely consume a user provided query string to a prefix search tsquery Sequelize literal.\n * For example, 'rabbit bee' gets converted to 'rabbit & bee:*' and therefore matches strings\n * that contain both the full word \"rabbit\" and the prefix bee.*. */\nfunction sequelizePostgresqlUserQueryToTsqueryPrefixLiteral(q) {\n  return sequelize.literal(\n    `regexp_replace(plainto_tsquery('english', ${sequelize.escape(q)})::text || ':*', '^..$', '')::tsquery`\n  )\n}\n\nasync function reset() {\n  await sequelize.truncate({ cascade: true })\n  await Strings.create({ mycol: 'chicken elephant' })\n  await Strings.create({ mycol: 'beetle rabbit' })\n  await Strings.create({ mycol: 'elephant beetle' })\n  if (sequelize.options.dialect === 'postgres') {\n    const col = 'mycol'\n    await sequelize.query(`ALTER TABLE \"${Strings.tableName}\" ADD COLUMN \"${col}_tsvector\" tsvector\nGENERATED ALWAYS AS (to_tsvector('english', \"${col}\")) STORED`)\n    await sequelize.query(`CREATE INDEX \"${Strings.tableName}_${col}_gin_idx\" ON \"${Strings.tableName}\" USING GIN (\"${col}_tsvector\")`)\n  }\n}\n\nconst sequelize = new Sequelize('tmp', undefined, undefined, {\n  dialect: 'postgres',\n  host: '/var/run/postgresql',\n})\nconst Strings = sequelize.define('Strings', {\n  mycol: { type: DataTypes.STRING },\n})\n;(async () => {\nawait sequelize.sync({ force: true })\nawait reset()\nlet rows\nif (sequelize.options.dialect === 'postgres') {\n  rows = await Strings.findAll({\n    //where: { mycol_tsvector: { [Op.match]: Sequelize.fn('to_tsquery', 'beetle') } },\n    where: { mycol_tsvector: { [Op.match]: Sequelize.fn('plainto_tsquery', 'beetle') } },\n  })\n  assertEqual(rows, [\n    { mycol: 'beetle rabbit' },\n    { mycol: 'elephant beetle' },\n  ])\n\n  // Prefix search on the last term. Does not blow up for arbitrary user input I believe.\n  rows = await Strings.findAll({\n    where: { mycol_tsvector: { [Op.match]: sequelizePostgresqlUserQueryToTsqueryPrefixLiteral('rabbit bee') } },\n    order: [['mycol', 'ASC']]\n  })\n  assertEqual(rows, [\n    { mycol: 'beetle rabbit' },\n  ])\n  // Mostly to check that these cases don't blow up due to bad to_tsquery.\n  rows = await Strings.findAll({\n    where: { mycol_tsvector: { [Op.match]: sequelizePostgresqlUserQueryToTsqueryPrefixLiteral('') } },\n    order: [['mycol', 'ASC']]\n  })\n  assertEqual(rows, [])\n  rows = await Strings.findAll({\n    where: { mycol_tsvector: { [Op.match]: sequelizePostgresqlUserQueryToTsqueryPrefixLiteral(',') } },\n    order: [['mycol', 'ASC']]\n  })\n  assertEqual(rows, [])\n}\n})().finally(() => { return sequelize.close() })\n```\n\n```text\n{\n  \"name\": \"tmp\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"pg\": \"8.5.1\",\n    \"pg-hstore\": \"2.3.3\",\n    \"sequelize\": \"6.14.0\"\n  }\n}\n```\n\n```text\nTSVECTOR\n```\n\n```text\nDataTypes.TSVECTOR\n```\n\n```text\nto_tsquery\n```\n\n```text\nto_tsquery\n```\n\n```text\nplainto_tsquery\n```\n\n```text\nto_tsquery\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":290,"estimatedTokens":1886}}659{"id":"stack-53146054","source":"stackoverflow","questionId":53146054,"title":"Foreign Key with Sequelize not working as expected","tags":["foreign-keys","sequelize.js"],"text":"Title: Foreign Key with Sequelize not working as expected\nTags: foreign-keys, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI was trying to create an association between two tables and I wanted to add a foreign key.\n\nThe two models are User and Companies\n\n`User.associate = (models) => {\n User.belongsTo(models.Companies, { foreignKey: 'Company' });\n};`\n\nMy expectation of the code above was that a Company ID field gets added in the user table which references the Company ID of the Companies table.\n\nOn running the code above, I don't see any additional columns getting created. I tried checking if a foreign key association is created in the DB and that also is missing.\n\nHowever, if I try to add a column with the same name while keeping the association code, I get a name conflict. This seems to suggest that the association is getting created but I am unable to see it.\n\nCould someone help me understand what I am doing wrong? Thanks for the help!\n\n**models/company.js**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n var Company = sequelize.define('company', {\n company: { type: DataTypes.STRING, primaryKey: true },\n });\n\n Company.associate = (models) => {\n Company.hasMany(models.user, { as: 'users' });\n };\n\n Company.sync();\n\n return Company;\n};\n```\n\n**models/user.js**\n\n```\nconst uuid = require('uuid/v4');\n\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n var User = sequelize.define('user', {\n id: { type: DataTypes.UUID, primaryKey: true },\n name: { type: DataTypes.STRING, allowNull: false }\n });\n\n User.associate = (models) => {\n User.belongsTo(models.company);\n };\n\n User.beforeCreate((user, _ ) => {\n user.id = uuid();\n return user;\n });\n\n User.sync();\n\n return User;\n};\n```\n\n**models/index.js**\n\n```\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(__filename);\nvar env = process.env.NODE_ENV || 'development';\n// var config = require(__dirname + '/../config/config.js')[env];\nvar db = {};\n\n// if (config.use_env_variable) {\n// var sequelize = new Sequelize(process.env[config.use_env_variable], config);\n// } else {\n// var sequelize = new Sequelize(config.database, config.username, config.password, config);\n// }\n\nconst sequelize = new Sequelize('postgres://postgres:user@localhost:5432/mydb');\n\nfs\n .readdirSync(__dirname)\n .filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n .forEach(file => {\n var model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n========================================\n\nTop Answer:\nYour model is fine! you must remove `sync` from models file , then check migration file for models with foreign key that `foregin key` is there, \n\n**for Migration User :**\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Users', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.UUID\n },\n name: {\n type: Sequelize.STRING\n },\n companyId: {\n type: Sequelize.UUID,\n references: {\n model: 'Company',// company migration define\n key: 'id'\n }\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Users');\n }\n};\n```\n\nfor create automate table from index.js and models you must install `sequelize-cli` \n\nby type `npm install --save sequelize-cli`\n\nthen you must run this command for create models table in db\n\n```\nsequelize db:migrate\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    var Company = sequelize.define('company', {\n        company: { type: DataTypes.STRING, primaryKey: true },\n    });\n\n    Company.associate = (models) => {\n        Company.hasMany(models.user, { as: 'users' });\n    };\n\n    Company.sync();\n\n    return Company;\n};\n```\n\n```text\nconst uuid = require('uuid/v4');\n\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n    var User = sequelize.define('user', {\n        id: { type: DataTypes.UUID, primaryKey: true },\n        name: { type: DataTypes.STRING, allowNull: false }\n    });\n\n    User.associate = (models) => {\n        User.belongsTo(models.company);\n    };\n\n    User.beforeCreate((user, _ ) => {\n        user.id = uuid();\n        return user;\n    });\n\n    User.sync();\n\n    return User;\n};\n```\n\n```text\n'use strict';\n\nvar fs        = require('fs');\nvar path      = require('path');\nvar Sequelize = require('sequelize');\nvar basename  = path.basename(__filename);\nvar env       = process.env.NODE_ENV || 'development';\n// var config    = require(__dirname + '/../config/config.js')[env];\nvar db        = {};\n\n// if (config.use_env_variable) {\n//   var sequelize = new Sequelize(process.env[config.use_env_variable], config);\n// } else {\n//   var sequelize = new Sequelize(config.database, config.username, config.password, config);\n// }\n\nconst sequelize = new Sequelize('postgres://postgres:user@localhost:5432/mydb');\n\nfs\n  .readdirSync(__dirname)\n  .filter(file => {\n    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n  })\n  .forEach(file => {\n      var model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(modelName => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nUser.associate = (models) => {\n    User.belongsTo(models.Companies, { foreignKey: 'Company' });\n};\n```\n\n```text\nforce\n```\n\n```text\nalter\n```\n\n```text\nsync\n```\n\n```text\nindex.js\n```\n\n```text\nsync\n```\n\n```text\nconst User = sequelize.define(\n  'user',\n  { /* columns */ },\n  { /* options */ }\n);\nUser.associate = (models) => {\n    User.belongsTo(models.Company);\n};\n\nconst Company = sequelize.define(\n  'company',\n  { /* columns */ },\n  { /* options */ }\n);\nCompany.associate = (models) => {\n    Company.hasMany(models.User, { as: 'users' });\n};\n```\n\n```text\nconst user = await User.findAll({ include: { model: Company } });\n/*\nuser = {\n  id: 1,\n  company_id: 1,\n  company: {\n    id: 1,\n  },\n};\n*/\n```\n\n```text\nconst company = await User.findAll({ include: { model: User, as: 'users' } });\n/*\ncompany = {\n  id: 1,\n  users: [{\n    id: 1\n    company_id: 1,\n  }],\n};\n*/\n```\n\n```text\nforeignKey: 'Company'\n```\n\n```text\nCompany\n```\n\n```text\ncompany\n```\n\n```text\ncompanies\n```\n\n```text\nforeignKey\n```\n\n```text\nCompany (id)\n```\n\n```text\nUser (id, company_id)\n```\n\n```text\nUser\n```\n\n```text\nCompany\n```\n\n```text\nCompany\n```\n\n```text\nUser\n```\n\n```text\nusers\n```\n\n```text\n// app.js (aka your main application)\nconst models = require('./models')(sequelize, DataTypes);\n\n// models.js\nmodule.exports = (sequelize, DataTypes) => {\n    const models = {\n        user: require('./userModel')(sequelize, DataTypes),\n        company: require('./companyModel')(sequelize, DataTypes)\n    };\n\n    Object.keys(models).forEach(key => {\n        if (models[key] && models[key].associate) {\n            models[key].associate(models);\n        }\n    });\n};\n\n// companyModel.js\nmodule.exports = (sequelize, DataTypes) => {\n    var Company = sequelize.define('company', {...});\n\n    Company.associate = (models) => {\n        Company.hasMany(models.user, { as: 'users' });\n    };\n\n    Company.sync();\n\n    return Company;\n};\n\n// userModel.js\nmodule.exports = (sequelize, DataTypes) => {\n    var User = sequelize.define('user', {...});\n\n    User.sync();\n\n    return User;\n};\n```\n\n```text\nassociate\n```\n\n```text\nassociate\n```\n\n```text\nassociate\n```\n\n```text\nmodels.js\n```\n\n```text\napp.js\n```\n\n```text\nsync\n```\n\n```text\nmodule.exports = {\n    up: (queryInterface, Sequelize) => {\n        return queryInterface.createTable('Users', {\n            id: {\n                allowNull: false,\n                autoIncrement: true,\n                primaryKey: true,\n                type: Sequelize.UUID\n            },\n            name: {\n                type: Sequelize.STRING\n            },\n            companyId: {\n                type: Sequelize.UUID,\n                references: {\n                    model: 'Company',// company migration define\n                    key: 'id'\n                }\n            },\n            createdAt: {\n                allowNull: false,\n                type: Sequelize.DATE\n            },\n            updatedAt: {\n                allowNull: false,\n                type: Sequelize.DATE\n            }\n        });\n    },\n    down: (queryInterface, Sequelize) => {\n        return queryInterface.dropTable('Users');\n    }\n};\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nsync\n```\n\n```text\nforegin key\n```\n\n```text\nsequelize-cli\n```\n\n```text\nnpm install --save sequelize-cli\n```\n\n========================================\n\nComments:\n- Your code sample is valid. I just tried and was able to create a field `Company` in the `users` table. Could you your full model definition as well are your DB config?\n- I have added it. I am using sequelize version ^4.41.0.\n- Please clarify via post edits, not comments.\n- Thanks for sharing the code samples. I have updated the post with what I have done (similar to your code), but I don't see the foreign key appear when I look at the table. I am using sequelize version ^4.41.0\n- Are you running `Sequelize.sync()`? The new column won't be automatically created...\n- Yes, I am calling the `sync()` function. I thought it would create the new column. What should I do then?\n- If I call `associate` in this way, it fails because the `associate` function is expecting models and we are sending nothing, and thus gets treated as undefined.\n- @NikhilBaliga I've updated my answer to include more details\n- Thanks for the updated code and the additional note, @mcranston18. However, I am calling the `associate` function. I have updated the query with the `index.js` file and if you notice, I am calling the `associate` function at the end. I had picked this code up as a standard way of doing it. I added `console.log` statements and found that the `associate` function is being called. But the relations are not getting created.\n- Or you can just create a migration file for each model and run `sequelize db:migrate` to create tables","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":37,"totalLines":501,"estimatedTokens":2621}}660{"id":"stack-50244763","source":"stackoverflow","questionId":50244763,"title":"how to search integer using ilike in sequelize","tags":["sequelize.js"],"text":"Title: how to search integer using ilike in sequelize\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to search row id = 123, if i have input field with 12 as input. Right now I have \n\n```\nwhere: {\n id: {\n [Op.iLike]: `%${req.body.gaugeId}%`,\n },\n },\n```\n\nThis works if I am searching text fields, but it does not work for searching integer fields. I understand this is related to casting, but I could have find a way to implement this.\n\n========================================\n\nTop Answer:\nI don't know which version you used but for\n\n`\"sequelize\": \"5.19.0\"`\n\nThe following works:\n\n```\nconst { sequelize } = require('../database/models')\n...\nconst results = await model.findAll({\n where: sequelize.where(sequelize.col('**column_name**'), 'LIKE', '%10%')\n```\n\nWhich gives us:\n\nhttps://i.sstatic.net/GHwYa.png\n\nand SQL:\n\n```\nWHERE `**column_name**` LIKE '%10%';\n```\n\nRegarding to documentation:\n\n`public static where(attr: Object, comparator: Symbol, logic: string | Object): *`\n\nThe third arg should be a `Symbol`(e.g. `Op.like`), but I find `string` working as well.\n\n========================================\n\nCode:\n```text\nwhere: {\n        id: {\n          [Op.iLike]: `%${req.body.gaugeId}%`,\n        },\n      },\n```\n\n```text\nsearch(req, res) {\n    return Gauge.findAll({\n      where: sequelize.where(\n        sequelize.cast(sequelize.col('Gauge.id'), 'varchar'),\n        {[Op.iLike]: `%${req.body.gaugeId}%`}\n      ),\n    }).then(gauges => {\n      res.status(200).send(gauges);\n    });\n  },\n```\n\n```text\nreturn Gauge.findAll({\n        attributes: ['id', 'stationName'],\n        where: {\n          [Op.or]: [\n            {stationName: {[Op.iLike]: `%${req.body.keyWord}%`}},\n            sequelize.where(\n              sequelize.cast(sequelize.col('Gauge.id'), 'varchar'),\n              {[Op.iLike]: `%${req.body.keyWord}%`}\n            ),\n          ],\n        },\n      })\n```\n\n```text\nModel.column_name\n```\n\n```text\nstring\n```\n\n```text\nvarchar\n```\n\n```text\nsequelize.or\n```\n\n```js\nconst { sequelize } = require('../database/models')\n...\nconst results = await model.findAll({\n where: sequelize.where(sequelize.col('**column_name**'), 'LIKE', '%10%')\n```\n\n```sql\nWHERE `**column_name**` LIKE '%10%';\n```\n\n```text\n\"sequelize\": \"5.19.0\"\n```\n\n```text\npublic static where(attr: Object, comparator: Symbol, logic: string | Object): *\n```\n\n```text\nSymbol\n```\n\n```text\nOp.like\n```\n\n```text\nstring\n```\n\n========================================\n\nComments:\n- `\"message\": \"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VARCHAR) LIKE '%1%'' at line 1\",`\n- Also, the import method should be like this `import { Sequelize } from 'sequelize';` or like this `import { Sequelize as sequelize } from 'sequelize';` unless it won't work in the latest versions of Sequalize JS.","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":140,"estimatedTokens":715}}661{"id":"stack-57739619","source":"stackoverflow","questionId":57739619,"title":"Using a raw SQL query with Sequelize ORM and literal","tags":["mysql","node.js","express","vue.js","sequelize.js"],"text":"Title: Using a raw SQL query with Sequelize ORM and literal\nTags: mysql, node.js, express, vue.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing the Sequelize ORM I am trying to update the field level_id where this field has a foreign key to the field Level in another table called level_tbl.\n\n```\nselect * from level_tbl;\n+----------+----------+\n| level_id | Level |\n+----------+----------+\n| 1 | Higher |\n| 2 | Ordinary |\n+----------+----------+\n```\n\nMy update task looks like this, and as you can see I am trying to get a raw sql query to work as a literal with Sequelize.\n\n```\n//Update task\n router.put(\"/task/:id\", (req, res) => {\n if (!req.body) {\n res.status(400)\n res.json({\n error: \"Bad Data....!\"\n })\n } else {\n Task.update({\n Level: req.body.Level,\n Level_id: [sequelize.literal(\"SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'\")],\n Year: req.body.Year,\n Question: req.body.Question,\n Answer: req.body.Answer,\n Topic: req.body.Topic,\n Sub_topic: req.body.Sub_topic,\n Question_type: req.body.Question_type,\n Marks: req.body.Marks,\n Question_number: req.body.Question_number,\n Part: req.body.Part,\n Sub_part: req.body.Sub_part\n }, {\n where: {\n id: req.params.id\n }\n })\n .then(() => {\n res.send(\"Task Updated\")\n })\n .error(err => res.send(err))\n }\n })\n```\n\nWhat would be the correct syntax for this line?\n\n```\nLevel_id: [sequelize.literal(\"SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'\")],\n```\n\nThe issue is that I already have imported a model and have access to the global Sequelize instance. Therefore example in the documentation don't apply this way, i.e.,\n\n```\norder: sequelize.literal('max(age) DESC')\n```\n\nFrom https://sequelize.org/master/manual/querying.html\n\nand also,\n\nhttps://github.com/sequelize/sequelize/issues/9410#issuecomment-387141567\n\nMy Task.js where the model is defined is as follows,\n\n```\nconst Sequelize = require(\"sequelize\")\nconst db = require(\"../database/db.js\")\n\nmodule.exports = db.sequelize.define(\n \"physics_tbls\", {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n Level: {\n type: Sequelize.STRING\n },\n Level_id: {\n type: Sequelize.INTEGER\n },\n Year: {\n type: Sequelize.INTEGER\n },\n .........\n }, {\n timestamps: false\n }\n)\n```\n\nI am using a MEVN stack -> MySQL, Express.js, Vue.js and Node.js\n\nAny help would be greatly appreciated,\n\nThanks,\n\n========================================\n\nTop Answer:\nI am using sequelize 6.3 and raw query on `where` is no longer supported\n\nI used this syntax :\n\n```\nwhere: sequelize.where(sequelize.col(\"table.column\"), \"=\", \"yourvalue\")\n```\n\nand it worked\n\n========================================\n\nCode:\n```text\nselect * from level_tbl;\n+----------+----------+\n| level_id | Level    |\n+----------+----------+\n|        1 | Higher   |\n|        2 | Ordinary |\n+----------+----------+\n```\n\n```text\n//Update task\n    router.put(\"/task/:id\", (req, res) => {\n      if (!req.body) {\n        res.status(400)\n        res.json({\n          error: \"Bad Data....!\"\n        })\n      } else {\n        Task.update({\n            Level: req.body.Level,\n            Level_id: [sequelize.literal(\"SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'\")],\n            Year: req.body.Year,\n            Question: req.body.Question,\n            Answer: req.body.Answer,\n            Topic: req.body.Topic,\n            Sub_topic: req.body.Sub_topic,\n            Question_type: req.body.Question_type,\n            Marks: req.body.Marks,\n            Question_number: req.body.Question_number,\n            Part: req.body.Part,\n            Sub_part: req.body.Sub_part\n          }, {\n            where: {\n              id: req.params.id\n            }\n          })\n          .then(() => {\n            res.send(\"Task Updated\")\n          })\n          .error(err => res.send(err))\n      }\n    })\n```\n\n```text\nLevel_id: [sequelize.literal(\"SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'\")],\n```\n\n```text\norder: sequelize.literal('max(age) DESC')\n```\n\n```text\nconst Sequelize = require(\"sequelize\")\nconst db = require(\"../database/db.js\")\n\nmodule.exports = db.sequelize.define(\n  \"physics_tbls\", {\n    id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    Level: {\n      type: Sequelize.STRING\n    },\n    Level_id: {\n      type: Sequelize.INTEGER\n    },\n    Year: {\n      type: Sequelize.INTEGER\n    },\n    .........\n  }, {\n    timestamps: false\n  }\n)\n```\n\n```text\nconst Sequelize = require('sequelize')\nvar express = require(\"express\")\nvar router = express.Router()\nconst Task = require(\"../model/Task\")\n```\n\n```text\nLevel_id: Sequelize.literal(\"(SELECT level_id FROM level_tbl WHERE Level = 'Higher')\"),\n```\n\n```text\nwhere: sequelize.where(sequelize.col(\"table.column\"), \"=\", \"yourvalue\")\n```\n\n```text\nwhere\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":221,"estimatedTokens":1190}}662{"id":"stack-59201727","source":"stackoverflow","questionId":59201727,"title":"Sequelize LEFT JOIN only single column value","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize LEFT JOIN only single column value\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo I have next structure: Comments, Users, Likes.\n\nUsers has many likes, Comments has many likes.\n\nI'm trying to get all Comments and check if User liked them. I have a raw query with LEFT JOIN that is working totally fine:\n\n```\nawait sequelize.query(`SELECT comments.*, likes.liked FROM comments LEFT JOIN \nlikes ON likes.commentId = comment.id AND likes.user_id = '123'`, {type: Sequelize.QueryTypes.SELECT});\n```\n\nI'm getting something like this: \n\n```\n[{\n \"id\": 1,\n \"userId\": \"123\",\n \"comment\": \"abcde\",\n \"liked\": true\n },\n {\n \"id\": 2,\n \"userId\": \"552\",\n \"comment\": \"abc\",\n \"liked\": null\n }]\n```\n\nNow I'm trying to implement the same using `findAll()` method.\n\n```\nawait Comment.findAll({\n include: [{\n model: Like,\n attributes: ['liked'],\n where: {user_id: id},\n required: false\n }]\n })\n```\n\nBut I'm getting this: \n\n```\n[{\n \"id\": 1,\n \"userId\": \"123\",\n \"comment\": \"abcde\",\n \"likes\": [{liked:true}]\n},\n{\n \"id\": 2,\n \"userId\": \"552\",\n \"comment\": \"abc\",\n \"likes\": []\n}]\n```\n\nSo the question is: How can I include only column `liked` and not array of `likes`? Thank you.\n\n========================================\n\nCode:\n```text\nawait sequelize.query(`SELECT comments.*, likes.liked FROM comments LEFT JOIN \nlikes ON likes.commentId = comment.id AND likes.user_id = '123'`, {type: Sequelize.QueryTypes.SELECT});\n```\n\n```text\n[{\n        \"id\": 1,\n        \"userId\": \"123\",\n        \"comment\": \"abcde\",\n        \"liked\": true\n    },\n    {\n        \"id\": 2,\n        \"userId\": \"552\",\n        \"comment\": \"abc\",\n        \"liked\": null\n    }]\n```\n\n```text\nawait Comment.findAll({\n        include: [{\n            model: Like,\n            attributes: ['liked'],\n            where: {user_id: id},\n            required: false\n        }]\n    })\n```\n\n```text\n[{\n    \"id\": 1,\n    \"userId\": \"123\",\n    \"comment\": \"abcde\",\n    \"likes\": [{liked:true}]\n},\n{\n    \"id\": 2,\n    \"userId\": \"552\",\n    \"comment\": \"abc\",\n    \"likes\": []\n}]\n```\n\n```text\nfindAll()\n```\n\n```text\nliked\n```\n\n```text\nlikes\n```\n\n```text\nawait Comment.findAll({\n   include: [{\n     model: Like,\n     attributes: [],   // attributes here are nested under \"Like\" \n     where: {user_id: id},\n       required: false\n     }],\n   attributes: {\n     include: [[Sequelize.col(\"liked\"), \"liked\"]]  // NOT nested\n   }\n })\n```\n\n========================================\n\nComments:\n- That's actually what I needed, thanks! So sad it's such a headache, raw query is kinda much intuitive..\n- Agreed, but there is some payback. For 1:M relationships, the nesting can be very helpful\n- Nice but the resulted object don't get the `liked` property (in v6 at least) which is annoying, it works with getDataValue but it's sill cumbersome. You might be better of mapping liked to `likes[0].liked`","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":146,"estimatedTokens":710}}663{"id":"stack-57130921","source":"stackoverflow","questionId":57130921,"title":"How to remove attribute from response using sequelize?","tags":["javascript","node.js","sequelize.js"],"text":"Title: How to remove attribute from response using sequelize?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\nconst User = sequelize.define('user', {\n // attributes\n firstName: {\n type: Sequelize.STRING,\n allowNull: false\n },\n lastName: {\n type: Sequelize.STRING\n // allowNull defaults to true\n }\n});\n\nconst Project = sequelize.define('project', {\n // attributes\n projectName: {\n type: Sequelize.STRING,\n allowNull: false\n }\n});\nUser.belongsToMany(Project,{as:'Projects',through:'user_project'});\nProject.belongsToMany(User,{as:'Users',through:'user_project'});\n```\n\n**Fetching data like this**\n\n```\napp.use('/get', (req, res) => {\n User.findAll({\n attributes: ['firstName'],\n include: [{\n model:Project,\n as:'Projects',\n attributes: ['projectName']\n }]}).then((result) => {\n res.json(result)\n })\n})\n```\n\n**getting a response like this**\n\n```\n[{\n \"firstName\": \"naveen\",\n \"Projects\": [\n {\n \"projectName\": \"EV\",\n \"user_project\": {\n \"createdAt\": \"2019-07-21T06:17:49.119Z\",\n \"updatedAt\": \"2019-07-21T06:17:49.119Z\",\n \"userId\": 1,\n \"projectId\": 3\n }\n }\n ]\n }]\n```\n\n**Expected response**\n\n```\n[{\n \"firstName\": \"naveen\",\n \"Projects\": [\n {\n \"projectName\": \"EV\",\n }\n ]\n }]\n```\n\nI am using sequelize in my project(http://docs.sequelizejs.com).I am fetching data from `DB`.I have **many to many mapping** I already add `attributes` property to remove unnecessary data. but it not works for me\n\n========================================\n\nTop Answer:\nUse delete key\n\n```\nvar YourJson = [{\n \"firstName\": \"naveen\",\n \"Projects\": [\n {\n \"projectName\": \"EV\",\n \"user_project\": {\n \"createdAt\": \"2019-07-21T06:17:49.119Z\",\n \"updatedAt\": \"2019-07-21T06:17:49.119Z\",\n \"userId\": 1,\n \"projectId\": 3\n }\n }\n ]\n }];\n\n delete YourJson['0']['Projects']['0']['user_project'];\n\n console.log(YourJson)\n```\n\n========================================\n\nCode:\n```text\nconst User = sequelize.define('user', {\n    // attributes\n    firstName: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    lastName: {\n        type: Sequelize.STRING\n        // allowNull defaults to true\n    }\n});\n\nconst Project = sequelize.define('project', {\n    // attributes\n    projectName: {\n        type: Sequelize.STRING,\n        allowNull: false\n    }\n});\nUser.belongsToMany(Project,{as:'Projects',through:'user_project'});\nProject.belongsToMany(User,{as:'Users',through:'user_project'});\n```\n\n```text\napp.use('/get', (req, res) => {\n    User.findAll({\n        attributes: ['firstName'],\n        include: [{\n         model:Project,\n            as:'Projects',\n            attributes: ['projectName']\n        }]}).then((result) => {\n        res.json(result)\n    })\n})\n```\n\n```text\n[{\n    \"firstName\": \"naveen\",\n    \"Projects\": [\n      {\n        \"projectName\": \"EV\",\n        \"user_project\": {\n          \"createdAt\": \"2019-07-21T06:17:49.119Z\",\n          \"updatedAt\": \"2019-07-21T06:17:49.119Z\",\n          \"userId\": 1,\n          \"projectId\": 3\n        }\n      }\n    ]\n  }]\n```\n\n```text\n[{\n    \"firstName\": \"naveen\",\n    \"Projects\": [\n      {\n        \"projectName\": \"EV\",\n      }\n    ]\n  }]\n```\n\n```text\nDB\n```\n\n```text\nattributes\n```\n\n```js\nUser.findAll({\n        attributes: ['firstName'],\n        include: [{\n         model:Project,\n            as:'Projects',\n            attributes: ['projectName'],\n            through: { attributes: [] } // using empty array will cause not to return the relation fields at all\n        }]}).then((result) => {\n        res.json(result)\n    })\n```\n\n```text\noptions.include[].through.attributes\n```\n\n```text\nvar YourJson = [{\n    \"firstName\": \"naveen\",\n    \"Projects\": [\n      {\n        \"projectName\": \"EV\",\n        \"user_project\": {\n          \"createdAt\": \"2019-07-21T06:17:49.119Z\",\n          \"updatedAt\": \"2019-07-21T06:17:49.119Z\",\n          \"userId\": 1,\n          \"projectId\": 3\n        }\n      }\n    ]\n  }];\n\n    delete YourJson['0']['Projects']['0']['user_project'];\n\n    console.log(YourJson)\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.392Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":219,"estimatedTokens":981}}664{"id":"stack-49424040","source":"stackoverflow","questionId":49424040,"title":"Why does Sequelize add extra columns to SELECT query?","tags":["node.js","sequelize.js"],"text":"Title: Why does Sequelize add extra columns to SELECT query?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen i want to get some records with joined data from the referenced tables, Sequelize adds the reference columns twice: the normal one and a copy of them, written just a little bit different.\n\nThis is my model:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('result', {\nid: {\n type: DataTypes.INTEGER(10),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n},\ntest_id: {\n type: DataTypes.INTEGER(10),\n allowNull: false,\n references: {\n model: 'test',\n key: 'id'\n }\n},\nitem_id: {\n type: DataTypes.INTEGER(10),\n allowNull: false,\n references: {\n model: 'item',\n key: 'id'\n }\n },\n}, // and many other fields\n{\ntableName: 'result',\ntimestamps: false, // disable the automatic adding of createdAt and updatedAt columns\nunderscored:true\n});\n}\n```\n\nIn my repository I have a method, which gets the result with joined data. And I defined the following associations:\n\n```\nconst Result = connection.import('../../models/storage/result');\nconst Item = connection.import('../../models/storage/item');\nconst Test = connection.import('../../models/storage/test');\n\nResult.belongsTo(Test, {foreignKey: 'test_id'});\nTest.hasOne(Result);\n\nResult.belongsTo(Item, {foreignKey: 'item_id'});\nItem.hasOne(Result);\n\n// Defining includes for JOIN querys\nvar include = [{\nmodel: Item,\nattributes: ['id', 'header_en']\n}, {\nmodel: Test,\nattributes: ['label']\n}];\n\nvar getResult = function(id) {\n\n return new Promise((resolve, reject) => { // pass result\n Result.findOne({\n where: { id : id },\n include: include,\n // attributes: ['id',\n // 'test_id',\n // 'item_id',\n // 'result',\n // 'validation'\n // ]\n }).then(result => {\n resolve(result);\n });\n }); \n}\n```\n\nThe function produces the following query:\n\n```\nSELECT `result`.`id`, `result`.`test_id`, `result`.`item_id`, `result`.`result`, `result`.`validation`, `result`.`testId`, `result`.`itemId`, `item`.`id` AS `item.id`, `item`.`title` AS `item.title`, `test`.`id` AS `test.id`, `test`.`label` AS `test.label` FROM `result` AS `result` LEFT OUTER JOIN `item` AS `item` ON `result`.`item_id` = `item`.`id` LEFT OUTER JOIN `test` AS `test` ON `result`.`test_id` = `test`.`id` WHERE `result`.`id` = '1';\n```\n\nNotice the extra itemId, testId it wants to select from the result table. I don't know where this happens. This produces: \n\n```\nUnhandled rejection SequelizeDatabaseError: Unknown column 'result.testId' in 'field list'\n```\n\nIt only works when i specify which attributes to select.\n\n**EDIT:** my tables in the database already have references to other tables with item_id and test_id. Is it then unnecessary to add the associations again in the application code like I do?\n\nA result always has one item and test it belongs to.\n\nHow can i solve this?\n\nThanks in advance, \n\nMike\n\n========================================\n\nTop Answer:\nSequelize uses these column name by adding an id to the model name by default. If you want to stop it, there is an option that you need to specify.\n\n`underscored: true`\n\nYou can specify this property on application level and on model level.\n\nAlso, you can turn off the timestamps as well. You need to use the timestamp option.\n\n`timestamps: false`\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\nreturn sequelize.define('result', {\nid: {\n  type: DataTypes.INTEGER(10),\n  allowNull: false,\n  primaryKey: true,\n  autoIncrement: true\n},\ntest_id: {\n  type: DataTypes.INTEGER(10),\n  allowNull: false,\n  references: {\n    model: 'test',\n    key: 'id'\n  }\n},\nitem_id: {\n  type: DataTypes.INTEGER(10),\n  allowNull: false,\n  references: {\n    model: 'item',\n    key: 'id'\n    }\n },\n}, // and many other fields\n{\ntableName: 'result',\ntimestamps: false, // disable the automatic adding of createdAt and    updatedAt columns\nunderscored:true\n});\n}\n```\n\n```text\nconst Result = connection.import('../../models/storage/result');\nconst Item = connection.import('../../models/storage/item');\nconst Test = connection.import('../../models/storage/test');\n\nResult.belongsTo(Test, {foreignKey: 'test_id'});\nTest.hasOne(Result);\n\nResult.belongsTo(Item, {foreignKey: 'item_id'});\nItem.hasOne(Result);\n\n// Defining includes for JOIN querys\nvar include = [{\nmodel: Item,\nattributes: ['id', 'header_en']\n}, {\nmodel: Test,\nattributes: ['label']\n}];\n\nvar getResult = function(id) {\n\n    return new Promise((resolve, reject) => { // pass result\n        Result.findOne({\n            where: { id : id },\n            include: include,\n        //     attributes: ['id',\n        // 'test_id',\n        // 'item_id',\n        // 'result',\n        // 'validation'\n        // ]\n        }).then(result => {\n            resolve(result);\n            });\n    }); \n}\n```\n\n```text\nSELECT `result`.`id`, `result`.`test_id`, `result`.`item_id`,  `result`.`result`, `result`.`validation`, `result`.`testId`, `result`.`itemId`, `item`.`id` AS `item.id`, `item`.`title` AS `item.title`, `test`.`id` AS `test.id`, `test`.`label` AS `test.label` FROM `result` AS `result` LEFT OUTER JOIN `item` AS `item` ON `result`.`item_id` = `item`.`id` LEFT OUTER JOIN `test` AS `test` ON `result`.`test_id` = `test`.`id` WHERE `result`.`id` = '1';\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: Unknown column 'result.testId' in 'field list'\n```\n\n```text\nResult.belongsTo(Test, {foreignKey: 'test_id'});\n// Test.hasMany(Result);\n\nResult.belongsTo(Item, {foreignKey: 'item_id'});\n// Item.hasOne(Result);\n```\n\n```text\nunderscored: true\n```\n\n```text\ntimestamps: false\n```\n\n```text\nResult.belongsTo(Test, {foreignKey: 'test_id'});\nTest.hasMany(Result, {foreignKey: 'test_id'});\n\nResult.belongsTo(Item, {foreignKey: 'item_id'});\nItem.hasOne(Result, {foreignKey: 'item_id'});\n```\n\n```text\ntest_id\n```\n\n```text\ntestId\n```\n\n```text\nitem_id\n```\n\n```text\nitemId\n```\n\n```text\nResult\n```\n\n========================================\n\nComments:\n- I tried underscored: true on all associated models, but it still wants to select result.itemId and result.testId. I already disabled timestamps, but I didn't include it in my model definition. :)\n- I can not see it in your code `{ tableName: 'result', timestamps: false, &#47;&#47; disable the automatic adding of createdAt and updatedAt columns }` Can you update your code and add `config.json` file as well\n- I forgot indeed, but adding the underscored true won't help on model level :(. Config.json, which config? Thanks for helping.\n- Can you try it before `tableName`, sounds dumb but worth a try i think :)\n- Didn't work, but I solved my problem. It was due to improper association definition. Thanks for the help, though!\n- That works for me too, but what if you want to access from, in your case, Test model? :\\\n- What do you mean with accessing the Test model? In my case it performs a join query and you can access it then by calling result.test.whatever on the data given back by Sequelize.\n- I mean, when you defined the has many association it's because you need to access from the test model to the result model(`test.getResults()`) . Deleting the has many association deletes that possibility as well, right?\n- Oh yeah, sure. I didn't need that.","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":261,"estimatedTokens":1807}}665{"id":"stack-47819438","source":"stackoverflow","questionId":47819438,"title":"Can I have custom Sequelize validators that depend on values?","tags":["node.js","validation","sequelize.js"],"text":"Title: Can I have custom Sequelize validators that depend on values?\nTags: node.js, validation, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn my model, I have\n\n```\nlevel: {\n type: DataTypes.ENUM('state', 'service-area'),\n allowNull: false,\n validate: {\n isIn: {\n args: [\n ['state', 'service-area']\n ],\n msg: 'level should be one of state,service-area'\n }\n }\n },\n assignedStates: {\n type: DataTypes.ARRAY(DataTypes.STRING),\n allowNull: true\n },\n assignedServiceAreas: {\n type: DataTypes.ARRAY(DataTypes.STRING),\n allowNull: true\n },\n```\n\nI'm trying to add a validator if `level` is `state` then `assignedStates` should not be null. How would I go about doing that?\n\n========================================\n\nCode:\n```text\nlevel: {\n    type: DataTypes.ENUM('state', 'service-area'),\n    allowNull: false,\n    validate: {\n      isIn: {\n        args: [\n          ['state', 'service-area']\n        ],\n        msg: 'level should be one of state,service-area'\n      }\n    }\n  },\n      assignedStates: {\n        type: DataTypes.ARRAY(DataTypes.STRING),\n        allowNull: true\n      },\n      assignedServiceAreas: {\n        type: DataTypes.ARRAY(DataTypes.STRING),\n        allowNull: true\n      },\n```\n\n```text\nlevel\n```\n\n```text\nstate\n```\n\n```text\nassignedStates\n```\n\n```js\nconst Levels = {\n  State: 'state',\n  ServiceArea: 'service-area'\n}\n\nconst Location = sequelize.define(\n  \"location\", {\n    level: {\n      type: DataTypes.ENUM(...Object.values(Levels)),\n      allowNull: false,\n      validate: {\n        isIn: {\n          args: [Object.values(Levels)],\n          msg: \"level should be one of state,service-area\"\n        }\n      }\n    },\n    assignedStates: {\n      type: DataTypes.ARRAY(DataTypes.STRING),\n      allowNull: true\n    },\n    assignedServiceAreas: {\n      type: DataTypes.ARRAY(DataTypes.STRING),\n      allowNull: true\n    }\n  }, {\n    validate: {\n      assignedValuesNotNul() {\n        // Here \"this\" is a refference to the whole object.\n        // So you can apply any validation logic.\n        if (this.level === Levels.State && !this.assignedStates) {\n          throw new Error(\n            'assignedStates should not be null when level is \"state\"'\n          );\n        }\n\n        if (this.level === Levels.ServiceArea && !this.assignedServiceAreas) {\n          throw new Error(\n            'assignedSerivceAreas should not be null when level is \"service-areas\"'\n          );\n        }\n      }\n    }\n  }\n);\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":117,"estimatedTokens":608}}666{"id":"stack-75495806","source":"stackoverflow","questionId":75495806,"title":"PostgreSQL ERROR: must be owner of schema public","tags":["javascript","postgresql","sequelize.js"],"text":"Title: PostgreSQL ERROR: must be owner of schema public\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to Postgres and am having an issue dropping all tables in a database. I have a database named \"mvp\" and the owner is set as \"postgres.\" I did the following in my terminal:\n\n```\npsql -d mvp postgres -W\npostgres=> \\l\n List of databases\n Name | Owner | Encoding | Collate | Ctype | Access privileges \n-----------+----------+----------+---------+-------+---------------------\n mvp | postgres | UTF8 | C | C | \npostgres=> \\c mvp\nYou are now connected to database \"mvp\" as user \"postgres\".\nmvp=> DROP SCHEMA public CASCADE;\nERROR: must be owner of schema public\n```\n\nIt is showing that I am logged in as the user \"postgres\" which happens to be the owner of the \"mvp\" database. However, I am receiving an error message saying I am not the owner.\n\n========================================\n\nCode:\n```text\npsql -d mvp postgres -W\npostgres=> \\l\n                            List of databases\n   Name    |  Owner   | Encoding | Collate | Ctype |  Access privileges  \n-----------+----------+----------+---------+-------+---------------------\n mvp       | postgres | UTF8     | C       | C     | \npostgres=> \\c mvp\nYou are now connected to database \"mvp\" as user \"postgres\".\nmvp=> DROP SCHEMA public CASCADE;\nERROR:  must be owner of schema public\n```\n\n```text\n\\dn public\n```\n\n```text\n\\c - username\n```\n\n```text\nDROP SCHEMA public CASCADE;\n```\n\n```text\npublic\n```\n\n```text\npostgres\n```\n\n```text\npostgres\n```\n\n```text\npublic\n```\n\n========================================\n\nComments:\n- To your question add the answers to the following commands run in `psql` 1) select version(); 2) `\\du postgres` 3) `\\dn public`\n- The `\\l` does confirm that postgres is the owner of the database. However, the error messages says that postgres is not the owner of the **schema**.","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":71,"estimatedTokens":472}}667{"id":"stack-61948302","source":"stackoverflow","questionId":61948302,"title":"Optional parameters on sequelize query","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Optional parameters on sequelize query\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nGood morning.\n\nI'm quite new to NodeJS / sequelize world and I'm currently facing a problem while trying to display a dashboard on screen.\n\nThis dashboard has three filters: two dates (period), client name, and employee name. The user can select none, one, two, or all the filters and my database needs to work accordingly.\n\nThat being said, my problem is with Sequelize because I don't know how to treat this problem of parameters not being \"always\" there.\n\nI've seen this question: \n\nSequelize optional where clause parameters?\n\nbut this answer doesn't work anymore. I also tried another way of building the where clause, but I failed on it as well (mainly due to sequelize operators).\nThe last thing I tried was to make a single query with all parameters included but try to find some value (or flag) that would make sequelize ignore the parameter, for the case when the parameter was no there*, but it looks like Sequelize doesn't have anything like that.\n\n* I've read a question here that has an answer saying that `{}` would do the trick but I tried that as well but didn't work.\n\nIn summary: I need to make a query that can \"change\" over time, for example:\n\n```\nFoo.findAll({\n where: { \n id : 1,\n }\n});\n\nFoo.findAll({\n where: { \n id {\n [Op.in] : [1,2,3,4,5]\n },\n name: \"palmeiira\",\n }\n});\n```\n\nDo you know a way of doing it without the need of using a lot if / switch statements?\n\nI'm currently using Sequelize v. 5.5.1.\n\n**Update**\n\nI tried doing as suggested by @Anatoly and created a function to build the parameters. It was something like that. (I tried a \"smaller\" version just to test)\n\n```\nasync function test() {\n const where = {};\n where[Op.and] = [];\n where[Op.eq].push({\n id: {\n [Op.in]: [1,2,3] \n }\n });\n\n return where;\n}\n```\n\nI setted the return value to a const:\n\n```\nconst query = await test()\n```\n\nAnd tried `console.log(query)`\nThe result was: **{ [Symbol(and)]: [ { id: [Object] } ] }**, which made me believe that the problem was parsing the `Op` part so i tried using `'Op.and'` and `'Op.in'` to avoid that and it solved this problem, but led to another on sequelize that said **Invalid value**\n\nDo you have any idea where is my error ?\n\nP.S.: @Anatoly very nice idea you gave me on original answer. Thank you very much.\n\n========================================\n\nCode:\n```text\nFoo.findAll({\n  where: { \n  id : 1,\n  }\n});\n\nFoo.findAll({\n  where: { \n  id {\n   [Op.in] : [1,2,3,4,5]\n  },\n  name: \"palmeiira\",\n  }\n});\n```\n\n```text\nasync function test() {\n  const where = {};\n  where[Op.and] = [];\n  where[Op.eq].push({\n    id: {\n    [Op.in]: [1,2,3] \n    }\n  });\n\n  return where;\n}\n```\n\n```text\nconst query = await test()\n```\n\n```text\n{}\n```\n\n```text\nconsole.log(query)\n```\n\n```text\nOp\n```\n\n```text\n'Op.and'\n```\n\n```text\n'Op.in'\n```\n\n```text\nconst where = {}\n\nif (datesFilter || clientNameFilter || employeenameFilter) {\n  where[Op.and] = []\n  if (datesFilter) {\n    where[Op.and].push({\n      dateField: {\n        [Op.between]: [datesFilter.start, datesFilter.finish]\n      }\n    })\n  }\n  if (clientNameFilter) {\n    where[Op.and].push({\n      name: {\n        [Op.iLike]: `%${clientNameFilter.value}%`\n      }\n    })\n  }\n  if (employeenameFilter) {\n    where[Op.and].push({\n      employeeName: {\n        [Op.iLike]: `%${employeenameFilter.value}%`\n      }\n    })\n  }\n}\n\nconst dashboardItems = await DashboardItem.findAll({ where }, {\n// some options here\n})\n```\n\n========================================\n\nComments:\n- four `if`'s will be enough?\n- @Anatoly i don't think it would be enough. For this specific case i guess I'd take at least 4! = 24 `if`'s. I believe that instead of using `if` 's to add (because I can't use inside Sequelize's where), in this case each `&#236;f` should correspond to a combination of parameters that can be sent inside the request, for example: 1. Start date and client name 2. Both dates and client name 3. Client name and employee name ..... and so go on.\n- ok, I'll try to show a solution in an answer\n- Ypu can't use an array for Op.eq just fro Op.or and Op.and\n- Thank you very, much, @Anatoly. With that new detail your solution worked pretty fine. However, I'd like to ask you another thing, if possible. Do you know the reason only Op.or and Op.and are accepted ? Again, thank you very much.\n- I suppose it's by design. AND and OR conditions expects there will be more then one condition on the other hands Op.eq relays on equality to a certain single value. In case you have several values you can always use Op.in.\n- I updated the question with the problem I'm having now that I tried your solution. Do you have any idea what might be causing it ? Thank you for your answer. @Anatoly\n- `DashboardItem.findAll(where,...` should be `DashboardItem.findAll({where: where}, ...`\n- @palmeiira You should replace ` where[Op.eq]` with ` where[Op.and]`","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":179,"estimatedTokens":1233}}668{"id":"stack-29697494","source":"stackoverflow","questionId":29697494,"title":"Sequelize Model Unit Test","tags":["node.js","testing","sequelize.js","sinon"],"text":"Title: Sequelize Model Unit Test\nTags: node.js, testing, sequelize.js, sinon\nSource: Stack Overflow\n\nQuestion:\nI have a `User` sequelize model that has a `beforeCreate` hook that encrypts the password using `bcrypyt`. `Bcrypyt` is loaded as a dependency by the model using a `require` statement.\n\nNow, I'm writing my tests for my models and I want to write a test that ensures `bcrypt` is hashing the password on create.\n\nAt the moment, I have added a setter onto the `User` model that sets the `bcrypt` object. In my tests, I can then create a spy using `sinon` and inject the spy using the setter and ensure it is called on create.\n\nIs this the correct way to do it? I feel as if I'm creating a setter purely for my tests and that it serves no other purpose.\n\n========================================\n\nCode:\n```text\nUser\n```\n\n```text\nbeforeCreate\n```\n\n```text\nbcrypyt\n```\n\n```text\nBcrypyt\n```\n\n```text\nrequire\n```\n\n```text\nbcrypt\n```\n\n```text\nUser\n```\n\n```text\nbcrypt\n```\n\n```text\nsinon\n```\n\n```text\nvar User = require( './User' )\nvar BCRYPT_HASH_BEGINNING = '$2a$'\nvar TEST_PASSWORD = 'hello there'\n\nUser.create({ password: TEST_PASSWORD }).then( function( user ){\n  if( !user ) throw new Error( 'User is null' )\n  if( !user.password ) throw new Error( 'Password was not saved' )\n  if( user.password === TEST_PASSWORD )\n    throw new Error( 'Password is plaintext' )\n  if( user.password.indexOf( BCRYPT_HASH_BEGINNING ) === -1 )\n    throw new Error( 'Password was not encrypted' )\n})\n```\n\n========================================\n\nComments:\n- Except that that test will leave your database in a dirty state; you don't clean up after it.\n- @Jez `And the setup and teardown is very scriptable`\n- Until a test fails and the teardown can't run for some reason.\n- This is more an end to end test, making sure the object was really created, not whether it's available to the application. The unit test should be fast and not access the actual database.\n- THIS IS NOT UNIT TEST! you are connecting to DB in `require('&#47;.User');`","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":75,"estimatedTokens":507}}669{"id":"stack-27782774","source":"stackoverflow","questionId":27782774,"title":"Custom json response in sequelize.js","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Custom json response in sequelize.js\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI using sequelize for getting json from mysql db. So I have two models `Menu` and `Product` further associations like:\n\n**Menu.js**\n\n```\nclassMethods: {\n associate: function(models) {\n Menu.hasMany(models.Product, {foreignKey: 'menu_id'})\n }\n }\n```\n\n**Product.js**\n\n```\nclassMethods: {\n associate: function(models) {\n Product.belongsTo(models.Menu, {foreignKey: 'menu_id'})\n }\n },\n // IF I ADD BELOW CODE I HAVE ERROR: Possibly unhandled ReferenceError: menu is not defined\n instanceMethods: {\n toJSON: function () {\n var values = this.get();\n if (this.Menu) {\n values.icon = menu.icon;\n }\n\n return values;\n }\n }\n```\n\nand\n\n```\nProduct.findAll({\n where: { /* id: */ },\n include: [\n { model: Menu }\n ]\n }).success(function(match) {\n res.json(match);\n });\n```\n\nThen I get:\n\n```\n{\n \"id\": 3,\n \"menu_id\": 1,\n \"product_title\": \"whatever\",\n \"price\": 22,\n \"createdAt\": \"0000-00-00 00:00:00\",\n \"updatedAt\": \"0000-00-00 00:00:00\",\n \"Menu\": {\n \"id\": 1,\n \"menu_title\": \"whatever\",\n \"icon\": \"someurlforicon\",\n \"createdAt\": \"2014-12-29T00:00:00.000Z\",\n \"updatedAt\": \"2014-12-29T00:00:00.000Z\"\n }\n}\n```\n\n**Is possible to just extend products array with icon from menu model ? LIKE:**\n\n```\n{\n \"id\": 3,\n \"menu_id\": 1,\n \"product_title\": \"whatever\",\n \"price\": 22,\n \"icon\": \"someurlforicon\",\n \"createdAt\": \"0000-00-00 00:00:00\",\n \"updatedAt\": \"0000-00-00 00:00:00\",\n}\n```\n\nThanks for any help!\n\n========================================\n\nTop Answer:\nThe product and The menu is a many-to-one associations. So Product.find() can't return the product array. Because the product corresponding to a menu.\n\n========================================\n\nCode:\n```text\nclassMethods: {\n    associate: function(models) {\n      Menu.hasMany(models.Product, {foreignKey: 'menu_id'})\n    }\n  }\n```\n\n```text\nclassMethods: {\n    associate: function(models) {\n      Product.belongsTo(models.Menu, {foreignKey: 'menu_id'})\n    }\n  },\n  // IF I ADD BELOW CODE I HAVE ERROR: Possibly unhandled ReferenceError: menu is not defined\n  instanceMethods: {\n     toJSON: function () {\n       var values = this.get();\n       if (this.Menu) {\n         values.icon = menu.icon;\n       }\n\n       return values;\n     }\n   }\n```\n\n```text\nProduct.findAll({\n      where: { /* id: */ },\n      include: [\n          { model: Menu }\n      ]\n  }).success(function(match) {\n    res.json(match);\n });\n```\n\n```text\n{\n  \"id\": 3,\n  \"menu_id\": 1,\n  \"product_title\": \"whatever\",\n  \"price\": 22,\n  \"createdAt\": \"0000-00-00 00:00:00\",\n  \"updatedAt\": \"0000-00-00 00:00:00\",\n  \"Menu\": {\n    \"id\": 1,\n    \"menu_title\": \"whatever\",\n    \"icon\": \"someurlforicon\",\n    \"createdAt\": \"2014-12-29T00:00:00.000Z\",\n    \"updatedAt\": \"2014-12-29T00:00:00.000Z\"\n  }\n}\n```\n\n```text\n{\n  \"id\": 3,\n  \"menu_id\": 1,\n  \"product_title\": \"whatever\",\n  \"price\": 22,\n  \"icon\": \"someurlforicon\",\n  \"createdAt\": \"0000-00-00 00:00:00\",\n  \"updatedAt\": \"0000-00-00 00:00:00\",\n}\n```\n\n```text\nMenu\n```\n\n```text\nProduct\n```\n\n```text\ninstanceMethods: {\n  toJSON: function () {\n    var values = this.get();\n\n    if (this.Menu) {\n      values.icon = this.Menu.icon;\n    }\n\n    return values;\n  }\n}\n```\n\n```text\ntoJSON\n```\n\n========================================\n\nComments:\n- Hello Jan Thanks for answer! I trying to add your solution but I have error : `Possibly unhandled ReferenceError: menu is not defined`\n- Sorry, I was a bit too quick - of course you have to actually access `this.Menu` after checking if it is defined\n- Thank you!!! Even next thing Can I remove menu child array somehow? Just have `icon` inside product array ?\n- `delete values.Menu` - This is just a plain javascript object we are working with :) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/&hellip;\n- This is outdated as of V4. You need to do Product.prototype.toJSON = function() {} docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":197,"estimatedTokens":987}}670{"id":"stack-19640201","source":"stackoverflow","questionId":19640201,"title":"Sequelize.js - model association during \"create\" or \"build\" call","tags":["node.js","sequelize.js"],"text":"Title: Sequelize.js - model association during \"create\" or \"build\" call\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a data model where an association/foreign key is required. Is there any way possible to enforce that constraint during model creation without getting into a chicken/egg situation?\n\nLet's say I have a `User` class which requires at least one `device` to be associated with it. Likewise, the `device` must belong to a user. Something like this (untested code, don't mind syntax errors):\n\n```\nUser = db.define(\"user\", {\n name: Sequelize.STRING\n})\n\nDevice = db.define(\"device\", {\n uuid: Sequelize.STRING\n})\n\nUser.hasMany(Device)\n```\n\nI want to ensure that when `create` is first called, that I have all `Device` information as well as all `User` information. Keeping with \"fat models, skinny controllers\" I'd like to put this into my models. Is it possible to do something like this?\n\n```\nuser = User.create(\n name: \"jesse\"\n device:\n uuid: \"84e824cb-bfae-4d95-a76d-51103c556057\"\n)\n```\n\nCan I override the `create` method? Or is there some type of `before` save event hook I can use?\n\n========================================\n\nCode:\n```text\nUser = db.define(\"user\", {\n    name: Sequelize.STRING\n})\n\nDevice = db.define(\"device\", {\n    uuid: Sequelize.STRING\n})\n\nUser.hasMany(Device)\n```\n\n```text\nuser = User.create(\n    name: \"jesse\"\n    device:\n        uuid: \"84e824cb-bfae-4d95-a76d-51103c556057\"\n)\n```\n\n```text\nUser\n```\n\n```text\ndevice\n```\n\n```text\ndevice\n```\n\n```text\ncreate\n```\n\n```text\nDevice\n```\n\n```text\nUser\n```\n\n```text\ncreate\n```\n\n```text\nbefore\n```\n\n```text\nvar User = sequelize.define('User', {\n  username: DataTypes.STRING\n}, {\n  hooks: {\n    beforeCreate: function(user, next) {\n      makeYourCheck(function() {\n        next(\"a string means that an error happened.\")\n      })\n    }\n  }\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":101,"estimatedTokens":461}}671{"id":"stack-44297624","source":"stackoverflow","questionId":44297624,"title":"Error: where: \"raw query\" has been removed, please use where [\"raw query\", [replacements]]","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Error: where: \"raw query\" has been removed, please use where [\"raw query\", [replacements]]\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUnhandled rejection Error: where: \"raw query\" has been removed, please\n use where [\"raw query\", [replacements]]\n\nI encountered this error while rendering the following code. It's a dynamic `where` clause, generated by the value entered by user in the `search` field:\n\n```\nvar queryWhere = {id: {$ne: null}};\nif (req.query) {\n if (req.query.gender && req.query.gender !== '') {\n searchGender = \"gender = '\" + req.query.gender + \"'\";\n } else if (req.query.gender && req.query.gender === '') {\n searchGender = \"gender IS NOT NULL \";\n }\n if (req.query.experience && req.query.experience !== '') {\n searchExperience = \"experience = '\" + req.query.experience + \"'\";\n } else if (req.query.gender && req.query.experience === '') {\n searchExperience = \"experience IS NOT NULL \";\n }\n queryWhere = {\n $and: [\n {$or: [\n searchGender,\n searchExperience]}\n ]\n };\n\n models.Users.findAll({\n offset: numPerPage * 50, \n limit: 50,\n where: queryWhere,\n include: [\n {model: models.Users_Answers}\n ],\n order: [\n [models.Sequelize.col('id'), 'ASC'],\n [models.Users_Answers, 'id', 'ASC']\n ]\n }).then(function(answers) {\n res.render('answers', {answers: answers, search: req.query.searchParam, moment: moment, pagesize: (numPerPage+1), total: totalCount / 50});\n });\n} else {\n res.render('answers');\n}\n```\n\nHow can I resolve this?\n\n========================================\n\nTop Answer:\nRecommended way is using Sequelize's own operators\n\n```\nif (req.query.gender && req.query.gender !== '') {\n searchGender = {'gender': req.query.gender};\n} else if (req.query.gender && req.query.gender === '') {\n searchGender = {'gender': {$not: null}};\n}\nif (req.query.experience && req.query.experience !== '') {\n searchExperience = {'experience': req.query.experience};\n} else if (req.query.gender && req.query.experience === '') {\n searchExperience = {'experience': {$not: null}};\n}\n```\n\n========================================\n\nCode:\n```text\nvar queryWhere = {id: {$ne: null}};\nif (req.query) {\n    if (req.query.gender && req.query.gender !== '') {\n        searchGender = \"gender = '\" + req.query.gender + \"'\";\n    } else if (req.query.gender && req.query.gender === '') {\n        searchGender = \"gender IS NOT NULL \";\n    }\n    if (req.query.experience && req.query.experience !== '') {\n        searchExperience = \"experience = '\" + req.query.experience + \"'\";\n    } else if (req.query.gender && req.query.experience === '') {\n        searchExperience = \"experience IS NOT NULL \";\n    }\n    queryWhere = {\n        $and: [\n            {$or: [\n                searchGender,\n                searchExperience]}\n        ]\n    };\n\n    models.Users.findAll({\n        offset: numPerPage * 50, \n        limit: 50,\n        where: queryWhere,\n        include: [\n            {model: models.Users_Answers}\n        ],\n        order: [\n            [models.Sequelize.col('id'), 'ASC'],\n            [models.Users_Answers, 'id', 'ASC']\n        ]\n    }).then(function(answers) {\n        res.render('answers', {answers: answers, search: req.query.searchParam, moment: moment, pagesize: (numPerPage+1), total: totalCount / 50});\n    });\n} else {\n    res.render('answers');\n}\n```\n\n```text\nwhere\n```\n\n```text\nsearch\n```\n\n```text\nqueryWhere = {\n    $and: [\n        {$or: [\n            [searchGender],\n            [searchExperience]]}\n    ]\n};\n```\n\n```text\nif (req.query.gender && req.query.gender !== '') {\n    searchGender = {'gender': req.query.gender};\n} else if (req.query.gender && req.query.gender === '') {\n    searchGender = {'gender': {$not: null}};\n}\nif (req.query.experience && req.query.experience !== '') {\n    searchExperience = {'experience': req.query.experience};\n} else if (req.query.gender && req.query.experience === '') {\n    searchExperience = {'experience': {$not: null}};\n}\n```\n\n```text\nvar defered = Q.defer();\nconst offset = queryString.offset * queryString.limit;\nconst limit = queryString.limit;\nvar queryWhere = { class_id: { $ne: null }, section_id: { $ne: null } };\nvar searchClass = {};\nvar searchSection = {};\nif (queryString) {\n    if (queryString.class && queryString.class !== \"\") {\n       searchClass = { class_id: { $eq: queryString.class } };\n    } else if (queryString.class && queryString.class === \"\") {\n       searchClass = { class_id: { $ne: null } };\n    }\n\nif (queryString.section && queryString.section !== \"\") {\n      searchSection = { section_id: { $eq: queryString.section } };\n} else if (queryString.section && queryString.section === \"\") {\n      searchSection = { section_id: { $ne: null } };\n}\n}\n\nqueryWhere = {\n    $and: [[searchClass], [searchSection]]\n};\nconst schoolDB = require(\"../../db/models/tenant\")(schema);\nconst Student = schoolDB.model(\"Student\");\nStudent.findAll({\n   attributes: [\n  \"id\",\n  \"first_name\",\n  \"last_name\",\n  \"profile_image_url\",\n  \"roll_number\",\n  \"emergency_contact_number\"\n],\noffset: offset,\nlimit: limit,\nwhere: queryWhere,\norder: [[\"roll_number\", \"ASC\"]]\n})\n.then(result => {\n  defered.resolve(result);\n})\n.catch(err => {\n  defered.reject(err);\n});\n```\n\n========================================\n\nComments:\n- please how to convert this ? [Op.or]: { [Op.like]: '%'+value+'%', [Op.like]: '%'+value.toUpperCase()+'%' }\n- @stackdave did you find any solution on how to convert the symbol based operators?","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":197,"estimatedTokens":1351}}672{"id":"stack-46421054","source":"stackoverflow","questionId":46421054,"title":"Querying JSONB field on a associated model with Sequelize.js and PostgreSQL","tags":["node.js","postgresql","typescript","sequelize.js"],"text":"Title: Querying JSONB field on a associated model with Sequelize.js and PostgreSQL\nTags: node.js, postgresql, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have my two models `Foo` and `Bar`. `Foo` has a field `barId`, therefore has one `Bar` object associated with it.\nI can query all my `Foo` objects and include their assiciated `Bar` object as so (I am using TypeScript with sequelize-typescript): \n\n```\nFoo.findAll({\n include: [{ model: Bar }]\n});\n```\n\n`Bar` object has a JSONB field `jsonb_field` with structure \n\n```\n{ inner_field1: 'some text', inner_field2: 'some more text' }\n```\n\nI can query `Bar` objects and filter by `inner_field1` as such:\n\n```\nBar.findAll({\n where: { 'jsonb_field': { inner_field1: 'text to find' } }\n});\n```\n\nThis produces following SQL query: \n\n```\nSELECT ... FROM \"Bar\" AS \"Bar\" \nWHERE (\"Bar\".\"jsonb_field\"#>>'{inner_field1}') = 'text to find'\n```\n\nSo far so good. Now let's try querying `Foo` objects, include `Bar` objects and filtering by `inner_field1`:\n\n```\nFoo.findAll({\n where: { '$bar.jsonb_field$': { inner_field1: 'text to find' } },\n include: [{ model: Bar }]\n});\n```\n\nNow this throws an exception:\n\n```\nError: Invalid value [object Object]\n at Object.escape ({project_root}\\node_modules\\sequelize\\lib\\sql-string.js:50:11)\n at Object.escape ({project_root}\\node_modules\\sequelize\\lib\\dialects\\abstract\\query-generator.js:917:22)\n at Object.whereItemQuery ({project_root}\\node_modules\\sequelize\\lib\\dialects\\abstract\\query-generator.js:2095:41)\n at _.forOwn ({project_root}\\node_modules\\sequelize\\lib\\dialects\\abstract\\query-generator.js:1937:25)\n ...\n```\n\nFor the record, I am including the Bar object correctly, because I can filter by other non-JSONB properties as such:\n\n```\nFoo.findAll({\n where: { '$bar.number_field$': 5 },\n include: [{ model: Bar }]\n});\n```\n\nAs far as I know, the problem lies in Sequelize not being aware of the type of `jsonb_field` so it throws an error when an object is passed to the where query.\n\nIs there a way around this error, maybe using `sequelize.literal()` or `sequelize.json()`?\n\n========================================\n\nTop Answer:\nSequelize has better support for JSON columns nowadays, I think since v6, see https://sequelize.org/docs/v7/querying/json/\n\nFor example:\n\n```\nFooModel.findAll({\n where: {\n 'jsonb_field.inner_field': 'text to find',\n },\n});\n```\n\nOr, when the inner field can be one of several options:\n\n```\nFooModel.findAll({\n where: {\n 'jsonb_field.inner_field': { [Op.in]: ['text to find', 'other text to find'] },\n },\n});\n```\n\n========================================\n\nCode:\n```text\nFoo.findAll<Foo>({\n  include: [{ model: Bar }]\n});\n```\n\n```text\n{ inner_field1: 'some text', inner_field2: 'some more text' }\n```\n\n```text\nBar.findAll<Bar>({\n  where: { 'jsonb_field': { inner_field1: 'text to find' } }\n});\n```\n\n```text\nSELECT ... FROM \"Bar\" AS \"Bar\" \nWHERE (\"Bar\".\"jsonb_field\"#>>'{inner_field1}') = 'text to find'\n```\n\n```text\nFoo.findAll<Foo>({\n  where: { '$bar.jsonb_field$': { inner_field1: 'text to find' } },\n  include: [{ model: Bar }]\n});\n```\n\n```text\nError: Invalid value [object Object]\n    at Object.escape ({project_root}\\node_modules\\sequelize\\lib\\sql-string.js:50:11)\n    at Object.escape ({project_root}\\node_modules\\sequelize\\lib\\dialects\\abstract\\query-generator.js:917:22)\n    at Object.whereItemQuery ({project_root}\\node_modules\\sequelize\\lib\\dialects\\abstract\\query-generator.js:2095:41)\n    at _.forOwn ({project_root}\\node_modules\\sequelize\\lib\\dialects\\abstract\\query-generator.js:1937:25)\n    ...\n```\n\n```text\nFoo.findAll<Foo>({\n  where: { '$bar.number_field$': 5 },\n  include: [{ model: Bar }]\n});\n```\n\n```text\nFoo\n```\n\n```text\nBar\n```\n\n```text\nFoo\n```\n\n```text\nbarId\n```\n\n```text\nBar\n```\n\n```text\nFoo\n```\n\n```text\nBar\n```\n\n```text\nBar\n```\n\n```text\njsonb_field\n```\n\n```text\nBar\n```\n\n```text\ninner_field1\n```\n\n```text\nFoo\n```\n\n```text\nBar\n```\n\n```text\ninner_field1\n```\n\n```text\njsonb_field\n```\n\n```text\nsequelize.literal()\n```\n\n```text\nsequelize.json()\n```\n\n```text\nFoo.findAll<Foo>({\n  where: { '$bar.jsonb_field$': {\n    $contains: sequelize.cast('{ \"inner_field1\": \"text to find\" }', 'jsonb')\n  },\n  include: [{ model: Bar }]\n});\n```\n\n```text\nFoo.findAll<Foo>({\n  where: { '$bar.jsonb_field$': {\n    $contains: sequelize.literal(`'{ \"inner_field1\": \"text to find\" }'::json`)\n  },\n  include: [{ model: Bar }]\n});\n```\n\n```text\nsequelize.cast\n```\n\n```text\n$contains\n```\n\n```text\nsequelize.literal\n```\n\n```text\n\"\n```\n\n```text\n'\n```\n\n```js\nFooModel.findAll({\n  where: {\n    'jsonb_field.inner_field': 'text to find',\n  },\n});\n```\n\n```js\nFooModel.findAll({\n  where: {\n    'jsonb_field.inner_field': { [Op.in]: ['text to find', 'other text to find'] },\n  },\n});\n```\n\n========================================\n\nComments:\n- It will work if you need to check for equality. But in case of [Op.Like], for example, it isn't helpful.\n- How would you do it if the `jsonb_field` object has more than just `inner_field1`, and you'd like to e.g. search for a `Foo` where `Bar.jsonb_field.inner_field2` is equal to `xyz`?","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":267,"estimatedTokens":1262}}673{"id":"stack-44964176","source":"stackoverflow","questionId":44964176,"title":"Only createdAt column in join table","tags":["node.js","sequelize.js"],"text":"Title: Only createdAt column in join table\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nBy default, sequelize will create createdAt and updatedAt columns in join table for many to many relationships but I only want to use `createdAt` column and set it automatically when row created. \n\ncustom `UserJob` model:\n\n```\nconst UserJob = sequelize.define('UserJob', {\n createdAt: DataTypes.DATE\n}, {\n timestamps: false\n});\nUserJob.beforeCreate((userJob, options) => {\n console.log('before create');\n userJob.createdAt = new Date();\n});\nreturn UserJob;\n```\n\nAssociations:\n\n```\nUser.belongsToMany(models.Job, {through: UserJob, foreignKey: 'user_id'});\nJob.belongsToMany(models.User, {through: UserJob, foreignKey: 'job_id'});\n```\n\nit doesn't set createdAt, what should I do?\n\n========================================\n\nCode:\n```text\nconst UserJob = sequelize.define('UserJob', {\n    createdAt: DataTypes.DATE\n}, {\n    timestamps: false\n});\nUserJob.beforeCreate((userJob, options) => {\n    console.log('before create');\n    userJob.createdAt = new Date();\n});\nreturn UserJob;\n```\n\n```text\nUser.belongsToMany(models.Job, {through: UserJob, foreignKey: 'user_id'});\nJob.belongsToMany(models.User, {through: UserJob, foreignKey: 'job_id'});\n```\n\n```text\ncreatedAt\n```\n\n```text\nUserJob\n```\n\n```text\nconst Foo = sequelize.define('foo', { /* bla */ \n  { // don't forget to enable timestamps! \n  timestamps: true,\n  // I don't want createdAt \n  createdAt: false,\n  // I want updatedAt to actually be called updateTimestamp\n  updatedAt: 'updateTimestamp'\n})\n```\n\n```text\nupdatedAt\n```\n\n========================================\n\nComments:\n- is it not getting date ? or what is inserting in 'userJob.createdAt'\n- before create not being called and createdAt is null in the table!","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":80,"estimatedTokens":444}}674{"id":"stack-71116347","source":"stackoverflow","questionId":71116347,"title":"excluding joined table data from final results","tags":["sequelize.js"],"text":"Title: excluding joined table data from final results\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet's suppose I have the following code:\n\n```\nconst { Entrada, Entidade } = require('./models');\nconst Sequelize = require('sequelize');\nconst Op = Sequelize.Op;\n\nlet nome = 'dd';\n\nasync function main() {\n\n Entrada.findOne({\n\n where: {\n ativa: true\n },\n\n include: [{\n model: Entidade,\n where: {\n nome: {\n [Op.like]: `%${nome.trim()}%`\n },\n ativa: true\n }\n }]\n\n }).then(entrada => {\n\n console.error(\n JSON.stringify(\n entrada, null, 2));\n\n });\n}\n\nmain();\n```\n\nWitch runs fine and will return me:\n\n```\n{\n \"id\": 1,\n \"numeroDaNota\": \"101011011\",\n \"dataDaNota\": \"2020-10-01\",\n \"dataDeEntrada\": \"2020-10-02\",\n \"valor\": 150,\n \"ativa\": true,\n \"lojaId\": 1,\n \"entidadeId\": 1,\n \"entidade\": {\n \"id\": 1,\n \"nome\": \"dddd\",\n \"fantasia\": null,\n \"documento\": \"dddd\",\n \"isentoDeInscricaoEstadual\": 1,\n \"inscricaoEstadualOuRg\": null,\n \"tipoDePessoa\": \"FISICA\",\n \"situacaoTributaria\": \"SIMPLES_NACIONAL\",\n \"email\": \"dddd\",\n \"emailNFE\": null,\n \"ativa\": true,\n \"foneFixo\": null,\n \"celular\": \"8888\",\n \"logradouro\": \"ooo\",\n \"cep\": \"111\",\n \"numero\": 111,\n \"complemento\": null,\n \"bairro\": \"111\",\n \"cliente\": true,\n \"fornecedor\": true,\n \"transportadora\": false,\n \"limiteDeCredito\": null,\n \"descontoEmVenda\": null,\n \"observacao\": null,\n \"suframa\": null,\n \"cidadeId\": 23,\n \"empresaId\": 1,\n \"paisId\": 206,\n \"atividadeFimId\": null,\n \"regiaoId\": null,\n \"figuraFiscalId\": null\n }\n}\n```\n\nHowever, I am not interested in property \"entidade\" from the model \"Entrada\" in my output. I've only joined it (by means of 'include: []') because I needed to filter \"Entrada\" by a property of \"Entidade\" (that property being \"nome\"). I'm aware I can use **toJSON() {}** when defining a model in order not to \"jsonning\" properties I don't want to, like passwords for instance.\n\nHowever isn't there a neat way to exclude joined models from the final output by simply using a sequelize parameter while querying? I took a look at:\n\n```\nMyModel.findAll({\n attributes: {exclude: ['some_field']}\n});\n```\n\nAnd tried to exclude \"entidade\" from the final JSON, but it seems it will not exclude joined models/tables from the end result. I find this lacking in sequelize. Coming from 17 years of experience with Hibernate, this seems frustrating.\n\nThere must be a way to do that, and I must be missing it.\n\nPlease, help me if you can. Thanks.\n\n========================================\n\nTop Answer:\nTry passing\n\n```\nattributes:[]\n```\n\nin your code such as\n\n```\ninclude: [{\n attributes: [],\n model: Entidade,\n where: {\n nome: {\n [Op.like]: `%${nome.trim()}%`\n },\n ativa: true\n }\n }]\n```\n\n========================================\n\nCode:\n```text\nconst { Entrada, Entidade } = require('./models');\nconst Sequelize = require('sequelize');\nconst Op = Sequelize.Op;\n\nlet nome = 'dd';\n\nasync function main() {\n\n    Entrada.findOne({\n\n        where: {\n            ativa: true\n        },\n\n        include: [{\n            model: Entidade,\n            where: {\n                nome: {\n                    [Op.like]: `%${nome.trim()}%`\n                },\n                ativa: true\n            }\n        }]\n\n    }).then(entrada => {\n\n        console.error(\n            JSON.stringify(\n                entrada, null, 2));\n\n    });\n}\n\nmain();\n```\n\n```text\n{\n  \"id\": 1,\n  \"numeroDaNota\": \"101011011\",\n  \"dataDaNota\": \"2020-10-01\",\n  \"dataDeEntrada\": \"2020-10-02\",\n  \"valor\": 150,\n  \"ativa\": true,\n  \"lojaId\": 1,\n  \"entidadeId\": 1,\n  \"entidade\": {\n    \"id\": 1,\n    \"nome\": \"dddd\",\n    \"fantasia\": null,\n    \"documento\": \"dddd\",\n    \"isentoDeInscricaoEstadual\": 1,\n    \"inscricaoEstadualOuRg\": null,\n    \"tipoDePessoa\": \"FISICA\",\n    \"situacaoTributaria\": \"SIMPLES_NACIONAL\",\n    \"email\": \"dddd\",\n    \"emailNFE\": null,\n    \"ativa\": true,\n    \"foneFixo\": null,\n    \"celular\": \"8888\",\n    \"logradouro\": \"ooo\",\n    \"cep\": \"111\",\n    \"numero\": 111,\n    \"complemento\": null,\n    \"bairro\": \"111\",\n    \"cliente\": true,\n    \"fornecedor\": true,\n    \"transportadora\": false,\n    \"limiteDeCredito\": null,\n    \"descontoEmVenda\": null,\n    \"observacao\": null,\n    \"suframa\": null,\n    \"cidadeId\": 23,\n    \"empresaId\": 1,\n    \"paisId\": 206,\n    \"atividadeFimId\": null,\n    \"regiaoId\": null,\n    \"figuraFiscalId\": null\n  }\n}\n```\n\n```text\nMyModel.findAll({\n  attributes: {exclude: ['some_field']}\n});\n```\n\n```js\ninclude: [{\n            model: Entidade,\n            attributes: [],\n            where: {\n                nome: {\n                    [Op.like]: `%${nome.trim()}%`\n                },\n                ativa: true\n            }\n        }]\n```\n\n```text\nattributes\n```\n\n```text\nattributes:[]\n```\n\n```sh\ninclude: [{\n            attributes: [],\n            model: Entidade,\n            where: {\n                nome: {\n                    [Op.like]: `%${nome.trim()}%`\n                },\n                ativa: true\n            }\n        }]\n```\n\n========================================\n\nComments:\n- It worked! Thanks.\n- It worked! Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":263,"estimatedTokens":1240}}675{"id":"stack-28449896","source":"stackoverflow","questionId":28449896,"title":"How to add context to a Sequelize hook?","tags":["sequelize.js"],"text":"Title: How to add context to a Sequelize hook?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to use a hook to perform access control on a row so that users can only access rows they own. The hook would add an additional where clause to ensure that the user is the owner of the row (ex: WHERE ownerId=user.id).\n\nThe problem is, how do I pass the user id to Sequelize so that the hook has it when the hook fires? I've looked through the documentation and it's not obvious to me if this is possible.\n\nThanks\n\nreference: http://sequelize.readthedocs.org/en/latest/docs/hooks/\n\n========================================\n\nCode:\n```text\noptions = {\n  attributes: ['id', 'column1', 'column2'],\n  where: { someColumn: 'aValue' }\n}\n\noptions.context = 'foo';\n```\n\n```text\nModel.findAll()\n```\n\n========================================\n\nComments:\n- `context` doesn't appear to be supported in the Sequelize docs: docs.sequelizejs.com/class/lib/&hellip; It's not in the Sequelize typescript definitions either, meaning that using this option won't allow your code to compile: github.com/types/sequelize/blob/master/lib/model.d.ts#L511-L&zwnj;&#8203;522 Are there any other suggestions on how to make this work?","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":33,"estimatedTokens":303}}676{"id":"stack-45859745","source":"stackoverflow","questionId":45859745,"title":"Where should I write queries in model or controller (sequelize)?","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Where should I write queries in model or controller (sequelize)?\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI try to figure out where should I write queries in node js application which uses sequalize as an ORM.\n\nFor example, I have a model address, and I write data to like this:\n\n```\nlet adr = await Address.create({street, number, city, state, country})\n```\n\nShould I write this code in the controller where I get the data or in the model and then just pass (for example full object address) to the method of the model? What is the best practice?\n\nI assume that is it better to write it in models because I can use the same code in many controllers. But maybe there are some other constraints.\n\n========================================\n\nCode:\n```text\nlet adr = await Address.create({street, number, city, state, country})\n```\n\n```text\n// repository.js\n\nmodule.exports = (db) => {\n   const findUserById = (id) => {\n        // db query your user by id\n   }\n\n   const createUser = (data) {\n       // db insert a new user\n   }\n\n   // ... other repository functions to deal with the database\n\n   return Object.create({\n     findUserById,\n     createUser,\n     // ...\n   })\n}\n```\n\n```text\nconst repository = require('./repository.js')(dbConnection);\n\napp.get('/users/:id', (req, res) => {\n   repository.findUserById(req.params.id);\n   // ...\n})\n```\n\n```text\nvar db = require('../models');\n\nvar UsersRepository = {\n    findByEmail: function(email) {\n        return db.User.findAll({\n            where: {\n                email: email\n            }\n        })\n    }\n}\n\nmodule.exports = UsersRepository;\n```\n\n```text\nrepository\n```\n\n```text\nmysql\n```\n\n```text\nmongodb\n```\n\n```text\nsequelize\n```\n\n========================================\n\nComments:\n- Is it a good practice to have one repository per model or one per whole application?\n- each model with his repository\n- In this way you will not have 2000 lines files, and is more structured\n- That sound reasonable. In this case, what should I put into the model except for data schema and hooks?\n- Model related function, and business logic, lets abstract in this way, if it is related with database put in repository, if it is related with the object instance put in the model.\n- Is there exist standard folder name for repositories? For example, I keep models in \"models\" folder and controllers in \"controllers\" folder.\n- I personally use `&#47;repository&#47;user-repository.js`\n- I'm I understand right that in controllers you use repositories and in repositories you use models?\n- But the question was where to define a custom query?\n- @RameshPareek Custome queries you define in the repositories\n- @AlexandruOlaru I got type error which will you please take a look? stackoverflow.com/questions/65181926/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":101,"estimatedTokens":701}}677{"id":"stack-33380641","source":"stackoverflow","questionId":33380641,"title":"Sequelize find. how to include constant value attributes in a find query","tags":["node.js","sequelize.js"],"text":"Title: Sequelize find. how to include constant value attributes in a find query\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n¿How can I retrieve all attributes from a table, plus a new column/attribute with a constant value for every row?\nAs I saw on the docs, it shuld be something similar to this:\n\n```\nmy_model.findAll({\n attributes:{\n include:[['constant_value','new_attribute_name']]\n }\n}).then(...);\n```\n\nAny clue?\n\nThank you!\n\n========================================\n\nTop Answer:\nYou can use literal function in sequelize.\n\n```\nmy_model.findAll({\n attributes: [['id', 'key'], 'title', 'description', [sequelize.literal(`\"constant_value\"`), 'new_attribute_name']]\n }\n}).then(...);\n```\n\nI just see this question was posted a long time ago but I hope this will be helpful for the others. Thanks\n\n========================================\n\nCode:\n```text\nmy_model.findAll({\n    attributes:{\n        include:[['constant_value','new_attribute_name']]\n    }\n}).then(...);\n```\n\n```text\nmy_model.findAll({\n    attributes: [['id', 'key'], 'title', 'description', [sequelize.literal(`\"constant_value\"`), 'new_attribute_name']]\n    }\n}).then(...);\n```\n\n========================================\n\nComments:\n- How should I add this new attribute inside the Hook? I'm doing somethig like *my_model_instance.dataValues.new_attr = attr_value*. Is this propertly done?\n- The model gets passed in as an argument to the hook. So if we use the top example from the hook documentation where it has a model called user. You would simply type user.yourConstant = constantValue or user.dataValues.yourConstant = constantvalue. You'll probably have to experiment with it a bit.\n- Actually the second example is the one that works for me. Thank you!\n- Small error - Should be a close bracket after the constant and before the comma: Sequelize.literal(`\"constant_value\"`)","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":59,"estimatedTokens":467}}678{"id":"stack-68132680","source":"stackoverflow","questionId":68132680,"title":"how to return values from joined tables in sequelize at the same level as master table","tags":["javascript","node.js","sequelize.js"],"text":"Title: how to return values from joined tables in sequelize at the same level as master table\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to find a way how to put all joined tables at the same level as my master table... so far it only results in the nested values in my final object ..\n\nHere is what I have\n\n```\nOrders.findAll({\n include: [\n {model: Products, attributes: ['product_name']}\n ],\n attributes: ['id_order', 'dtime_order', 'amount']\n})\n```\n\nwhat I am getting is:\n\n```\n[\n {\n id_order: 1, \n dtime_order: '2021-05-24T22:00:00.000Z',\n amount: 20,\n products: {\n product_name: 'Picture'\n }\n }\n]\n```\n\nbut what I wanna get is:\n\n```\n[\n {\n id_order: 1, \n dtime_order: '2021-05-24T22:00:00.000Z',\n amount: 20,\n product_name: 'Picture'\n }\n]\n```\n\nI tried this How to return result from include model in same level of main model in Sequelize? but unfortunately when I did:\n\n```\nOrders.findAll({\n include: [\n {model: Products, attributes: []}\n ],\n attributes: ['id_order', 'dtime_order', 'amount', ['products.product_name', 'product_name']]\n})\n```\n\ndoesn't work for me saying\n\n```\ncolumn \"products.product_name\" does not exist\n```\n\nThere might be a hacky way to modify the object before sending it back in the response .. but I would rather do it within Sequelize ..\n\nany idea is very welcome... thank you guys!\n\nEDIT: adding the generated SQL\n\n```\nExecuting (default): SELECT \"orders\".\"id_order\", \"orders\".\"dtime_order\", \"orders\".\"amount\", \"products.product_name\", FROM \"orders\" AS \"orders\" LEFT OUTER JOIN \"products\" AS \"products\" ON \"orders\".\"id_order\" = \"products\".\"ir_order\";\nerror: Get dashboard data error: column \"products.product_name\" does not exist\n```\n\n**SOLUTION:**\n\nI had to use an alias in my association\n\n`Orders.hasOne(Products, {as: 'products', ....})`\n\nAnd then use that EXACTLY SAME alias in my include and referencing\n\n`include: [{model: Products, attributes: [], as: 'products'}]`\n\nAnd\n\n`attributes: [ ... , [Sequelize.col('products.product_name', 'product_name')]`\n\nwithout the `raw: true` works like a charm :) Thank you @Emma !!!\n\n========================================\n\nCode:\n```text\nOrders.findAll({\n   include: [\n      {model: Products, attributes: ['product_name']}\n   ],\n   attributes: ['id_order', 'dtime_order', 'amount']\n})\n```\n\n```text\n[\n {\n   id_order: 1, \n   dtime_order: '2021-05-24T22:00:00.000Z',\n   amount: 20,\n   products: {\n      product_name: 'Picture'\n   }\n }\n]\n```\n\n```text\n[\n {\n   id_order: 1, \n   dtime_order: '2021-05-24T22:00:00.000Z',\n   amount: 20,\n   product_name: 'Picture'\n }\n]\n```\n\n```text\nOrders.findAll({\n   include: [\n      {model: Products, attributes: []}\n   ],\n   attributes: ['id_order', 'dtime_order', 'amount', ['products.product_name', 'product_name']]\n})\n```\n\n```text\ncolumn \"products.product_name\" does not exist\n```\n\n```text\nExecuting (default): SELECT \"orders\".\"id_order\", \"orders\".\"dtime_order\", \"orders\".\"amount\", \"products.product_name\", FROM \"orders\" AS \"orders\" LEFT OUTER JOIN \"products\" AS \"products\" ON \"orders\".\"id_order\" = \"products\".\"ir_order\";\nerror:   Get dashboard data error: column \"products.product_name\" does not exist\n```\n\n```text\nOrders.hasOne(Products, {as: 'products', ....})\n```\n\n```text\ninclude: [{model: Products, attributes: [], as: 'products'}]\n```\n\n```text\nattributes: [ ... , [Sequelize.col('products.product_name', 'product_name')]\n```\n\n```text\nraw: true\n```\n\n```text\nOrders.findAll({\n  include: [\n    {model: Products, attributes: []}\n  ],\n  attributes: ['id_order', 'dtime_order', 'amount', [Sequelize.col('products.product_name'), 'product_name']],\n  raw: true\n})\n```\n\n```text\nSequelize.col\n```\n\n========================================\n\nComments:\n- You are missing `raw: true`. Also perhaps, `products.product_name` (lower case p). You can find what table name exactly in generated SQL.\n- I tried `raw: true` but it doesn't work.. .and yes, the lowercase doesn't work either.. on top of that, what's the point of Sequelize if I have to \"hardcode\" the table name directly.. where is the abstraction then?\n- What is the generated SQL? Also *most* of the cases, you use model instance and don't have to hardcode, this is one of the special case.\n- Could you also try `[Sequelize.col('products.product_name'), 'product_name']`? In some version, I needed to have `Sequelize.col`.\n- I added the SQL query I am getting .... there is a weird part about the quotes - it does not quote the table name and column separately but as one string .. that might be the problem\n- oh yes cool... I thought I tried that `Sequelize.col` before but obviously I didn't :) it works great ... thx a lot .. pls use it as an answer so I can tag it properly !! thx a lot\n- Nice! Glad it worked.\n- oh I see why it didn't worked before.. I had to use an alias to the table ...\n- I had to use an alias (esp to avoid directly addressing the table name) and `raw: true` is not needed in my case .. but tagging this as a good answer because of `Sequelize.col()`","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":186,"estimatedTokens":1243}}679{"id":"stack-62009286","source":"stackoverflow","questionId":62009286,"title":"SELECT WITH CAST OR CONVERT IN iLike USING SEQUELIZE","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: SELECT WITH CAST OR CONVERT IN iLike USING SEQUELIZE\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to do a full-text search with Sequelize, but when i have to use an iLike with a INTEGER or a DATE column i can't send a String in the where clause, how can i do the cast off an column?\n\nExample with a Postgresql query what I want to do:\n\n```\nSELECT \"Proposta\".id, \"Proposta\".id_segurado, \"Proposta\".data_implantacao, \"Proposta\".data_assinatura, \"Proposta\".status, \"Proposta\".numero_proposta,\n \"Segurado\".documento, \"Segurado\".nome,\n p1.id, p1.nome, p1.codigo, p1.documento, p2.id,\n p2.nome, p2.codigo, p2.documento\nFROM \"Proposta\"\nLEFT JOIN \"Segurado\" ON \"Proposta\".id_segurado = \"Segurado\".id\nLEFT JOIN \"Produtor\" p1 ON p1.id = \"Proposta\".id_produtor1\nLEFT JOIN \"Produtor\" p2 ON p2.id = \"Proposta\".id_produtor2\nWHERE ((p1.codigo = '8002866' OR p2.codigo = '8002866') \nAND (\"Proposta\".status ILIKE '%108297494%' OR \"Proposta\".numero_proposta ILIKE '%108297494%'\n OR CAST(\"Proposta\".data_implantacao AS VARCHAR) ILIKE '%108297494%'\n OR CAST(\"Proposta\".data_assinatura AS VARCHAR) ILIKE '%108297494%'))\n```\n\nAnd this what i tried to do with Sequelize:\n\n```\nconst propostas = await Proposta.findAll({\n where: {\n [Op.or]: [\n { \"$produtor1.codigo$\": documento_produtor },\n { \"$produtor2.codigo$\": documento_produtor },\n ],\n [Op.or]: [\n {\n status: {\n [Op.iLike]: `%${search}%`,\n },\n },\n {\n numero_proposta: {\n [Op.iLike]: `%${search}%`,\n },\n },\n db.Sequelize.where(\n db.Sequelize.cast(\n db.Sequelize.col(\"$produtor1.codigo$\", \"VARCHAR\"),\n { [Op.iLike]: `%${search}%` }\n )\n ),\n db.Sequelize.where(\n db.Sequelize.cast(\n db.Sequelize.col(\"$produtor2.codigo$\", \"VARCHAR\"),\n { [Op.iLike]: `%${search}%` }\n )\n ),\n ],\n },\n include: [\n {\n model: Segurado,\n as: \"segurado\",\n },\n {\n model: Produtor,\n as: \"produtor1\",\n },\n {\n model: Produtor,\n as: \"produtor2\",\n },\n ]\n })\n```\n\n========================================\n\nCode:\n```text\nSELECT  \"Proposta\".id,  \"Proposta\".id_segurado, \"Proposta\".data_implantacao, \"Proposta\".data_assinatura, \"Proposta\".status, \"Proposta\".numero_proposta,\n            \"Segurado\".documento, \"Segurado\".nome,\n            p1.id, p1.nome, p1.codigo, p1.documento, p2.id,\n            p2.nome, p2.codigo, p2.documento\nFROM \"Proposta\"\nLEFT JOIN \"Segurado\" ON \"Proposta\".id_segurado = \"Segurado\".id\nLEFT JOIN \"Produtor\" p1 ON p1.id = \"Proposta\".id_produtor1\nLEFT JOIN \"Produtor\" p2 ON p2.id = \"Proposta\".id_produtor2\nWHERE ((p1.codigo = '8002866' OR p2.codigo = '8002866') \nAND (\"Proposta\".status ILIKE '%108297494%' OR \"Proposta\".numero_proposta ILIKE '%108297494%'\n     OR CAST(\"Proposta\".data_implantacao AS VARCHAR) ILIKE '%108297494%'\n     OR CAST(\"Proposta\".data_assinatura AS VARCHAR) ILIKE '%108297494%'))\n```\n\n```text\nconst propostas = await Proposta.findAll({\n            where: {\n                [Op.or]: [\n                    { \"$produtor1.codigo$\": documento_produtor },\n                    { \"$produtor2.codigo$\": documento_produtor },\n                ],\n                [Op.or]: [\n                    {\n                        status: {\n                            [Op.iLike]: `%${search}%`,\n                        },\n                    },\n                    {\n                        numero_proposta: {\n                            [Op.iLike]: `%${search}%`,\n                        },\n                    },\n                    db.Sequelize.where(\n                        db.Sequelize.cast(\n                            db.Sequelize.col(\"$produtor1.codigo$\", \"VARCHAR\"),\n                            { [Op.iLike]: `%${search}%` }\n                        )\n                    ),\n                    db.Sequelize.where(\n                        db.Sequelize.cast(\n                            db.Sequelize.col(\"$produtor2.codigo$\", \"VARCHAR\"),\n                            { [Op.iLike]: `%${search}%` }\n                        )\n                    ),\n                ],\n            },\n            include: [\n                {\n                    model: Segurado,\n                    as: \"segurado\",\n                },\n                {\n                    model: Produtor,\n                    as: \"produtor1\",\n                },\n                {\n                    model: Produtor,\n                    as: \"produtor2\",\n                },\n            ]\n        })\n```\n\n```text\nconst {sequelize} = require(\"{path}/models/index.js\")\n```\n\n```text\nsequelize.where(\n    sequelize.cast(sequelize.col(\"produtor1.codigo\"),\"varchar\"),\n    { [Op.iLike]: `%${search}%` }\n)\n```\n\n========================================\n\nComments:\n- Please don't shout - use normal casing for the title\n- But for import the sequelize you need to use require: const { sequelize } = require(\"../models/index\");","metadata":{"transformedAt":"2026-08-18T18:33:34.393Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":158,"estimatedTokens":1188}}680{"id":"stack-64240880","source":"stackoverflow","questionId":64240880,"title":"How to store html values through sequelize ORM in nodeJS application?","tags":["node.js","express","orm","sequelize.js"],"text":"Title: How to store html values through sequelize ORM in nodeJS application?\nTags: node.js, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am working on one NodeJs application with NodeJS, Sequelize ORM and mysql2 database.\n\nI am creating a model xyz with one field called \"text\" which should hold HTML values from frontend as its getting values from a text editor in frontend with bold or italic functionalities among many.\n\nWhat datatype should I assign to this field \"text\" in Sequelize as I am lost and I searched but could not find.\n\nI think we cannot store that in String.\n\nCany anyone suggest ?\n\n========================================\n\nCode:\n```text\nLONGTEXT\n```\n\n```text\nMEDIUMTEXT\n```\n\n```text\nTEXT\n```\n\n```text\nTINYTEXT\n```\n\n```text\nTEXT\n```\n\n```text\nMEDIUMTEXT\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":41,"estimatedTokens":199}}681{"id":"stack-51384405","source":"stackoverflow","questionId":51384405,"title":"Sequelize is chopping of nested key length","tags":["postgresql","express","sequelize.js"],"text":"Title: Sequelize is chopping of nested key length\nTags: postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a model named `ManufacturerGuideline` which is nested at the 4th level. When I try to fetch the record, its chopping of `ManufacturerGuideline` keys length to 5 characters. Although the Key value stored in postgreSQL table has full length.\n\n**Routes:**\n\n```\nrouter.get('/:manufacturer_id', function(req, res) {\n var manufacturer_id = req.params.manufacturer_id;\n models.Manufacturer.findAll({\n where: {\n id: manufacturer_id\n },\n order: [[models.ManufacturerTab, 'sequence', 'ASC']],\n include: [{\n model: models.ManufacturerTab, \n include: [{\n model: models.ManufacturerField, \n include: [models.ManufacturerGuideline]\n }]\n }\n ]\n }).\n then(function(manufacturers) { \n res.status(200).json(manufacturers); \n }, function(error) { \n res.status(500).send(error); \n }); \n});\n```\n\nSo if the column name is `Manufacturer` it displays as `Manuf`. This issue is only appearing with `ManufacturerGuideline` table and not with the parent associated table.\n\n========================================\n\nCode:\n```text\nrouter.get('/:manufacturer_id', function(req, res) {\n  var manufacturer_id = req.params.manufacturer_id;\n  models.Manufacturer.findAll({\n    where: {\n      id: manufacturer_id\n    },\n    order: [[models.ManufacturerTab, 'sequence', 'ASC']],\n    include: [{\n                model: models.ManufacturerTab, \n                include: [{\n                  model: models.ManufacturerField, \n                  include: [models.ManufacturerGuideline]\n              }]\n            }\n        ]\n  }).\n  then(function(manufacturers) {  \n      res.status(200).json(manufacturers);  \n  }, function(error) {  \n     res.status(500).send(error);  \n  });  \n});\n```\n\n```text\nManufacturerGuideline\n```\n\n```text\nManufacturerGuideline\n```\n\n```text\nManufacturer\n```\n\n```text\nManuf\n```\n\n```text\nManufacturerGuideline\n```\n\n```text\ninclude: [{\n  separate: true,\n  model: models.ManufacturerGuideline\n}]\n```\n\n```text\nseparate: true\n```\n\n========================================\n\nComments:\n- Only supported for hasMany associations sequelize.org/master/class/lib/&hellip;\n- Any reason why this is necessary to add? What is the necessity to Sequelize clipping the key name for nested joins like this one?","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":100,"estimatedTokens":577}}682{"id":"stack-47455126","source":"stackoverflow","questionId":47455126,"title":"Sequelize findOrCreate returns SequelizeUniqueContraintError on a model with an additional unique keys","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize findOrCreate returns SequelizeUniqueContraintError on a model with an additional unique keys\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize with NodeJS and MySql. (latest versions)\n\nI have a user model with -\n\n- 'id' and unique and primary key. 'id' is set to auto increment.\n\n- some user details such as firstName, lastName, email etc.\n\n- Two additional unique keys (marked as unique in the sequelize model and in the database) - 'username' and 'email'\n\nI am using the 'findOrCreate' method to create or lookup. My code creates a record if it does not exist but throws a UniqueConstraintError (ER_DUP_ENTRY) --> SequelizeUniqueContraintError on the \"username\" field when I try to find this record. Basically, the findOrCreate tries to create a record for the second time instead of finding it.\n\n I was able to fix this issue by manually doing a find and if not found\n then create. But I need the flag returned by the 'findOrCreate' method\n which helps determine whether a record was created or found.\n\nCan someone please help?\n\n========================================\n\nCode:\n```text\nEmployee.findOrCreate({where: {employeeId: 'ABCD1234'}, defaults: {role: 'Analyst'}});\n```\n\n========================================\n\nComments:\n- I have already referred to the following links. (My question is not a duplicate) stackoverflow.com/questions/35248117/&hellip;\n- This is a similar issue - github.com/sequelize/sequelize/issues/5134","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":35,"estimatedTokens":372}}683{"id":"stack-57720255","source":"stackoverflow","questionId":57720255,"title":"How to get datavalues in sequelize with `findAll()` and without `raw:true`?","tags":["node.js","sequelize.js"],"text":"Title: How to get datavalues in sequelize with `findAll()` and without `raw:true`?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni want to get datavalues when iam using findAll() in sequelize without using raw:true\n\n```\nActivities.findAll({\n include: [\n { \n all: true \n } \n ], \n })\n .then(activities => { \n });\n```\n\n========================================\n\nTop Answer:\nThis is how i solve without using `row: true`\n\n```\nlet rows = await Activities.findAll();\nrows = JSON.stringify(rows);\nrows = JSON.parse(rows);\n```\n\nrows only get data\n\n========================================\n\nCode:\n```text\nActivities.findAll({\n         include: [\n         {       \n           all: true         \n          }   \n         ],  \n       })\n        .then(activities => {   \n        });\n```\n\n```text\nActivities.findAll({\n    include: [{\n        all: true\n    }],\n}).then(activities => {\n    return activities.map( activity => el.get({ plain: true }) );\n});\n```\n\n```text\nActivities.findAll({\n    raw : true ,\n    nest: true , // <--- The issue of raw true, will be solved by this\n    include: [{\n        all: true\n    }],\n}).then(activities => {\n    console.log(activities);\n});\n```\n\n```text\nraw:true\n```\n\n```text\nraw : true\n```\n\n```text\n.\n```\n\n```text\nnest : true\n```\n\n```text\nlet rows = await Activities.findAll();\nrows = JSON.stringify(rows);\nrows = JSON.parse(rows);\n```\n\n```text\nrow: true\n```\n\n========================================\n\nComments:\n- If I remember correctly. findAll returns an array that each element has his own dataValues...","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":99,"estimatedTokens":386}}684{"id":"stack-50834623","source":"stackoverflow","questionId":50834623,"title":"Sequelizejs: error: duplicate key value violates unique constraint \"message_pkey\"","tags":["sequelize.js"],"text":"Title: Sequelizejs: error: duplicate key value violates unique constraint \"message_pkey\"\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a PostrgresDB i am connected to with my Nodejs app using sequelize, i am trying to create and save a model, but it is throwing `error: duplicate key value violates unique constraint \"message_pkey\"`\n\nThe problem is that there are entities already in the database, and it is trying to start saving incrementally from ID 1 which is already in the database, how can i make it save starting from the last ID saved in the database ? this is my Model\n\n```\nvar Sequelize = require('sequelize');\n\nvar db = require('../database/postgres');\n\nvar Message =db.define('message', {\n\n id: {\n type: Sequelize.INTEGER,\n field: 'id',\n autoIncrement: true,\n allowNull: true,\n primaryKey: true\n },\n\n time: {\n type: Sequelize.DATE,\n field: 'time'\n },\n\n isread: {\n type: Sequelize.BOOLEAN,\n field: 'isread'\n },\n\n message: {\n type: Sequelize.STRING,\n field: 'message'\n },\n\n messagestatus: {\n type: Sequelize.ENUM,\n values: ['UNDELIVERED', 'DELIVERED', 'UNREAD', 'READ'],\n field: 'messagestatus'\n },\n\n receiver: {\n type: Sequelize.INTEGER,\n field: 'receiver'\n },\n\n sender: {\n type: Sequelize.INTEGER,\n\n field: 'sender'\n },\n\n}, {\n tableName: 'message',\n\n timestamps: false\n});\n\nmodule.exports = Message;\n```\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\n\nvar db = require('../database/postgres');\n\n\nvar Message =db.define('message', {\n\n    id: {\n        type: Sequelize.INTEGER,\n        field: 'id',\n        autoIncrement: true,\n        allowNull: true,\n        primaryKey: true\n    },\n\n    time: {\n        type: Sequelize.DATE,\n        field: 'time'\n    },\n\n    isread: {\n        type: Sequelize.BOOLEAN,\n        field: 'isread'\n    },\n\n    message: {\n        type: Sequelize.STRING,\n        field: 'message'\n    },\n\n    messagestatus: {\n        type: Sequelize.ENUM,\n        values: ['UNDELIVERED', 'DELIVERED', 'UNREAD', 'READ'],\n        field: 'messagestatus'\n    },\n\n    receiver: {\n        type: Sequelize.INTEGER,\n        field: 'receiver'\n    },\n\n    sender: {\n        type: Sequelize.INTEGER,\n\n        field: 'sender'\n    },\n\n}, {\n    tableName: 'message',\n\n    timestamps: false\n});\n\n\nmodule.exports = Message;\n```\n\n```text\nerror: duplicate key value violates unique constraint \"message_pkey\"\n```\n\n```text\nSELECT setval('TABLENAME_id_seq', (SELECT MAX(id) FROM \"TABLENAME\"));\n// Change TABLENAME with your table\n```\n\n========================================\n\nComments:\n- @Thanus , Glad to here that :) , Happy coding BTW\n- @Thanus , Thanks :)","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":140,"estimatedTokens":656}}685{"id":"stack-56149251","source":"stackoverflow","questionId":56149251,"title":"Node.js Sequelize virtual column pulling value from other model","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: Node.js Sequelize virtual column pulling value from other model\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm working with Sequelize 5.7, trying to utilize virtual datatype,\n\nto pull related information into a model.\n\nGiven simplified `company` and `user` models, how do I get `company.name`\n\ninto `user.companyname` ?\n\n***company***\n\n```\nlet Schema = sequelize.define(\n \"company\",\n {\n id: {\n type: DataTypes.INTEGER.UNSIGNED,\n autoIncrement: true,\n primaryKey: true\n },\n name: {\n type: DataTypes.STRING(45)\n }\n }\n );\n```\n\n***user***\n\n```\nlet Schema = sequelize.define(\n \"user\",\n {\n id: {\n type: DataTypes.INTEGER.UNSIGNED,\n autoIncrement: true,\n primaryKey: true\n },\n login: {\n type: DataTypes.STRING(45),\n unique: true\n },\n company: {\n type: DataTypes.INTEGER.UNSIGNED,\n references: {\n model: sequelize.model('company'),\n key: 'id'\n }\n },\n\n /* This companyname contruct is pure fantasy, and the target of my question */\n\n companyname: {\n type: new DataTypes.VIRTUAL(DataTypes.STRING,['company']),\n references: {\n model: 'company',\n key: 'name'\n }\n }\n }\n );\n```\n\n========================================\n\nTop Answer:\nI solved the problem by using `type: DataTypes.VIRTUAL` in model\n\n```\nconst { Model, DataTypes } = require('sequelize');\n\nclass User extends Model {\n static init(sequelize) {\n super.init({\n id: {\n type: DataTypes.INTEGER.UNSIGNED,\n autoIncrement: true,\n primaryKey: true\n },\n login: {\n type: DataTypes.STRING(45),\n unique: true\n },\n company_id: {\n type: DataTypes.INTEGER.UNSIGNED,\n },\n companyname:{\n type: DataTypes.VIRTUAL,\n get() {\n return this.Company?.get().name;\n },\n set(/*value*/) {\n throw new Error('Do not try to set the `companyname` value!');\n }\n },\n }, {\n sequelize\n })\n }\n static associate(models) {\n this.belongsTo(Company, {\n foreignKey: 'company_id',\n });\n }\n}\n\nmodule.exports = User;\n```\n\nto search just include the association :\n\n```\nUser.findAll({ include: Company })\n```\n\nI usually create each model using 'class' in different files, but if you need, just include the code below in the @jalex19 solution\n\n```\ncompanyname:{\n type: DataTypes.VIRTUAL,\n get() {\n return this.Company?.get().name;\n },\n set(/*value*/) {\n throw new Error('Do not try to set the `fullName` value!');\n }\n},\n```\n\n========================================\n\nCode:\n```text\nlet Schema = sequelize.define(\n    \"company\",\n    {\n      id: {\n        type: DataTypes.INTEGER.UNSIGNED,\n        autoIncrement: true,\n        primaryKey: true\n      },\n      name: {\n        type: DataTypes.STRING(45)\n      }\n    }\n  );\n```\n\n```text\nlet Schema = sequelize.define(\n    \"user\",\n    {\n      id: {\n        type: DataTypes.INTEGER.UNSIGNED,\n        autoIncrement: true,\n        primaryKey: true\n      },\n      login: {\n        type: DataTypes.STRING(45),\n        unique: true\n      },\n      company: {\n          type: DataTypes.INTEGER.UNSIGNED,\n          references: {\n            model: sequelize.model('company'),\n            key: 'id'\n          }\n      },\n\n      /* This companyname contruct is pure fantasy, and the target of my question */\n\n      companyname: {\n        type: new DataTypes.VIRTUAL(DataTypes.STRING,['company']),\n          references: {\n            model: 'company',\n            key: 'name'\n          }\n      }\n    }\n  );\n```\n\n```text\ncompany\n```\n\n```text\nuser\n```\n\n```text\ncompany.name\n```\n\n```text\nuser.companyname\n```\n\n```text\nconst User = sequelize.define('user', {\n  id: {\n    type: DataTypes.INTEGER.UNSIGNED,\n    autoIncrement: true,\n    primaryKey: true\n  },\n  login: {\n    type: DataTypes.STRING(45),\n    unique: true\n  },\n  company_id: {\n    type: DataTypes.INTEGER.UNSIGNED,\n  },\n});\n\nconst Company = sequelize.define('company', {\n  id: {\n    type: DataTypes.INTEGER.UNSIGNED,\n    autoIncrement: true,\n    primaryKey: true,\n  },\n  name: {\n    type: DataTypes.STRING,\n  },\n});\n\nUser.belongsTo(Company, {\n  foreignKey: 'company_id', // you can use this to customize the fk, default would be like companyId\n});\n\nCompany.hasMany(User);\n```\n\n```text\nUser.findAll({ include: Company }).then(users => console.log(users));\n```\n\n```text\nconst { Model, DataTypes } = require('sequelize');\n\nclass User extends Model {\n    static init(sequelize) {\n        super.init({\n            id: {\n                type: DataTypes.INTEGER.UNSIGNED,\n                autoIncrement: true,\n                primaryKey: true\n            },\n            login: {\n                type: DataTypes.STRING(45),\n                unique: true\n            },\n            company_id: {\n                type: DataTypes.INTEGER.UNSIGNED,\n            },\n            companyname:{\n                type: DataTypes.VIRTUAL,\n                get() {\n                    return this.Company?.get().name;\n                },\n                set(/*value*/) {\n                    throw new Error('Do not try to set the `companyname` value!');\n                }\n            },\n        }, {\n            sequelize\n        })\n    }\n    static associate(models) {\n        this.belongsTo(Company, {\n          foreignKey: 'company_id',\n        });\n    }\n}\n\nmodule.exports = User;\n```\n\n```text\nUser.findAll({ include: Company })\n```\n\n```text\ncompanyname:{\n    type: DataTypes.VIRTUAL,\n    get() {\n        return this.Company?.get().name;\n    },\n    set(/*value*/) {\n        throw new Error('Do not try to set the `fullName` value!');\n    }\n},\n```\n\n```text\ntype: DataTypes.VIRTUAL\n```\n\n========================================\n\nComments:\n- Yes. That's pretty much what I ended up doing, 3 months ago :) I'm still hoping there is some sneaky solution, that I missed, because this is not optimal.\n- :) Thanks. I'll try out your solution, if I can remember what project it was needed in, and I still got the source around. It does look promising though.","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":306,"estimatedTokens":1439}}686{"id":"stack-44829040","source":"stackoverflow","questionId":44829040,"title":"How to handle new replica in RDS Cluster with Sequelize?","tags":["sequelize.js","scalability","amazon-rds","amazon-aurora"],"text":"Title: How to handle new replica in RDS Cluster with Sequelize?\nTags: sequelize.js, scalability, amazon-rds, amazon-aurora\nSource: Stack Overflow\n\nQuestion:\nWe are prepping for a very large surge of traffic, but the question is also meant as a generic one: \n\nKnowing that you can set up Sequelize to use a cluster of RDS Databases (in our case: Aurora) like so:\n\n```\nconst master = { rdsClusterWriterEndpoint, username, password, port, database }\nconst replica = { rdsClusterReaderEndpoint, username, password, port, database }\nconst Sequelize = require('sequelize')\nconst sequelize = new Sequelize(null, null, null, {\n dialect: 'mysql',\n pool: {\n handleDisconnects: true,\n min: 0,\n max: 10,\n idle: 10000,\n },\n replication: {\n write: master,\n read: [replica],\n },\n})\n```\n\nHow could I handle adding a new RDS instance to the cluster to load balance reads even more without reloading the app?\n\nI've pocked around but couldn't find a good way to do it.\nThe DNS resolution seems to be done once at startup time and I haven't found a way to refresh it every once in a while.\n\nHas someone found a safe way of doing this?\n\nThanks\n\n========================================\n\nCode:\n```js\nconst master = { rdsClusterWriterEndpoint, username, password, port, database }\nconst replica = { rdsClusterReaderEndpoint, username, password, port, database }\nconst Sequelize = require('sequelize')\nconst sequelize = new Sequelize(null, null, null, {\n  dialect: 'mysql',\n  pool: {\n    handleDisconnects: true,\n    min: 0,\n    max: 10,\n    idle: 10000,\n  },\n  replication: {\n    write: master,\n    read: [replica],\n  },\n})\n```\n\n```js\nconst getRandomWithinRange = (min, max) => {\n  min = Math.ceil(min)\n  max = Math.floor(max)\n  return Math.floor(Math.random() * (max - min + 1)) + min // The maximum is inclusive and the minimum is inclusive\n}\nconst maxConnectionAge = moment.duration(10, 'minutes').asSeconds()\nconst pool =     {\n  handleDisconnects: true,\n  min: pool.min || 1, // Keep one connection open\n  max: pool.max || 10, // Max 10 connections\n  idle: pool.idle || 9000, // 9 seconds\n  validate: (obj) => {\n    // Recycle connections periodically\n    if (!obj.recycleWhen) {\n      // Setup expiry on new connections and return the connection as valid\n      obj.recycleWhen = moment().add(getRandomWithinRange(maxConnectionAge, maxConnectionAge * 2), 'seconds')\n      return true\n    }\n    // Recycle the connection if it expired\n    return moment().diff(obj.recycleWhen, 'seconds') < 0\n  }\n}\nconst master = { rdsClusterWriterEndpoint, username, password, port, database, pool }\nconst replica = { rdsClusterReaderEndpoint, username, password, port, database, pool }\nconst sequelize = new Sequelize(null, null, null, {\n  dialect: 'mysql',\n  replication: {\n    write: master,\n    read: [replica]\n  }\n}\n```\n\n========================================\n\nComments:\n- Did you find anything better than this?\n- @fedtuck we introduced some random to connexion recycle to prevent all connections from recycling at the same time but no, we didn't investigate much more, it's worked for us sufficiently well that we never needed a better solution. We have a specific configuration for both read & write to manage connections. If you find a better way, I'm still interested!\n- I didn't find any other good solution so far. Testing the one you posted with AWS and Aurora (Postgres), it is creating new connections after the time out, but not removing the previous, so it is crashing after a few hours of running.\n- `pool: { handleDisconnects: true, min: pool.min || 1, max: pool.max || 10, idle: pool.idle || 9000, validate: (obj) => { &#47;&#47; Recycle connexions periodically if (!obj.recycleWhen) { &#47;&#47; Setup expiry on new connexions and return the connexion as valid obj.recycleWhen = moment().add(getRandomWithinRange(maxConnectionAge, maxConnectionAge * 2), 'seconds') return true } &#47;&#47; Recycle the connexion if it has expired return moment().diff(obj.recycleWhen, 'seconds') < 0 } }` Hope this helps @fedtuck\n- I've edited the answer above with the code including the random part","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":101,"estimatedTokens":1018}}687{"id":"stack-61250827","source":"stackoverflow","questionId":61250827,"title":"Sequelize - Abstracted query to select all records older than 5 minutes using MySQL","tags":["javascript","mysql","node.js","orm","sequelize.js"],"text":"Title: Sequelize - Abstracted query to select all records older than 5 minutes using MySQL\nTags: javascript, mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm struggling to write an abstracted query using sequelize that will identify a record older than 5 minutes using the \"updatedAt\" column. My query reads as follows:\n\n```\nconst Jts = await models.Jts.findOne({\n where: {\n publish: true,\n retry: {\n [Op.lte]: 3\n },\n updatedAt: {\n [Op.lte]: [sequelize.fn(\"(NOW() - INTERVAL 5 MINUTE)\")]\n }\n },\n include: [\"OrgSetEntries\"],\n paranoid: false,\n order: [\n [\"effectiveDate\", \"ASC\"],\n [\"updatedAt\", \"ASC\"]\n ]\n});\n```\n\nI have tried a few syntaxes but am struggling. The generated query always produces \"Invalid Date\" string eg: \n\n```\n... updatedAt` &lt;= 'Invalid date';\n```\n\nAny advice is greatly appreciated.\n\n========================================\n\nCode:\n```text\nconst Jts = await models.Jts.findOne({\n    where: {\n        publish: true,\n        retry: {\n            [Op.lte]: 3\n        },\n        updatedAt: {\n            [Op.lte]: [sequelize.fn(\"(NOW() - INTERVAL 5 MINUTE)\")]\n        }\n    },\n    include: [\"OrgSetEntries\"],\n    paranoid: false,\n    order: [\n        [\"effectiveDate\", \"ASC\"],\n        [\"updatedAt\", \"ASC\"]\n    ]\n});\n```\n\n```text\n... updatedAt` &lt;= 'Invalid date';\n```\n\n```js\nimport { sequelize } from '../../db';\nimport Sequelize, { Model, DataTypes, Op } from 'sequelize';\n\nclass Jts extends Model {}\nJts.init(\n  {\n    publish: DataTypes.BOOLEAN,\n    retry: DataTypes.INTEGER,\n    updatedAt: DataTypes.DATE,\n  },\n  { sequelize, modelName: 'jts' },\n);\n\n(async function test() {\n  try {\n    // create tables\n    await sequelize.sync({ force: true });\n    // seed\n    let date1 = new Date();\n    date1.setHours(date1.getHours() - 1);\n    await Jts.bulkCreate([\n      { publish: false, retry: 2 },\n      { publish: false, retry: 5 },\n      { publish: true, retry: 2, updatedAt: date1 },\n      { publish: true, retry: 1, updatedAt: new Date() },\n    ]);\n    // test\n    const result = await Jts.findOne({\n      where: {\n        publish: true,\n        retry: {\n          [Op.lte]: 3,\n        },\n        updatedAt: {\n          [Op.lte]: Sequelize.literal(\"NOW() - (INTERVAL '5 MINUTE')\"),\n        },\n      },\n      raw: true,\n    });\n    console.log('result:', result);\n  } catch (error) {\n    console.log(error);\n  } finally {\n    await sequelize.close();\n  }\n})();\n```\n\n```sh\nExecuting (default): DROP TABLE IF EXISTS \"jts\" CASCADE;\nExecuting (default): DROP TABLE IF EXISTS \"jts\" CASCADE;\nExecuting (default): CREATE TABLE IF NOT EXISTS \"jts\" (\"id\"   SERIAL , \"publish\" BOOLEAN, \"retry\" INTEGER, \"updatedAt\" TIMESTAMP WITH TIME ZONE, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'jts' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): INSERT INTO \"jts\" (\"id\",\"publish\",\"retry\",\"updatedAt\") VALUES (DEFAULT,false,2,NULL),(DEFAULT,false,5,NULL),(DEFAULT,true,2,'2020-04-16 12:50:43.458 +00:00'),(DEFAULT,true,1,'2020-04-16 13:50:43.458 +00:00') RETURNING *;\nExecuting (default): SELECT \"id\", \"publish\", \"retry\", \"updatedAt\" FROM \"jts\" AS \"jts\" WHERE \"jts\".\"publish\" = true AND \"jts\".\"retry\" <= 3 AND \"jts\".\"updatedAt\" <= NOW() - (INTERVAL '5 MINUTE') LIMIT 1;\nresult: { id: 3,\n  publish: true,\n  retry: 2,\n  updatedAt: 2020-04-16T12:50:43.458Z }\n```\n\n```sh\nnode-sequelize-examples=# select * from \"jts\";\n id | publish | retry |         updatedAt\n----+---------+-------+----------------------------\n  1 | f       |     2 |\n  2 | f       |     5 |\n  3 | t       |     2 | 2020-04-16 12:50:43.458+00\n  4 | t       |     1 | 2020-04-16 13:50:43.458+00\n(4 rows)\n```\n\n```text\nSequelize.literal(\"NOW() - (INTERVAL '5 MINUTE')\")\n```\n\n```text\nid = 3\n```\n\n========================================\n\nComments:\n- Hey, thanks for the great answer! I had to tweak my version, perhaps a difference in MySQL versions(?) Mine reads [Op.lte]: Sequelize.literal(\"DATE_SUB(NOW(), INTERVAL 5 MINUTE)\")\n- @prime sorry. I use PostgreSQL, so maybe there is a little difference with MySQL\n- If it's to get records older than 5 min shouldnt the query be [Op.gte]: Sequelize.literal(\"DATE_SUB(NOW(), INTERVAL 5 MINUTE)\") instead of [Op.lte]: Sequelize.literal(\"DATE_SUB(NOW(), INTERVAL 5 MINUTE)\") I'm just curious pls anyone can enlighten me","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":149,"estimatedTokens":1178}}688{"id":"stack-50764005","source":"stackoverflow","questionId":50764005,"title":"Sequelize same N:M table for different associations","tags":["mysql","sql","database","sequelize.js"],"text":"Title: Sequelize same N:M table for different associations\nTags: mysql, sql, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn a Node + MySQL project I got 4 Tables:\n\n- `Users` describes a registered user,\n\n- `InvitedUsers` a proto-user, contains some informations of a non registered user,\n\n- `Projects` describes a project,\n\n- `ProjectMembers` the N:M associations of `Projects` and `Users`\n\nNow I got the association of the N:M like this:\n\n```\nUsers.belongsToMany(Projects, { through: ProjectMembers });\nProjects.belongsToMany(Users, { through: ProjectMembers });\n```\n\n**I need to use the same `ProjectMembers` table as N:M for `InvitedUsers` and `Projects`**\n\n**Is this possible?** I suppose that it's not since the foreign key constrains on the N:M table cannot choose on which table (`Users` or `InvitedUsers`) has to be applied\n\nI've tried adding (omitting the options):\n\n```\nInvitedUsers.belongsToMany(Projects, { through: ProjectMembers });\nProjects.belongsToMany(InvitedUsers, { through: ProjectMembers });\n```\n\nAnd no error is displayed during the associations definition but when i try to add an entry in the `ProjectMembers` table coping a `InvitedUsers`'s id as FK, I got a foreign key constrain error. \n\nSo my question is if I can use a N:M table for different N:M relations.\n\n========================================\n\nTop Answer:\nSpeaking from MySQL's perspective...\n\nA many:many *database* table is essentially 2 columns (`project_id`, `person_id`) with two indexes (`(project_id, person_id)` and `(person_id, project_id)`). If is reasonable to add a 3rd column to qualify the type of relationship between the (\"member\" versus \"invited user\").\n\nMore discussion of the table: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table\n\n========================================\n\nCode:\n```text\nUsers.belongsToMany(Projects, { through: ProjectMembers });\nProjects.belongsToMany(Users, { through: ProjectMembers });\n```\n\n```text\nInvitedUsers.belongsToMany(Projects, { through: ProjectMembers });\nProjects.belongsToMany(InvitedUsers, { through: ProjectMembers });\n```\n\n```text\nUsers\n```\n\n```text\nInvitedUsers\n```\n\n```text\nProjects\n```\n\n```text\nProjectMembers\n```\n\n```text\nProjects\n```\n\n```text\nUsers\n```\n\n```text\nProjectMembers\n```\n\n```text\nInvitedUsers\n```\n\n```text\nProjects\n```\n\n```text\nUsers\n```\n\n```text\nInvitedUsers\n```\n\n```text\nProjectMembers\n```\n\n```text\nInvitedUsers\n```\n\n```text\nUser.belongsToMany(Project, { through: ProjectMembers, foreignKey: 'user_id' });\nProject.belongsToMany(User, { through: ProjectMembers, foreignKey: 'project_id' });\nInvited.belongsToMany(Project, { through: ProjectMembers, foreignKey: 'invited_id' });\nProject.belongsToMany(Invited, { through: ProjectMembers, foreignKey: 'project_id' });\n```\n\n```text\nconst User = sequelize.define('user', {\n  username: Sequelize.STRING,\n});\n\nconst Invited = sequelize.define('invited', {\n  username: Sequelize.STRING,\n});\n\nconst Project = sequelize.define('project', {\n  name: Sequelize.STRING,\n});\n\nconst ProjectMembers = sequelize.define('project_members', {\n  id: {\n    allowNull: false,\n    autoIncrement: true,\n    primaryKey: true,\n    type: Sequelize.INTEGER,\n  },\n  user_id: {\n    type: Sequelize.INTEGER,\n  },\n  project_id: Sequelize.INTEGER,\n  invited_id: Sequelize.INTEGER,\n});\n\nUser.belongsToMany(Project, { through: ProjectMembers, foreignKey: 'user_id' });\nProject.belongsToMany(User, { through: ProjectMembers, foreignKey: 'project_id' });\nInvited.belongsToMany(Project, { through: ProjectMembers, foreignKey: 'invited_id' });\nProject.belongsToMany(Invited, { through: ProjectMembers, foreignKey: 'project_id' });\n\nsequelize.sync({ force: true })\n  .then(() => {\n    User.create({\n      username: 'UserOne',\n      projects: {\n        projectName: 'projectOne'\n      }\n    }, { include: [Project] }).then((result) => {\n      Invited.create({\n        username: 'InvitedOne',\n        projects: {\n          projectName: 'projectTwo'\n        }\n      }, { include: [Project] }).then((result2) => {\n        console.log(result2);\n\n      })\n    })\n  })\n```\n\n```text\nforeignKey\n```\n\n```text\nuser\n```\n\n```text\nInvitedUser\n```\n\n```text\nproject_members\n```\n\n```text\nproject_id\n```\n\n```text\nperson_id\n```\n\n```text\n(project_id, person_id)\n```\n\n```text\n(person_id, project_id)\n```\n\n```text\n//User-projects via ProjectMembers\nUsers.belongsToMany(Projects, { through: ProjectMembers, as: 'ProjectMembers' });\nProjects.belongsToMany(Users, { through: ProjectMembers, as: 'ProjectMembers' });\n\n//InvitedUsers-Projects via ProjectMembers\nInvitedUsers.belongsToMany(Projects, { through: ProjectMembers, as: 'ProjectInvitedMembers' });\nProjects.belongsToMany(InvitedUsers, { through: ProjectMembers, as: 'ProjectInvitedMembers' });\n```\n\n```text\nas\n```\n\n```text\nbelongsToMany\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":220,"estimatedTokens":1196}}689{"id":"stack-39580973","source":"stackoverflow","questionId":39580973,"title":"Node.js: Defining Postgres Schemas in Sequelize","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Node.js: Defining Postgres Schemas in Sequelize\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe Official Documentation doesn't explains clearly how define schemas for database by themselves. I'm assuming that Sequelize is more related to MySql than Postgres (where schemas are mandatory).\n\nIf I've already created some schemas in Postgres, how I could sync them with Sequelize?\n\n========================================\n\nCode:\n```text\nvar City = sequelize.define('City', {\n    id: {\n        type: sequelize.Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true,\n        field: 'id'\n    },\n    name: {\n        type: sequelize.Sequelize.STRING,\n        field: 'name'   \n    }\n  }, {\n    timestamps: false,\n    tableName: 'cities'\n    });\nCity.schema(\"public\");\n```\n\n```text\nmodel.schema\n```\n\n========================================\n\nComments:\n- I think you need to recreate the models using sequelize before you can sync. There was a project I saw that generated models from an existing db (SQL Server(?)) but it didn't work very well for me.\n- I can recreate the models (tables) perfectly with Sequelize. My issue are the Postgres Schemas (public, security, audit, whatever...), that I've created in Postgres. These schemas will contain the models (tables), but for themselves I don't know how sync them with Sequelize.\n- I think you meant City.schema(\"public\")\n- I figured but JavaScript doesn't know that!\n- Thank you so much! It is just all want!\n- And also, this answer is valid to me: stackoverflow.com/a/32025860/6291719\n- Nice, this is the way\n- is it possible to set schema for all models at once at connection time?\n- Answer for the above: stackoverflow.com/questions/58070444/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":47,"estimatedTokens":438}}690{"id":"stack-38304349","source":"stackoverflow","questionId":38304349,"title":"Multi tenant (SAAS) using nodejs sequelize","tags":["node.js","postgresql","sequelize.js","multi-tenant","saas"],"text":"Title: Multi tenant (SAAS) using nodejs sequelize\nTags: node.js, postgresql, sequelize.js, multi-tenant, saas\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a multi tenant ( / Software as a service) using nodejs and postgres, sequelize as ORM. I decided to go with separate DBs for each client, rather than having single DB with all table having the extra column, because of security reasons. I achieved the result, but performance was not good, since i have to initialise models for each DB according to sequelize(for almost each request). Is there any better way to do this? Am I missing something in sequelize?\n\n========================================\n\nTop Answer:\nA quick implementation of my comment above.\n\napp.js:\n\n```\nconst Sequelize = require('sequelize');\n\nconst connections = {\n client1: new Sequelize('postgres://user:pass@example.com:5432/client1'),\n client2: new Sequelize('postgres://user:pass@example.com:5432/client2'),\n client3: new Sequelize('postgres://user:pass@example.com:5432/client3'),\n};\n\nconst User = require('./models/user');\nconst Post = require('./models/post');\nconst Comment = require('./models/comment');\n\nObject.keys(connections).forEach(connection => {\n connection.define('User', userColumns);\n connection.define('Post', postColumns);\n connection.define('Comment', commentColumns);\n});\n```\n\nmodels/user.js:\n\n```\nmodule.exports = {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n username: Sequelize.STRING,\n email: Sequelize.STRING\n // etc, etc\n};\n```\n\nObviously whatever server framework you use you'll need to detect (from the url I imagine) which client connection to use for a given request.\n\nAlternatively, consider writing a single-connection app and deploying multiple instances of it (I'm doing this currently). Might be a simpler choice if you're set on separate DBs.\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\n\nconst connections = {\n  client1: new Sequelize('postgres://user:pass@example.com:5432/client1'),\n  client2: new Sequelize('postgres://user:pass@example.com:5432/client2'),\n  client3: new Sequelize('postgres://user:pass@example.com:5432/client3'),\n};\n\nconst User = require('./models/user');\nconst Post = require('./models/post');\nconst Comment = require('./models/comment');\n\nObject.keys(connections).forEach(connection => {\n  connection.define('User', userColumns);\n  connection.define('Post', postColumns);\n  connection.define('Comment', commentColumns);\n});\n```\n\n```text\nmodule.exports = {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  username: Sequelize.STRING,\n  email: Sequelize.STRING\n  // etc, etc\n};\n```\n\n========================================\n\nComments:\n- Use pools with single database (Postgres) you will have far better scalability and less headaches\n- Maybe post some code? FWIW, you should only need to initialise your models once (you definitely don't need to redefine them on each request). You can keep your separate DBs if you wish - simply create a sequelize instance for each db using the releveant connection details and pass your model definitions to each one at app startup.\n- medium.com/@mohamedsameer72/&hellip;\n- How scalable is this solution? What if I have thousands of databases, and I create an instance for each?\n- @TFischer that's probably a question for your DB server. Node shouldn't have a problem forwarding that many connections, and I can't imagine PG will have a problem serving them.\n- PG has a default of 100 concurrent connections, three of which are reserved for super-user connections, though it can be modified. postgresql.org/docs/13/runtime-config-connection.html -- more tot he point, though, 1000s of connections, if they all are used at the same time, will likely start degrading PG performance pretty severely.","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":98,"estimatedTokens":965}}691{"id":"stack-42708811","source":"stackoverflow","questionId":42708811,"title":"\"has many through\" association in Sequelize","tags":["sequelize.js"],"text":"Title: \"has many through\" association in Sequelize\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet's say we have three models: \n\n- books\n\n- chapters\n\n- paragraphs\n\nHere are their associations:\n\n- **Books** have many **chapters**.\n\n- **Chapters** have many **paragraphs**.\n\n- **Books** have many **paragraphs**, through **chapters**.\n\n**Is it possible to define a 'has many, through' relationship with Sequelize? If so, how?**\n\nHere are very basic models for Book, Chapter, and Paragraph:\n\n```\n// Book model\nconst Book = sequelize.define('Book', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true\n },\n title: {\n type: DataTypes.STRING\n }\n}, {\n classMethods: {\n associate: (models) => {\n Book.hasMany(models.Chapter, {\n foreignKey: 'bookId',\n as: 'chapters'\n });\n }\n // How can you add an association for a book having many paragraphs, through chapters?\n }\n});\n\n// Chapter model\nconst Chapter = sequelize.define('Chapter', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true\n },\n title: {\n type: DataTypes.STRING\n }\n}, {\n classMethods: {\n associate: (models) => {\n Chapter.hasMany(models.Paragraph, {\n foreignKey: 'chapterId',\n as: 'paragraphs'\n });\n\n Chapter.belongsTo(models.Book, {\n foreignKey: 'bookId'\n });\n }\n }\n});\n\n// Paragraph Model\nconst Paragraph = sequelize.define('Paragraph', {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true\n },\n content: {\n type: DataTypes.TEXT\n }\n}, {\n classMethods: {\n associate: (models) => {\n Paragraph.belongsTo(models.Chapter, {\n foreignKey: 'chapterId'\n });\n }\n // How can you add an association for paragraphs belonging to a book \"through\" chapters?\n }\n});\n```\n\n========================================\n\nCode:\n```text\n// Book model\nconst Book = sequelize.define('Book', {\n  id: {\n    type: DataTypes.INTEGER,\n    allowNull: false,\n    primaryKey: true\n  },\n  title: {\n    type: DataTypes.STRING\n  }\n}, {\n  classMethods: {\n    associate: (models) => {\n      Book.hasMany(models.Chapter, {\n        foreignKey: 'bookId',\n        as: 'chapters'\n      });\n    }\n    // How can you add an association for a book having many paragraphs, through chapters?\n  }\n});\n\n\n// Chapter model\nconst Chapter = sequelize.define('Chapter', {\n  id: {\n    type: DataTypes.INTEGER,\n    allowNull: false,\n    primaryKey: true\n  },\n  title: {\n    type: DataTypes.STRING\n  }\n}, {\n  classMethods: {\n    associate: (models) => {\n      Chapter.hasMany(models.Paragraph, {\n        foreignKey: 'chapterId',\n        as: 'paragraphs'\n      });\n\n      Chapter.belongsTo(models.Book, {\n        foreignKey: 'bookId'\n      });\n    }\n  }\n});\n\n\n// Paragraph Model\nconst Paragraph = sequelize.define('Paragraph', {\n  id: {\n    type: DataTypes.INTEGER,\n    allowNull: false,\n    primaryKey: true\n  },\n  content: {\n    type: DataTypes.TEXT\n  }\n}, {\n  classMethods: {\n    associate: (models) => {\n      Paragraph.belongsTo(models.Chapter, {\n        foreignKey: 'chapterId'\n      });\n    }\n    // How can you add an association for paragraphs belonging to a book \"through\" chapters?\n  }\n});\n```\n\n```js\n// in Book model\ninstanceMethods: {\n    getParagraphs: function(options){\n        options.include = [\n            {\n                model: sequelize.models.Chapter,\n                attributes: [],\n                where: {\n                    bookId: this.get('id')\n                }\n            }\n        ];\n\n        return sequelize.models.Paragraph.findAll(options);\n    }\n}\n```\n\n```text\ninstanceMethods\n```\n\n```text\nBook\n```\n\n```text\nParagraph\n```\n\n```text\ngetParagraphs\n```\n\n```text\ngetBook\n```\n\n```text\ngetBook\n```\n\n```text\nParagraph\n```\n\n```text\nfindAll\n```\n\n```text\ninclude\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":224,"estimatedTokens":913}}692{"id":"stack-38882185","source":"stackoverflow","questionId":38882185,"title":"sequelize, Statement(where) in statement(where)","tags":["javascript","angularjs","node.js","sequelize.js","angular-fullstack"],"text":"Title: sequelize, Statement(where) in statement(where)\nTags: javascript, angularjs, node.js, sequelize.js, angular-fullstack\nSource: Stack Overflow\n\nQuestion:\nI'm trying for 2 hours to resolve a little problem which is not one.\nI'm on an generated yeoman Angular-fullstack App.\n\nI want to write this code with sequelize:\n\n```\nSELECT * \nFROM demand \nWHERE city_id NOT IN (\nSELECT city_id\nFROM demand\nWHERE user_id=req.params.user_id)\n```\n\nI have yet the following code but that doesn't work. I get only []\n\n```\nexport function getCity(req, res) {\n return Demand.findAll({\n where: {\n city_id:{ $notIn: Demand.findAll({\n attributes: ['city_id'],\n where: {\n user_id: req.params.user_id,\n }\n })}\n }\n })\n .then(handleEntityNotFound(res))\n .then(respondWithResult(res))\n .catch(handleError(res));\n}\n```\n\nHave you a clue?\nThank you.\n\n========================================\n\nTop Answer:\nThe problem from your first query is there because the findall method of sequelize returns a promise. \n\nThe only way to use subqueries in where condition with sequelize is through the literal method: `sequelize.literal('your query');`\n\nCheck this issue to get more informations https://github.com/sequelize/sequelize/issues/3961\n\n========================================\n\nCode:\n```text\nSELECT * \nFROM demand \nWHERE city_id NOT IN (\nSELECT city_id\nFROM demand\nWHERE user_id=req.params.user_id)\n```\n\n```text\nexport function getCity(req, res) {\n  return Demand.findAll({\n    where: {\n      city_id:{ $notIn: Demand.findAll({\n        attributes: ['city_id'],\n        where: {\n          user_id: req.params.user_id,\n        }\n      })}\n    }\n  })\n  .then(handleEntityNotFound(res))\n  .then(respondWithResult(res))\n  .catch(handleError(res));\n}\n```\n\n```text\nexport function showDemandArtistNoUser(req, res) {\n  return db.sequelize.query('SELECT * FROM demands WHERE city_id NOT IN (SELECT city_id FROM demands WHERE user_id='+req.params.user_id+')', { type: db.sequelize.QueryTypes.SELECT })\n  .then(handleEntityNotFound(res))\n  .then(respondWithResult(res))\n  .catch(handleError(res));\n}\n```\n\n```text\nimport db from '../../sqldb';\n```\n\n```text\nsequelize.literal('your query');\n```\n\n```text\nconst tempSQL = sequelize.dialect.QueryGenerator.selectQuery('MyOtherTable',{\n    attributes: ['fkey'],\n    where: {\n         field1: 1,\n         field2: 2,\n         field3: 3\n    }})\n    .slice(0,-1); // to remove the ';' from the end of the SQL\n\nMyTable.find( {\n    where: {\n        id: {\n             $notIn: sequelize.literal('(' + tempSQL + ')'),\n        }\n    } \n} );\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":116,"estimatedTokens":636}}693{"id":"stack-74961531","source":"stackoverflow","questionId":74961531,"title":"Why is Sequelize upsert not working with composite unique key?","tags":["sql","node.js","postgresql","sequelize.js"],"text":"Title: Why is Sequelize upsert not working with composite unique key?\nTags: sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI use this table in a PostgreSQL database:\n\n```\ncreate table if not exists \"Service\" (\n _id uuid not null primary key,\n service text not null,\n \"count\" integer not null,\n \"date\" timestamp with time zone,\n team uuid,\n organisation uuid,\n \"createdAt\" timestamp with time zone not null,\n \"updatedAt\" timestamp with time zone not null,\n unique (service, \"date\", organisation),\n foreign key (\"team\") references \"Team\"(\"_id\"),\n foreign key (\"organisation\") references \"Organisation\"(\"_id\")\n);\n```\n\nWhen I try an `upsert` with `Sequelize` with the following code, it throws an error:\n\n```\nService.upsert({ team, date, service, organisation, count }, { returning: true })\n```\n\nError is:\n\nerror: duplicate key value violates unique constraint \"Service_service_date_organisation_key\"\n\nKey (service, date, organisation)= (xxx, 2022-12-30 01:00:00+01, 12345678-5f63-1bc6-3924-517713f97cc3) already exists.\n\nBut according to Sequelize documentation it should work: https://sequelize.org/docs/v6/other-topics/upgrade/#modelupsert\n\nNote for Postgres users: If upsert payload contains PK field, then PK will be used as the conflict target. Otherwise first unique constraint will be selected as the conflict key.\n\nHow can I find this duplicate key error and get it work with the composite unique key: `unique (service, \"date\", organisation)`?\n\n========================================\n\nTop Answer:\n### References\n\nSimilar questions were asked on GitHub, see:\n\n- https://github.com/sequelize/sequelize/issues/13240\n\n- https://github.com/sequelize/sequelize/issues/13412\n\nand they were not solved so far, so, as the time of this writing, this issue seems to be unresolved, so you will need to work-around it. Below I will provide a few ideas to solve this, but since I have never worked with Sequelize, it is possible that I have some syntax error or some misunderstanding. If so, please point it out and I'll fix it.\n\n### Approach 1: Querying by your unique key and inserting/updating by it\n\n```\nPost.findAll({\n where: {\n service: yourservice,\n date: yourdate,\n organization: yourorganization\n }\n});\n```\n\nAnd then `insert` if the result is empty, update otherwise.\n\n### Approach 2: Modifying your schema\n\nSince your composite `unique` key is a candidate key, an option would be to remove your `_id` field and make your `(service, \"date\", organization)` unique.\n\n### Approach 3: Implement an insert trigger on your table\n\nYou could simply call `insert` from Sequelize and let a PostgreSQL `trigger` handle the upserting, see: How to write an upsert trigger in PostgreSQL?\n\nExample trigger:\n\n```\nCREATE OR REPLACE FUNCTION on_before_insert_versions() RETURNS trigger\n LANGUAGE plpgsql AS\n$$BEGIN\n IF pg_trigger_depth() = 1 THEN\n INSERT INTO versions (key, version) VALUES (NEW.key, NEW.version)\n ON CONFLICT (key)\n DO UPDATE SET version = NEW.version;\n RETURN NULL;\n ELSE\n RETURN NEW;\n END IF;\nEND;$$;\n```\n\nYou of course will need to change table and field names accordingly to your schema and command.\n\n========================================\n\nCode:\n```sql\ncreate table if not exists \"Service\" (\n    _id uuid not null primary key,\n    service text not null,\n    \"count\" integer not null,\n    \"date\" timestamp with time zone,\n    team uuid,\n    organisation uuid,\n    \"createdAt\" timestamp with time zone not null,\n    \"updatedAt\" timestamp with time zone not null,\n    unique (service, \"date\", organisation),\n    foreign key (\"team\") references \"Team\"(\"_id\"),\n    foreign key (\"organisation\") references \"Organisation\"(\"_id\")\n);\n```\n\n```js\nService.upsert({ team, date, service, organisation, count }, { returning: true })\n```\n\n```text\nupsert\n```\n\n```text\nSequelize\n```\n\n```text\nunique (service, \"date\", organisation)\n```\n\n```js\nService.upsert(\n    { team, date, service, organisation, count }, \n    { conflictFields: [\"service\", \"date\", \"organisation\"] },\n    { returning: true }\n)\n```\n\n```text\nconflictFields\n```\n\n```text\nPost.findAll({\n  where: {\n    service: yourservice,\n    date: yourdate,\n    organization: yourorganization\n  }\n});\n```\n\n```text\nCREATE OR REPLACE FUNCTION on_before_insert_versions() RETURNS trigger\n   LANGUAGE plpgsql AS\n$$BEGIN\n   IF pg_trigger_depth() = 1 THEN\n      INSERT INTO versions (key, version) VALUES (NEW.key, NEW.version)\n         ON CONFLICT (key)\n         DO UPDATE SET version = NEW.version;\n      RETURN NULL;\n   ELSE\n      RETURN NEW;\n   END IF;\nEND;$$;\n```\n\n```text\ninsert\n```\n\n```text\nunique\n```\n\n```text\n_id\n```\n\n```text\n(service, \"date\", organization)\n```\n\n```text\ninsert\n```\n\n```text\ntrigger\n```\n\n========================================\n\nComments:\n- *first unique constraint will be selected as the conflict key* - I wonder in what order. This could mean that if there's no PK in the payload but the PK happens to be the first unique constraint, it'll still target the PK. If constraints are selected based on the order of their names, you could rename the constraints so that yours comes first. If it skips the PK but there happens to be some other constraint that's picked before yours - you can list them - you could just drop/recreate/rename that.\n- This doesn't work with postgres if the `conflictFields` are not unique indexes, right?\n- That's right. There must be a constraint that the `insert` would violate, so that the violation is caught and handled with an `update` instead. The fields listed as `conflictFields` are used to guess what constraint you wish to handle based on what index uses them. In plain SQL you can also name the specific constraint directly. More on the `on conflict...do update` here. More on `constraints` here.","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":197,"estimatedTokens":1431}}694{"id":"stack-53049815","source":"stackoverflow","questionId":53049815,"title":"How to group by createdAt column's date part?","tags":["javascript","node.js","date","sequelize.js","grouping"],"text":"Title: How to group by createdAt column's date part?\nTags: javascript, node.js, date, sequelize.js, grouping\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get some subtotals using Sequelize, and this is how my query looks like.\n\n```\nconst getAllCustomerEarnings = async (customerAccountId) => {\n return await customerEarnings.findAll({\n attributes: [\n [Sequelize.fn('SUM', Sequelize.col('amount')), 'amount'],\n [Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdAt'],\n ],\n where: { \n [Op.and]: [\n {customerAccountId: customerAccountId},\n ] \n },\n order: [['createdAt', 'ASC']],\n group: 'createdAt'\n })\n}\n```\n\nHowever, what I get as an output are not subtotals on per-day basis. I actually get each and every record from the table, with time part set to 00:00:000Z\n\nWhat should I change in order to get subtotals for each day?\n\n========================================\n\nCode:\n```text\nconst getAllCustomerEarnings = async (customerAccountId) => {\n  return await customerEarnings.findAll({\n    attributes: [\n      [Sequelize.fn('SUM', Sequelize.col('amount')), 'amount'],\n      [Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdAt'],\n    ],\n    where: { \n      [Op.and]: [\n        {customerAccountId: customerAccountId},\n      ] \n    },\n    order: [['createdAt', 'ASC']],\n    group: 'createdAt'\n  })\n}\n```\n\n```text\nSELECT SUM(\"amount\") AS \"amount\", date_trunc('day', \"createdAt\") AS \"createdAt\"\nFROM \"CustomerEarnings\" AS \"CustomerEarning\"\nWHERE (\"CustomerEarning\".\"customerAccountId\" = 5)\nGROUP BY \"createdAt\"\nORDER BY \"CustomerEarning\".\"createdAt\" ASC;\n```\n\n```text\nconst getAllCustomerEarnings = async (customerAccountId) => {\n  return await customerEarnings.findAll({\n    attributes: [\n      [Sequelize.fn('SUM', Sequelize.col('amount')), 'amount'],\n      [Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdOn'],\n    ],\n    where: { \n      [Op.and]: [\n        {customerAccountId: customerAccountId},\n      ] \n    },\n    order: [[Sequelize.literal('\"createdOn\"'), 'ASC']],\n    group: 'createdOn'\n  })\n}\n```\n\n```text\n[[Sequelize.literal('\"createdOn\"'), 'ASC']],\n```\n\n========================================\n\nComments:\n- Have you tried grouping with `[Sequelize.fn('date_trunc', 'day', Sequelize.col('createdAt')), 'createdAt']`\n- Yes, with no effect, unfortunatelly","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":85,"estimatedTokens":583}}695{"id":"stack-52548428","source":"stackoverflow","questionId":52548428,"title":"sequelize: relations in both directions needed?","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: sequelize: relations in both directions needed?\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two existing tables in my database: \"user\" with the columns \"id\" and \"depId\" and \"department\" with \"id\" and \"name\". (user.depId ist the foreign key for department.id)\n\nNow I'd like to create a sequelize model for this. \n\nI already added this \n\n```\nUser.belongsTo (Department, { foreignKey: 'depId', targetKey: 'id'});\n```\n\nDo I have to add this also:\n\n```\nDepartment.HasMany(User)\n```\n\nor is one direction enough to work properly?\n\n========================================\n\nCode:\n```text\nUser.belongsTo (Department, { foreignKey: 'depId', targetKey: 'id'});\n```\n\n```text\nDepartment.HasMany(User)\n```\n\n```text\nUser.belongsTo (Department, { foreignKey: 'depId', targetKey: 'id'});\n```\n\n```text\nDepartment.HasMany(User)\n```\n\n========================================\n\nComments:\n- So this should work for my example: User.belongsTo (Department, { foreignKey: 'depId', targetKey: 'id'}); Department.hasMany(User, { foreignKey: 'depId', targetKey: 'id'}) ?\n- @Franken , try `User.belongsTo(Department,{foreignKey : 'depId' }); Department.hasMany(User,{foreignKey:'depId'});`","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":303}}696{"id":"stack-41682504","source":"stackoverflow","questionId":41682504,"title":"How can i minus value from 2 columns and then apply max function in sequelizejs?","tags":["mysql","node.js","sequelize.js"],"text":"Title: How can i minus value from 2 columns and then apply max function in sequelizejs?\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to get a max record after minus 2 columns value. I am able to make that query on phpMyAdmin \n\n```\nSELECT `storage_id`, `host` FROM `storages` \nWHERE size - used = (SELECT MAX(size - used) FROM `storages`\n```\n\nbut struggling on sequelizejs. Any help? \n\n**Updated:** \n\nI have updated my query and now it's easier than previous.\n\n```\nSELECT `storage_id`, `host`, size - used AS free FROM `storages` ORDER BY free DESC LIMIT 1\n```\n\n========================================\n\nCode:\n```text\nSELECT `storage_id`, `host` FROM `storages` \nWHERE size - used = (SELECT MAX(size - used) FROM `storages`\n```\n\n```text\nSELECT `storage_id`, `host`, size - used AS free FROM `storages` ORDER BY free DESC LIMIT 1\n```\n\n```text\nStorage.findOne({\n    attributes: ['storage_id', 'host', [Sequelize.literal('size - used'), 'free']],\n    order: 'free DESC'\n  })\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.394Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":40,"estimatedTokens":253}}697{"id":"stack-49946600","source":"stackoverflow","questionId":49946600,"title":"Error seeding JSON data with sequelize into PostgreSQL database","tags":["postgresql","sequelize.js","sequelize-cli"],"text":"Title: Error seeding JSON data with sequelize into PostgreSQL database\nTags: postgresql, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nOccurs when I run the sequelize-cli command `sequelize db:seed:all`\n\nWhen I try and seed an object as JSON I get the following error:\n\n```\nERROR: Invalid value { viewId: null,\n dateRanges: [ { startDate: null, endDate: null } ],\n samplingLevel: 'DEFAULT',\n dimensions: [ { name: 'ga:channelGrouping' } ],\n metrics: [ { expression: 'ga:users' } ] }\n```\n\nThis is my model\n\n```\nmodule.exports = (Sequelize, DataTypes) => {\n const Report = Sequelize.define('Report', {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n validate: {\n is: /^[a-z0-9\\_\\-]+$/i,\n },\n },\n platform: {\n type: DataTypes.STRING,\n allowNull: false,\n validate: {\n is: /^[a-z0-9\\_\\-]+$/i,\n },\n },\n query: {\n type: DataTypes.JSON,\n },\n });\n return Report;\n};\n```\n\nThis is my seed file\n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.bulkInsert('Reports', [\n {\n name: 'users per channel',\n platform: 'google',\n query: {\n \"viewId\": null,\n \"dateRanges\": [\n {\n \"startDate\": null,\n \"endDate\": null,\n },\n ],\n \"samplingLevel\": \"DEFAULT\",\n \"dimensions\": [\n {\n \"name\": \"ga:channelGrouping\",\n },\n ],\n \"metrics\": [{ \"expression\": \"ga:users\" }],\n },\n createdAt: new Date(),\n updatedAt: new Date(),\n },\n ]);\n },\n\n down: (queryInterface, Sequelize) => {},\n};\n```\n\nI was able to insert the same data directly with this query\n\n```\nINSERT INTO \"Reports\" (id, name, platform, query, \"createdAt\", \"updatedAt\") VALUES (1, 'users per channel', 'google', '{\"viewId\":null,\"dateRanges\":[{\"startDate\":null,\"endDate\":null}],\"samplingLevel\":\"DEFAULT\",\"dimensions\":[{\"name\":\"ga:channelGrouping\"}],\"metrics\":[{\"expression\":\"ga:users\"}]}', '2018-04-15 08:55:12.449-05', '2018-04-15 08:55:12.449-05');\n```\n\nI wasn't able to find anyone having the same issue as me so I believe it is something simple but I cannot see it.\n\nI'm able to run the seed with no problem if I wrap the object in JSON.stringify() but surely that isn't what is intended.\n\n========================================\n\nCode:\n```text\nERROR: Invalid value { viewId: null,\n  dateRanges: [ { startDate: null, endDate: null } ],\n  samplingLevel: 'DEFAULT',\n  dimensions: [ { name: 'ga:channelGrouping' } ],\n  metrics: [ { expression: 'ga:users' } ] }\n```\n\n```text\nmodule.exports = (Sequelize, DataTypes) => {\n  const Report = Sequelize.define('Report', {\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true,\n      validate: {\n        is: /^[a-z0-9\\_\\-]+$/i,\n      },\n    },\n    platform: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      validate: {\n        is: /^[a-z0-9\\_\\-]+$/i,\n      },\n    },\n    query: {\n      type: DataTypes.JSON,\n    },\n  });\n  return Report;\n};\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.bulkInsert('Reports', [\n      {\n        name: 'users per channel',\n        platform: 'google',\n        query: {\n          \"viewId\": null,\n          \"dateRanges\": [\n            {\n              \"startDate\": null,\n              \"endDate\": null,\n            },\n          ],\n          \"samplingLevel\": \"DEFAULT\",\n          \"dimensions\": [\n            {\n              \"name\": \"ga:channelGrouping\",\n            },\n          ],\n          \"metrics\": [{ \"expression\": \"ga:users\" }],\n        },\n        createdAt: new Date(),\n        updatedAt: new Date(),\n      },\n    ]);\n  },\n\n  down: (queryInterface, Sequelize) => {},\n};\n```\n\n```text\nINSERT INTO \"Reports\" (id, name, platform, query, \"createdAt\", \"updatedAt\") VALUES (1, 'users per channel', 'google', '{\"viewId\":null,\"dateRanges\":[{\"startDate\":null,\"endDate\":null}],\"samplingLevel\":\"DEFAULT\",\"dimensions\":[{\"name\":\"ga:channelGrouping\"}],\"metrics\":[{\"expression\":\"ga:users\"}]}', '2018-04-15 08:55:12.449-05', '2018-04-15 08:55:12.449-05');\n```\n\n```text\nsequelize db:seed:all\n```\n\n```text\n'{\n   \"viewId\": null,\n   \"dateRanges\": [\n      {\n         \"startDate\": null,\n         \"endDate\": null,\n      },\n   ],\n   \"samplingLevel\": \"DEFAULT\",\n   \"dimensions\": [\n        {\n           \"name\": \"ga:channelGrouping\",\n        },\n    ],\n   \"metrics\": [{ \"expression\": \"ga:users\" }],\n}'\n```\n\n```text\nINSERT INTO \"Reports\" (id, name, platform, query, \"createdAt\", \"updatedAt\") VALUES (1, 'users per channel', 'google', '{\"viewId\":null,\"dateRanges\":[{\"startDate\":null,\"endDate\":null}],\"samplingLevel\":\"DEFAULT\",\"dimensions\":[{\"name\":\"ga:channelGrouping\"}],\"metrics\":[{\"expression\":\"ga:users\"}]}', '2018-04-15 08:55:12.449-05', '2018-04-15 08:55:12.449-05');\n```\n\n```text\nquery\n```\n\n========================================\n\nComments:\n- Possible duplicate of Error in creating seed file for sequalize involving DataTypes.JSON","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":203,"estimatedTokens":1201}}698{"id":"stack-55497199","source":"stackoverflow","questionId":55497199,"title":"(Sequelize) Using A Model By Name Dynamically","tags":["node.js","sequelize.js"],"text":"Title: (Sequelize) Using A Model By Name Dynamically\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm wondering if it is possible with Sequelize to create the needed models and then use one based on a value received from a request. I've tried different means to accomplish this but not finding a working solution. I accept it may not exist. But if so, does anyone have ideas on how to accomplish this?\n\n```\nconst express = require('express');\nconst router = express.Router();\nconst Models = require('../models');\n\n...\n\nfor (let modelName in tablesObj) {\n if (modelName == primaryTable) {\n Models.modelName.findAll()\n .then(results => {\n console.log(result);\n });\n }\n}\n```\n\n========================================\n\nTop Answer:\nFor me, there was no need to add/modify the `index.js` file. The `index.js` was already present inside models folder by default.\n\nBelow code `works for me!!`,\n\n```\nconst models = require(\"../../models\");\n let modeName, runningModel;\n\n router.get('/api/:module', (req, res) => {\n\n modelName = (req.params.module)\n runningModel = models[modelName];\n\n runningModel.findAndCountAll({\n //your code goes here\n })\n .then(resutls => res.json(results)\n .catch(err => res.json(err);\n }\n```\n\nThe following are the package and version used in my project\n\n```\n\"express\": \"^4.17.1\",\n\"morgan\": \"^1.10.0\",\n\"pg\": \"^8.2.1\",\n\"sequelize\": \"^5.21.4\",\n\"sequelize-cli\": \"^5.5.1\"\n```\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst router = express.Router();\nconst Models = require('../models');\n\n...\n\nfor (let modelName in tablesObj) {\n  if (modelName == primaryTable) {\n    Models.modelName.findAll()\n    .then(results => {\n      console.log(result);\n    });\n  }\n}\n```\n\n```text\nconst fs = require('fs');\nconst path = require('path');\nconst sequelize = // your db connection\n\n// object to hold all the models to export\nconst models = {};\n\n// Read all the files from this dir and load the models\nfs.readdirSync(__dirname)\n    .forEach((file) => {\n      if (file !== path.basename(__filename) && file.endsWith('.js')) {\n        const model = sequelize.import(\n            path.join(__dirname, '/', file.replace(/\\.js$/, ''))\n        );\n        models[model.name] = model;\n      }\n    });\n\n/* anything else you want to do goes here */\n\n// export the models\nmodule.exports = models;\n```\n\n```text\nconst models = require('../models');\n\nasync function runQuery() {\n  // access \"modelName\" model\n  const result = await models.modelName.findByPk(1);\n  // rest of your method\n}\n```\n\n```text\nconst Express = require('express');\nconst models = require('./models');\nconst app = new Express();\n\napp.model = (model) => models[model];\n```\n\n```text\n// assuming the model name is \"Widget\"\nconst widget = await app.models('Widget').findOne(...);\n```\n\n```text\n/models\n```\n\n```text\nModels\n```\n\n```text\nmodels\n```\n\n```text\nmodels\n```\n\n```text\napp\n```\n\n```text\nconst models = require(\"../../models\");\n    let modeName, runningModel;\n\n    router.get('/api/:module', (req, res) => {\n\n      modelName = (req.params.module)\n      runningModel = models[modelName];\n\n      runningModel.findAndCountAll({\n        //your code goes here\n      })\n      .then(resutls => res.json(results)\n      .catch(err => res.json(err);\n    }\n```\n\n```text\n\"express\": \"^4.17.1\",\n\"morgan\": \"^1.10.0\",\n\"pg\": \"^8.2.1\",\n\"sequelize\": \"^5.21.4\",\n\"sequelize-cli\": \"^5.5.1\"\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\nworks for me!!\n```\n\n========================================\n\nComments:\n- Thanks for the response, @doublesharp. I'll up once I put this into action.\n- UPDATE: I did not add that I was working with Express routers as well, but when I applied your use of setting the models as a property on the *request* with a router.use, it worked beautifully! Thank you again!","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":188,"estimatedTokens":953}}699{"id":"stack-51165181","source":"stackoverflow","questionId":51165181,"title":"graphql with sequelize join foreign key","tags":["sequelize.js","graphql"],"text":"Title: graphql with sequelize join foreign key\nTags: sequelize.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI made simple board api system with graphql.\n\nAnd I use sequelize(version 4) for connect to database.\n\n[schema.graphql]\n\n```\ntype Article {\n article_no: Int!\n subject: String!\n content: String!\n createdAt: String!\n updatedAt: String!\n comment: String\n}\n\ntype Comment {\n article_no: Int!\n content: String!,\n createdAt: String!\n}\n\ntype Query {\n articles: [Article]!\n article(article_no: Int!): Article\n comments: [Comment]!\n comment(article_no: Int!): Comment\n}\n\ntype Mutation {\n createArticle(subject: String!, content: String!, password: String!): Boolean!\n createComment(article_no: Int!, content: String!, password: String!): Boolean!\n}\n```\n\n[resolvers.js]\n\n```\nimport { Article, Comment } from './db';\n\nconst resolvers = {\n Query: {\n articles: async () => {\n return Article.all();\n },\n article: async(_, args) => {\n return Article.find({\n where: args.article_no,\n });\n },\n comments: async () => {\n return Comment.all();\n },\n comment: async(_, args) => {\n return Comment.find({\n where: args.article_no\n });\n }\n },\n Mutation: {\n createArticle: async (_, args) => {\n try {\n const article = await Article.create({\n subject: args.subject,\n content: args.content,\n password: args.password\n });\n return true;\n } catch(e) {\n return false;\n }\n },\n createComment: async(_, args) => {\n try {\n const comment = await Comment.create({\n article_no: args.article_no,\n content: args.content,\n password: args.password\n })\n return comment;\n } catch(e) {\n return false;\n }\n }\n }\n}\n\nexport default resolvers;\n```\n\n[db.js]\n\n```\nconst Sequelize = require('sequelize');\nimport config from '../config/config';\n\nconst db = new Sequelize(config.DB, config.USER, config.PASS, {\n host: 'localhost',\n dialect: 'mysql'\n})\n\nexport const Article = db.define('article', {\n article_no: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n subject: {\n type: Sequelize.STRING(30),\n allowNull: false\n },\n content: {\n type: Sequelize.STRING(100),\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(20),\n allowNull: false\n },\n comment: Sequelize.STRING\n}, {\n freezeTableName: true,\n timestamps: true,\n underscored: true\n})\n\nexport const Comment = db.define('comment', {\n content: {\n type: Sequelize.STRING(150),\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(20),\n allowNull: false\n },\n}, {\n freezeTableName: true,\n timestamps: true,\n underscored: true\n})\n\nArticle.hasMany(Comment, {\n foreignKey: 'article_no',\n scope: {\n comment: 'comment'\n }\n})\nComment.belongsTo(Article, {\n foreignKey: 'article_no',\n targetKey: 'article_no',\n allowNull: false,\n as: 'comment'\n});\ndb.sync()\n.then(console.log('[*] DB Sync Done'))\n```\n\n`Article` and `Comment` is 1:N realtionship.\n\nSo I set `hasMany` to `Article` and set `belongsTo` to `Comment`.\n\nAlso Comment as comment and include it to Article's scope.\n\nBut when I request query `{ article(id:1) { subject, comment } }`,\n\ncomment return null.\n\nI refer document http://docs.sequelizejs.com/manual/tutorial/associations.html#foreign-keys and as well.\n\nBut it doesn't work.\n\nMy Expected result is here:\n\n```\n{\n \"data\": {\n \"article\": {\n \"subject\": \"test\",\n \"comment\": {\n \"article_no\":1,\n \"content: \"first comment\",\n \"created_at\": \"2018010101001\",\n # every comment related article is here\n }\n }\n }\n}\n```\n\nCurrent result is here:\n\n```\n{\n \"data\": {\n \"article\": {\n \"subject\": \"test\",\n \"comment\": null\n }\n }\n}\n```\n\nI want to display all the comments that related specific article.\n\nIs there any solution about this?\n\nThanks.\n\n========================================\n\nTop Answer:\nThere are problems with your graphql schema, and your sequelize schema...\n\nLets look at your graphql schema\n\ntype Article {\n ...\n comment: String\n}\n\nYou wrote that Article and Comment have a 1:M relation\nbut here the comment field is of type string and not even an array of string\n\nthe correct type definition for Article should be (imo):\n\ntype Article {\n ...\n comments: [Comment] \n}\n\nnow if you make the adjustments to your sequelize schema that @Daniel-Rearden\nwrote in his answer your `Article` model should have a `comments` property so it will be returned by default from the `default resolver` of the `Article` type\n\n========================================\n\nCode:\n```text\ntype Article {\n    article_no: Int!\n    subject: String!\n    content: String!\n    createdAt: String!\n    updatedAt: String!\n    comment: String\n}\n\ntype Comment {\n    article_no: Int!\n    content: String!,\n    createdAt: String!\n}\n\ntype Query {\n    articles: [Article]!\n    article(article_no: Int!): Article\n    comments: [Comment]!\n    comment(article_no: Int!): Comment\n}\n\ntype Mutation {\n    createArticle(subject: String!, content: String!, password: String!): Boolean!\n    createComment(article_no: Int!, content: String!, password: String!): Boolean!\n}\n```\n\n```text\nimport { Article, Comment } from './db';\n\nconst resolvers = {\n    Query: {\n        articles: async () => {\n            return Article.all();\n        },\n        article: async(_, args) => {\n            return Article.find({\n                where: args.article_no,\n            });\n        },\n        comments: async () => {\n            return Comment.all();\n        },\n        comment: async(_, args) => {\n            return Comment.find({\n                where: args.article_no\n            });\n        }\n    },\n    Mutation: {\n        createArticle: async (_, args) => {\n            try {\n                const article = await Article.create({\n                    subject: args.subject,\n                    content: args.content,\n                    password: args.password\n                });\n                return true;\n            } catch(e) {\n                return false;\n            }\n        },\n        createComment: async(_, args) => {\n            try {\n                const comment = await Comment.create({\n                    article_no: args.article_no,\n                    content: args.content,\n                    password: args.password\n                })\n                return comment;\n            } catch(e) {\n                return false;\n            }\n        }\n    }\n}\n\nexport default resolvers;\n```\n\n```text\nconst Sequelize = require('sequelize');\nimport config from '../config/config';\n\nconst db = new Sequelize(config.DB, config.USER, config.PASS, {\n    host: 'localhost',\n    dialect: 'mysql'\n})\n\nexport const Article = db.define('article', {\n    article_no: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    subject: {\n        type: Sequelize.STRING(30),\n        allowNull: false\n    },\n    content: {\n        type: Sequelize.STRING(100),\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING(20),\n        allowNull: false\n    },\n    comment: Sequelize.STRING\n}, {\n    freezeTableName: true,\n    timestamps: true,\n    underscored: true\n})\n\nexport const Comment = db.define('comment', {\n    content: {\n        type: Sequelize.STRING(150),\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING(20),\n        allowNull: false\n    },\n}, {\n    freezeTableName: true,\n    timestamps: true,\n    underscored: true\n})\n\nArticle.hasMany(Comment, {\n    foreignKey: 'article_no',\n    scope: {\n        comment: 'comment'\n    }\n})\nComment.belongsTo(Article, {\n    foreignKey: 'article_no',\n    targetKey: 'article_no',\n    allowNull: false,\n    as: 'comment'\n});\ndb.sync()\n.then(console.log('[*] DB Sync Done'))\n```\n\n```text\n{\n  \"data\": {\n    \"article\": {\n      \"subject\": \"test\",\n      \"comment\": {\n           \"article_no\":1,\n           \"content: \"first comment\",\n           \"created_at\": \"2018010101001\",\n           # every comment related article is here\n      }\n    }\n  }\n}\n```\n\n```text\n{\n  \"data\": {\n    \"article\": {\n      \"subject\": \"test\",\n      \"comment\": null\n    }\n  }\n}\n```\n\n```text\nArticle\n```\n\n```text\nComment\n```\n\n```text\nhasMany\n```\n\n```text\nArticle\n```\n\n```text\nbelongsTo\n```\n\n```text\nComment\n```\n\n```text\n{ article(id:1) { subject, comment } }\n```\n\n```text\nArticle.findAll({ include: [Comment] })\n```\n\n```text\nArticle.addScope('defaultScope', {\n  include: [Comment],\n}, { override: true })\n```\n\n```text\nArticle.find({ where: { article_no: args.article_no } })\n\n// or possibly even\nArticle.find({ where: args })\n```\n\n```text\nArticle.hasMany(Comment)\n```\n\n```text\ncomments\n```\n\n```text\nArticle\n```\n\n```text\nComment\n```\n\n```text\nComment.belongsTo(Article)\n```\n\n```text\narticle\n```\n\n```text\nComment\n```\n\n```text\nArticle\n```\n\n```text\ninclude\n```\n\n```text\naddScope\n```\n\n```text\noverride\n```\n\n```text\ninclude\n```\n\n```text\nwhere\n```\n\n```text\nfind\n```\n\n```text\ntype Article {\n    ...\n    comment: String\n}\n```\n\n```text\ntype Article {\n    ...\n    comments: [Comment] \n}\n```\n\n```text\nArticle\n```\n\n```text\ncomments\n```\n\n```text\ndefault resolver\n```\n\n```text\nArticle\n```\n\n========================================\n\nComments:\n- You said `if you call Article.hasMany(Comment), this will create a comments property on the Article model and will affect the Comment model`. But after I check the database, there is no additional column. So I think, additional column doesn't apply to real database, right?\n- And, should I set both `Article.hasMany(Comment)` and `Comment.belongsTo(Article)` in 1:N relationship? Or just set one relationship between that?\n- If I remember correctly, either `hasMany` or `belongsTo` should create the appropriate column (in this case in the articles table). Whether you use one or the other, or both depends on, again, whether you need your Article model instance to have a `comments` property or you need your Comments model instance to have an `article` property (or both).\n- FWIW, when using `sequelize.sync()` you may need to set the `force` option to true to see your changes applied to your db (docs.sequelizejs.com/class/lib/&hellip;)\n- Thanks! I will try it.\n- `Comment[]` is throw errors `Syntax Error: Expected Name, found [`. Maybe `[Comment]` is correct way.","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":555,"estimatedTokens":2497}}700{"id":"stack-26080842","source":"stackoverflow","questionId":26080842,"title":"Sequelizejs - custom message for allowNull","tags":["validation","sequelize.js"],"text":"Title: Sequelizejs - custom message for allowNull\nTags: validation, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIf I have a model User:\n\n```\nvar User = sequelize.define('User', {\n name: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n notEmpty: {\n msg: 'not empty'\n }\n }\n },\n nickname: {\n type: Sequelize.STRING\n }\n});\n```\n\nHow can I specify a message for when name is null or not provided?\n\nThis code:\n\n```\nUser.create({}).complete(function (err, user) {\n console.log(err);\n console.log(user);\n});\n```\n\nProduces:\n\n```\n{ [SequelizeValidationError: Validation error]\n name: 'SequelizeValidationError',\n message: 'Validation error',\n errors: \n [ { message: 'name cannot be null',\n type: 'notNull Violation',\n path: 'name',\n value: null } ] }\n```\n\nThe message 'name cannot be null' is generated and doesn't appear to be under my control.\n\nUsing User.create({name:''}) shows me my custom message 'not empty':\n\n```\n{ [SequelizeValidationError: Validation error]\n name: 'SequelizeValidationError',\n message: 'Validation error',\n errors: \n [ { message: 'not empty',\n type: 'Validation error',\n path: 'name',\n value: 'not empty',\n __raw: 'not empty' } ] }\n```\n\nIs there a way to supply the message for allowNull ?\n\nThanks\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {\n  name: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    validate: {\n      notEmpty: {\n        msg: 'not empty'\n      }\n    }\n  },\n  nickname: {\n    type: Sequelize.STRING\n  }\n});\n```\n\n```text\nUser.create({}).complete(function (err, user) {\n  console.log(err);\n  console.log(user);\n});\n```\n\n```text\n{ [SequelizeValidationError: Validation error]\n  name: 'SequelizeValidationError',\n  message: 'Validation error',\n  errors: \n   [ { message: 'name cannot be null',\n       type: 'notNull Violation',\n       path: 'name',\n       value: null } ] }\n```\n\n```text\n{ [SequelizeValidationError: Validation error]\n  name: 'SequelizeValidationError',\n  message: 'Validation error',\n  errors: \n   [ { message: 'not empty',\n       type: 'Validation error',\n       path: 'name',\n       value: 'not empty',\n       __raw: 'not empty' } ] }\n```\n\n```text\nUser.create({}).then(function () { /* ... */ }).catch(Sequelize.ValidationError, function (e) {\n    var i;\n    for (i = 0; i < e.errors.length; i++) {\n      if (e.errors[i].type === 'notNull Violation') {\n        // Depending on your structure replace with a reference\n        // to the msg within your Model definition\n        e.errors[i].message = 'not empty';\n      }\n    }\n})\n```\n\n```text\nnotNull\n```\n\n```text\nSequelize.ValidationError\n```\n\n========================================\n\nComments:\n- Sorry, forgot to mention I'm using sequelize 2.0.0-rc1","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":143,"estimatedTokens":680}}701{"id":"stack-65533376","source":"stackoverflow","questionId":65533376,"title":"Nested inner join in Sequelize","tags":["node.js","sequelize.js"],"text":"Title: Nested inner join in Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to Inner Join five tables using **Sequelize**. I know I have to use `required: true` for inner join. But even after using the `required: true` it is not generating the query I am trying to achieve. Here, I have attached the code without the `required: true` statement. How should I place the `required: true` statement to inner join the five tables?\n\n```\nconst db = require('../models');\n\nconst data = await db.A.findAll({\n where: conditionA,\n include: [{\n model: db.B,\n where: conditionB,\n include: [\n {\n model: db.C,\n where: conditionC,\n include: [{\n model: db.D,\n where: conditionD\n }],\n },\n {\n model: db.E,\n where: conditionE,\n }\n ]\n }]\n});\n```\n\nModel associations\n\n```\ndb.A.hasMany(db.B);\ndb.C.hasMany(db.B);\ndb.E.hasMany(db.B);\ndb.D.hasMany(db.C);\n\ndb.B.belongsTo(db.A);\ndb.B.belongsTo(db.C);\ndb.B.belongsTo(db.E);\ndb.C.belongsTo(db.D);\n```\n\nAny help would be appreciated. Thanks in advance.\n\n========================================\n\nCode:\n```text\nconst db = require('../models');\n\nconst data = await db.A.findAll({\n    where: conditionA,\n    include: [{\n        model: db.B,\n        where: conditionB,\n        include: [\n            {\n                model: db.C,\n                where: conditionC,\n                include: [{\n                    model: db.D,\n                    where: conditionD\n                }],\n            },\n            {\n                model: db.E,\n                where: conditionE,\n            }\n        ]\n    }]\n});\n```\n\n```text\ndb.A.hasMany(db.B);\ndb.C.hasMany(db.B);\ndb.E.hasMany(db.B);\ndb.D.hasMany(db.C);\n\ndb.B.belongsTo(db.A);\ndb.B.belongsTo(db.C);\ndb.B.belongsTo(db.E);\ndb.C.belongsTo(db.D);\n```\n\n```text\nrequired: true\n```\n\n```text\nrequired: true\n```\n\n```text\nrequired: true\n```\n\n```text\nrequired: true\n```\n\n```text\nrequired: true\n```\n\n```text\ninclude\n```\n\n```text\nsubQuery: false\n```\n\n========================================\n\nComments:\n- Show model associations\n- I have edited the question.\n- Did you try `subQuery: false` option indicated in `A` options?\n- And yes, you should indicate `required: true` in all model's options in `include`'s\n- I haven't tried \"subQuery: false\". So I have edited the code as you said. Should I try this? Sorry for sharing the code here. await db.A.findAll({ where: conditionA, required: true, subQuery: false, include: [{ model: db.B, where: conditionB, required: true, include: [ { model: db.C, where: conditionC, required: true include: [{ model: db.D, where: conditionD, required: true }], }, { model: db.E, where: conditionE, required: true } ] }] });\n- Yes, but `required: true` in main options makes no sense, remove it.\n- Thank you so much. \"subQuery: false\" part worked. You can post it as the answer. One last query. Why do I need \"subQuery: false\"?","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":128,"estimatedTokens":713}}702{"id":"stack-18950886","source":"stackoverflow","questionId":18950886,"title":"SequelizeJS - hasMany to hasMany on the same table with a join table","tags":["mysql","sequelize.js"],"text":"Title: SequelizeJS - hasMany to hasMany on the same table with a join table\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy problem is quite simple:\n\nI got a table named **users**.\nThose users can have a lot of contacts. Those contacts are other users.\n\nSo I have a table named **userHasContacts**, with the id of the owner (**userID**), and the id of the contact (**contactID**).\n\nBoth of those foreign keys are referencing **users** table.\n\nHere is my beautiful diagram:\n\n```\n---------------- \n______________|____ ____|____\n| userHasContacts | | users |\n------------------- ---------\n| #userID | | id |\n| #contactID | ---------\n------------------- |\n | |\n ----------------\n```\n\nIn sequelize, in my logic, I would write:\n\n```\nUsers.hasMany(Users, {foreignKey: 'userID', joinTableName: 'userHasContacts'} );\nUsers.hasMany(Users, {as: 'Contacts', foreignKey: 'contactID', joinTableName: 'userHasContacts'} );\n```\n\nBut it seems like it doesn't work this way, and it's been 2 hours I am trying several ways to write this relation...\n\nThe only line that worked for me was\n\n```\nUsers.hasMany(UserHasContacts, {foreignKey: 'contactID', joinTableName: 'userHasContacts'} );\n\nUserHasContacts.findAndCountAll({ where: {userID: id} }).success( function(result) { \n res.json(result);\n});\n```\n\nBut then I cannot join **users** table in my find query (via Eager loading) and it simply returns the data inside **userHasContacts**.\n\nIf anyone got an hint, you are welcome!\n\nThanks by advance !\n\n========================================\n\nCode:\n```text\n----------------  \n______________|____      ____|____\n| userHasContacts |      | users |\n-------------------      ---------\n| #userID         |      | id    |\n| #contactID      |      ---------\n-------------------          |\n              |              |\n              ----------------\n```\n\n```text\nUsers.hasMany(Users, {foreignKey: 'userID', joinTableName: 'userHasContacts'} );\nUsers.hasMany(Users, {as: 'Contacts', foreignKey: 'contactID', joinTableName: 'userHasContacts'} );\n```\n\n```text\nUsers.hasMany(UserHasContacts, {foreignKey: 'contactID', joinTableName: 'userHasContacts'} );\n\nUserHasContacts.findAndCountAll({ where: {userID: id} }).success( function(result) {        \n    res.json(result);\n});\n```\n\n```text\nUser.hasMany(User, { as: 'Contacts', joinTableName: 'userHasContacts'})\n```\n\n```text\nCREATE TABLE IF NOT EXISTS `userHasContacts` (`userId` INTEGER , `ContactsId` INTEGER , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`userId`,`ContactsId`)) ENGINE=InnoDB;\n```\n\n```text\nUser.find({ where: ..., include: [{model: User, as: 'Contacts'}]})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":92,"estimatedTokens":661}}703{"id":"stack-51585833","source":"stackoverflow","questionId":51585833,"title":"How to query many to many relation in sequelize","tags":["sequelize.js","feathersjs","feathers-sequelize"],"text":"Title: How to query many to many relation in sequelize\nTags: sequelize.js, feathersjs, feathers-sequelize\nSource: Stack Overflow\n\nQuestion:\nI've been using feathersjs/nodejs over postgres db via sequelize. In my db i have Users table and Events table. They are twice in relation: \n\n```\nevents.belongsTo(models.users, {\n foreignKey: {\n name: 'creatorId',\n allowNull: false\n },\n onDelete: 'CASCADE',\n as: 'creator'\n});\n\nevents.belongsToMany(models.users, {\n through: 'event_participants',\n as: 'participants',\n foreignKey: 'eventId',\n otherKey: 'userId'\n});\nmodels.users.belongsToMany(events, {\n through: 'event_participants',\n as: 'events'\n});\n```\n\nEverything works just fine, table is created and with include im getting users inside of event as participants. Problem is querying by association. I'm trying to fetch events for current user, so I need events where creator is current user AND events where one of participants is current user. Problem is the second part 'querying where current user is one of participants'. I was expecting something like this \n\n`'api/events?$or[0][creatorId]=currUserId&$or[1][participants][$contains]=currUserId'`\n\nbut its not working cause there is no such column as 'participants' its being included so i cant query it. So for now I'm just fetching all events and filtering them for current user in after hooks, but it just seems wrong. What is the right way to do this? \n\nAnd yea I know I can get events where user is one of participants by including them into user and fetching him but problem with that is i cant sort that data all together, its being sorted separately and another problem is doin pagination on frontend.\n\n========================================\n\nTop Answer:\nWith the help of @daff 's answer I found my solution like this... Error that I was getting can be found here.\n\n```\nconst { authenticate } = require('@feathersjs/authentication').hooks;\n\nfunction includeBefore(hook) {\n currUserId = hook.params.user.id;\n userModel = hook.app.services.users.Model\n hook.params.sequelize = {\n where: {\n $or: [\n {\n creatorId: currUserId\n },\n {\n '$participants.id$': currUserId //no idea what are '$$' for but it made it work\n }\n ]\n },\n include: [\n {\n model: userModel,\n as: 'creator',\n }, {\n model: userModel,\n as: 'participants',\n duplicating: false //fixed error that I was getting \n }\n ],\n }\n return hook;\n}\n\nmodule.exports = {\n before: {\n all: [\n authenticate('jwt'),\n hook => includeBefore(hook)\n ],\n.........\n```\n\n========================================\n\nCode:\n```text\nevents.belongsTo(models.users, {\n  foreignKey: {\n    name: 'creatorId',\n    allowNull: false\n  },\n  onDelete: 'CASCADE',\n  as: 'creator'\n});\n\nevents.belongsToMany(models.users, {\n  through: 'event_participants',\n  as: 'participants',\n  foreignKey: 'eventId',\n  otherKey: 'userId'\n});\nmodels.users.belongsToMany(events, {\n  through: 'event_participants',\n  as: 'events'\n});\n```\n\n```text\n'api/events?$or[0][creatorId]=currUserId&$or[1][participants][$contains]=currUserId'\n```\n\n```js\n// GET /my-service?name=John&include=1\n    function (context) {\n       if (context.params.query.include) {\n          const AssociatedModel = context.app.services.fooservice.Model;\n          context.params.sequelize = {\n             include: [{\n               model: AssociatedModel\n               // normal Sequelize where query here\n              }]\n          };\n          // delete any special query params so they are not used\n          // in the WHERE clause in the db query.\n          delete context.params.query.include;\n       }\n\n       return Promise.resolve(context);\n    }\n```\n\n```text\nconst { authenticate } = require('@feathersjs/authentication').hooks;\n\nfunction includeBefore(hook) {\n  currUserId = hook.params.user.id;\n  userModel = hook.app.services.users.Model\n  hook.params.sequelize = {\n    where: {\n      $or: [\n        {\n          creatorId: currUserId\n        },\n        {\n          '$participants.id$': currUserId  //no idea what are '$$' for but it made it work\n        }\n      ]\n    },\n    include: [\n      {\n        model: userModel,\n        as: 'creator',\n      }, {\n        model: userModel,\n        as: 'participants',\n        duplicating: false //fixed error that I was getting \n      }\n    ],\n  }\n  return hook;\n}\n\n\nmodule.exports = {\n  before: {\n    all: [\n      authenticate('jwt'),\n      hook => includeBefore(hook)\n    ],\n.........\n```\n\n========================================\n\nComments:\n- add your query here\n- @Priyank what query? I said I'm fetching all the data and filtering it in after hooks, so there is no query, its just 'api/events' .. the one I thought would work is already up there.\n- thanks for the answer.. correct me if im wrong, but if im including participants in events this gonna give me filtered participants instead of events? this basically says events include participants where *some query*... but instead i want to get events where *one of participants is current user*\n- Try writing the query directly with just Sequelize as shown in the Testing queries in isolation chapter. After that it usually makes much more sense how to integrate it into the hook.","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":179,"estimatedTokens":1280}}704{"id":"stack-33662670","source":"stackoverflow","questionId":33662670,"title":"Error: null value in column \"id\" violates not-null constraint in sequelize","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Error: null value in column \"id\" violates not-null constraint in sequelize\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to change the Datatype of my primarykey to String in sequelize and am getting the following error while trying to create using upsert.\n\n```\nerror: SequelizeDatabaseError: null value in column \"id\" violates not-null constraint\n```\n\nhere is the code:\n\n```\nid: {\n type: DataTypes.STRING,\n primaryKey: true,\n allowNull: true,\n autoIncrement: false,\n field: \"id\"\n }\n```\n\nHow do I make this work? \nthanks in advance.\n\n========================================\n\nCode:\n```text\nerror:  SequelizeDatabaseError: null value in column \"id\" violates not-null constraint\n```\n\n```text\nid: {\n      type: DataTypes.STRING,\n      primaryKey: true,\n      allowNull: true,\n      autoIncrement: false,\n      field: \"id\"\n    }\n```\n\n```text\n...\n    allowNull: false,\n  ...\n```\n\n========================================\n\nComments:\n- Are you saying I can't change the datatype of primary key?\n- You can change the type of primary key, but it is always **not null**.\n- how do I change it to a string type?\n- Try with `allowNull: false`.\n- You can change the type with this SQL: `alter table *table_name* alter id type text`. Unfortunately, I don't use sequelize.","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":57,"estimatedTokens":326}}705{"id":"stack-49836049","source":"stackoverflow","questionId":49836049,"title":"Associations in sequelize not working as intended","tags":["javascript","postgresql","sequelize.js"],"text":"Title: Associations in sequelize not working as intended\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am attempting to output a nested relation where\n\nCat.hasMany(legs)\n\nLeg.belongsTo(cat)\n\nLeg.hasOne(paw)\n\npaw.hasMany(leg)\n\nHere is my Cat Model:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Cat = sequelize.define('Cat', {\n userId: {\n type: DataTypes.STRING,\n },\n }, {});\n\n Cat.associate = function (models) {\n Cat.hasMany(models.Leg, {\n foreignKey: 'catId',\n as: 'legs',\n });\n };\n return Cat;\n};\n```\n\nMy Legs Model:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Leg = sequelize.define('Leg', {\n originalValue: DataTypes.JSON,\n newValue: DataTypes.JSON,\n legId: DataTypes.INTEGER,\n objectId: DataTypes.INTEGER,\n pawId: DataTypes.INTEGER,\n }, {});\n\n Leg.associate = function (models) {\n Leg.belongsTo(models.Cat, {\n foreignKey: 'LegId',\n onDelete: 'CASCADE',\n });\n Leg.hasOne(models.Paw, {\n foreignKey: 'pawId',\n });\n };\n return Leg;\n};\n```\n\nHere is my Paw model\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Paw = sequelize.define('Paw', {\n pawType: DataTypes.STRING,\n }, {});\n Paw.associate = function (models) {\n Paw.hasMany(models.Leg, {\n foreignKey: 'pawId',\n as: 'paws',\n });\n };\n return Paw;\n};\n```\n\nCurrently My code is outputting this when i query the Cat Table\n\n```\n[\n {\n \"id\": 1,\n \"userId\": \"2wdfs\",\n \"createdAt\": \"2018-04-14T20:12:47.112Z\",\n \"updatedAt\": \"2018-04-14T20:12:47.112Z\",\n \"legs\": [\n {\n \"id\": 1,\n \"catId\": 1,\n \"pawId\": 1,\n \"createdAt\": \"2018-04-14T20:12:54.500Z\",\n \"updatedAt\": \"2018-04-14T20:12:54.500Z\"\n }\n ]\n }\n]\n```\n\nHowever I would like the pawType from the paws table to also be present when listing everything from the cat table. Something more along the lines of this:\n\n```\n[\n {\n \"id\": 1,\n \"userId\": \"2wdfs\",\n \"createdAt\": \"2018-04-14T20:12:47.112Z\",\n \"updatedAt\": \"2018-04-14T20:12:47.112Z\",\n \"legs\": [\n {\n \"id\": 1,\n \"catId\": 1,\n \"paws\" : [\n {\n \"id\": 1,\n \"pawType\": \"cute\"\n }\n ]\n \"createdAt\": \"2018-04-14T20:12:54.500Z\",\n \"updatedAt\": \"2018-04-14T20:12:54.500Z\"\n }\n ]\n }\n]\n```\n\nAdditionally, Here is the query I am using to retrieve the Cats.\n\n```\nreturn Cat.findAll({ include: [{ model: Leg, as: 'legs',include [{model: Paw,}], }], })\n```\n\nThis is the error that is returning,\n\n```\n{ SequelizeDatabaseError: column legs->Paw.pawId does not exist\n{ error: column legs->Paw.pawId does not exist\n```\n\nAnd the full SQL command\n\n```\nsql: 'SELECT \"Cat\".\"id\", \"Cat\".\"userId\", \"Cat\".\"createdAt\", \"Cat\".\"updatedAt\", \"legs\".\"id\" AS \"legs.id\", \"legs\".\"originalValue\" AS \"legs.originalValue\", \"legs\".\"newValue\" AS \"legs.newValue\", \"legs\".\"catId\" AS \"legs.catId\", \"legs\".\"objectId\" AS \"legs.objectId\", \"legs\".\"pawId\" AS \"legs.pawId\", \"legs\".\"createdAt\" AS \"legs.createdAt\", \"legs\".\"updatedAt\" AS \"legs.updatedAt\", \"legs->Paw\".\"id\" AS \"legs.Paw.id\", \"legs->Paw\".\"paw\" AS \"legs.Paw.paw\", \"legs->Paw\".\"pawId\" AS \"legs.Paw.pawId\", \"legs->Paw\".\"createdAt\" AS \"legs.Paw.createdAt\", \"legs->Paw\".\"updatedAt\" AS \"legs.Paw.updatedAt\" FROM \"Cats\" AS \"Cat\" LEFT OUTER JOIN \"Legs\" AS \"legs\" ON \"Cat\".\"id\" = \"legs\".\"catId\" LEFT OUTER JOIN \"Paws\" AS \"legs->Paw\" ON \"legs\".\"id\" = \"legs->Paw\".\"pawId\";' },\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Cat = sequelize.define('Cat', {\n    userId: {\n      type: DataTypes.STRING,\n    },\n  }, {});\n\n  Cat.associate = function (models) {\n    Cat.hasMany(models.Leg, {\n      foreignKey: 'catId',\n      as: 'legs',\n    });\n  };\n  return Cat;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Leg = sequelize.define('Leg', {\n    originalValue: DataTypes.JSON,\n    newValue: DataTypes.JSON,\n    legId: DataTypes.INTEGER,\n    objectId: DataTypes.INTEGER,\n    pawId: DataTypes.INTEGER,\n  }, {});\n\n  Leg.associate = function (models) {\n    Leg.belongsTo(models.Cat, {\n      foreignKey: 'LegId',\n      onDelete: 'CASCADE',\n    });\n    Leg.hasOne(models.Paw, {\n      foreignKey: 'pawId',\n    });\n  };\n  return Leg;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Paw = sequelize.define('Paw', {\n    pawType: DataTypes.STRING,\n  }, {});\n  Paw.associate = function (models) {\n    Paw.hasMany(models.Leg, {\n      foreignKey: 'pawId',\n      as: 'paws',\n    });\n  };\n  return Paw;\n};\n```\n\n```text\n[\n    {\n        \"id\": 1,\n        \"userId\": \"2wdfs\",\n        \"createdAt\": \"2018-04-14T20:12:47.112Z\",\n        \"updatedAt\": \"2018-04-14T20:12:47.112Z\",\n        \"legs\": [\n            {\n                \"id\": 1,\n                \"catId\": 1,\n                \"pawId\": 1,\n                \"createdAt\": \"2018-04-14T20:12:54.500Z\",\n                \"updatedAt\": \"2018-04-14T20:12:54.500Z\"\n            }\n        ]\n    }\n]\n```\n\n```text\n[\n    {\n        \"id\": 1,\n        \"userId\": \"2wdfs\",\n        \"createdAt\": \"2018-04-14T20:12:47.112Z\",\n        \"updatedAt\": \"2018-04-14T20:12:47.112Z\",\n        \"legs\": [\n            {\n                \"id\": 1,\n                \"catId\": 1,\n                \"paws\" : [\n                   {\n                    \"id\": 1,\n                    \"pawType\": \"cute\"\n                   }\n                ]\n                \"createdAt\": \"2018-04-14T20:12:54.500Z\",\n                \"updatedAt\": \"2018-04-14T20:12:54.500Z\"\n            }\n        ]\n    }\n]\n```\n\n```text\nreturn Cat.findAll({ include: [{ model: Leg, as: 'legs',include [{model: Paw,}], }], })\n```\n\n```text\n{ SequelizeDatabaseError: column legs->Paw.pawId does not exist\n{ error: column legs->Paw.pawId does not exist\n```\n\n```text\nsql: 'SELECT \"Cat\".\"id\", \"Cat\".\"userId\", \"Cat\".\"createdAt\", \"Cat\".\"updatedAt\", \"legs\".\"id\" AS \"legs.id\", \"legs\".\"originalValue\" AS \"legs.originalValue\", \"legs\".\"newValue\" AS \"legs.newValue\", \"legs\".\"catId\" AS \"legs.catId\", \"legs\".\"objectId\" AS \"legs.objectId\", \"legs\".\"pawId\" AS \"legs.pawId\", \"legs\".\"createdAt\" AS \"legs.createdAt\", \"legs\".\"updatedAt\" AS \"legs.updatedAt\", \"legs->Paw\".\"id\" AS \"legs.Paw.id\", \"legs->Paw\".\"paw\" AS \"legs.Paw.paw\", \"legs->Paw\".\"pawId\" AS \"legs.Paw.pawId\", \"legs->Paw\".\"createdAt\" AS \"legs.Paw.createdAt\", \"legs->Paw\".\"updatedAt\" AS \"legs.Paw.updatedAt\" FROM \"Cats\" AS \"Cat\" LEFT OUTER JOIN \"Legs\" AS \"legs\" ON \"Cat\".\"id\" = \"legs\".\"catId\" LEFT OUTER JOIN \"Paws\" AS \"legs->Paw\" ON \"legs\".\"id\" = \"legs->Paw\".\"pawId\";' },\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  var Leg = sequelize.define('Leg', {\n    originalValue: DataTypes.JSON,\n    newValue: DataTypes.JSON,\n    objectId: DataTypes.INTEGER // not entirely sure what this is \n  })\n  Leg.associate = function (models) {\n    // associations\n  }\n  return Leg\n}\n```\n\n```text\nLeg.hasOne(Paw)\nPaw.hasMany(Leg)\n\nUnhandled rejection Error: Cyclic dependency found. Legs is dependent of itself.\nDependency chain: Legs -> Paws => Legs\n```\n\n```text\nLeg.associate = function (models) {\n  // Leg.belongsTo(models.Cat)\n  Leg.hasOne(models.Paw, {\n    foreignKey: 'pawId',\n    as: 'paw'\n  })\n}\n\nPaw.associate = function (models) {\n  Paw.belongsTo(models.Leg, {\n    as: 'leg' // note this changed to make more sense\n    foreignKey: 'pawId'\n  })\n}\n```\n\n```text\nLeg.belongsTo(models.Cat, {\n  foreignKey: 'catId', // this should match\n  onDelete: 'CASCADE'\n})\n\nCat.hasMany(models.Leg, {\n  foreignKey: 'catId', // this should match\n  as: 'legs'\n})\n```\n\n```text\nCat.findAll({\n  include: [{\n    model: Leg,\n    as: 'legs', // Cat.legs \n    include: [{\n      model: Paw,\n      as: 'paw' // Leg.paw instead of Leg.pawId\n    }]\n  }]\n})\n```\n\n```text\n[\n  {\n    \"id\": 1,\n    \"userId\": \"1\",\n    \"createdAt\": \"2018-04-15T11:22:59.888Z\",\n    \"updatedAt\": \"2018-04-15T11:22:59.888Z\",\n    \"legs\": [\n      {\n        \"id\": 1,\n        \"originalValue\": null,\n        \"newValue\": null,\n        \"objectId\": null,\n        \"createdAt\": \"2018-04-15T11:22:59.901Z\",\n        \"updatedAt\": \"2018-04-15T11:22:59.901Z\",\n        \"catId\": 1,\n        \"paw\": {\n          \"id\": 1,\n          \"pawType\": null,\n          \"createdAt\": \"2018-04-15T11:22:59.906Z\",\n          \"updatedAt\": \"2018-04-15T11:22:59.906Z\",\n          \"pawId\": 1\n        }\n      }\n    ]\n  }\n]\n```\n\n```text\nPaw.associate = function (models) {\n  Paw.belongsToMany(models.Leg, {\n    foreignKey: 'pawId',\n    through: 'PawLegs  // a through join table MUST be defined\n  })\n}\n```\n\n```text\nLeg.hasOne(paw)\npaw.hasMany(leg)\n```\n\n```text\nprimaryKey\n```\n\n```text\nid\n```\n\n```text\nlegId\n```\n\n```text\nforeignKey\n```\n\n```text\npawId\n```\n\n```text\nLegs.js\n```\n\n```text\npgAdmin\n```\n\n```text\nLeg\n```\n\n```text\nPaw\n```\n\n```text\ninclude\n```\n\n```text\nas\n```\n\n```text\nPaw\n```\n\n```text\nbelongsToMany\n```\n\n========================================\n\nComments:\n- Additionally, Here is the query I am using to retrieve the Cats. `return Cat.findAll({ include: [{ model: Leg, as: 'legs', }], })`\n- I tried this, however, it returns an error. I updated my question to include the query as well as the error that is being returned. Thank you in advance.\n- I've done a massive update to my answer. In the future, do not update your question based off of an answer right away. Instead use the comment section and let the user that answered update their answer. Only update the question based on comments made directly to the question or as a final resort (say the answer user becomes non-responsive). This is because modifying a question completely invalidates existing answers.\n- Hey thanks for your update. This helps me understand associations much better. I do have one question regarding paw and leg through join. Lets say i had a list of paws in a table and i wanted my 'legs' table to be able to add the id of any paw within the paw table, how would i go about doing that. Similar to this: `\"legs\": [ { \"id\": 20, \"catId\": 1, \"pawId\": 3 \"paw\": { \"id\": 3, \"pawType\": null, \"createdAt\": \"2018-04-15T11:22:59.906Z\", \"updatedAt\": \"2018-04-15T11:22:59.906Z\", } } ]`\n- No problem at all. Sorry for the additional commentary, just trying to help explain how the site works (most of what I said is available in the help center). If you're only adding a single paw `id` per `leg`, then you have a **one-to-one** relationship. Use `hasOne` and `belongsTo`. Otherwise I'm not sure I entirely get the question unfortunately.\n- In your edited comment, you have `pawId` and `paw.id` - it's redundant. I think you may find it helpful to read very carefully the **target** and **source** in the associations documentation. In a `source.hasOne(target)` relationship, the `target` gets a column `sourceId`. **HasOne associations are associations where the foreign key for the one-to-one relation exists on the target model.**. You wouldn't want a `pawId` column on `Leg`, AND a `LegId` column on `Paw` in a *one-to-one* relationship.\n- It seems as thou in the example above, the leg `id` and the `pawId` have to match in order for `paw` to be included in the output, however is there a way to specify `pawId` in the `legs` table so that the output includes whatever is found in the `paws` table that matches the `pawId` residing in the `legs` table?\n- I will say that I can't figure out a use-case for that, but it is possible. you'll need to do something like: `Leg.findAll({ include: [{ model: Paw, where: { id: &#47;&#47; use this } }] })`\n- Ahh ok great. Thanks so much for the help!\n- No problem. Just be aware that if you delete the `Paw` with `id` you're referencing in that column, you have to also delete it there as well (hence why it's not very practical to do this). Upvoted question, thanks for accepting my answer. If you found it useful, please upvote the answer as well. Hope everything helped.","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":434,"estimatedTokens":2870}}706{"id":"stack-47404648","source":"stackoverflow","questionId":47404648,"title":"Sequelize query on join table","tags":["node.js","sequelize.js"],"text":"Title: Sequelize query on join table\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to querying a join table using sequelize:\nHere is the model:\n\n```\ndb.client.belongsToMany(db.user, {\n through: db.clientUser,\n onDelete: 'cascade',\n});\ndb.user.belongsToMany(db.client, {\n through: db.clientUser,\n });\n```\n\nand this is what I am trying to do:\n\n```\ndb.user.findAll({\n where: {\n group_id: 1,\n },\n include: [{\n model: db.clientUser,\n where: {\n is_manager: 1,\n }\n }],\n raw: true,\n })\n```\n\nHowever I get the following error: `client_user is not associated to user!`\n\nAny idea what could be the cause of this issue?\n\n========================================\n\nCode:\n```text\ndb.client.belongsToMany(db.user, {\n  through: db.clientUser,\n   onDelete: 'cascade',\n});\ndb.user.belongsToMany(db.client, {\n   through: db.clientUser,\n });\n```\n\n```text\ndb.user.findAll({\n      where: {\n        group_id: 1,\n      },\n      include: [{\n        model: db.clientUser,\n        where: {\n          is_manager: 1,\n        }\n      }],\n      raw: true,\n    })\n```\n\n```text\nclient_user is not associated to user!\n```\n\n```text\ndb.user.findAll({\n  where: {\n    group_id: 1,\n  },\n  include: [{\n    model: db.client,\n    through: {\n      where: {\n        is_manager: 1, // Assuming clientUser.is_manager?\n      },\n    }],\n  raw: true,\n})\n```\n\n```text\nclient\n```\n\n```text\nuser\n```\n\n```text\nclientUser\n```\n\n```text\nclient\n```\n\n```text\nclientUser\n```\n\n```text\nbelongsToMany\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":110,"estimatedTokens":367}}707{"id":"stack-52070119","source":"stackoverflow","questionId":52070119,"title":"How to INSERT a reference to UUID from another table in PostgreSQL?","tags":["sql","postgresql","sequelize.js","uuid"],"text":"Title: How to INSERT a reference to UUID from another table in PostgreSQL?\nTags: sql, postgresql, sequelize.js, uuid\nSource: Stack Overflow\n\nQuestion:\nI'm learning to use Sequelize to use with a PostgreSQL database. All of the following is happening on a dev. environment. This happened while manually trying to insert data into my tables to check if things are setup correctly through Sequelize, check on failing unit tests, etc.\n\nI've made two tables with Sequelize models: User and Publication. Both these tables are generating UUIDv4. I've associated the User `hasMany` Publications, and Publication `belongsTo` User (you may reference the extra info).\n\nOn my `psql` shell, I've inserted the following record to my User table (rest of the data cut out for brevity):\n\n```\n| id | firstName | lastName | ..| \n|----------------------------------------|------------|-----------|---|\n| 8c878e6f-ee13-4a37-a208-7510c2638944 | Aiz | .... |...|\n```\n\nNow I'm trying to insert a record into my Publication table while referencing my newly created user above. Here's what I entered into the shell:\n\n```\nINSERT INTO \"Publications\"(\"title\", \"fileLocation\", ..., \"userId\")VALUES('How to Pasta', 'www.pasta.com', ..., 8c878e6f-ee13-4a37-a208-7510c2638944);\n```\n\nIt fails and I receive the following error:\n\n```\nERROR: syntax error at or near \"c878e6f\"\nLINE 1: ...8c878e6f-ee...\n```\n\n(it points to the second character on the terminal in LINE 1 reference - the 'c').\n\n**What's wrong here? Are we supposed to enter UUIDs another way if we want to do it manually in psql? Do we paste the referenced UUID as a string? Is there a correct way I'm missing from my own research?**\n\n### Some extra info if it helps:\n\nFrom my models:\n\n```\nPublication.associate = function(models) {\n // associations can be defined here\n Publication.belongsTo(models.User, {\n foreignKey: \"userId\" \n });\n};\n```\n\nand\n\n```\nUser.associate = function(models) {\n // associations can be defined here\n User.hasMany(models.Publication, {\n foreignKey: \"userId\",\n as: \"publications\"\n });\n};\n```\n\nHere's how I've defined `userId` in Publication:\n\n```\nuserId: {\n type: DataTypes.UUID,\n references: {\n model: \"User\",\n key: \"id\",\n as: \"userId\"\n }\n}\n```\n\nIf it's worth anything, my (primaryKey) `id` on both models are `type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4` (I don't know if this is an issue).\n\n========================================\n\nCode:\n```text\n|                   id                   |  firstName | lastName  | ..| \n|----------------------------------------|------------|-----------|---|\n|  8c878e6f-ee13-4a37-a208-7510c2638944  |   Aiz      |    ....   |...|\n```\n\n```text\nINSERT INTO \"Publications\"(\"title\", \"fileLocation\", ..., \"userId\")VALUES('How to Pasta', 'www.pasta.com', ..., 8c878e6f-ee13-4a37-a208-7510c2638944);\n```\n\n```text\nERROR:  syntax error at or near \"c878e6f\"\nLINE 1: ...8c878e6f-ee...\n```\n\n```text\nPublication.associate = function(models) {\n  // associations can be defined here\n  Publication.belongsTo(models.User, {\n    foreignKey: \"userId\" \n  });\n};\n```\n\n```text\nUser.associate = function(models) {\n  // associations can be defined here\n  User.hasMany(models.Publication, {\n    foreignKey: \"userId\",\n    as: \"publications\"\n  });\n};\n```\n\n```text\nuserId: {\n  type: DataTypes.UUID,\n  references: {\n    model: \"User\",\n    key: \"id\",\n    as: \"userId\"\n  }\n}\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsTo\n```\n\n```text\npsql\n```\n\n```text\nuserId\n```\n\n```text\nid\n```\n\n```text\ntype: DataTypes.UUID, defaultValue: DataTypes.UUIDV4\n```\n\n```text\nINSERT INTO \"Publications\"(\"title\", \"fileLocation\", ..., \"userId\")VALUES('How to Pasta', 'www.pasta.com', ..., '8c878e6f-ee13-4a37-a208-7510c2638944');\n```\n\n```text\nINSERT INTO \"Publications\"(\"title\", \"fileLocation\", ..., \"userId\")VALUES('How to Pasta', 'www.pasta.com', ..., '{8c878e6f-ee13-4a37-a208-7510c2638944}');\n```\n\n========================================\n\nComments:\n- Thank you. I wasn't sure if this was the case since postgres has a UUID type. However, it seems that the type is only useful for generating UUIDs vs storing into as a string in reference fields. Nevertheless, this makes the manual entry work.\n- If you've declared your column type as uuid then when you pass the string pgsql will cast and store it as a uuid, surely.. It is passed as a string as without it it looks like things subtracted from each other, hence th syntax error. They probably could have come up with some other delimiter but that is more work for developers to remember yet another quirk, when casting from a string is easy and works and nothing to remember :)","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":159,"estimatedTokens":1144}}708{"id":"stack-49761768","source":"stackoverflow","questionId":49761768,"title":"How to do \"WHERE\" in Sequelize, but EXCLUDE nested Model?","tags":["node.js","sequelize.js"],"text":"Title: How to do \"WHERE\" in Sequelize, but EXCLUDE nested Model?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThere are two models: User and Client.\n\n```\nClient.hasMany(User);\nUser.belongsTo(Client);\n```\n\nNext, I'm doing:\n\n```\nUser.findAll({\n include: [{\n model: Client,\n where: {\n id: “1”\n }\n }]\n});\n```\n\nThis code works fine, but includes Client model in final output with all attributes. How can I still do “where” statement, but exlcude Client model at all?\n\n========================================\n\nTop Answer:\nIts a little janky and not *really* what you want but I had a similar situation and I solved it like this.\n\n```\nnew Promise((resolve, reject) => {\n User.findAll({\n include: [{\n model: Client,\n where: {\n id: \"1\"\n }\n }]\n }).then(users => {\n users.forEach(u => u.client = null);\n resolve(users);\n }).catch(e => {\n reject(e);\n });\n});\n```\n\nSo your wrapping the request in a promise and grading the result of the querying, removing the property you don't want (I just nulled it out but you could get more creative mapping the object if wanted), then return the object as you like.\n\n**TLDR;**\n\nYou can't (afaik). You have to do something like this if your **absolutely** do not want the client in the response.\n\n========================================\n\nCode:\n```text\nClient.hasMany(User);\nUser.belongsTo(Client);\n```\n\n```text\nUser.findAll({\n    include: [{\n        model: Client,\n        where: {\n            id: “1”\n        }\n    }]\n});\n```\n\n```text\nUser.findAll({\n    attributes : ['User.*'] // might be user.* or users.* . as per your query genetaion\n    include: [{\n        model: Client,\n        where: {\n            id: \"1\"\n        }\n    }]\n});\n\n//OR\n\n{\n  attributes: {\n    include: [], // define columns that you want to show\n    exclude: [] // define columns that you don't want \n  }\n}\n```\n\n```text\nnew Promise((resolve, reject) => {\n  User.findAll({\n    include: [{\n      model: Client,\n      where: {\n        id: \"1\"\n      }\n    }]\n  }).then(users => {\n    users.forEach(u => u.client = null);\n    resolve(users);\n  }).catch(e => {\n    reject(e);\n  });\n});\n```\n\n========================================\n\nComments:\n- To be clear, you still want to query based on the client but you just don't need that object back in the response?","metadata":{"transformedAt":"2026-08-18T18:33:34.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":118,"estimatedTokens":568}}709{"id":"stack-64350040","source":"stackoverflow","questionId":64350040,"title":"Sequelize bulkcreate is throwing error that syntax error at or near \")\"","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize bulkcreate is throwing error that syntax error at or near \")\"\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHere I am updating `user_features` in database and I found from ***here*** that I can Bulk update through `updateOnDuplicate:` But it's throwing error like below\n\n```\nSequelizeDatabaseError: syntax error at or near \")\"\n```\n\nI have tried `updateOnDuplicate: true` but it only supports in mysql not in postgresql\n\n```\nvar feature_body_list = [];\n\n for (let index = 0; index but when I remove updateonDuplicate it works perfectly and throws UniqueConstraintError duplication of key\nso, how can I bulk update ???\n\n========================================\n\nCode:\n```text\nSequelizeDatabaseError: syntax error at or near \")\"\n```\n\n```text\nvar feature_body_list = [];\n\n        for (let index = 0; index < req.body.features.length; index++) {\n            let feature_body = {\n                user_id: req.body.id,\n                feature_id: req.body.features[index]\n            }\n            feature_body_list.push(feature_body);\n        }\n\n        await sequelize.user_features.bulkCreate(feature_body_list, { updateOnDuplicate: [\"user_id\", \"feature_id\"] });\n```\n\n```text\nuser_features\n```\n\n```text\nupdateOnDuplicate:\n```\n\n```text\nupdateOnDuplicate: true\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":51,"estimatedTokens":326}}710{"id":"stack-57680942","source":"stackoverflow","questionId":57680942,"title":"Sequelize get data of another column while using Aggregate Function","tags":["node.js","sql-server","sequelize.js"],"text":"Title: Sequelize get data of another column while using Aggregate Function\nTags: node.js, sql-server, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get data using **Sequelize** in my **Express** app and I'm using **SQL Server** as database.\n\nHere is my code:\n\n```\nOrder.findAll({\n attributes:[\n [Sequelize.fn('SUM', Sequelize.col('total_price')), 'total_price'],\n ],\n include:[\n {model: Customer, attributes:['name']}\n ],\n group:['Customer.id','Customer.name']\n}).then(result =>res.json(result))\n```\n\nThis code is running well, and successfully returns the data with *aggregate function*. But when I did added another attribute like `'product_id', 'status', 'expired_date'` that doesn't need aggregation, it returns me an error like\n\n Column 'Customer.product_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.\n\nBased on this article, it only can get columns which are in the GROUP BY list.\n\nBut how is the best way get the added attribute and the aggregation result? Like:\n\n```\n{\n 'total_price': 2000,\n 'name': 'Jack',\n 'status': 'Paid'\n}\n```\n\nShould do 2 get data in a function, like first I get the aggregate, and then get another data. I'm worried there are possibilities return unrelated data.\n\n========================================\n\nCode:\n```text\nOrder.findAll({\n    attributes:[\n        [Sequelize.fn('SUM', Sequelize.col('total_price')), 'total_price'],\n    ],\n    include:[\n        {model: Customer, attributes:['name']}\n    ],\n    group:['Customer.id','Customer.name']\n}).then(result =>res.json(result))\n```\n\n```text\n{\n     'total_price': 2000,\n     'name': 'Jack',\n     'status': 'Paid'\n}\n```\n\n```text\n'product_id', 'status', 'expired_date'\n```\n\n```text\nOrder.findAll({\nattributes:[\n    'product_id', 'status', 'expired_date',\n    [Sequelize.fn('SUM', Sequelize.col('total_price')), 'total_price'],\n],\ninclude:[\n    {model: Customer, attributes:['name']}\n],\ngroup:['Customer.id','Customer.name','Order.product_id', 'Order.status', 'Order.expired_date']\n}).then(result =>res.json(result))\n```\n\n========================================\n\nComments:\n- How do I get these columns that I was not grouped??","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":83,"estimatedTokens":549}}711{"id":"stack-60939232","source":"stackoverflow","questionId":60939232,"title":"In TypeORM how do I have a pre-calculated field on an Entity based on other fields of that Entity?","tags":["javascript","sql","typescript","sequelize.js","typeorm"],"text":"Title: In TypeORM how do I have a pre-calculated field on an Entity based on other fields of that Entity?\nTags: javascript, sql, typescript, sequelize.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to make a 'rating' field on my User Entity.\nThe User Entity has a relationship to the Rating Entity, on User there is a field called ratingsReceived, which is an eager load of all Ratings assigned to that User.\n\nI want the 'rating' field on User to be a mean calculation of all rating values which is a field on Rating Entity called 'ratingValue'.\n\nSo essentially I want this calculation to be the value of every User 'rating' field:\n\n`ratingsReceived.reduce((acc, curr) => acc + curr.ratingValue, 0) / ratingsReceived.length`\n\nThe fields in question are 'ratingsReceived' on User:\n\n```\n@OneToMany(\n () => Rating,\n rating => rating.ratingTo\n )\n ratingsReceived: Rating[];\n```\n\nAnd 'ratingValue' on Rating:\n\n```\n@Column('decimal')\n @Min(0)\n @Max(5)\n ratingValue: number;\n```\n\n========================================\n\nCode:\n```text\n@OneToMany(\n    () => Rating,\n    rating => rating.ratingTo\n  )\n  ratingsReceived: Rating[];\n```\n\n```text\n@Column('decimal')\n  @Min(0)\n  @Max(5)\n  ratingValue: number;\n```\n\n```text\nratingsReceived.reduce((acc, curr) => acc + curr.ratingValue, 0) / ratingsReceived.length\n```\n\n```text\n// After load is called after the entity loads during find() and similar\n// I placed this decorator on my User Entity\n@AfterLoad()\n  calculateRating = async () => {\n    const result = await getRepository(Rating)\n      .createQueryBuilder('ratings')\n      .where('ratings.\"ratingToId\" = :id', { id: this.id })\n      .getRawAndEntities();\n\n    const ratingsAboveZero = result?.entities?.filter(x => parseFloat(x.ratingValue));\n    const count = ratingsAboveZero.length;\n\n    if (count > 0) {\n      this.rating =\n        ratingsAboveZero.reduce((acc, curr) => {\n          return acc + parseFloat(curr.ratingValue);\n        }, 0) / count;\n\n      this.ratingCount = count;\n    } else {\n      this.rating = 0;\n      this.ratingCount = 0;\n    }\n  };\n```\n\n========================================\n\nComments:\n- typeorm.io/listeners-and-subscribers","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":86,"estimatedTokens":540}}712{"id":"stack-54780920","source":"stackoverflow","questionId":54780920,"title":"How to delete property from object received in sequelize?","tags":["node.js","sequelize.js"],"text":"Title: How to delete property from object received in sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a model which requires a date input in the where clause for a query.\n\n```\nconst Model = sequelizeTwo.define('model', {\n A: Sequelize.BIGINT,\n B: Sequelize.DOUBLE,\n C: Sequelize.DOUBLE,\n D: Sequelize.DOUBLE,\n E: Sequelize.DOUBLE, \n F: Sequelize.DOUBLE,\n DATE: Sequelize.DATEONLY, \n newCol: Sequelize.VIRTUAL\n\n},{\n tableName: \"Model\",\n timestamps: false,\n freezeTableName: true\n})\n```\n\n`DATE` here is used as a params for the query to display information on the client. But that is the end of it's use. I don't want to send `DATE` to the client back but I see no way to remove it. \n\nIf i remove it from the model, it gives a timezone error which is another problem as well.\n\n```\napp.get('/api/:date', (req, res) => {\n var date = req.params.date\n\n Model.findAll({\n where: {\n DATE: {\n [Op.eq]: date\n }\n },\n order: [\n ['A', 'ASC']\n ]\n }).then(result => {\n\n ...\n\n for (i; i I have tried using the delete operator inside and outside the loop, but it's of no use. It still retains the property and sends it back to the client\n\n```\ndelete result[i].DATE //Inside loop\n```\n\n```\ndelete result.DATE //before loop\n```\n\nThe values do they get updated when assignment is done but the property/key can't be modified.\n\n```\nresult[i].DATE = null or undefined\n```\n\nWhat i want to achieve here is that I just want to send an object back which has all the properties in the sequelize model *except* `DATE`\n\n========================================\n\nTop Answer:\nI think that the best practice is to create another model for the view as a data transfer object (DTO), and to map only the desired properties to it (without the `Date`).\n\nFurther read: DTO.\n\nPseudocode example:\n\n```\nModel.findAll({\n //...\n}).then(result => {\n\n ...\n let resultDTO = mapToDTO(result);\n\n res.json(resultDTO);\n})\n```\n\n========================================\n\nCode:\n```text\nconst Model = sequelizeTwo.define('model', {\n    A: Sequelize.BIGINT,\n    B: Sequelize.DOUBLE,\n    C: Sequelize.DOUBLE,\n    D: Sequelize.DOUBLE,\n    E: Sequelize.DOUBLE, \n    F: Sequelize.DOUBLE,\n    DATE: Sequelize.DATEONLY,  \n    newCol: Sequelize.VIRTUAL\n\n},{\n    tableName: \"Model\",\n    timestamps: false,\n    freezeTableName: true\n})\n```\n\n```text\napp.get('/api/:date', (req, res) => {\n    var date = req.params.date\n\n    Model.findAll({\n        where: {\n            DATE: {\n                [Op.eq]: date\n            }\n        },\n        order: [\n            ['A', 'ASC']\n        ]\n    }).then(result => {\n\n        ...\n\n        for (i; i < result.length; i++) {\n\n            ...\n            delete result[i].DATE \n            console.log(result[i].DATE)\n            result[i][\"newCol\"] = values;\n        }\n        res.json(result);\n    })\n})\n```\n\n```text\ndelete result[i].DATE //Inside loop\n```\n\n```text\ndelete result.DATE //before loop\n```\n\n```text\nresult[i].DATE = null or undefined\n```\n\n```text\nDATE\n```\n\n```text\nDATE\n```\n\n```text\nDATE\n```\n\n```text\nModel.findAll({\n    where: {\n        DATE: {\n            [Op.eq]: date\n        }\n    },\n    order: [\n        ['A', 'ASC']\n    ],\n    attributes: { exclude: ['DATE'] }\n})\n```\n\n```text\nexcludes\n```\n\n```text\nModel.findAll({\n    //...\n}).then(result => {\n\n    ...\n    let resultDTO = mapToDTO(result);\n\n    res.json(resultDTO);\n})\n```\n\n```text\nDate\n```\n\n========================================\n\nComments:\n- Thanks! Had to redo some calculations but worked like a charm.","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":197,"estimatedTokens":871}}713{"id":"stack-41773927","source":"stackoverflow","questionId":41773927,"title":"Run sequelize model hooks when seeding","tags":["node.js","postgresql","orm","sequelize.js","sequelize-cli"],"text":"Title: Run sequelize model hooks when seeding\nTags: node.js, postgresql, orm, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI'm currently trying to seed a postgresql database with sequelize, I have hooks declared on my model that work just fine when creating separate records (e.g. tests)\n\nDoes the data in my seed file need to be as how would show in the final table or can I call the hooks when creating?\n\nHere are my files:\n\n```\n/*users-seed.js*/\n'use strict'\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert('Users', [/*users-data*/])\n },\n down: function (queryInterface, Sequelize) {\n return queryInterface.bulkDelete('Users', null, {})\n }\n}\n```\n\nAnd\n\n```\n/*user.js*/\nmodule.exports = function (sequelize, DataTypes) {\n let User = sequelize.define('User', {\n /* user attributes */\n }, {\n instanceMethods: {\n hashPassword: function (password) {\n return bcrypt.hash(password, 15)\n },\n hashEmail: function (email) {\n return crypto.createHash('sha256').update(email).digest('hex')\n }\n },\n hooks: {\n beforeCreate: function (user) {\n return user.hashPassword(user.password_digest).then(function (hashedPassword) {\n user.email = user.hashEmail(user.email)\n user.password_digest = hashedPassword\n }).catch(e => { console.log('e', e); throw new Error(e) })\n },\n beforeBulkCreate: function (users) {\n return users.forEach(function (user) {\n return user.hashPassword(user.password_digest).then(function (hashedPassword) {\n user.email = user.hashEmail(user.email)\n user.password_digest = hashedPassword\n }).catch(e => { console.log('e', e); throw new Error(e) })\n })\n }\n }\n })\n return User\n}\n```\n\n========================================\n\nCode:\n```text\n/*users-seed.js*/\n'use strict'\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.bulkInsert('Users', [/*users-data*/])\n  },\n  down: function (queryInterface, Sequelize) {\n    return queryInterface.bulkDelete('Users', null, {})\n  }\n}\n```\n\n```text\n/*user.js*/\nmodule.exports = function (sequelize, DataTypes) {\n  let User = sequelize.define('User', {\n    /* user attributes */\n  }, {\n      instanceMethods: {\n        hashPassword: function (password) {\n          return bcrypt.hash(password, 15)\n        },\n        hashEmail: function (email) {\n          return crypto.createHash('sha256').update(email).digest('hex')\n        }\n      },\n      hooks: {\n        beforeCreate: function (user) {\n          return user.hashPassword(user.password_digest).then(function (hashedPassword) {\n            user.email = user.hashEmail(user.email)\n            user.password_digest = hashedPassword\n          }).catch(e => { console.log('e', e); throw new Error(e) })\n        },\n        beforeBulkCreate: function (users) {\n          return users.forEach(function (user) {\n           return user.hashPassword(user.password_digest).then(function (hashedPassword) {\n              user.email = user.hashEmail(user.email)\n              user.password_digest = hashedPassword\n            }).catch(e => { console.log('e', e); throw new Error(e) })\n         })\n        }\n      }\n    })\n  return User\n}\n```\n\n```text\nqueryInterface.bulkInsert()\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":117,"estimatedTokens":794}}714{"id":"stack-51533572","source":"stackoverflow","questionId":51533572,"title":"Sequelize: How to make relationship between 3 tables","tags":["node.js","sequelize.js"],"text":"Title: Sequelize: How to make relationship between 3 tables\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIf you have the following entities: Users, Roles, Organizations.\nYou want to setup the relationships so that each user has an organization-role. \n\nIn simple each user can belong to multiple organizations and the user has a specific role in each organization.\n\n**How would you model this with Sequelize?**\n\nI have tried by creating a junction table called organisation_users and then in that table adding a organisationUsers.belongsTo(role);\nFrom I have read Sequelize doesnt support associations on junction tables and so that solution doesn't work.\n\nRegards,\nEmir\n\n========================================\n\nTop Answer:\nIt may vary upon your requirements of fetching the data from these 3 tables\nConsider this Example :\nTables : login, userProfile, farmer\nRequirements : Farmer has one user Profile , User Profile has one Login.\nAlong with these tables we can register a user as a Farmer.\n\n```\n--------------------------------------------------------------------------\nfarmer.js\n\nmodule.exports = (Sequelize, DataTypes) => {\n const Farmer = Sequelize.define(\"farmer\", { /*attributes*/});\n return Farmer;\n};\n\n--------------------------------------------------------------------------\nlogin.js\n\nmodule.exports = (Sequelize, DataTypes) => {\n const Login = Sequelize.define(\"login\", {*attributes*/});\n\n return Login;\n};\n--------------------------------------------------------------------------\nuserProfile.js\n\nmodule.exports = (Sequelize, DataTypes) => {\n const UserProfile = Sequelize.define(\"userProfile\", {*attributes*/});\n\n return UserProfile;\n};\n\n--------------------------------------------------------------------------\nindex.js\n\nconst dbConfig = require(\"../config/dbConfig\"); // your config file\nconst { Sequelize, DataTypes } = require(\"sequelize\");\n\n//object initilize. (pass parameter to constructor)\nconst sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {\n host: dbConfig.HOST,\n dialect: dbConfig.dialect,\n operatorsAliases: false, //hide errors\n pool: {\n max: dbConfig.pool.max,\n min: dbConfig.pool.min,\n acquire: dbConfig.pool.acquire,\n idle: dbConfig.pool.idle,\n },\n});\n\nsequelize\n .authenticate()\n .then(() => {\n console.log(\"DB connected!\");\n })\n .catch((err) => {\n console.log(\"Error \" + err);\n });\n\nconst db = {}; // Empty object\n\ndb.Sequelize = Sequelize;\ndb.sequelize = sequelize;\n\ndb.login = require(\"./login.js\")(sequelize, DataTypes);\ndb.userProfile = require(\"./userProfile.js\")(sequelize, DataTypes);\ndb.farmer = require(\"./farmer.js\")(sequelize, DataTypes);\n\n//relations\ndb.farmer.userProfile = db.farmer.belongsTo(db.userProfile);\n\ndb.userProfile.login = db.userProfile.belongsTo(db.login);\n\ndb.sequelize\n .sync({ force: false }) //force :true - drop all tables before start\n .then(() => {\n console.log(\"yes-sync done!\");\n });\n\nmodule.exports = db;\n\n//Declare follwing things in a separate location (may be controllers__.js\n-----------INSERT DATA (CREATE)--------------------------\n\nconst saved = await Farmer.create(\n {\n supplierCode: \"SUP0001\",\n userProfile: {\n firstName: \"ssss\",\n middleName: \"ssss\",\n lastName: \"ssss\",\n address: \"ssss\",\n login: {\n name: \"ssss\",\n email: \"ssss\",\n password: \"ssss\",\n role: \"ssss\",\n lastLogin: null,\n avatar: \"ssss\",\n status: \"ssss\",\n },\n },\n },\n {\n include: [\n {\n association: Farmer.userProfile,\n include: [Login],\n },\n ],\n }\n );\n```\n\nObserve the usage of the include option in the Farmer.create call. That is necessary for Sequelize to understand what you are trying to create along with the association.\n\nNote: here, our user model is called farmer, with a lowercase f - This means that the property in the object should also be farmer. If the name given to sequelize.define was Farmer, the key in the object should also be Farmer.\n\n```\n-----------FETCH DATA (SELECT)-------------------------- \n\nconst users = await Farmer.findAll({\n include: [\n {\n association: Farmer.userProfile,\n include: [Login],\n },\n ],\n });\n\nOutput:\n[\n {\n \"id\": 1,\n \"supplierCode\": \"SUP0001\",\n \"createdAt\": \"2021-11-17T07:39:13.000Z\",\n \"updatedAt\": \"2021-11-17T07:39:13.000Z\",\n \"userProfileId\": 1,\n \"userProfile\": {\n \"id\": 1,\n \"firstName\": \"ssss\",\n \"middleName\": \"ssss\",\n \"lastName\": \"ssss\",\n \"address\": \"ssss\",\n \"createdAt\": \"2021-11-17T07:39:13.000Z\",\n \"updatedAt\": \"2021-11-17T07:39:13.000Z\",\n \"loginId\": 1,\n \"login\": {\n \"id\": 1,\n \"name\": \"ssss\",\n \"email\": \"ssss\",\n \"password\": \"ssss\",\n \"role\": \"ssss\",\n \"lastLogin\": null,\n \"avatar\": \"ssss\",\n \"status\": \"ssss\",\n \"createdAt\": \"2021-11-17T07:39:13.000Z\",\n \"updatedAt\": \"2021-11-17T07:39:13.000Z\"\n }\n }\n }\n]\n```\n\nAssume you want to add another user Role/Type (we have Farmer already). then you can make coordinater.js (example user role/type) and defind attributes\n\nin above index.js you can add this relation\n\n//Coordinator relation\n\n```\ndb.coordinator.userProfile = db.coordinator.belongsTo(db.userProfile, {\n onDelete: \"CASCADE\",\n onUpdate: \"CASCADE\",\n});\n```\n\nNow you can register users with different users Roles/Types :\nCoordinator.create.... give correct associations\n\n========================================\n\nCode:\n```text\nconst Asso_Organization_User = sequelize.define('Asso_Organization_User', {\n    id: DataTypes.STRING,\n    userId: DataTypes.STRING,\n    organizationId: DataTypes.STRING\n});\nUser.Organizations = User.belongsToMany(Organization, {\n    through: Asso_Organization_User,\n    foreignKey: 'userId',\n    otherKey: 'organizationId',\n    as: 'organizations'\n})\n```\n\n```text\nconst Asso_Organization_User = sequelize.define('Asso_Organization_User', {\n    id: DataTypes.STRING,\n    userId: DataTypes.STRING,\n    organizationId: DataTypes.STRING\n});\nUser.Organizations = User.belongsToMany(Organization, {\n    through: Asso_Organization_User,\n    foreignKey: 'userId',\n    otherKey: 'organizationId',\n    as: 'organizations'\n})\n```\n\n```text\nUser: id\nRole: id, userId, organizationId\nOrganizations: id\nAsso_Organization_User: id, userId, organizationId\n```\n\n```text\nUser.Organizations = User.belongsToMany(Organization, {\n    through: Asso_Organization_User\n})\nOrganization.Roles = Organization.haMany(Role, {\n    foreignKey: 'organizationId'\n})\n```\n\n```text\nUser.findAll({\n        include: [ {\n            model: Organization,\n            include: {\n                model: Role  \n            }\n        } ]\n        where: {\n            'role.userId': Sequelize.col(\"User.id\")\n        }\n    });\n```\n\n```text\n--------------------------------------------------------------------------\nfarmer.js\n\nmodule.exports = (Sequelize, DataTypes) => {\n  const Farmer = Sequelize.define(\"farmer\", { /*attributes*/});\n  return Farmer;\n};\n\n--------------------------------------------------------------------------\nlogin.js\n\nmodule.exports = (Sequelize, DataTypes) => {\n  const Login = Sequelize.define(\"login\", {*attributes*/});\n\n  return Login;\n};\n--------------------------------------------------------------------------\nuserProfile.js\n\nmodule.exports = (Sequelize, DataTypes) => {\n  const UserProfile = Sequelize.define(\"userProfile\", {*attributes*/});\n\n  return UserProfile;\n};\n\n--------------------------------------------------------------------------\nindex.js\n\nconst dbConfig = require(\"../config/dbConfig\"); // your config file\nconst { Sequelize, DataTypes } = require(\"sequelize\");\n\n//object initilize. (pass parameter to constructor)\nconst sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {\n  host: dbConfig.HOST,\n  dialect: dbConfig.dialect,\n  operatorsAliases: false, //hide errors\n  pool: {\n    max: dbConfig.pool.max,\n    min: dbConfig.pool.min,\n    acquire: dbConfig.pool.acquire,\n    idle: dbConfig.pool.idle,\n  },\n});\n\nsequelize\n  .authenticate()\n  .then(() => {\n    console.log(\"DB connected!\");\n  })\n  .catch((err) => {\n    console.log(\"Error \" + err);\n  });\n\nconst db = {}; // Empty object\n\ndb.Sequelize = Sequelize;\ndb.sequelize = sequelize;\n\ndb.login = require(\"./login.js\")(sequelize, DataTypes);\ndb.userProfile = require(\"./userProfile.js\")(sequelize, DataTypes);\ndb.farmer = require(\"./farmer.js\")(sequelize, DataTypes);\n\n//relations\ndb.farmer.userProfile = db.farmer.belongsTo(db.userProfile);\n\ndb.userProfile.login = db.userProfile.belongsTo(db.login);\n\ndb.sequelize\n  .sync({ force: false }) //force :true - drop all tables before start\n  .then(() => {\n    console.log(\"yes-sync done!\");\n  });\n\nmodule.exports = db;\n\n//Declare follwing things in a separate location (may be controllers__.js\n-----------INSERT DATA (CREATE)--------------------------\n\nconst saved = await Farmer.create(\n    {\n      supplierCode: \"SUP0001\",\n      userProfile: {\n        firstName: \"ssss\",\n        middleName: \"ssss\",\n        lastName: \"ssss\",\n        address: \"ssss\",\n        login: {\n          name: \"ssss\",\n          email: \"ssss\",\n          password: \"ssss\",\n          role: \"ssss\",\n          lastLogin: null,\n          avatar: \"ssss\",\n          status: \"ssss\",\n        },\n      },\n    },\n    {\n      include: [\n        {\n          association: Farmer.userProfile,\n          include: [Login],\n        },\n      ],\n    }\n  );\n```\n\n```text\n-----------FETCH DATA (SELECT)-------------------------- \n\nconst users = await Farmer.findAll({\n    include: [\n      {\n        association: Farmer.userProfile,\n        include: [Login],\n      },\n    ],\n  });\n\nOutput:\n[\n    {\n        \"id\": 1,\n        \"supplierCode\": \"SUP0001\",\n        \"createdAt\": \"2021-11-17T07:39:13.000Z\",\n        \"updatedAt\": \"2021-11-17T07:39:13.000Z\",\n        \"userProfileId\": 1,\n        \"userProfile\": {\n            \"id\": 1,\n            \"firstName\": \"ssss\",\n            \"middleName\": \"ssss\",\n            \"lastName\": \"ssss\",\n            \"address\": \"ssss\",\n            \"createdAt\": \"2021-11-17T07:39:13.000Z\",\n            \"updatedAt\": \"2021-11-17T07:39:13.000Z\",\n            \"loginId\": 1,\n            \"login\": {\n                \"id\": 1,\n                \"name\": \"ssss\",\n                \"email\": \"ssss\",\n                \"password\": \"ssss\",\n                \"role\": \"ssss\",\n                \"lastLogin\": null,\n                \"avatar\": \"ssss\",\n                \"status\": \"ssss\",\n                \"createdAt\": \"2021-11-17T07:39:13.000Z\",\n                \"updatedAt\": \"2021-11-17T07:39:13.000Z\"\n            }\n        }\n    }\n]\n```\n\n```text\ndb.coordinator.userProfile = db.coordinator.belongsTo(db.userProfile, {\n  onDelete: \"CASCADE\",\n  onUpdate: \"CASCADE\",\n});\n```\n\n========================================\n\nComments:\n- Thanks for taking the time to write this out Philippe, I will test it out in the next 2 days and get back to you.\n- Adding a complication to the problem :p... I have the concept of permissions and roles, a role is just a combination of permissions. So Roles has a belongs to many with permissions. With this in regards what would you do with the `Role: id, userId, organizationId` model?\n- It would not change the Role model, your Permission table would just have a roleId column pointing to the role.\n- I am quite new to sequelize, so apologies for some of the questions. If permissions and roles has a many to many relationship how would I establish: \"your Permission table would just have a roleId column pointing to the role\". Currently I have a role_permissions table, which has permission and role ID foreign keys.\n- In case of a many to many you indeed need a role_permission table making the association between the two. For that I suggest looking at sequelize doc, especially the part \"many-to-many\" associations, looking for the \"through\" option : docs.sequelizejs.com/manual/tutorial/&hellip; Feel free to ask a new question if you need further help in this area.\n- Thank you. I did create a join table called by simply adding a sequelize model relation (belongsToMany) on the permissions and the roles models. That works fine. The part I am unsure about is now making the link between `User: id Organizations: id Asso_Organization_User: id, userId, organizationId` and `role &#47; role_permissions`\n- The same way as we did for including the other associations, you should use \"include\" on the role when making your query\n- Thank you, let me give it a shot and will let you know. Thanks\n- hahaha, dont worry i wont hesitate, just want to check if I can set it up and everything works. If so will do ASAP.\n- When you include the role model with the organisations model for users.findall, I dont see the role attached to the request. Its basically no different then just including organisations without role. Does sequelize support this on a join on a junction table?\n- Yes it does support this ! If you want to check the query being made to debug, you can activate it in the sequelize config. Doing so, every SQL query would be logged so you can verify.\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":440,"estimatedTokens":3188}}715{"id":"stack-57581944","source":"stackoverflow","questionId":57581944,"title":"RangeError [ERR_OUT_OF_RANGE]: The value of \"value\" is out of range. It must be >= 0 and <= 4294967295. Received 9433906525","tags":["node.js","sql-server","express","sequelize.js"],"text":"Title: RangeError [ERR_OUT_OF_RANGE]: The value of \"value\" is out of range. It must be >= 0 and <= 4294967295. Received 9433906525\nTags: node.js, sql-server, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting this range error for a value I am not inserting.\n\n```\nconst createTransaction = async (yodleeAccountId, transaction) => {\n try {\n const savedRecord = await YodleeTransaction.create({\n YodleeAccountID: 373,\n YodleeID: 1887219837,\n Amount: 40518.32,\n AmountCurrency: 'USD',\n BaseType: 'CREDIT',\n Container: 'bank',\n PostDate: '2016-03-19',\n OriginalDescription: 'info about transaction',\n SimpleDescription: 'info',\n CategoryID: '2',\n Category: 'giving idk',\n CategoryType: 'the important type',\n })\n console.log('post create')\n return savedRecord\n } catch (error) {\n console.error('error finally caught', error)\n return error\n }\n}\n```\n\nYodleeTransaction model:\n\n```\nmodule.exports = (sequelize, type) => {\n return sequelize.define(\n 'YodleeTransaction',\n {\n ID: { type: type.BIGINT, primaryKey: true, autoIncrement: true },\n YodleeAccountID: { type: type.BIGINT, allowNull: false },\n YodleeID: { type: type.BIGINT, allowNull: false },\n Amount: { type: type.DECIMAL(12, 2), allowNull: false },\n AmountCurrency: { type: type.STRING(3) },\n BaseType: { type: type.STRING(25), allowNull: false },\n Container: { type: type.STRING(50) },\n PostDate: { type: type.DATE, allowNull: false },\n OriginalDescription: { type: type.STRING(800) },\n SimpleDescription: { type: type.STRING(500) },\n CategoryID: { type: type.INTEGER },\n Category: { type: type.STRING(50) },\n CategoryType: { type: type.STRING(50) },\n },\n { freezeTableName: true, tableName: 'YodleeTransaction' }\n )\n}\n```\n\nError:\n\n RangeError [ERR_OUT_OF_RANGE]: The value of \"value\" is out of range. It must be >= 0 and \n\nI know that 9433906525 is somehow based on the `Amount` because when I change the `Amount`, the value in the error message changes.\nFor example if I change Amount from 40518.32 to 8989.33 the new value received is 10728568304.\nNew error:\n\n RangeError [ERR_OUT_OF_RANGE]: The value of \"value\" is out of range. It must be >= 0 and\n\n========================================\n\nCode:\n```text\nconst createTransaction = async (yodleeAccountId, transaction) => {\n  try {\n    const savedRecord = await YodleeTransaction.create({\n      YodleeAccountID: 373,\n      YodleeID: 1887219837,\n      Amount: 40518.32,\n      AmountCurrency: 'USD',\n      BaseType: 'CREDIT',\n      Container: 'bank',\n      PostDate: '2016-03-19',\n      OriginalDescription: 'info about transaction',\n      SimpleDescription: 'info',\n      CategoryID: '2',\n      Category: 'giving idk',\n      CategoryType: 'the important type',\n    })\n    console.log('post create')\n    return savedRecord\n  } catch (error) {\n    console.error('error finally caught', error)\n    return error\n  }\n}\n```\n\n```text\nmodule.exports = (sequelize, type) => {\n  return sequelize.define(\n    'YodleeTransaction',\n    {\n      ID: { type: type.BIGINT, primaryKey: true, autoIncrement: true },\n      YodleeAccountID: { type: type.BIGINT, allowNull: false },\n      YodleeID: { type: type.BIGINT, allowNull: false },\n      Amount: { type: type.DECIMAL(12, 2), allowNull: false },\n      AmountCurrency: { type: type.STRING(3) },\n      BaseType: { type: type.STRING(25), allowNull: false },\n      Container: { type: type.STRING(50) },\n      PostDate: { type: type.DATE, allowNull: false },\n      OriginalDescription: { type: type.STRING(800) },\n      SimpleDescription: { type: type.STRING(500) },\n      CategoryID: { type: type.INTEGER },\n      Category: { type: type.STRING(50) },\n      CategoryType: { type: type.STRING(50) },\n    },\n    { freezeTableName: true, tableName: 'YodleeTransaction' }\n  )\n}\n```\n\n```text\nAmount\n```\n\n```text\nAmount\n```\n\n```text\nbulkCreate\n```\n\n```text\nbulkUpdate\n```\n\n```text\nsequelize.query('UPDATE YodleeTransaction SET Amount=344.88')\n```\n\n========================================\n\nComments:\n- It appears to be related to this: github.com/tediousjs/tedious/issues/474.\n- I'd like to point that I have the same issue in my project which doesn't use Sequelize. On looking for existing issues, I've come to think it's a Buffer issue in my case, which (maybe) is similar to what Sequelize uses internally.\n- @roshnet Well it was something going on with tedious.","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":148,"estimatedTokens":1078}}716{"id":"stack-34886063","source":"stackoverflow","questionId":34886063,"title":"Sequelize synchronous find","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize synchronous find\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nCan I do a synchronous `find()` with Sequelize? e.g.\n\n```\nconst user = User.find({ id: 1 })\n```\n\n(This seems to just get a promise.)\n\n========================================\n\nTop Answer:\nSequelize its all based in promises , if you are facing a use case like auth , you probably want to add a layer to your application , like middleware in express , so before your application execute some action , you need to authenticate users ( auth middleware ) and then pass to the next function.\n\n```\n//Auth Middleware example\nfunction(req,res,next){\n User.find({id:1)\n .then(function(user){\n req.user = user;\n next();\n })\n .catch(function(error){\n next(error)\n })\n}\n```\n\n========================================\n\nCode:\n```text\nconst user = User.find({ id: 1 })\n```\n\n```text\nfind()\n```\n\n```text\nconst user = yield User.find({ id });\n```\n\n```text\n//Auth Middleware example\nfunction(req,res,next){\n  User.find({id:1)\n  .then(function(user){\n     req.user = user;\n     next();\n  })\n  .catch(function(error){\n     next(error)\n   })\n}\n```\n\n```text\nconst user = await User.findById(id);\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- The answer is here: stackoverflow.com/questions/26839320/&hellip;\n- Why would you need that?\n- @VsevolodGoloviznin Koa/generators.\n- Related: stackoverflow.com/questions/39928452/&hellip;\n- In my case yield return Generator { suspended }, What is the way to enable this feature with Node.js 4? :)\n- Agree with @JuanDavid, I would love to know the answer to this.\n- @NobleUplift I was using Koa with generators I think. You should look up async/await where this is pretty easy and no generators or koa required. But I don't think Node 4 works.\n- this can only be used inside async function","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":80,"estimatedTokens":462}}717{"id":"stack-59712807","source":"stackoverflow","questionId":59712807,"title":"sequelize: How to log raw query","tags":["javascript","postgresql","sequelize.js"],"text":"Title: sequelize: How to log raw query\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI use `sequelize` with `postgresql` and logger `winston`. Here is my code:\n\n```\nlogging: e => logger('sequelize').info(e)\n```\n\nthis logs the result like this:\n\n```\nINSERT INTO \"test\" (\"id\",\"aa\",\"bb\",\"cc\") VALUES (DEFAULT,$1,$2,$3) RETURNING *; // I don't want this\n```\n\nhow to change so that the output will like this?\n\n```\nINSERT INTO \"test\" (\"id\",\"aa\",\"bb\",\"cc\") VALUES (DEFAULT,\"AA\",\"BB\",\"CC\") RETURNING *; // I want this\n```\n\n========================================\n\nCode:\n```text\nlogging: e => logger('sequelize').info(e)\n```\n\n```text\nINSERT INTO \"test\" (\"id\",\"aa\",\"bb\",\"cc\") VALUES (DEFAULT,$1,$2,$3) RETURNING *; // I don't want this\n```\n\n```text\nINSERT INTO \"test\" (\"id\",\"aa\",\"bb\",\"cc\") VALUES (DEFAULT,\"AA\",\"BB\",\"CC\") RETURNING *; // I want this\n```\n\n```text\nsequelize\n```\n\n```text\npostgresql\n```\n\n```text\nwinston\n```\n\n```text\nlogQueryParameters : true\n```\n\n========================================\n\nComments:\n- Related: stackoverflow.com/questions/55715724/&hellip;\n- It really should be true by default! The format will be like this `INSERT INTO \"test\" (\"id\",\"aa\",\"bb\",\"cc\") VALUES (DEFAULT,$1,$2,$3) RETURNING *; \"AA\", \"BB\", \"CC\"`","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":59,"estimatedTokens":315}}718{"id":"stack-32092369","source":"stackoverflow","questionId":32092369,"title":"Sequelize save() issue","tags":["node.js","sequelize.js"],"text":"Title: Sequelize save() issue\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing Sequelize with NodeJS I have found an issue with the .save() method on a model.\n\nAssume a database table with entries such as:\n\n```\n{ id : 1, name : \"mary\", enteredCompetition : 1, won : 0 }\n{ id : 2, name : \"mark\", enteredCompetition : 1, won : 0 }\n{ id : 3, name : \"maya\", enteredCompetition : 1, won : 0 }\n{ id : 4, name : \"maci\", enteredCompetition : 0, won : 0 }\n```\n\nI retrieve one user that has entered the competition, and set this user as having won the prize:\n\n```\nUser.findOne( { where : { enteredCompetition : 1 } } )\n .then( function( user ) {\n user.won = 1;\n user.save().then( function() {\n // done\n } );\n } );\n```\n\nThe issue is that this code then proceeds to update all of the users in the database that have \"enteredCompetition\" set to 1.\n\nI assume this has something to do with options of the model object that is returned from the findOne method. The whereCollection is set to { enteredCompetition: 1 }, therefore I assume when save() is called on it, it uses those where conditions in the update sql:\n\n```\nUPDATE `users` SET `won`=1,`updatedAt`='2015-08-19 09:59:27' WHERE `enteredCompetition` = 1\n```\n\nMy question: is this expected behavior? I personally assumed that it would only update the record it originally pulled from the database, but perhaps I am missing a method that achieves this?\n\nMy current solution is to simply call findOne again with the id of the object that the original query returned, then call save() on this.\n\n========================================\n\nTop Answer:\nTry to **console log** the user and see what it contains\n\n========================================\n\nCode:\n```text\n{ id : 1, name : \"mary\", enteredCompetition : 1, won : 0 }\n{ id : 2, name : \"mark\", enteredCompetition : 1, won : 0 }\n{ id : 3, name : \"maya\", enteredCompetition : 1, won : 0 }\n{ id : 4, name : \"maci\", enteredCompetition : 0, won : 0 }\n```\n\n```text\nUser.findOne( { where : { enteredCompetition : 1 } } )\n    .then( function( user ) {\n        user.won = 1;\n        user.save().then( function() {\n            // done\n        } );\n    } );\n```\n\n```text\nUPDATE `users` SET `won`=1,`updatedAt`='2015-08-19 09:59:27' WHERE `enteredCompetition` = 1\n```\n\n```text\n+----+-------------+--------+\n| id |  username   |  type  |\n+----+-------------+--------+\n|  1 | joshua f    | NORMAL |\n|  2 | joshua f jr | NORMAL |\n+----+-------------+--------+\n```\n\n```js\ndb.user.findOne({\n  where: {\n    type: 'NORMAL'\n  }\n}).then(function(instance) {\n  instance.type = 'IRONMAN';\n  instance.save().then(function() {\n    console.log('saved');\n  });\n});\n```\n\n```text\nUPDATE `users` SET `type`='IRONMAN',`updatedAt`='2015-08-20 05:07:49' WHERE `id` = 2\n```\n\n```text\n+----+-------------+---------+\n| id |  username   |  type   |\n+----+-------------+---------+\n|  1 | joshua f    | IRONMAN |\n|  2 | joshua f jr | NORMAL  |\n+----+-------------+---------+\n```\n\n========================================\n\nComments:\n- You were correct! It does work. The problem was with the definition of my table. I overlooked and therefore did not include the Primary Key option, \"primaryKey : true\", I just assumed it would assign a default primary key to id. I added it in myself and it works great. Thanks!\n- Glad you figured it out :)","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":828}}719{"id":"stack-68925794","source":"stackoverflow","questionId":68925794,"title":"Trying to Order By in Sequelize but get error \"Unable to find a valid association for model\"","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: Trying to Order By in Sequelize but get error \"Unable to find a valid association for model\"\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to order a findByPk result that includes an association (Many to many) in Sequelize, but I'm having some issues. I keep getting the error:\n\nError: Unable to find a valid association for model, 'Item'\n\nThe query:\n\n```\nGuest.findByPk(id,\n {\n include: { model: db.Item, as: 'items' },\n order: [\n [ { model: db.sequelize.models.Item, as: 'items' }, 'dexId', 'ASC' ]\n ]\n })\n .then(data => {\n res.status(200).json({ items: data.items});\n })\n .catch(err => {\n const error = new createError(500, \"Error retrieving Guest with id=\" + id);\n return next(error);\n });\n```\n\nItem model:\n\n```\n'use strict';\nconst {\n Model\n} = require('sequelize');\nmodule.exports = (sequelize, DataTypes) => {\n class Item extends Model {\n /**\n * Helper method for defining associations.\n * This method is not a part of Sequelize lifecycle.\n * The `models/index` file will call this method automatically.\n */\n static associate(models) {\n Item.belongsToMany(models.Guest, {\n //through: 'GuestItems',\n through: {\n model: 'GuestItems',\n unique: false\n },\n constraints: false,\n as: 'guests',\n foreignKey: 'itemId',\n otherKey: 'guestId'\n });\n Item.belongsToMany(models.User, {\n //through: 'UserItems',\n through: {\n model: 'UserItems',\n unique: false\n },\n constraints: false,\n as: 'users',\n foreignKey: 'itemId',\n otherKey: 'userId'\n });\n }\n }\n\n Item.init({\n dexId: {\n allowNull: true,\n type: DataTypes.INTEGER,\n defaultValue: null\n },\n name: {\n type: DataTypes.STRING,\n unique: true,\n allowNull: false\n },\n description: DataTypes.STRING,\n filename: DataTypes.STRING,\n }, {\n sequelize,\n modelName: 'Item',\n paranoid: true\n });\n return Item;\n};\n```\n\nGuest model\n\n```\n'use strict';\nconst {\n Model\n} = require('sequelize');\nmodule.exports = (sequelize, DataTypes) => {\n class Guest extends Model {\n /**\n * Helper method for defining associations.\n * This method is not a part of Sequelize lifecycle.\n * The `models/index` file will call this method automatically.\n */\n static associate(models) {\n Guest.belongsToMany(models.Item, {\n through: 'GuestItems',\n as: 'items',\n foreignKey: 'guestId',\n otherKey: 'itemId'\n });\n }\n }\n Guest.init({\n id: {\n type: DataTypes.BIGINT,\n primaryKey: true,\n autoIncrement: true,\n allowNull: false\n },\n token: DataTypes.STRING,\n role: {\n type: DataTypes.ENUM,\n values: [\"guest\"],\n defaultValue: \"guest\"\n },\n lastIPAddress: DataTypes.STRING\n }, {\n sequelize,\n modelName: 'Guest',\n associations: true\n });\n return Guest;\n};\n```\n\nI know for a fact db.sequelize.models.Item exists, I've also tried calling db.Item (Which again, exists and is used elsewhere) - and neither work.\nI've also tried\n\n```\n[ db.sequelize.models.Item, 'dexId', 'ASC' ]\n```\n\ninstead of the { as 'items' } bit, but I still get that error.\n\nI'm using the latest versions of Sequelize and Postgresql\n\n========================================\n\nCode:\n```js\nGuest.findByPk(id,\n            {\n                include: { model: db.Item, as: 'items' },\n                order: [\n                    [ { model: db.sequelize.models.Item, as: 'items' }, 'dexId', 'ASC' ]\n                ]\n            })\n            .then(data => {\n                res.status(200).json({ items: data.items});\n            })\n            .catch(err => {\n                const error = new createError(500, \"Error retrieving Guest with id=\" + id);\n                return next(error);\n            });\n```\n\n```js\n'use strict';\nconst {\n    Model\n} = require('sequelize');\nmodule.exports = (sequelize, DataTypes) => {\n    class Item extends Model {\n        /**\n         * Helper method for defining associations.\n         * This method is not a part of Sequelize lifecycle.\n         * The `models/index` file will call this method automatically.\n         */\n        static associate(models) {\n            Item.belongsToMany(models.Guest, {\n                //through: 'GuestItems',\n                through: {\n                    model: 'GuestItems',\n                    unique: false\n                },\n                constraints: false,\n                as: 'guests',\n                foreignKey: 'itemId',\n                otherKey: 'guestId'\n            });\n            Item.belongsToMany(models.User, {\n                //through: 'UserItems',\n                through: {\n                    model: 'UserItems',\n                    unique: false\n                },\n                constraints: false,\n                as: 'users',\n                foreignKey: 'itemId',\n                otherKey: 'userId'\n            });\n        }\n    }\n\n    Item.init({\n        dexId: {\n            allowNull: true,\n            type: DataTypes.INTEGER,\n            defaultValue: null\n        },\n        name: {\n            type: DataTypes.STRING,\n            unique: true,\n            allowNull: false\n        },\n        description: DataTypes.STRING,\n        filename: DataTypes.STRING,\n    }, {\n        sequelize,\n        modelName: 'Item',\n        paranoid: true\n    });\n    return Item;\n};\n```\n\n```js\n'use strict';\nconst {\n  Model\n} = require('sequelize');\nmodule.exports = (sequelize, DataTypes) => {\n  class Guest extends Model {\n    /**\n     * Helper method for defining associations.\n     * This method is not a part of Sequelize lifecycle.\n     * The `models/index` file will call this method automatically.\n     */\n    static associate(models) {\n      Guest.belongsToMany(models.Item, {\n        through: 'GuestItems',\n        as: 'items',\n        foreignKey: 'guestId',\n        otherKey: 'itemId'\n      });\n    }\n  }\n  Guest.init({\n    id: {\n      type: DataTypes.BIGINT,\n      primaryKey: true,\n      autoIncrement: true,\n      allowNull: false\n    },\n    token: DataTypes.STRING,\n    role: {\n      type: DataTypes.ENUM,\n      values: [\"guest\"],\n      defaultValue: \"guest\"\n    },\n    lastIPAddress: DataTypes.STRING\n  }, {\n    sequelize,\n    modelName: 'Guest',\n    associations: true\n  });\n  return Guest;\n};\n```\n\n```js\n[ db.sequelize.models.Item, 'dexId', 'ASC' ]\n```\n\n```text\nGuest.findByPk(id, {\n        include: {model: db.Item, as: 'items', required: true},\n        order: [[sequelize.literal('\"items\".\"dexId\"'), 'ASC']] \n})\n    .then((data) => {\n            res.status(200).json({items: data.items});\n    })\n    .catch((err) => {\n                return next(error);\n    });\n```\n\n========================================\n\nComments:\n- TypeError: Cannot read property 'type' of undefined\n- updated code, please try with `required: true`\n- Same error, TypeError: Cannot read property 'type' of undefined\n- minor project with github\n- order: [[sequelize.literal('\"items\".\"dexId\"'), 'ASC']] Works, but only if there are entries in both tables - how can I make it work in the case of an empty table? \"TypeError: Cannot read property 'items' of null\" is what happens when a table is empty","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":296,"estimatedTokens":1725}}720{"id":"stack-40655459","source":"stackoverflow","questionId":40655459,"title":"Creating elements of a hasMany association","tags":["javascript","node.js","sequelize.js"],"text":"Title: Creating elements of a hasMany association\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nFirst time asking a Stack Overflow question so I hope I phrase it correctly: I'm trying to build a simple blog application as a homework assignment while using Sequelize for the database management. However, I have a problem when trying to create some testdata when I try to create elements that are associated to my model. Here is my code, it should be same syntax as in the documentation (http://docs.sequelizejs.com/en/v3/docs/associations/#creating-elements-of-a-hasmany-or-belongstomany-association). \n\n**Current behavior: both users are created with all attributes, Posts are not created at all and no errors are given.** \n\n```\nmasterdb.sync({force:true}).then( x => {\n return Promise.all([\n User.create({\n username:'Timothy',\n password:'plain-text',\n email:'x@msn.nl',\n Posts: [\n { body: 'Hello everyone, my name is Timothy.' },\n { body: 'Today was a good day.'}\n ]\n }, {\n include: [ Post ]\n }),\n User.create({\n username:'Jack Sparrow', \n password:'plain-text', \n email:'jacksparrow@msn.nl'\n }),\n ])\n}).catch(x => console.log(x))\n```\n\nAnd here are my model and relations declarations:\n\n```\nconst Sequelize = require('sequelize')\nconst masterdb = new Sequelize('blogapplication', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD, {\n dialect: 'postgres',\n})\nconst User = masterdb.define('user', {\n username: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false\n },\n email: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false\n }\n}, {\n paranoid: true\n})\n\nconst Post = masterdb.define('post', {\n body: {\n type: Sequelize.STRING(9001),\n allowNull: false,\n unique:true,\n }\n}, {\n paranoid: true\n})\n\nUser.hasMany(Post)\n```\n\n========================================\n\nCode:\n```text\nmasterdb.sync({force:true}).then( x => {\n    return Promise.all([\n        User.create({\n            username:'Timothy',\n            password:'plain-text',\n            email:'x@msn.nl',\n            Posts: [\n                { body: 'Hello everyone, my name is Timothy.' },\n                { body: 'Today was a good day.'}\n            ]\n        }, {\n            include: [ Post ]\n        }),\n        User.create({\n            username:'Jack Sparrow', \n            password:'plain-text', \n            email:'jacksparrow@msn.nl'\n        }),\n    ])\n}).catch(x => console.log(x))\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst masterdb = new Sequelize('blogapplication', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD, {\n    dialect: 'postgres',\n})\nconst User = masterdb.define('user', {\n    username: {\n        type: Sequelize.STRING,\n        unique: true,\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    email: {\n        type: Sequelize.STRING,\n        unique: true,\n        allowNull: false\n    }\n}, {\n    paranoid: true\n})\n\nconst Post = masterdb.define('post', {\n    body: {\n        type: Sequelize.STRING(9001),\n        allowNull: false,\n        unique:true,\n    }\n}, {\n    paranoid: true\n})\n\nUser.hasMany(Post)\n```\n\n```text\nposts: [\n                { body: 'Hello everyone, my name is Timothy.' },\n                { body: 'Today was a good day.'}\n            ]\n```\n\n```text\nPosts: [\n            { body: 'Hello everyone, my name is Timothy.' },\n            { body: 'Today was a good day.'}\n        ]\n```\n\n```text\ntestdb=# select * from users; \n id |   username   |  password  |       email        |         createdAt          |         updatedAt          | deletedAt \n----+--------------+------------+--------------------+----------------------------+----------------------------+-----------\n  1 | Jack Sparrow | plain-text | jacksparrow@msn.nl | 2016-11-17 22:38:06.493+01 | 2016-11-17 22:38:06.493+01 | \n  2 | Timothy      | plain-text | x@msn.nl           | 2016-11-17 22:38:06.492+01 | 2016-11-17 22:38:06.492+01 | \n(2 rows)\n\ntestdb=# select * from posts; \n id |                body                 |         createdAt          |         updatedAt          | deletedAt | userId \n----+-------------------------------------+----------------------------+----------------------------+-----------+--------\n  1 | Hello everyone, my name is Timothy. | 2016-11-17 22:38:06.515+01 | 2016-11-17 22:38:06.515+01 |           |      2\n  2 | Today was a good day.               | 2016-11-17 22:38:06.515+01 | 2016-11-17 22:38:06.515+01 |           |      2\n(2 rows)\n```\n\n```text\nconst Post = masterdb.define('post', {\n```\n\n```text\nconst Sequelize = require('sequelize')\nconst masterdb = new Sequelize('testdb', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD, {\n    dialect: 'postgres',\n})\nconst User = masterdb.define('user', {\n    username: {\n        type: Sequelize.STRING,\n        unique: true,\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING,\n        allowNull: false\n    },\n    email: {\n        type: Sequelize.STRING,\n        unique: true,\n        allowNull: false\n    }\n}, {\n    paranoid: true\n})\n\nvar Tag = masterdb.define('Tag', { //this is 'tag' in their tutorial\n  name: Sequelize.STRING\n}, {\n    paranoid: true\n})\n\nUser.hasMany(Tag)\n\nmasterdb.sync({force:true}).then( x => {\n    return Promise.all([\n        User.create({\n            username:'Timothy',\n            password:'plain-text',\n            email:'x@msn.nl',\n            Tags: [\n            { name: 'Alpha'},\n            { name: 'Beta'}\n          ]\n        }, {\n          include: [ Tag ]\n        }),\n        User.create({\n            username:'Jack Sparrow', \n            password:'plain-text', \n            email:'jacksparrow@msn.nl'\n        }),\n    ])\n}).catch(x => console.log(x))\n```\n\n```text\nPost\n```\n\n```text\npost\n```\n\n```text\nvar Tag = this.sequelize.definte('tag', {\n```\n\n```text\nvar Tag = masterdb.define('tag', {\n```\n\n```text\nthis.sequelize\n```\n\n========================================\n\nComments:\n- You don't have foreign keys defined\n- Also, why is body unique? If it's a post you won't be able to have two with the same text\n- @yBrodsky Aren't foreign keys automatically set correctly when I declare relationships? In the Postgres the posts table is currently linked to users table via the userID column. Body having the attribute unique shouldn't matter for this problem, but my intention there was to prevent people (or bots) from spamming posts.\n- If you have the foreign key already created in the table, add it to the fields in your Post model definition and also add it when defining the relationship. User.hasMany(Post, {foreignKey: 'yourFK'}). Also you should define the relationship the other way around, Post.belongsTo(User, {foreignKey: 'bla'});\n- @yBrodsky You're right about both, I just updated my code to include the belongsTo relationship and explicitly defined foreign keys. Problem keeps occurring though. The accepted answer solved it!\n- I see. Well, in your relationship options you can define as: 'Posts' for example, or whatever you want to call them. Then you can pass the object with key Post or whatever.\n- Wow yes, calling it exactly as the defined string does solve it. Apart from that the only difference is how they use this.sequelize.define, whereas I can't get that to work with the this. I'll make a issue on the Sequelize GitHub about it. Thanks!\n- In my test code when I console logged `this` I got `{}` back. I didn't know what to expect, but I didn't expect an empty object.\n- Got a response on Github that it's a bug in the documentation. \"The name of the attribute (User) has to match the name of the association (user)\" github.com/sequelize/sequelize/issues/6882","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":254,"estimatedTokens":1923}}721{"id":"stack-51691036","source":"stackoverflow","questionId":51691036,"title":"Save data from Sequelize query as a plain JavaScript object in a variable?","tags":["node.js","express","sequelize.js"],"text":"Title: Save data from Sequelize query as a plain JavaScript object in a variable?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am writing a node API and want to save the results of a Sequelize query in a variable as a plain JavaScript object *outside* of the `findAll` block. I have something that works, but not as well as I would like. Here is what I have:\n\n```\nrouter.get('/', (req, res, next) => {\n\n models.User.findAll({\n attributes: ['id', 'name'],\n raw: true\n }).then(function (results) {\n\n console.log(results); // Plain JavaScript object, which is good\n\n // Do logic on results \n\n //Return results\n res.status(200).json({\n results\n });\n });\n});\n```\n\nBut I really don't want to keep all my logic within the `then()` block, especially since I might want to do some other queries before or after this one. I really want something like (if this was a thing):\n\n```\nrouter.get('/', (req, res, next) => {\n\n var users = models.User.findAll({\n attributes: ['id', 'name'],\n raw: true\n }).then(function (results) { \n });\n });\n\n // Do logic on results\n\n // return results\n res.status(200).json({\n results\n });\n});\n```\n\nI tried to save the sequelize query in a function below the `router.get()` call and return the results while they were a JavaScript object, but that didn't work. I am very new to JavaScript, so I appreciate the advice.\n\n========================================\n\nTop Answer:\nmy friend is very simple to do logic on your result in same place that your retrieve you data for example in your code that i modify :\n\n```\nrouter.get('/', (req, res, next) => {\n var users = models.User.findAll({\n attributes: ['id', 'name'],\n raw: true\n }).then((results) => { \n //here do you logic with results \n //after\n res.status(200).json({data : result});\n }).catch(error => res.status(400).json({error}));\n});\n```\n\n========================================\n\nCode:\n```text\nrouter.get('/', (req, res, next) => {\n\n    models.User.findAll({\n        attributes: ['id', 'name'],\n        raw: true\n    }).then(function (results) {\n\n        console.log(results); // Plain JavaScript object, which is good\n\n        // Do logic on results \n\n        //Return results\n        res.status(200).json({\n            results\n        });\n    });\n});\n```\n\n```text\nrouter.get('/', (req, res, next) => {\n\n    var users = models.User.findAll({\n        attributes: ['id', 'name'],\n        raw: true\n    }).then(function (results) {            \n        });\n    });\n\n    // Do logic on results\n\n    // return results\n    res.status(200).json({\n        results\n    });\n});\n```\n\n```text\nfindAll\n```\n\n```text\nthen()\n```\n\n```text\nrouter.get()\n```\n\n```text\nrouter.get('/', async (req, res, next) => {\n\n    var results = await models.User.findAll({\n        attributes: ['id', 'name'],\n        raw: true\n    });\n\n     // you've result variable available here, use it.\n    // Do logic on results\n\n    // return results\n    res.status(200).json({\n        results\n    });\n});\n```\n\n```text\nthen\n```\n\n```text\nasync-await\n```\n\n```text\nthen\n```\n\n```text\nresults\n```\n\n```text\nrouter.get('/', (req, res, next) => {\n     var users = models.User.findAll({\n            attributes: ['id', 'name'],\n            raw: true\n        }).then((results) => {            \n            //here do you logic with results \n              //after\n                res.status(200).json({data : result});\n        }).catch(error => res.status(400).json({error}));\n});\n```\n\n========================================\n\nComments:\n- you can use async-await.\n- Wow, perfect! Thanks!\n- happy to help mate :))","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":175,"estimatedTokens":890}}722{"id":"stack-69853774","source":"stackoverflow","questionId":69853774,"title":"What is the use of defining a mixin instead of a instance method in sequilizejs?","tags":["node.js","express","sequelize.js"],"text":"Title: What is the use of defining a mixin instead of a instance method in sequilizejs?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI was trying through some advanced techniques used to refactor `sequilize.js` models and came across how `instanceMethods` method can be used and util functions can be attached to it.\n\n**Example**:\n\n```\nfunction get_instance_methods(sequelize) {\n return {\n is_admin : function() {\n return this.admin === true;\n },\n };\n};\n```\n\nand then the above can be used like so :\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\n var instance_methods = get_instance_methods(sequelize);\n\n var User = sequelize.define(\"User\", {\n email : {\n type : DataTypes.STRING,\n allowNull : false\n },\n }, {\n instanceMethods : instance_methods,\n });\n\n return User;\n};\n```\n\nBut now I came across a `mixin` being defined and then being used like so inside a modal **HERE** .\n\n```\nwithCompanyAwareness.call ( instance_methods, sequelize ) ;\n```\n\nthe code for the `mixin` itself is being defined **HERE**. A snapshot of what the mixin looks like can be found below :-\n\n```\nmodule.exports = function(sequelize){\n // more methods defined here .. just adding a snapshot here.\n this.get_company_with_all_leave_types = function() {\n return this.getCompany({\n include : [{\n model : sequelize.models.LeaveType,\n as : 'leave_types',\n }],\n order : [\n [{ model : sequelize.models.LeaveType, as : 'leave_types' }, 'sort_order', 'DESC'],\n [{ model : sequelize.models.LeaveType, as : 'leave_types' }, 'name']\n ]\n });\n };\n\n};\n```\n\nWhat exactly is the purpose of defining a mixin vs using instance methods? Why is there a need for defining a mixin?\n\n========================================\n\nCode:\n```text\nfunction get_instance_methods(sequelize) {\n  return {\n    is_admin : function() {\n      return this.admin === true;\n    },\n  };\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n  var instance_methods = get_instance_methods(sequelize);\n\n  var User = sequelize.define(\"User\", {\n      email : {\n          type      : DataTypes.STRING,\n          allowNull : false\n      },\n  }, {\n      instanceMethods : instance_methods,\n    });\n\n    return User;\n};\n```\n\n```text\nwithCompanyAwareness.call ( instance_methods, sequelize ) ;\n```\n\n```text\nmodule.exports = function(sequelize){\n  // more methods defined here .. just adding a snapshot here.\n  this.get_company_with_all_leave_types = function() {\n    return this.getCompany({\n      include : [{\n        model : sequelize.models.LeaveType,\n        as    : 'leave_types',\n      }],\n      order : [\n        [{ model : sequelize.models.LeaveType, as : 'leave_types' }, 'sort_order', 'DESC'],\n        [{ model : sequelize.models.LeaveType, as : 'leave_types' }, 'name']\n      ]\n    });\n  };\n\n};\n```\n\n```text\nsequilize.js\n```\n\n```text\ninstanceMethods\n```\n\n```text\nmixin\n```\n\n```text\nmixin\n```\n\n```text\ninstance_methods.myNewMethod = function () { ... }\n```\n\n```text\nfunction with_my_new_method () {\n    this.myNewMethod = function () { ... }\n}\n```\n\n```text\n// Model1.js:\nvar instance_methods = get_instance_methods(sequelize);\nvar Model1 = sequelize.define(\"Model1\", {\n  ...\n}, {\n  instanceMethods: instance_methods\n});\n\n// Model2.js:\nvar instance_methods = get_instance_methods(sequelize);\nwith_my_new_method.call(instance_methods)\nvar Model2 = sequelize.define(\"Model2\", {\n  ...\n}, {\n  instanceMethods: instance_methods\n});\n\n// Model3.js:\nvar instance_methods = get_instance_methods(sequelize);\nwith_my_new_method.call(instance_methods)\nvar Model3 = sequelize.define(\"Model3\", {\n  ...\n}, {\n  instanceMethods: instance_methods\n});\n```\n\n```text\ninstanceMethods\n```\n\n```text\nget_instance_methods(sequelize)\n```\n\n```text\nget_instance_methods(...)\n```\n\n```text\ninstanceMethods\n```\n\n```text\ninstance_methods\n```\n\n```text\nmyNewMethod\n```\n\n```text\nget_instance_methods\n```\n\n```text\nmyNewMethod\n```\n\n```text\nmyNewMethod\n```\n\n```text\nwith_my_new_method\n```\n\n```text\n.call\n```\n\n```text\ninstance_methods\n```\n\n```text\ninstance_methods\n```\n\n```text\nthis\n```\n\n========================================\n\nComments:\n- @Ionica thank you for taking the time for the long explanation , you've theoretically answered my question , i'll go try this out now by myself and see how it work. Thanks a ton :D","metadata":{"transformedAt":"2026-08-18T18:33:34.398Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":236,"estimatedTokens":1065}}723{"id":"stack-65641430","source":"stackoverflow","questionId":65641430,"title":"Sequelize.sync: Create indexes when table does not exist","tags":["node.js","postgresql","orm","sequelize.js"],"text":"Title: Sequelize.sync: Create indexes when table does not exist\nTags: node.js, postgresql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAccording to documentation `sequelize.sync()` without `{force: true}` or `{alter:true}` is supposed to ignore already existing tables and create/sync only new ones. But there are at least two use cases when existing tables are not fully ignored and there are errors introduced.\n\nMy setup:\n\n- `sequelize.sync()` is used as a pre-migration step to create tables that don't exist in the schema\n\n- `sequelize.migrate()` is used to alter any existing tables.\n\nNote: Sequelize models are treated as a single source of truth for reflecting database schema. They are always updated to reflect all the indexes/fields existing in the database.\n\n**Steps to reproduce**\n\n**Step 1**: Create `User` model with two fields `name` and `email`. `Email` has a unique index\n\n```\nconst users = sequelizeClient.define('users', {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n }, {\n indexes: [\n {\n unique: true,\n fields: ['email'],\n },\n ],\n });\n```\n\nThere is no migration, so the table is expected to be created using `sequelize.sync()`.\nEverything works as expected. Here are the generated SQL scripts.\n\n```\nExecuting (default): CREATE TABLE IF NOT EXISTS \"users\" (\"id\" SERIAL , \"name\" VARCHAR(255) NOT NULL, \"email\" VARCHAR(255) NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): CREATE UNIQUE INDEX \"users_email\" ON \"users\" (\"email\")\n```\n\n**Step 2** Add a new field `phonenumber` to the Users table and add a unique index. Add a migration that will alter the table structure and create the index. The `sequelize.sync()` is expected to ignore this table but migration is never executed as `sequelize.sync()` throws the following error.\n\n```\nExecuting (default): CREATE TABLE IF NOT EXISTS \"users\" (\"id\" SERIAL , \"name\" VARCHAR(255) NOT NULL, \"email\" VARCHAR(255) NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): CREATE UNIQUE INDEX \"users_phonenumber\" ON \"users\" (\"phonenumber\")\n{\"_bitField\":18087936,\"_fulfillmentHandler0\":{\"name\":\"SequelizeDatabaseError\",\"parent\":{\"name\":\"error\",\"length\":101,\"severity\":\"ERROR\",\"code\":\"42703\",\"file\":\"indexcmds.c\",\"line\":\"1083\",\"routine\":\"ComputeIndexAttrs\",\"sql\":\"CREATE UNIQUE INDEX \\\"users_phonenumber\\\" ON \\\"users\\\" (\\\"phonenumber\\\")\"},\"original\":{\"name\":\"error\",\"length\":101,\"severity\":\"ERROR\",\"code\":\"42703\",\"file\":\"indexcmds.c\",\"line\":\"1083\",\"routine\":\"ComputeIndexAttrs\",\"sql\":\"CREATE UNIQUE INDEX \\\"users_phonenumber\\\" ON \\\"users\\\" (\\\"phonenumber\\\")\"},\"sql\":\"CREATE UNIQUE INDEX \\\"users_phonenumber\\\" ON \\\"users\\\" (\\\"phonenumber\\\")\"},\"_trace\":{\"_promisesCreated\":0,\"_length\":1},\"level\":\"error\",\"message\":\"Unhandled Rejection at: Promise \"}\n```\n\nHere's the final model\n\n```\nconst users = sequelizeClient.define('users', {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n phoneNumber: { // new field\n type: DataTypes.STRING,\n allowNull: false,\n },\n\n }, {\n indexes: [\n {\n unique: true,\n fields: ['email'],\n },\n { // new index\n unique: true,\n fields: ['phoneNumber'],\n },\n ],\n });\n```\n\nCan someone suggest a workaround here so the index creation happens only if the table doesn't exist\n\nAnother use case is when you add a new field with a comment\n\n```\nfieldWithComment: {\n type: DataTypes.STRING,\n comment: 'my comment goes here',\n },\n```\n\nGenerated SQL which obviously throws an error as the new column does not exist yet.\n\n```\nCREATE TABLE IF NOT EXISTS \"users\" (\n \"id\" SERIAL, \n \"name\" VARCHAR(255) NOT NULL, \n \"email\" VARCHAR(255) NOT NULL, \n \"phonenumber\" VARCHAR(255) NOT NULL, \n \"fieldWithComment\" VARCHAR(255) , PRIMARY KEY (\"id\")); \n COMMENT ON COLUMN \"users\".\"fieldWithComment\" IS 'my comment goes here';\n```\n\n========================================\n\nTop Answer:\nIf anyone still struggling, not satisfied with the above answer because of sequelize updates, etc like me, here is how I solved the problem.\n\nI was using `underscore:true` option.\n\nSo, I've changed the line `fields: [\"phone\", \"countryCode\"],` to `fields: [\"phone\", \"country_code\"],`.\n\n```\nsequelize.define(\n \"user\",\n {\n phone: {\n type: DataTypes.STRING(20),\n allowNull: false,\n },\n countryCode: {\n type: DataTypes.STRING(4),\n allowNull: false,\n },\n // other attributes ...\n },\n {\n freezeTableName: true,\n timestamps: true,\n underscored: true,\n indexes: [\n {\n unique: true,\n fields: [\"phone\", \"country_code\"],\n },\n ],\n }\n);\n```\n\n========================================\n\nCode:\n```text\nconst users = sequelizeClient.define('users', {\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n    email: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n  }, {\n    indexes: [\n      {\n        unique: true,\n        fields: ['email'],\n      },\n    ],\n  });\n```\n\n```text\nExecuting (default): CREATE TABLE IF NOT EXISTS \"users\" (\"id\"  SERIAL , \"name\" VARCHAR(255) NOT NULL, \"email\" VARCHAR(255) NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): CREATE UNIQUE INDEX \"users_email\" ON \"users\" (\"email\")\n```\n\n```text\nExecuting (default): CREATE TABLE IF NOT EXISTS \"users\" (\"id\"  SERIAL , \"name\" VARCHAR(255) NOT NULL, \"email\" VARCHAR(255) NOT NULL, PRIMARY KEY (\"id\"));\nExecuting (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;\nExecuting (default): CREATE UNIQUE INDEX \"users_phonenumber\" ON \"users\" (\"phonenumber\")\n{\"_bitField\":18087936,\"_fulfillmentHandler0\":{\"name\":\"SequelizeDatabaseError\",\"parent\":{\"name\":\"error\",\"length\":101,\"severity\":\"ERROR\",\"code\":\"42703\",\"file\":\"indexcmds.c\",\"line\":\"1083\",\"routine\":\"ComputeIndexAttrs\",\"sql\":\"CREATE UNIQUE INDEX \\\"users_phonenumber\\\" ON \\\"users\\\" (\\\"phonenumber\\\")\"},\"original\":{\"name\":\"error\",\"length\":101,\"severity\":\"ERROR\",\"code\":\"42703\",\"file\":\"indexcmds.c\",\"line\":\"1083\",\"routine\":\"ComputeIndexAttrs\",\"sql\":\"CREATE UNIQUE INDEX \\\"users_phonenumber\\\" ON \\\"users\\\" (\\\"phonenumber\\\")\"},\"sql\":\"CREATE UNIQUE INDEX \\\"users_phonenumber\\\" ON \\\"users\\\" (\\\"phonenumber\\\")\"},\"_trace\":{\"_promisesCreated\":0,\"_length\":1},\"level\":\"error\",\"message\":\"Unhandled Rejection at: Promise \"}\n```\n\n```text\nconst users = sequelizeClient.define('users', {\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n    email: {\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n    phoneNumber: { // new field\n      type: DataTypes.STRING,\n      allowNull: false,\n    },\n\n  }, {\n    indexes: [\n      {\n        unique: true,\n        fields: ['email'],\n      },\n      { // new index\n        unique: true,\n        fields: ['phoneNumber'],\n      },\n    ],\n  });\n```\n\n```text\nfieldWithComment: {\n      type: DataTypes.STRING,\n      comment: 'my comment goes here',\n    },\n```\n\n```text\nCREATE TABLE IF NOT EXISTS \"users\" (\n    \"id\"   SERIAL, \n    \"name\" VARCHAR(255) NOT NULL, \n    \"email\" VARCHAR(255) NOT NULL, \n    \"phonenumber\" VARCHAR(255) NOT NULL, \n    \"fieldWithComment\" VARCHAR(255) , PRIMARY KEY (\"id\")); \n        COMMENT ON COLUMN \"users\".\"fieldWithComment\" IS 'my comment goes here';\n```\n\n```text\nsequelize.sync()\n```\n\n```text\n{force: true}\n```\n\n```text\n{alter:true}\n```\n\n```text\nsequelize.sync()\n```\n\n```text\nsequelize.migrate()\n```\n\n```text\nUser\n```\n\n```text\nname\n```\n\n```text\nemail\n```\n\n```text\nEmail\n```\n\n```text\nsequelize.sync()\n```\n\n```text\nphonenumber\n```\n\n```text\nsequelize.sync()\n```\n\n```text\nsequelize.sync()\n```\n\n```js\nsequelize.define(\n  \"user\",\n  {\n    phone: {\n      type: DataTypes.STRING(20),\n      allowNull: false,\n    },\n    countryCode: {\n      type: DataTypes.STRING(4),\n      allowNull: false,\n    },\n    // other attributes ...\n  },\n  {\n    freezeTableName: true,\n    timestamps: true,\n    underscored: true,\n    indexes: [\n      {\n        unique: true,\n        fields: [\"phone\", \"country_code\"],\n      },\n    ],\n  }\n);\n```\n\n```text\nunderscore:true\n```\n\n```text\nfields: [\"phone\", \"countryCode\"],\n```\n\n```text\nfields: [\"phone\", \"country_code\"],\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":321,"estimatedTokens":2485}}724{"id":"stack-35792847","source":"stackoverflow","questionId":35792847,"title":"Is Sequelize model.build(req.body) safe for injections?","tags":["node.js","code-injection","sequelize.js"],"text":"Title: Is Sequelize model.build(req.body) safe for injections?\nTags: node.js, code-injection, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to Sequelize (a node.js ORM) and wondering if the following code is safe:\n\n```\nvar models = require('../models');\nvar router = require('express').Router();\n\nrouter.post('/', function(req, res, next){\n models.Account\n .create(req.body) // If you are using this, could this be unsafe in some way?\nThe other solution would be:\n\n```\nvar models = require('../models');\nvar router = require('express').Router();\n\nrouter.post('/', function(req, res, next){\n models.Account\n .create({\n username: req.body.username, // So basically my question is: is it safe to use the full request body as an input to the `model.create()` function (and `model.set()` and `model.build()`)?\n\n========================================\n\nCode:\n```text\nvar models = require('../models');\nvar router = require('express').Router();\n\nrouter.post('/', function(req, res, next){\n  models.Account\n    .create(req.body)       // <-- THIS IS WHAT MY QUESTION IS ABOUT, IS THIS SAFE?\n    .then(function(result){\n      res.status(200)\n        .send(result)\n        .end();\n    }).catch(next);\n});\n```\n\n```text\nvar models = require('../models');\nvar router = require('express').Router();\n\nrouter.post('/', function(req, res, next){\n  models.Account\n    .create({\n      username:    req.body.username, // <-- THIS IS MORE VERBOSE BUT PROBABLY SAFER?\n      accountname: req.body.accountname,\n      level:       req.body.level\n    })\n    .then(function(result){\n      res.status(200)\n        .send(result)\n        .end();\n    }).catch(next);\n});\n```\n\n```text\nmodel.create()\n```\n\n```text\nmodel.set()\n```\n\n```text\nmodel.build()\n```\n\n```text\nmodels.Account.create\n```\n\n========================================\n\nComments:\n- Sounds like a valid point in general (as you said). But in this case with this special ORM, validation functionality for the model is already in the ORM. Shouldn't all validation be done in the ORM? Keeping thin controllers is generally considered good practice.\n- If you want to look at it a different way, you are dealing with two end points that talk to external systems (what those are makes no difference). The data that comes in and goes out of those end points should be designed for those end points (which is not necessarily the same as what your system needs, or other end points need).\n- Sorry, that was quite an abstract response.","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":84,"estimatedTokens":617}}725{"id":"stack-35753733","source":"stackoverflow","questionId":35753733,"title":"Using Sequelize how can I specify which field to sort / limit by?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Using Sequelize how can I specify which field to sort / limit by?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy query is:\n\n```\ndb.Question.findAll\n where:\n id:\n $notIn: if questionIds.length > 0 then questionIds else [-1]\n TopicId: topicCount.id\n PassageId: null\n status: 'active'\n level:\n $lte: startLevel\n $gte: endLevel\n include: [\n model: db.Answer\n ]\n order: [db.Sequelize.fn 'RANDOM']\n limit: questionSections[sectionIndex].goal * 2\n```\n\nAnd that generates the following query:\n\n```\nSELECT \"Question\".*, \n \"answers\".\"id\" AS \"Answers.id\", \n \"answers\".\"answertext\" AS \"Answers.answerText\", \n \"answers\".\"iscorrect\" AS \"Answers.isCorrect\", \n \"answers\".\"createdat\" AS \"Answers.createdAt\", \n \"answers\".\"updatedat\" AS \"Answers.updatedAt\", \n \"answers\".\"questionid\" AS \"Answers.QuestionId\" \nFROM (SELECT \"Question\".\"id\", \n \"Question\".\"status\", \n \"Question\".\"questiontext\", \n \"Question\".\"level\", \n \"Question\".\"originalid\", \n \"Question\".\"createdbyuserid\", \n \"Question\".\"editedbyuserid\", \n \"Question\".\"createdat\", \n \"Question\".\"updatedat\", \n \"Question\".\"instructionid\", \n \"Question\".\"topicid\", \n \"Question\".\"subjectid\", \n \"Question\".\"passageid\" \n FROM \"questions\" AS \"Question\" \n WHERE \"Question\".\"id\" NOT IN ( -1 ) \n AND \"Question\".\"topicid\" = '79' \n AND \"Question\".\"passageid\" IS NULL \n AND \"Question\".\"status\" = 'active' \n AND ( \"Question\".\"level\" = 65 ) \n LIMIT 300) AS \"Question\" \n LEFT OUTER JOIN \"answers\" AS \"Answers\" \n ON \"Question\".\"id\" = \"answers\".\"questionid\" \nORDER BY Random();\n```\n\nThat's all well and good, except I want the `ORDER BY` to apply to the inner Query (`SELECT \"Question\".\"id\", \"Question\".\"status\",`). How can I achieve this?\n\n========================================\n\nCode:\n```text\ndb.Question.findAll\n      where:\n        id:\n          $notIn: if questionIds.length > 0 then questionIds else [-1]\n        TopicId: topicCount.id\n        PassageId: null\n        status: 'active'\n        level:\n          $lte: startLevel\n          $gte: endLevel\n      include: [\n        model: db.Answer\n      ]\n      order: [db.Sequelize.fn 'RANDOM']\n      limit: questionSections[sectionIndex].goal * 2\n```\n\n```text\nSELECT \"Question\".*, \n       \"answers\".\"id\"         AS \"Answers.id\", \n       \"answers\".\"answertext\" AS \"Answers.answerText\", \n       \"answers\".\"iscorrect\"  AS \"Answers.isCorrect\", \n       \"answers\".\"createdat\"  AS \"Answers.createdAt\", \n       \"answers\".\"updatedat\"  AS \"Answers.updatedAt\", \n       \"answers\".\"questionid\" AS \"Answers.QuestionId\" \nFROM   (SELECT \"Question\".\"id\", \n               \"Question\".\"status\", \n               \"Question\".\"questiontext\", \n               \"Question\".\"level\", \n               \"Question\".\"originalid\", \n               \"Question\".\"createdbyuserid\", \n               \"Question\".\"editedbyuserid\", \n               \"Question\".\"createdat\", \n               \"Question\".\"updatedat\", \n               \"Question\".\"instructionid\", \n               \"Question\".\"topicid\", \n               \"Question\".\"subjectid\", \n               \"Question\".\"passageid\" \n        FROM   \"questions\" AS \"Question\" \n        WHERE  \"Question\".\"id\" NOT IN ( -1 ) \n               AND \"Question\".\"topicid\" = '79' \n               AND \"Question\".\"passageid\" IS NULL \n               AND \"Question\".\"status\" = 'active' \n               AND ( \"Question\".\"level\" <= 95 \n                     AND \"Question\".\"level\" >= 65 ) \n        LIMIT  300) AS \"Question\" \n       LEFT OUTER JOIN \"answers\" AS \"Answers\" \n                    ON \"Question\".\"id\" = \"answers\".\"questionid\" \nORDER  BY Random();\n```\n\n```text\nORDER BY\n```\n\n```text\nSELECT \"Question\".\"id\", \"Question\".\"status\",\n```\n\n```text\ndb.Question.scope('random').findAll({\n  where:{\n    ..........\n  },\n  include: [{\n    model: db.Answer\n  }],\n  //order: [db.Sequelize.fn 'RANDOM'] <<<<<<< moved to custom scope\n  limit: questionSections[sectionIndex].goal * 2\n })\n```\n\n```text\nrandom\n```\n\n========================================\n\nComments:\n- The purpose of adding `ORDER BY` to the inner query is so that the `LIMIT 300` causes 300 random tuples to be selected as candidates for the left join, right?\n- Right - that's what I want","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":147,"estimatedTokens":1031}}726{"id":"stack-33113942","source":"stackoverflow","questionId":33113942,"title":"Accessing an associated table from a Sequelize getter method","tags":["javascript","node.js","express","database-design","sequelize.js"],"text":"Title: Accessing an associated table from a Sequelize getter method\nTags: javascript, node.js, express, database-design, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThis is my first node.js web app after 20 years of C++, and I think I just need someone to point me in the right direction here.\n\nI'm writing the server side of an app that deals with schools and students. When the client sends a request (via my REST API) for a particular student, I want to return the student's first and last name and school. I'm using a library called epilogue that parses the requests, reads/writes to the MySQL database via sequelize, and wraps up the result in a JSON response. It will send all the fields I have defined for student as well as the values of any getters I have defined. Everything has been working great. I have been able to use epilogue to POST, PUT, GET and generally keep the MySQL database updated. \n\nHowever, things got tricky when I tried to define a getter method that returns the student's school name. In order to do that, I have to access a record in the school table and get the school name. \n\n\r\n\r\n\n```\nvar school = sequelize.define(\"School\", {\r\n SchoolName: {\r\n type: DataTypes.STRING,\r\n },\r\n }, {\r\n classMethods: {\r\n associate: function(models) {\r\n school.hasMany(models.Student);\r\n }\r\n }\r\n }\r\n}\r\n\r\nvar student = sequelize.define(\"Student\", {\r\n FirstName: {\r\n type: DataTypes.STRING,\r\n },\r\n LastName: {\r\n type: DataTypes.STRING,\r\n },\r\n }, {\r\n classMethods: {\r\n associate: function(models) {\r\n student.belongsTo(models.School);\r\n },\r\n },\r\n getterMethods: {\r\n FullName: function() {\r\n return this.FirstName + ' ' + this.LastName; // This works just fine\r\n },\r\n SchoolName: function() {\r\n return this.getSchool().SchoolName; // This doesn't work because getSchool is asynchronous\r\n }\r\n }\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nThe problem is that .getSchool() is asynchronous, so it seems I would have to use .then to access the result. Promises are a new concept for me, but I've tried things like:\n\n\r\n\r\n\n```\nSchoolName: function {\r\n return this.getSchool.then(function(school) {\r\n return school.SchoolName;\r\n });\r\n}\n```\n\n\r\n\r\n\r\n\nBut it seems this just returns the Promise itself instead of the results of the promise because the promise isn't fulfilled at the time the getter returns. So, I end up sending the client something like:\n\n\r\n\r\n\n```\n{\r\n \"FullName\": \"John Doe\", \r\n \"SchoolName\": {\r\n \"isFulfilled\": false, \r\n \"isRejected\": false\r\n },\r\n \"id\":1,\r\n \"FirstName\":\"John\",\r\n \"LastName\":\"Doe\"\r\n}\n```\n\n\r\n\r\n\r\n\nIt seems like the getters here are necessarily synchronous, so it looks like I just need some way to tell the getter to stop and wait until the Promise is fulfilled and then return the value. But that seems to violate the asynchronous nature of node.js. So, I have a hunch that I am fundamentally misunderstanding something important about sequelize.js or node.js or promises or maybe even database design. Can someone redirect me, please? Mainly, I would like to know: what is the *right* way to do this?\n\n========================================\n\nCode:\n```js\nvar school = sequelize.define(\"School\", {\n    SchoolName: {\n      type: DataTypes.STRING,\n    },\n  }, {\n    classMethods: {\n      associate: function(models) {\n        school.hasMany(models.Student);\n      }\n    }\n  }\n}\n\nvar student = sequelize.define(\"Student\", {\n    FirstName: {\n      type: DataTypes.STRING,\n    },\n    LastName: {\n      type: DataTypes.STRING,\n    },\n  }, {\n    classMethods: {\n      associate: function(models) {\n        student.belongsTo(models.School);\n      },\n    },\n    getterMethods: {\n      FullName: function() {\n        return this.FirstName + ' ' + this.LastName; // This works just fine\n      },\n      SchoolName: function() {\n        return this.getSchool().SchoolName; // This doesn't work because getSchool is asynchronous\n      }\n    }\n  }\n}\n```\n\n```js\nSchoolName: function {\n  return this.getSchool.then(function(school) {\n    return school.SchoolName;\n  });\n}\n```\n\n```css\n{\n  \"FullName\": \"John Doe\", \n  \"SchoolName\": {\n    \"isFulfilled\": false, \n    \"isRejected\": false\n  },\n  \"id\":1,\n  \"FirstName\":\"John\",\n  \"LastName\":\"Doe\"\n}\n```\n\n```text\ngetSchool()\n```\n\n```text\nassociations: true\n```\n\n========================================\n\nComments:\n- Yes! That was it! All I had to do was add \"associations: true\" when I create the resource and then return this.School.SchoolName from the getter. That's exactly what I needed. Thanks!\n- @JeffWilhite where exactly are you putting `associations: true` ?\n- @noodles_ftw Are you using epilogue too, or any other package for handling REST api? I use koa.js (instead of express.js) with sequelize and koa-router for routing, and since koa is based on generators (for ES6), or await/async (for ES7), `yield`/`async&#47;await` worked for me.\n- @JeffWilhite although this question is marked answered, I'd like to point out that `this.getSchool.then(..)` should be `this.getSchool().then(..)`","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":176,"estimatedTokens":1233}}727{"id":"stack-64237525","source":"stackoverflow","questionId":64237525,"title":"How to dynamically connect to a database in nestjs?","tags":["typescript","sequelize.js","nestjs"],"text":"Title: How to dynamically connect to a database in nestjs?\nTags: typescript, sequelize.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have multiple databases that I want to connect. but just one of them have static name. for example the name of that database is `stores`, and in that I have a table that indicates the name of the other databases. now I want to change the connection provider after the first route being called. how can I do that?\n\nI tried to use the Dynamic modules, but I don't know how to use it.\n\n========================================\n\nCode:\n```text\nstores\n```\n\n```text\n@Injectable({ scope: Scope.REQUEST })\nexport class MongooseConfigService implements MongooseOptionsFactory {\n    constructor(\n        @Inject(REQUEST) private readonly request: Request,) {\n    }\n\n    createMongooseOptions(): MongooseModuleOptions {\n        return {\n            uri: request.params.uri, // Change this to whatever you want\n        };\n    }\n}\n```\n\n========================================\n\nComments:\n- Create your own Database module, and pass a database name to provider, or uri that you want to connect with, store somewhere these information with relations to the connection, like string -> connection, fe: Map with DB URI or DB Name with key as connection handler. Then you should be able to achieve your goal.\n- @cojack, thanks. but can you give an example on how to do that?","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":36,"estimatedTokens":347}}728{"id":"stack-31559424","source":"stackoverflow","questionId":31559424,"title":"How to make sure a MySQL database exists before running Node.js app","tags":["javascript","mysql","node.js","npm","sequelize.js"],"text":"Title: How to make sure a MySQL database exists before running Node.js app\nTags: javascript, mysql, node.js, npm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a Node.js/Express based app that is using Sequelize to talk to a MySQL server. What is the best way to ensure that a specific database exists before starting the app using `npm start`? I guess it would be some kind of one-time database initialization script that runs `CREATE DATABASE IF NOT EXISTS foo;` - I am just not sure where to put it and how to hook it up to a lifecycle event.\n\n========================================\n\nCode:\n```text\nnpm start\n```\n\n```text\nCREATE DATABASE IF NOT EXISTS foo;\n```\n\n```text\n{ \"scripts\" :\n  { \n  \"prestart\" : \"node scripts/mysqlCheck.js\", \n  \"start\" : \"node index.js\"\n  }\n}\n```\n\n```text\nprestart\n```\n\n```text\nmysqlCheck.js\n```\n\n```text\nnpm start\n```\n\n```text\nprestart\n```\n\n```text\nindex.js\n```\n\n========================================\n\nComments:\n- Just try to connect to database. If database doesn't exists, you will get error.","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":51,"estimatedTokens":259}}729{"id":"stack-72784036","source":"stackoverflow","questionId":72784036,"title":"Cannot redeclare block-scoped variable, even though they are inside different cases","tags":["node.js","visual-studio-code","sequelize.js"],"text":"Title: Cannot redeclare block-scoped variable, even though they are inside different cases\nTags: node.js, visual-studio-code, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nInside a controller method I have the code block below. Visual Studio Code gives the error:\n\nCannot redeclare block-scoped variable 'count' and 'rows'\n\nBut I don't understand this because these variables are declared inside different cases and only 1 case will fire. How should I handle this?\n\n```\nswitch (tab) {\n case \"active\":\n const { count, rows } = await User.findAndCountAll({\n where: {\n ...query,\n },\n offset,\n limit,\n });\n\n break;\n\n case \"favourites\":\n const { count, rows } = await User.findAndCountAll({\n where: {\n ...query,\n [Op.or]: [{ name: {[Op.like]: `%${searchText}%` }}],\n },\n offset,\n limit,\n });\n ...\n```\n\n========================================\n\nCode:\n```text\nswitch (tab) {\n    case \"active\":\n        const { count, rows } = await User.findAndCountAll({\n            where: {\n                ...query,\n            },\n            offset,\n            limit,\n        });\n\n        break;\n\n    case \"favourites\":\n        const { count, rows } = await User.findAndCountAll({\n            where: {\n                ...query,\n                [Op.or]: [{ name: {[Op.like]: `%${searchText}%` }}],\n            },\n            offset,\n            limit,\n        });\n        ...\n```\n\n```text\nswitch(1) {\n    case 1:\n        console.log('case 1');\n    case 2:\n        console.log('case 2');\n}\n// OUTPUT:\n// case 1\n// case 2\n```\n\n```text\nswitch(1) {\n    case 1: {\n        const n = 1\n        console.log('case ' + n)\n        break\n    }\n    case 2: {\n        const n = 2\n        console.log('case ' + n)\n        break\n    }\n}\n// That's valid\n```\n\n```text\nconst query = { /* whatever */ }\n\nconst { count, rows } = await User.findAndCountAll({\n    where: tab === 'active' ? {\n        ...query,\n    } : {\n        ...query,\n        [Op.or]: [{ name: {[Op.like]: `%${searchText}%` }}]\n    },\n    offset,\n    limit,\n})\n```\n\n```text\nbreak\n```\n\n```text\ncase\n```\n\n```text\nswitch\n```\n\n```text\nbreak\n```\n\n========================================\n\nComments:\n- Thanks for such a clear explanation! Is there also a way to solve it by not defining `count` and `rows` as constants? I tried `let count, rows;` outside the scope of the cases, but that didn't work, I think because it's `{ count, rows }`.\n- Yep, you're destructuring them so the only alternative can be declaring them outside of the switch and then manually assign the values, in this case it's better destructuring them even if you'll have duplicate variable names. I'm editing my answer to show you another approach\n- I just edited my answer to show you what i would probably do to achieve your goal, hope it helps","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":129,"estimatedTokens":685}}730{"id":"stack-52680436","source":"stackoverflow","questionId":52680436,"title":"Node.js Database Module with Sequelize","tags":["javascript","node.js","async-await","sequelize.js","require"],"text":"Title: Node.js Database Module with Sequelize\nTags: javascript, node.js, async-await, sequelize.js, require\nSource: Stack Overflow\n\nQuestion:\nTo make my code more readable, I'm trying to move all database related code into a single file. and use Sequelize as ORM. I would like that this file, when included provide a ready to use Database. Tables schemas are also managed by Sequelize which is why I use the `sync()` method to create the tables on the first run. Unfortunately, when I run the application for the first time, I get an error that the table doesn't exist when using this code:\n\nFile: test.js\n\n```\nconst database = require('./dbInit');\n\n(async () => {\n\n await database.testTable.max('id').then((maxId) => {\n console.log(maxId);\n });\n\n})();\n```\n\nFile: dbInit.js\n\n```\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('mysql://root:root@localhost:3306/test');\n\nconst testTable = sequelize.import('testTable');\n\nconst database = {\n sequelize: sequelize,\n testTable: testTable,\n};\n\nsequelize\n .authenticate()\n .then(() => {\n console.log('Connection to the database has been established successfully.');\n })\n .catch(error => {\n console.error(error);\n });\n\nsequelize.sync();\n\nmodule.exports = database;\n```\n\nFile: testTable.js\n\n```\nconst Sequelize = require('sequelize');\n\nmodule.exports = (sequelize, DataTypes) => {\n return sequelize.define('testTable',\n {\n id: {\n type: Sequelize.BIGINT(19).UNSIGNED,\n primaryKey: true,\n autoIncrement: false,\n }\n }\n );\n};\n```\n\nWhen I run the code as is, without tables created, I can see from the logs that the query is run before the connection to the database is available:\n\n```\n> node .\\test.js\nExecuting (default): SELECT 1+1 AS result\nExecuting (default): SELECT max(`id`) AS `max` FROM `testTables` AS `testTable`;\nConnection to the database has been established successfully.\n(node:1572) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Table 'test.testtables' doesn't exist\n```\n\nI have found a way to make it work by adding this like, just before the call to the DB (in test.js before the `max('id')` call):\n\n```\nawait database.sequelize.sync();\n```\n\nIs there any other way to have the dbInit module completely independent and not having to add this `sync()` call inside all other files which will require database connectivity?\n\nI've looked for sync module loading but it doesn't seem an option yet.\n\n========================================\n\nTop Answer:\nYou can up my github repo Sequelize-DemoApp. It's a fully working full stack application made especially to demonstrate and understand Sequelize.js and it's integration with nodejs\n\n========================================\n\nCode:\n```text\nconst database = require('./dbInit');\n\n(async () => {\n\n    await database.testTable.max('id').then((maxId) => {\n        console.log(maxId);\n    });\n\n})();\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('mysql://root:root@localhost:3306/test');\n\nconst testTable = sequelize.import('testTable');\n\nconst database = {\n    sequelize: sequelize,\n    testTable: testTable,\n};\n\nsequelize\n    .authenticate()\n    .then(() => {\n        console.log('Connection to the database has been established successfully.');\n    })\n    .catch(error => {\n        console.error(error);\n    });\n\nsequelize.sync();\n\nmodule.exports = database;\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nmodule.exports = (sequelize, DataTypes) => {\n    return sequelize.define('testTable',\n        {\n            id: {\n                type: Sequelize.BIGINT(19).UNSIGNED,\n                primaryKey: true,\n                autoIncrement: false,\n            }\n        }\n    );\n};\n```\n\n```text\n> node .\\test.js\nExecuting (default): SELECT 1+1 AS result\nExecuting (default): SELECT max(`id`) AS `max` FROM `testTables` AS `testTable`;\nConnection to the database has been established successfully.\n(node:1572) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Table 'test.testtables' doesn't exist\n```\n\n```text\nawait database.sequelize.sync();\n```\n\n```text\nsync()\n```\n\n```text\nmax('id')\n```\n\n```text\nsync()\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('mysql://root:root@localhost:3306/test');\n\nconst connect = async () => {\n  try {\n    await sequelize.authenticate();\n    await sequelize.sync();\n\n    console.log('Connection to the database has been established successfully.');\n  }\n  catch (error) {\n    console.error(error.message);\n    process.exit(-1);\n  }\n});\n\nconst model = name => database.models[name];\n\nconst User = sequelize.import('./schemas/User');\n\nconst database = {\n    sequelize: sequelize,\n    models: {User},\n    connect,\n    model\n};\n\nmodule.exports = database;\n```\n\n```text\nconst db = require('./db');\n\n(async () => {\n    await db.connect();\n\n    const User = db.model('User');\n\n    const id = await User.max('id');\n\n    console.log(id);\n})();\n```\n\n```text\ndb\n```\n\n```text\ndb/schemas/User.js\n```\n\n```text\ndb/index.js\n```\n\n```text\ntest.js\n```\n\n========================================\n\nComments:\n- This is strange, now the logs look fine but I'm still getting ` 'test.testtables' doesn't exist` error - any idea?\n- @NicolasBouvrette read about Migrations docs.sequelizejs.com/manual/tutorial/migrations.html tables must be created before of everything\n- Isn't that what `sync()` does? I was looking for a clean way to create tables dynamically. Seems like my issues is more a Node.js sync-async problem right now?\n- BTW look at this: docs.sequelizejs.com/manual/installation/usage.html OPTIONS section, it has `sync: true` it's enabled by default. Very strange that tables not creating.\n- @NicolasBouvrette try second option in my answer by passing `sync: {force: true}`\n- Yep, just tried, and getting the same result. I noticed something odd (might not be related) but Sequelize adds an 's' character when doing queries to my table: `Table 'test.testtables' doesn't exist` I also see this in the logs before the connection: `Executing (default): SELECT max(`id`) AS `max` FROM `testtables` AS `testtable`;`\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":245,"estimatedTokens":1525}}731{"id":"stack-76037548","source":"stackoverflow","questionId":76037548,"title":"\"Uncaught TypeError: LRU is not a constructor\" when trying to connect to a MySQL server via Sequelize","tags":["javascript","mysql","npm","sequelize.js","lru"],"text":"Title: \"Uncaught TypeError: LRU is not a constructor\" when trying to connect to a MySQL server via Sequelize\nTags: javascript, mysql, npm, sequelize.js, lru\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a web application based on boardgame.io that is just their *Tic-Tac-Toe* tutorial game, but the results of each match get saved to a MySQL database. In its current state, my code just tries to connect to the database, the result of which should be displayed into the browser's console.\n\n```\nimport { Client } from 'boardgame.io/client';\nimport { TicTacToe } from './Game';\n\nclass TicTacToeClient {\n constructor(rootElement) {\n this.client = Client({ game: TicTacToe });\n this.client.start();\n this.rootElement = rootElement;\n this.createBoard();\n this.attachListeners();\n this.client.subscribe(state => this.update(state));\n const { Sequelize, DataTypes } = require(\"sequelize\");\n const sequelize = new Sequelize(\n 'tictactoetest',\n 'xxxx',\n 'xxxx',\n {\n host: 'localhost',\n dialect: 'mysql',\n dialectModule: require('mysql2')\n }\n );\n \n sequelize.authenticate().then(() => \n {\n console.log('Connection has been established successfully.');\n }).catch((error) => {\n console.error('Unable to connect to the database: ', error);\n });\n const Record = sequelize.define(\"record\", \n {\n log: \n {\n type: DataTypes.STRING,\n allowNull: false\n },\n winner: \n {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n tableName: 'record'\n });\n \n sequelize.sync().then(() => {\n console.log('Record table created successfully!');\n }).catch((error) => {\n console.error('Unable to create table : ', error);\n });\n }\n\n createBoard() \n {\n //Irrelevant\n }\n\n attachListeners() \n {\n //Irrelevant\n }\n\n update(state) \n {\n //Irrelevant\n }\n}\n\nconst appElement = document.getElementById('app');\nconst app = new TicTacToeClient(appElement);\n```\n\nThe game itself works properly, but instead of the confirmation of success/failure, I get `\"Uncaught TypeError: LRU is not a constructor\"`. I have tried installing all the LRU libraries I could with NPM, nothing helps. I have successfully ran the same DB connection code in a separate file using `\"node\"`, so I have no idea where the issue could be.\n\n========================================\n\nTop Answer:\nIf you `npm ls lru-cache`, I'm willing to bet that one of your direct or transitive dependencies depend on version 8 or earlier of `lru-cache`, and are instead getting version 9 or 10.\n\nI'm also willing to bet, if this is the case, that you're using yarn. It's broken. I recommend switching to npm or pnpm, since these are capable of resolving a package tree according to the stated dependency ranges.\n\n========================================\n\nCode:\n```text\nimport { Client } from 'boardgame.io/client';\nimport { TicTacToe } from './Game';\n\nclass TicTacToeClient {\n  constructor(rootElement) {\n    this.client = Client({ game: TicTacToe });\n    this.client.start();\n    this.rootElement = rootElement;\n    this.createBoard();\n    this.attachListeners();\n    this.client.subscribe(state => this.update(state));\n    const { Sequelize, DataTypes } = require(\"sequelize\");\n    const sequelize = new Sequelize(\n      'tictactoetest',\n      'xxxx',\n      'xxxx',\n       {\n         host: 'localhost',\n         dialect: 'mysql',\n         dialectModule: require('mysql2')\n       }\n     );\n     \n     sequelize.authenticate().then(() => \n     {\n         console.log('Connection has been established successfully.');\n      }).catch((error) => {\n         console.error('Unable to connect to the database: ', error);\n      });\n      const Record = sequelize.define(\"record\", \n      {\n          log: \n          {\n            type: DataTypes.STRING,\n            allowNull: false\n          },\n          winner: \n          {\n            type: DataTypes.STRING,\n            allowNull: false\n          }\n      }, {\n          tableName: 'record'\n      });\n  \n      sequelize.sync().then(() => {\n          console.log('Record table created successfully!');\n       }).catch((error) => {\n          console.error('Unable to create table : ', error);\n       });\n  }\n\n  createBoard() \n  {\n    //Irrelevant\n  }\n\n  attachListeners() \n  {\n    //Irrelevant\n  }\n\n  update(state) \n  {\n    //Irrelevant\n  }\n}\n\nconst appElement = document.getElementById('app');\nconst app = new TicTacToeClient(appElement);\n```\n\n```text\n\"Uncaught TypeError: LRU is not a constructor\"\n```\n\n```text\n\"node\"\n```\n\n```text\n\"dependencies\": {\n\"mysql2\": \"^2.2.5\",\n\"pg-hstore\": \"^2.3.4\",\n\"sequelize\": \"^5.22.5\"\n},\n```\n\n```text\npackage.json\n```\n\n```text\nnpm ls lru-cache\n```\n\n```text\nlru-cache\n```\n\n```js\nconst { use } = require('use-m');\n\nuse('lru-cache@8').then((LRU) => {\n  const cache = new LRU({\n    max: 100, // Define maximum cache size\n  });\n  console.log('Cache created with max size of', cache.max);\n});\n```\n\n```js\nimport { use } from 'use-m';\n\nconst LRU = await use('lru-cache@8');\n\nconst cache = new LRU({\n  max: 100, // Define maximum cache size\n});\nconsole.log('Cache created with max size of', cache.max);\n```\n\n```text\nnpm list lru-cache\n```\n\n```text\nuse-m\n```\n\n```text\nuse-m\n```\n\n```text\nnpm i use-m\n```\n\n```text\nyarn add use-m\n```\n\n```text\nLRU\n```\n\n```text\nUncaught TypeError: LRU is not a constructor\n```\n\n========================================\n\nComments:\n- There might be some truth to this, but like I said above, the whole code was fundamentally incorrect. My approach to the issue was completely wrong. I have already understood the issue and finished this project (it was my bachelor's thesis), and it works.\n- I had similar issue and you was right - it occures because of dependency conflict. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":248,"estimatedTokens":1398}}732{"id":"stack-62455442","source":"stackoverflow","questionId":62455442,"title":"Sequelize Model Mocking findAll and findOne using sequelize-mock and jest","tags":["node.js","unit-testing","jestjs","sequelize.js"],"text":"Title: Sequelize Model Mocking findAll and findOne using sequelize-mock and jest\nTags: node.js, unit-testing, jestjs, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nFor my User's CRUD, I am writing a UNIT test using sequelize-mock and jest. Model mocking works for me but my issue is regarding the mock model `findAll()` and `findOne()` calling both of them in my Users test suite both returns the queued results I defined in my mock model. I'm expecting that if i call `findAll()`, I should get all the data that are defined in my queued results and if i call `findOne()` I should only get one data from the queued result based on the id i passed. Setting mock model `autoQueryFallback: false` doesn't work for me.\n\nHere is a code snippet:\n\nIn my `controllers/users.js`\n\n```\nmodule.exports = {\n async list (req, res) {\n Users.findAndCountAll({\n limit: 10,\n offset: 0\n }).then(data => {\n console.log('Users >>> ', data);\n });\n },\n async view (req, res) {\n Users.findOne({\n where: { id: req.params.id }\n }).then(data => {\n console.log('User Data by ID >>> ', data);\n });\n }\n};\n```\n\nTo mock my users model, I have to create a `__mocks__` directory adjacent to the models (this is how Jest works). So, I have this directory structure in my models\n\n```\n> models/users.js\n> models/__mocks__/users.js\n```\n\n```\nconst Users = dbMock.define('users', {}, { autoQueryFallback: false });\nUsers.$queueResult([\n Users.build({\n id: 1,\n email: 'testActive@test.com',\n fullname : 'Test Active Users',\n status: 'active', \n }),\n Users.build({\n id: 2,\n email: 'testDeleted@test.com',\n fullname: 'Test Deleted Users',\n status: 'deleted', \n }),\n]);\n```\n\n### Mocks\n\nI want to test both users.list and users.view using the set of data's in my mocked model\n\n```\njest.mock('../models/users');\ndescribe('Testing use.list()', () => {\n it('UsersController.list() should return a status code 201 and all Users data in object array', async () => {\n await users.list(req, res);\n expect(res.json).toBeCalledWith(\n expect.objectContaining({\n data: expect.any(Object)\n })\n );\n });\n it('UsersController.view() should return a status code 201 and user data obj', async () => {\n //Passed req.params.id = 2\n await user.login(req, res);\n expect(res.status).toHaveBeenCalledWith(failureCode);\n expect(res.json).toBeCalledWith(\n expect.objectContaining({\n data: expect.any(Object)\n })\n );\n });\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n    async list (req, res) {\n        Users.findAndCountAll({\n            limit: 10,\n            offset: 0\n        }).then(data => {\n            console.log('Users >>> ', data);\n        });\n    },\n    async view (req, res) {\n        Users.findOne({\n            where: { id: req.params.id }\n        }).then(data => {\n            console.log('User Data by ID >>> ', data);\n        });\n    }\n};\n```\n\n```text\n> models/users.js\n> models/__mocks__/users.js\n```\n\n```text\nconst Users = dbMock.define('users', {}, { autoQueryFallback: false });\nUsers.$queueResult([\n    Users.build({\n        id: 1,\n        email: 'testActive@test.com',\n        fullname : 'Test Active Users',\n        status: 'active', \n    }),\n    Users.build({\n        id: 2,\n        email: 'testDeleted@test.com',\n        fullname: 'Test Deleted Users',\n        status: 'deleted', \n    }),\n]);\n```\n\n```text\njest.mock('../models/users');\ndescribe('Testing use.list()', () => {\n    it('UsersController.list() should return a status code 201 and all Users data in object array', async () => {\n        await users.list(req, res);\n        expect(res.json).toBeCalledWith(\n            expect.objectContaining({\n                data: expect.any(Object)\n            })\n        );\n    });\n    it('UsersController.view() should return a status code 201 and user data obj', async () => {\n        //Passed req.params.id = 2\n        await user.login(req, res);\n        expect(res.status).toHaveBeenCalledWith(failureCode);\n        expect(res.json).toBeCalledWith(\n            expect.objectContaining({\n                data: expect.any(Object)\n            })\n        );\n    });\n});\n```\n\n```text\nfindAll()\n```\n\n```text\nfindOne()\n```\n\n```text\nfindAll()\n```\n\n```text\nfindOne()\n```\n\n```text\nautoQueryFallback: false\n```\n\n```text\ncontrollers/users.js\n```\n\n```text\n__mocks__\n```\n\n```js\n// define user model\nmodule.exports = {};\n```\n\n```js\nconst Users = require('../models/users');\n\nmodule.exports = {\n  async list(req, res) {\n    return Users.findAndCountAll({\n      limit: 10,\n      offset: 0,\n    }).then((data) => {\n      console.log('Users >>> ', data);\n      res.status(201).json({ data });\n    });\n  },\n  async view(req, res) {\n    return Users.findOne({\n      where: { id: req.params.id },\n    }).then((data) => {\n      console.log('User Data by ID >>> ', data);\n      res.status(201).json({ data });\n    });\n  },\n};\n```\n\n```js\nconst users = require('./users');\n\njest.mock('../models/users', () => {\n  const SequelizeMock = require('sequelize-mock');\n  const dbMock = new SequelizeMock();\n  const UserMock = dbMock.define('user');\n  UserMock.$queryInterface.$useHandler((query, queryOptions) => {\n    if (query === 'findAndCountAll') {\n      return { count: 2, rows: [UserMock.build({ id: 1 }), UserMock.build({ id: 2 })] };\n    } else if (query === 'findOne') {\n      return UserMock.build({ id: queryOptions[0].where.id });\n    }\n  });\n  return UserMock;\n});\n\ndescribe('Testing use.list()', () => {\n  it('UsersController.list() should return a status code 201 and all Users data in object array', async () => {\n    const req = {};\n    const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };\n    await users.list(req, res);\n    expect(res.status).toHaveBeenCalledWith(201);\n    expect(res.json).toBeCalledWith(\n      expect.objectContaining({\n        data: expect.objectContaining({\n          count: 2,\n          rows: expect.arrayContaining([\n            expect.objectContaining({\n              id: expect.any(Number),\n              createdAt: expect.any(Date),\n              updatedAt: expect.any(Date),\n            }),\n          ]),\n        }),\n      }),\n    );\n  });\n  it('UsersController.view() should return a status code 201 and user data obj', async () => {\n    const req = { params: { id: 2 } };\n    const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };\n    await users.view(req, res);\n    expect(res.status).toHaveBeenCalledWith(201);\n    expect(res.json).toBeCalledWith(\n      expect.objectContaining({\n        data: expect.objectContaining({\n          id: 2,\n          createdAt: expect.any(Date),\n          updatedAt: expect.any(Date),\n        }),\n      }),\n    );\n  });\n});\n```\n\n```bash\nPASS  src/examples/stackoverflow/62455442/controller/users.test.js\n  Testing use.list()\n    ✓ UsersController.list() should return a status code 201 and all Users data in object array (12ms)\n    ✓ UsersController.view() should return a status code 201 and user data obj (12ms)\n\n  console.log src/examples/stackoverflow/62455442/controller/users.js:9\n    Users >>>  {\n      count: 2,\n      rows: [\n        fakeModelInstance {\n          options: [Object],\n          _values: [Object],\n          dataValues: [Object],\n          hasPrimaryKeys: true,\n          __validationErrors: []\n        },\n        fakeModelInstance {\n          options: [Object],\n          _values: [Object],\n          dataValues: [Object],\n          hasPrimaryKeys: true,\n          __validationErrors: []\n        }\n      ]\n    }\n\n  console.log src/examples/stackoverflow/62455442/controller/users.js:17\n    User Data by ID >>>  fakeModelInstance {\n      options: {\n        timestamps: true,\n        paranoid: undefined,\n        createdAt: undefined,\n        updatedAt: undefined,\n        deletedAt: undefined,\n        isNewRecord: true\n      },\n      _values: {\n        id: 2,\n        createdAt: 2023-03-21T06:19:42.373Z,\n        updatedAt: 2023-03-21T06:19:42.373Z\n      },\n      dataValues: {\n        id: 2,\n        createdAt: 2023-03-21T06:19:42.373Z,\n        updatedAt: 2023-03-21T06:19:42.373Z\n      },\n      hasPrimaryKeys: true,\n      __validationErrors: []\n    }\n\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        2.794s, estimated 3s\n```\n\n```json\n\"sequelize-mock\": \"^0.10.2\",\n\"jest\": \"^29.5.0\",\n\"sequelize\": \"^5.21.3\",\n```\n\n```text\nquery\n```\n\n```text\nqueryOptions\n```\n\n```text\nmodels/users.js\n```\n\n```text\ncontroller/users.js\n```\n\n```text\ncontroller/users.test.js\n```\n\n========================================\n\nComments:\n- Did you manage to solve this issue? I'm running into the same case scenario.","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":354,"estimatedTokens":2134}}733{"id":"stack-50311854","source":"stackoverflow","questionId":50311854,"title":"List applied sequelize migrations","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: List applied sequelize migrations\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nIs there a way to show the migrations already applied ?\n\nI would like to know which migration is the last one, so I can decide whether to undo it or not.\n\n========================================\n\nTop Answer:\n```\nnpx sequelize db:migrate:status\n```\n\nworks fine for me (Sequelize 6)\n\n========================================\n\nCode:\n```text\nNODE_ENV=test ./node_modules/.bin/sequelize db:migrate:status\n```\n\n```text\nenv\n```\n\n```text\nUp\n```\n\n```text\nSequelize/index.js\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nsequelize migrate:status\n// or if your sequelize is used within node modules folder\n./node_modules/.bin/sequelize migrate:status\n```\n\n```text\nnpx sequelize-cli db:migrate:status\n```\n\n```text\nnpx sequelize db:migrate:status\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":54,"estimatedTokens":213}}734{"id":"stack-61010966","source":"stackoverflow","questionId":61010966,"title":"sequelize beforeCreate hook is not executing","tags":["node.js","sequelize.js"],"text":"Title: sequelize beforeCreate hook is not executing\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI wrote a BeforeCreate hook in my sequelize model. when i hit create user route then it saying user.user_id can't be null and even before create hook function not executing. I have followed documentation of sequelize.They have mentioned same as I use.I wrote a BeforeCreate hook in my sequelize model. when i hit create user route then it saying user.user_id can't be null and even before create hook function not executing. I have followed documentation of sequelize.They have mentioned same as I use.\n\n```\nconst sequelize = require(\"kvell-db-plugin-sequelize\").dbInstance;\nconst Sequelize = require(\"kvell-db-plugin-sequelize\").dbLib;\nconst shortid = require(\"shortid\");\nconst User = sequelize.define(\n \"user\",\n {\n id: {\n type: Sequelize.INTEGER,\n autoIncrement: true,\n allowNull: false\n },\n user_id: {\n type: Sequelize.STRING,\n allowNull: false,\n primaryKey: true,\n unique: true\n },\n user_fname: {\n type: Sequelize.STRING,\n allowNull: false\n },\n user_lname: {\n type: Sequelize.STRING,\n allowNull: false\n },\n user_fullName: {\n type: Sequelize.VIRTUAL,\n get() {\n return `${this.user_fname} ${this.user_lname}`;\n },\n set(value) {\n throw new Error(\"Do not try to set the `fullName` value!\");\n }\n },\n user_email: {\n type: Sequelize.STRING,\n allowNull: false,\n primaryKey: true,\n validate: {\n isEmail: true\n },\n\n unique: {\n args: true,\n msg: \"Email address already in use!\"\n }\n },\n user_credential: {\n type: Sequelize.STRING,\n allowNull: false\n },\n user_roles: {\n type: Sequelize.ARRAY(Sequelize.STRING),\n allowNull: false,\n defaultValue: [\"Admin\"]\n },\n admin: {\n type: Sequelize.BOOLEAN,\n allowNull: false,\n defaultValue: true\n },\n user_img: {\n type: Sequelize.STRING,\n allowNull: true\n }\n },\n {\n timestamps: true\n\n }\n);\n\nUser.beforeCreate(async (user, options) => {\n console.log(\"inside hooks\");\n let id = `user_${shortid.generate()}`;\n user.user_id = id;\n});\n\nconst toJSON = User.prototype.toJSON;\n\nUser.prototype.toJSON = function({ attributes = [] } = {}) {\n const obj = toJSON.call(this);\n\n if (!attributes.length) {\n return obj;\n }\n\n return attributes.reduce((result, attribute) => {\n result[attribute] = obj[attribute];\n\n return result;\n }, {});\n};\n\nmodule.exports = User;\n```\n\n========================================\n\nTop Answer:\nThe real answer (alluded to, but not explicitly stated, in one of the comments) is that `beforeCreate` hooks are applied *after* model validation.\n\nThis means if you have any field in your model (eg `id` ) which cannot be null, Sequelize will evaluate this prior to applying the `beforeCreate` field. In your case, Sequelize never gets as far as the `beforeCreate` hook, because the null `id` is failing validation every time.\n\nYour accepted answer works around this by setting `allowNull = true`, thus circumventing the validation of your (briefly) null `id`. But the better option (rather than to distort your model by allowing null `id`) is almost certainly to instead use the correct hook: `beforeValidate`. This hook is applied *before* the model criteria are evaluated.\n\nIt is a very simple change:\n\n```\nUser.beforeValidate(async (user, options) => {\n console.log(\"inside hooks\");\n let id = `user_${shortid.generate()}`;\n user.user_id = id;\n});\n```\n\nNB: `async` is redundant here.\n\n========================================\n\nCode:\n```text\nconst sequelize = require(\"kvell-db-plugin-sequelize\").dbInstance;\nconst Sequelize = require(\"kvell-db-plugin-sequelize\").dbLib;\nconst shortid = require(\"shortid\");\nconst User = sequelize.define(\n  \"user\",\n  {\n    id: {\n      type: Sequelize.INTEGER,\n      autoIncrement: true,\n      allowNull: false\n    },\n    user_id: {\n      type: Sequelize.STRING,\n      allowNull: false,\n      primaryKey: true,\n      unique: true\n    },\n    user_fname: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    user_lname: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    user_fullName: {\n      type: Sequelize.VIRTUAL,\n      get() {\n        return `${this.user_fname} ${this.user_lname}`;\n      },\n      set(value) {\n        throw new Error(\"Do not try to set the `fullName` value!\");\n      }\n    },\n    user_email: {\n      type: Sequelize.STRING,\n      allowNull: false,\n      primaryKey: true,\n      validate: {\n        isEmail: true\n      },\n\n      unique: {\n        args: true,\n        msg: \"Email address already in use!\"\n      }\n    },\n    user_credential: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    user_roles: {\n      type: Sequelize.ARRAY(Sequelize.STRING),\n      allowNull: false,\n      defaultValue: [\"Admin\"]\n    },\n    admin: {\n      type: Sequelize.BOOLEAN,\n      allowNull: false,\n      defaultValue: true\n    },\n    user_img: {\n      type: Sequelize.STRING,\n      allowNull: true\n    }\n  },\n  {\n    timestamps: true\n\n }\n);\n\nUser.beforeCreate(async (user, options) => {\n  console.log(\"inside hooks\");\n  let id = `user_${shortid.generate()}`;\n  user.user_id = id;\n});\n\nconst toJSON = User.prototype.toJSON;\n\nUser.prototype.toJSON = function({ attributes = [] } = {}) {\n  const obj = toJSON.call(this);\n\n  if (!attributes.length) {\n    return obj;\n  }\n\n  return attributes.reduce((result, attribute) => {\n    result[attribute] = obj[attribute];\n\n    return result;\n  }, {});\n};\n\nmodule.exports = User;\n```\n\n```text\nuser_id: {\n      type: Sequelize.STRING,\n      allowNull: false,\n      primaryKey: true,\n      unique: true\n    }\n```\n\n```text\nallowNull = false\n```\n\n```text\nuser.user_id===null\n```\n\n```text\nallowNull===true\n```\n\n```text\nasync (user, options)\n```\n\n```text\nUser.beforeValidate(async (user, options) => {\n  console.log(\"inside hooks\");\n  let id = `user_${shortid.generate()}`;\n  user.user_id = id;\n});\n```\n\n```text\nbeforeCreate\n```\n\n```text\nid\n```\n\n```text\nbeforeCreate\n```\n\n```text\nbeforeCreate\n```\n\n```text\nid\n```\n\n```text\nallowNull = true\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nbeforeValidate\n```\n\n```text\nasync\n```\n\n========================================\n\nComments:\n- Could you show full code example of what you did. Im having the same issue.\n- I have same issues but now OK. We need to make sure that our model attributes do not encounter any validation error. Please see this: sequelize.org/master/manual/hooks.html#hooks-firing-order.","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":305,"estimatedTokens":1578}}735{"id":"stack-42811710","source":"stackoverflow","questionId":42811710,"title":"Sequelize umzug migrations","tags":["node.js","sequelize.js","umzug"],"text":"Title: Sequelize umzug migrations\nTags: node.js, sequelize.js, umzug\nSource: Stack Overflow\n\nQuestion:\nI am using `sequelize js` and developed a `node js application`, which is deployed to production and have live DB.\n\nwhile in development mode, if I need to `alter` the `DB`, I used to do it using **`Sequelize.sync({ force: true })`** and it worked well.\n\nBut now, after development is done **I want to alter a table and add a column to it.**\n\n**I searched many posts but, didn't get an exact example on how to run these migrations.**\n\nI tried to use `Umzug` and run a migration, but it is throwing me errors.\n\nHere is the code I tried,\n\n**migrations/barmigration.js:**\n\n```\nvar Sequelize = require('sequelize');\n\n\"use strict\";\n\nmodule.exports = {\n\n up: function(migration, DataTypes) {\n return [\n migration.addColumn(\n 'Bars',\n 'PrinterId',\n Sequelize.STRING\n ),\n migration.addColumn(\n 'Bars',\n 'PrinterStatus',\n Sequelize.STRING\n )]\n\n },\n\n down: function(migration, DataTypes) {\n return\n [\n migration.removeColumn('Bars', 'PrinterStatus'),\n migration.removeColumn('Bars', 'PrinterId')\n ]\n }\n\n};\n```\n\nHere is the **`umzug configuration`:**\n\n```\nvar Umzug = require('umzug');\n var sequelize = require('sequelize');\n\n var umzug = new Umzug({\n\n // storage: 'sequelize',\n model: 'Bar',\n\n storageOptions: {\n sequelize: sequelize,\n },\n\n migrations: {\n path: './migrations',\n pattern: /\\.js$/\n }\n\n });\n\n // umzug.up().then(function(migrations) {\n // console.log('Migration complete!');\n // });\n\n umzug.down().then(function(migrations) {\n console.log('Migration complete!');\n });\n```\n\nWhen I run that file, I am getting an error in `up function`, at this position **`return migration.addColumn`**\n\n**Error:**\n\n**`Unhandled rejection TypeError: Cannot read property 'addColumn' of undefined`**\n\nSo, the parameter migration seems to be `undefined`. Pls help me out.\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\n\n\"use strict\";\n\nmodule.exports = {\n\n    up: function(migration, DataTypes) {\n      return [\n      migration.addColumn(\n        'Bars',\n        'PrinterId',\n        Sequelize.STRING\n      ),\n      migration.addColumn(\n        'Bars',\n        'PrinterStatus',\n        Sequelize.STRING\n      )]\n\n    },\n\n    down: function(migration, DataTypes) {\n        return\n         [\n            migration.removeColumn('Bars', 'PrinterStatus'),\n            migration.removeColumn('Bars', 'PrinterId')\n        ]\n    }\n\n};\n```\n\n```text\nvar Umzug = require('umzug');\n    var sequelize = require('sequelize');\n\n    var umzug = new Umzug({\n\n        // storage: 'sequelize',\n        model: 'Bar',\n\n\n        storageOptions: {\n            sequelize: sequelize,\n        },\n\n        migrations: {\n            path: './migrations',\n            pattern: /\\.js$/\n        }\n\n    });\n\n    //  umzug.up().then(function(migrations)  {\n    //    console.log('Migration complete!');\n   //     });\n\n    umzug.down().then(function(migrations)  {\n      console.log('Migration complete!');\n    });\n```\n\n```text\nsequelize js\n```\n\n```text\nnode js application\n```\n\n```text\nalter\n```\n\n```text\nDB\n```\n\n```text\nSequelize.sync({ force: true })\n```\n\n```text\nUmzug\n```\n\n```text\numzug configuration\n```\n\n```text\nup function\n```\n\n```text\nreturn migration.addColumn\n```\n\n```text\nUnhandled rejection TypeError: Cannot read property 'addColumn' of undefined\n```\n\n```text\nundefined\n```\n\n```text\n{\n    storage: 'sequelize',\n    storageOptions: {\n        sequelize: sequelize // here should be a sequelize instance, not the Sequelize module\n    },\n    migrations: {\n        params: [\n            sequelize.getQueryInterface(),\n            Sequelize // Sequelize constructor - the required module\n        ],\n        path: './migrations',\n        pattern: /\\.js$/\n    }\n}\n```\n\n```text\n- db\n     - database.js\n     - umzug.js\n```\n\n```text\n// database.js\n const Sequelize = require('sequelize');\n\n const db = {\n     sequelize: new Sequelize(connectionString, options),\n     Sequelize: Sequelize\n };\n\n module.exports = db;\n```\n\n```text\n// umzug.js\nconst db = require('./database');\n\n// here comes the configuration and initialization of Umzug instance with use of db object\n// db.sequelize -> sequelize instance\n// db.Sequelize -> sequelize constructor (class)\n```\n\n```text\nparams\n```\n\n```text\nmigrations\n```\n\n```text\nUmzug\n```\n\n```text\nup\n```\n\n```text\ndown\n```\n\n```text\nmigration\n```\n\n```text\nsequelize.getQueryInterface()\n```\n\n```text\nqueryInterface\n```\n\n```text\nDataTypes\n```\n\n```text\nSequelize\n```\n\n```text\nmodel\n```\n\n```text\nSequelizeMeta\n```\n\n```text\nUmzug\n```\n\n```text\nstorageOptions\n```\n\n```text\ndatabase.js\n```\n\n```text\nUmzug\n```\n\n========================================\n\nComments:\n- thnx for your response. but I am getting error, `TypeError: sequelize.getQueryInterface is not a function`. I required `sequelize` in the file.\n- `sequelize.getQueryInterface` must be run on Sequelize instance, not on the constructor itself. Did you create a sequelize instance in separate file and required it in this one?\n- yes, I have an instance of `sequelize` and exported that instance.\n- Then you must be doing something wrong. You would have to update the question with your new code version.\n- I have edited the answer, maybe now it will help you.\n- thnx for your update, now I got my migration working. but not completely. When I call `up()` method it is working fine. but, when I call `down()`, strangely it is not working. updated my latest code in the question.\n- Not working in what way? What happens when you call `down()`?\n- the migration method gets called, but `drop query` is not getting called.\n- I have tested above configuration and everything works fine, source of the problem with not removing columns must be somewhere else...\n- thank you. It worked now and strangely I didn't change any code.","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":33,"totalLines":322,"estimatedTokens":1452}}736{"id":"stack-39009062","source":"stackoverflow","questionId":39009062,"title":"Sequelize-CLI Add Column to Existing Model","tags":["sequelize.js","sequelize-cli"],"text":"Title: Sequelize-CLI Add Column to Existing Model\nTags: sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI have been reading through a good amount of the sequelize-cli documentation and can't seem to figure out how to add a column to an existing model that I have in place. I have a model called, `models/team.js` and want to add a column named `role_name` to the model with `sequelize model:create --name team --attributes role_name:string`, but I receive a message to overwrite rather then modify:\n\n```\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\nThe file /Users/user/Desktop/Projects/node/app-repo/app/models/team.js already exists. Run \"sequelize model:create --force\" to overwrite it.\n```\n\nI don't want to overwrite the file that makes me think that this isn't the right command to use. It also makes me wonder if this is not possible from the cli and must be adjusted at the migration file level.\n\n========================================\n\nTop Answer:\nIn case you want to do multiple changes in single migration, you can just return chained promises like this:\n\n```\nmodule.exports = {\nup: function (queryInterface, Sequelize) {\n return queryInterface.addColumn('yourTableName', 'firstNewColumnName', Sequelize.STRING)\n .then(_ => queryInterface.addColumn('yourTableName', 'secondNewColumnName', Sequelize.STRING))\n .then(_ => queryInterface.addColumn('yourTableName', 'thirdNewColumnName', Sequelize.STRING));\n },\n\ndown: function (queryInterface, _Sequelize) {\n return queryInterface.removeColumn('yourTableName', 'firstNewColumnName')\n .then(_ => queryInterface.removeColumn('yourTableName', 'secondNewColumnName'))\n .then(_ => queryInterface.removeColumn('yourTableName', 'thirdNewColumnName'));\n },\n};\n```\n\n========================================\n\nCode:\n```text\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\nThe file /Users/user/Desktop/Projects/node/app-repo/app/models/team.js already exists. Run \"sequelize model:create --force\" to overwrite it.\n```\n\n```text\nmodels/team.js\n```\n\n```text\nrole_name\n```\n\n```text\nsequelize model:create --name team --attributes role_name:string\n```\n\n```text\nqueryInterface.addColumn(\n     'nameOfAnExistingTable',\n      'nameofTheNewAttribute',\n      Sequelize.STRING)\n```\n\n```text\nqueryInterface.removeColumn(\n      'nameOfAnExistingTable',\n      'nameOfTheAttribute')\n```\n\n```text\nmodule.exports = {\nup: function (queryInterface, Sequelize) {\n    return queryInterface.addColumn('yourTableName', 'firstNewColumnName', Sequelize.STRING)\n        .then(_ => queryInterface.addColumn('yourTableName', 'secondNewColumnName', Sequelize.STRING))\n        .then(_ => queryInterface.addColumn('yourTableName', 'thirdNewColumnName', Sequelize.STRING));\n    },\n\ndown: function (queryInterface, _Sequelize) {\n    return queryInterface.removeColumn('yourTableName', 'firstNewColumnName')\n        .then(_ => queryInterface.removeColumn('yourTableName', 'secondNewColumnName'))\n        .then(_ => queryInterface.removeColumn('yourTableName', 'thirdNewColumnName'));\n    },\n};\n```\n\n```text\nqueryInterface.addColumn\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize model:generate\n```\n\n```text\nmodel:create\n```\n\n```text\nsequelize migration:generate\n```\n\n```text\n--name\n```\n\n```text\nsequelize migration:generate --name add-registration-complete-and-currency-column\n```\n\n```text\nQueryInterface\n```\n\n========================================\n\nComments:\n- How can I generate another migration file with command as we have command like this 'node_modules/.bin/sequelize model:generate --name User --attributes firstName:string' This will generate Model and migration file at the same time.\n- And as you suggest, I do the same but Model file is not updated with new fields in migration file.\n- @KetavChotaliya did you ever figure this out? I just ran my first migration, but my models file was not updated :/ - Is the expectation that you manually update the models file with each migration?\n- You could use Promise.all to create multiple promises","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":125,"estimatedTokens":1012}}737{"id":"stack-77061603","source":"stackoverflow","questionId":77061603,"title":"Sequelize v7 alpha @ decorators not working","tags":["mysql","node.js","typescript","sequelize.js"],"text":"Title: Sequelize v7 alpha @ decorators not working\nTags: mysql, node.js, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhile testing sequelize v7 (alpha) I came across several errors while using simple examples straight from their documentation. For example, straight from the documentation\n\n```\nimport { Sequelize, DataTypes, Model, InferAttributes, InferCreationAttributes, CreationOptional } from '@sequelize/core';\nimport { Attribute, PrimaryKey, AutoIncrement, NotNull } from '@sequelize/core/decorators-legacy';\n\nconst sequelize = new Sequelize('sqlite::memory:');\n\nexport class User extends Model, InferCreationAttributes> {\n @Attribute(DataTypes.INTEGER)\n @PrimaryKey\n @AutoIncrement\n declare id: CreationOptional;\n\n @Attribute(DataTypes.STRING)\n @NotNull\n declare firstName: string;\n\n @Attribute(DataTypes.STRING)\n declare lastName: string | null;\n}\n```\n\nResults in import error `Cannot find module '@sequelize/core/decorators-legacy' or its corresponding type declarations.`\n\nAlso, `Decorators are not valid here.` where we declare the `@Attribute` decorators error as well.\n\nFollowing along with their documentation is proving to be difficult. Has anyone managed to implement sequelize v7 alpha? What am I doing wrong?\n\n========================================\n\nTop Answer:\nAccording this thread Cannot import decorators-legacy in V7 you need change **moduleResolution** property in your *tsconfig.json* to **node16** or **nodenext** value.\n\nIn my case I have a *tsconfig.json* and a *tsconfig.serve.json* I change both.\n\nNote that after update **moduleResolution** you also need update de **module** property to the same value\n\nSee an example\n\n```\n\"compilerOptions\": {\n \"module\": \"NodeNext\",\n \"moduleResolution\": \"NodeNext\",\n \"strict\": true,\n \"outDir\": \"./dist/out-tsc\",\n \"sourceMap\": true,\n \"declaration\": false\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Sequelize, DataTypes, Model, InferAttributes, InferCreationAttributes, CreationOptional } from '@sequelize/core';\nimport { Attribute, PrimaryKey, AutoIncrement, NotNull } from '@sequelize/core/decorators-legacy';\n\nconst sequelize = new Sequelize('sqlite::memory:');\n\nexport class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {\n  @Attribute(DataTypes.INTEGER)\n  @PrimaryKey\n  @AutoIncrement\n  declare id: CreationOptional<number>;\n\n  @Attribute(DataTypes.STRING)\n  @NotNull\n  declare firstName: string;\n\n  @Attribute(DataTypes.STRING)\n  declare lastName: string | null;\n}\n```\n\n```text\nCannot find module '@sequelize/core/decorators-legacy' or its corresponding type declarations.\n```\n\n```text\nDecorators are not valid here.\n```\n\n```text\n@Attribute\n```\n\n```json\n\"compilerOptions\": {\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"experimentalDecorators\": true\n    ...\n}\n```\n\n```text\nCannot find module '@sequelize/core/decorators-legacy' or its corresponding type declarations\n```\n\n```text\nDecorators are not valid here.\n```\n\n```text\n\"compilerOptions\": {\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"strict\": true,\n    \"outDir\": \"./dist/out-tsc\",\n    \"sourceMap\": true,\n    \"declaration\": false\n    ...\n}\n```\n\n========================================\n\nComments:\n- That solved the import issue, but I'm still getting \"TS1206: Decorators are not valid here.\". Did you manage to solve it, @bricewa?","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":126,"estimatedTokens":845}}738{"id":"stack-26277831","source":"stackoverflow","questionId":26277831,"title":"In sequelize updateattributes method can update only one attribute in a table?","tags":["node.js","sequelize.js"],"text":"Title: In sequelize updateattributes method can update only one attribute in a table?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI tried(sequelize model) to update the values in the table, but it will update the only one value in the table.check the below example\n\n```\nemployee.updateAttributes({first_name : value.first_name},\n {last_name : value.last_name},\n {email : value.email},\n {password : value.password},\n {phone : value.phone}\n ).on('success',function(employee){\n message.message = \"Employee updated successfully\";\n message.employee = employee;\n message.successMessage = \"Success\";\n callback(message);\n})\n```\n\n========================================\n\nTop Answer:\nuse .update() in lieu of .updateAttributes()\n\n========================================\n\nCode:\n```text\nemployee.updateAttributes({first_name : value.first_name},\n            {last_name : value.last_name},\n            {email : value.email},\n            {password : value.password},\n            {phone : value.phone}\n            ).on('success',function(employee){\n    message.message = \"Employee updated successfully\";\n    message.employee = employee;\n    message.successMessage = \"Success\";\n    callback(message);\n})\n```\n\n```text\nemployee.updateAttributes({\n  first_name : value.first_name,\n  last_name : value.last_name,\n  email : value.email,\n  password : value.password,\n  phone : value.phone\n})\n```\n\n```text\nuser.Addresses.forEach((oldAddress, i) => {\n    oldAddress.update(newAddresses[i])\n});\n```\n\n========================================\n\nComments:\n- What version of `sequelize` are you using?\n- This helped for hasMany relationship","metadata":{"transformedAt":"2026-08-18T18:33:34.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":64,"estimatedTokens":408}}739{"id":"stack-35780156","source":"stackoverflow","questionId":35780156,"title":"Sequelize under Angular2 w/ Typescript","tags":["angular","sequelize.js"],"text":"Title: Sequelize under Angular2 w/ Typescript\nTags: angular, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm brand new to Angular and just getting started on getting my head wrapped around how it works. Please, Internet, be gentle...\n\nI've completed the Angular2 5 min Quickstart through Tour of Heroes and have that working without an issue. Now I'm trying get connectivity to my local MS SQL server as I have a SQL-based project coming where Angular2 is the required platform. I've been banging my head against the wall for days on getting Sequelize to work and could really use some help.\n\nWhat I've done so far based on different things I've read:\n\n- Used npm to install sequelize and verified that sequelize and the dependencies of lodash, bluebird and validator all exist under node_modules\n\n- Downloaded bluebird.d.ts, lodash.d.ts, sequelize.d.ts and validator.d.ts from the DefinitelyTyped project on GitHub and put them in my typings folder\n\n- In tsConfig.json, I changed the compilerOptions --> target from es5 to es6\n\n- Created a simple db.component.ts file (see below)\n\n- Updated app.component.ts to import the db.component and added a route to it\n\nAt this point the simple page comes up, but I am unable to figure out how to get Sequelize working.\n\nScript errors I'm seeing (based on using Visual Studio Code as my editor):\n\n- When I open sequelize.d.ts, there is an error on the line '*declare module \"sequelize\" {*' stating that \"Ambient modules cannot be nested other modules\"\n\n- When I open lodash.d.ts, there are errors on lines 239 and 240 (the underscores) that states \"*Duplicate Identifier '_'*\"\n\nI've tried a number of different approaches (guesses) on how to get sequelize to connect to my database and just cannot get anything to work. I understand that I need either (both?) an import and/or a require in the db.component.ts file, but only end up with errors either in the IDE as bad syntax or in the browser (Chrome).\n\nI do understand that in the long run, my route/config/etc that I'm testing with here is not going to be the \"right\" way to do it, but I just need to get past the basic proof-of-concept that I can do something with the database before I re-engineer it (e.g. - can I connect to the database and query a table)\n\n**app.component.ts**\n\n```\nimport { Component } from 'angular2/core';\nimport { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';\n\nimport { DashboardComponent } from './dashboard.component';\nimport { HeroService } from './hero.service';\nimport { HeroesComponent } from './heroes.component';\nimport { HeroDetailComponent } from './hero-detail.component';\n\nimport { dbComponent } from './db.component';\n\n@Component({\n selector: 'my-app',\n template: `\n \n\n### {{title}}\n\n \n Dashboard\n Heroes\n \n \n `,\n styleUrls: ['app/app.component.css']\n directives: [ROUTER_DIRECTIVES],\n providers: [\n ROUTER_PROVIDERS,\n HeroService\n ]\n})\n\n@RouteConfig([\n {\n path: '/dashboard',\n name: 'Dashboard',\n component: DashboardComponent,\n useAsDefault: true\n },\n {\n path: '/heroes',\n name: 'Heroes',\n component: HeroesComponent\n },\n {\n path: '/detail/:id',\n name: 'HeroDetail',\n component: HeroDetailComponent\n },\n {\n path: '/sql',\n name: 'SqlTest',\n component: dbComponent\n } \n])\n\nexport class AppComponent {\n title = 'Sample App';\n}\n```\n\n**db.component.ts**\n\n```\n/// \n\nimport { Component, OnInit } from 'angular2/core';\nimport Sequelize = require('sequelize'); My console.log message are coming up so I believe that I have the core functionality basically working, but I'm at a loss on what I need to do to get Sequelize functional.\n\nThere's a piece of the puzzle that I'm missing and I'm at my wits end on this. Thanks in advance for any direction...\n\n========================================\n\nTop Answer:\nAs far as I know Sequelize is a orm for backend. The solution to your problem would be creating api (if you want to use Sequelize then probably use nodeJs) with which your frontend app could talk.\n\n========================================\n\nCode:\n```text\nimport { Component }            from 'angular2/core';\nimport { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';\n\nimport { DashboardComponent }   from './dashboard.component';\nimport { HeroService }          from './hero.service';\nimport { HeroesComponent }      from './heroes.component';\nimport { HeroDetailComponent }  from './hero-detail.component';\n\nimport { dbComponent }          from './db.component';\n\n@Component({\n    selector: 'my-app',\n    template: `\n        <h1>{{title}}</h1>\n        <nav>\n            <a [routerLink]=\"['Dashboard']\">Dashboard</a>\n            <a [routerLink]=\"['Heroes']\">Heroes</a>\n        </nav>\n        <router-outlet></router-outlet>\n    `,\n    styleUrls: ['app/app.component.css']\n    directives: [ROUTER_DIRECTIVES],\n    providers: [\n        ROUTER_PROVIDERS,\n        HeroService\n    ]\n})\n\n@RouteConfig([\n    {\n        path: '/dashboard',\n        name: 'Dashboard',\n        component: DashboardComponent,\n        useAsDefault: true\n    },\n    {\n        path: '/heroes',\n        name: 'Heroes',\n        component: HeroesComponent\n    },\n    {\n        path: '/detail/:id',\n        name: 'HeroDetail',\n        component: HeroDetailComponent\n    },\n    {\n        path: '/sql',\n        name: 'SqlTest',\n        component: dbComponent\n    }   \n])\n\nexport class AppComponent {\n  title = 'Sample App';\n}\n```\n\n```text\n/// <reference path=\"../typings/sequelize.d.ts\" />\n\nimport { Component, OnInit }            from 'angular2/core';\nimport Sequelize = require('sequelize');  <-- I dont know if this is doing anything\n\n//- This just errors out with require not being found (tds@latest installed)\n//var Sequelize = require(\"sequelize\");\n\n//- I know this goes somewhere, but I have no idea where\n//var sql = new Sequelize('dbName', 'uName', 'pw', {\n//  host: \"127.0.0.1\",\n//  dialect: 'mssql',\n//  port: 1433 <-- SqlExpress\n//});\n\n@Component({\n    selector: 'my-sql',\n    template:`\n        <h1>SQL Test</h1>\n    `\n})\n\nexport class dbComponent implements OnInit {\n\n    constructor(\n    ) { }\n\n    auth() {\n        console.log('auth');\n        //sql.authenticate().then(function(errors) { console.log(errors) });\n    }\n\n    ngOnInit() {\n        console.log('onInit');\n        this.auth();\n    }\n}\n```\n\n```text\nvar express = require('express');\n\nvar http = require('http');\nvar path = require('path');\nvar bodyParser = require('body-parser');\nvar mysql = require('ms-sql');//Note not entirely sure if this is the correct library for MS-SQL Server I would google how to use this.\n\nvar app = express();  \napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(express.static(path.join(__dirname, 'public')));\n```\n\n```text\nvar server = http.createServer(app);\n\nserver.listen(app.get('port'), function(){\n  console.log('Express server listening on port ' + app.get('port'));\n});\n```\n\n```text\napp.get('/', function(req, res){\n    res.render('index.html');\n});\n```\n\n```text\napp.use(\n\n    connection(mysql,{\n\n        host: 'localhost',//or the IP address\n        user: 'root',\n        password : 'myPassword',\n        port : 3306, //port mysql\n        database:'myDatabaseName'\n    },'request')\n);\n```\n\n```text\napp.get('/api/heroes', function(req, res){\n    req.getConnection(function(err,connection){\n\n       connection.query(\"SELECT ID, ROLE_NAME, DESCRIPTION, ACTIVE_FLAG FROM ROLES\",function(err,rows)     {\n\n           if(err)\n               console.log(\"Error Selecting : %s \",err );\n\n           res.json({data:rows});\n\n        });\n\n     });\n});\n```\n\n```text\nimport { Component, OnInit }            from 'angular2/core';\nimport {Http} from 'angular2/http':\n\n\n@Component({\n    selector: 'my-sql',\n    template:`\n        <h1>SQL Test</h1>\n         {{myData}}\n    `\n})\n\nexport class dbComponent implements OnInit {\n\n    myData: any;\n    constructor(public http: Http) { }\n\n\n    ngOnInit() {\n        this.http.get('api/heroes/').map((response => this.myData = response.json().data));\n    }\n}\n```\n\n```text\nnpm install express-generator -g\n```\n\n```text\nexpress myapp\n```\n\n```text\nnode myapp.js\n```\n\n========================================\n\nComments:\n- please provide errors explicitly\n- @PatrickMotard: The ones I listed in the \"script errors\" may be the root of the problem, but I'm not sure what to do about them or, since they only show in the IDE, if they are \"true\" errors. The 'require' error mentioned in the db.components.ts snippet shows up in the browser as \"require is not defined\".\n- Perfect! This gave me exactly what I needed. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":314,"estimatedTokens":2136}}740{"id":"stack-42286766","source":"stackoverflow","questionId":42286766,"title":"How to remove associations from the output in Sequelize?","tags":["node.js","express","sequelize.js"],"text":"Title: How to remove associations from the output in Sequelize?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a classMethod defined for the Model User\n\n```\n// model user.js\nclassMethods: {\n associate: function(models) {\n User.belongsToMany(models.project, {through: 'user_project', foreignKey: 'user_id', otherKey: 'project_id'})\n }\n}\n```\n\nFrom a route in Express i then query for the projects of this user and output it as JSON\n\n```\nuser.getProjects({\n attributes: ['id', 'title'],\n})\n.then(function(projects) {\n res.json(projects)\n})\n```\n\nThis works fine, except for the fact the output also contains the `user_project` property which I would like to hide/omit/remove\n\n```\n[\n {\n \"id\": 8,\n \"title\": \"Some project\",\n \"user_project\": {\n \"created_at\": \"2017-02-16T22:52:48.000Z\",\n \"updated_at\": \"2017-02-16T22:52:48.000Z\",\n \"project_id\": 8,\n \"user_id\": 5\n }\n },\n //etc.\n```\n\nI have tried various exclude and include statements, but the output always contains it.\n\nIs there a way to not have this show up in the output?\n\n========================================\n\nTop Answer:\nYou should try the following\n\n```\nuser.getProjects({\n attributes: ['id', 'title'],\n through: {\n attributes: []\n }\n})\n.then(function(projects) {\n res.json(projects)\n})\n```\n\n========================================\n\nCode:\n```text\n// model user.js\nclassMethods: {\n    associate: function(models) {\n        User.belongsToMany(models.project, {through: 'user_project', foreignKey: 'user_id', otherKey: 'project_id'})\n    }\n}\n```\n\n```text\nuser.getProjects({\n    attributes: ['id', 'title'],\n})\n.then(function(projects) {\n    res.json(projects)\n})\n```\n\n```text\n[\n  {\n    \"id\": 8,\n    \"title\": \"Some project\",\n    \"user_project\": {\n       \"created_at\": \"2017-02-16T22:52:48.000Z\",\n       \"updated_at\": \"2017-02-16T22:52:48.000Z\",\n       \"project_id\": 8,\n       \"user_id\": 5\n     }\n  },\n  //etc.\n```\n\n```text\nuser_project\n```\n\n```text\nuser.getProjects({\n    attributes: ['id', 'title'],\n    joinTableAttributes: []\n})\n.then(function(projects) {\n    res.json(projects)\n})\n```\n\n```text\n[\n  {\n    \"id\": 8,\n    \"title\": \"Test Project\",\n  },\n  {\n    \"id\": 4,\n    \"title\": \"Another one\",\n  }\n]\n```\n\n```text\njoinTableAttributes\n```\n\n```text\nuser.getProjects({\n    attributes: ['id', 'title'],\n    through: {\n        attributes: []\n    }\n})\n.then(function(projects) {\n    res.json(projects)\n})\n```\n\n```text\n{ attributes: [] }\n```\n\n```text\nuser.getProjects({\n    attributes: ['id', 'title'],\n    through: {\n        attributes: []\n    }\n})\n```\n\n```text\nsequelize: \"^6.18.0\"\n```\n\n========================================\n\nComments:\n- I tried it that way, but it still shows the 'user_project' as part of the response.\n- Interesting, when I upgrade to sequelize@4.0.0-2 it should work, but then 'getProjects' is not defined.\n- I tried that method on `sequelize` 4.37.6 but it doesn't remove the joined attributes, in fact only `joinTableAttributes` from the other answer was the one to work on the version i am working on\n- Cool, Good to know\n- Must admit that it is nicely hidden in the sequelize documentation, only single sentence about `joinTableAttributes` ;)","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":169,"estimatedTokens":787}}741{"id":"stack-49010851","source":"stackoverflow","questionId":49010851,"title":"sequelize & postgis sort by distance from point","tags":["javascript","node.js","postgresql","sequelize.js","postgis"],"text":"Title: sequelize & postgis sort by distance from point\nTags: javascript, node.js, postgresql, sequelize.js, postgis\nSource: Stack Overflow\n\nQuestion:\nI have a problem with search including sort by distance from some point. Here is my code and what I'm trying to do. Thanks for help\n\n```\nconst Sequelize = require('sequelize');\n\nvar Flat = db.define('flat', {\n id: {\n type: Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true\n }\n});\n\nvar FlatAddress = db.define('flat_address', {\n id: {\n type: Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n flat_id: {\n type: Sequelize.INTEGER,\n foreignKey:true,\n allowNull:false,\n references: {\n model:'flats',\n key: 'id'\n }\n },\n city: {\n type: Sequelize.STRING(50) //post_town\n },\n location: {\n type: Sequelize.GEOMETRY('POINT')\n }\n});\n\nFlat.hasOne(FlatAddress, { as: 'Address', foreignKey: 'flat_id', otherKey: 'id', onDelete: 'cascade' });\n\nFlatAddress.belongsTo(Flat, { foreignKey: 'id', otherKey: 'flat_id', onDelete: 'cascade' });\n```\n\nand i want to do something like this \n\n```\nvar POINT = {lat, lng} ?? \nFlats.findAndCountAll({\n where: filter,\n order: [\n [ { model: FlatAddresses, as: 'Address' },\n '//here should be something like distance from POINT//', 'ACS']\n ],\n include: [\n { model: FlatAddresses, as: 'Address'}\n ],\n offset,\n limit\n })\n```\n\nI didn't find examples or docs for my case. thanks\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\n\nvar Flat = db.define('flat', {\n    id: {\n        type: Sequelize.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    }\n});\n\nvar FlatAddress = db.define('flat_address', {\n    id: {\n        type: Sequelize.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    flat_id: {\n        type: Sequelize.INTEGER,\n        foreignKey:true,\n        allowNull:false,\n        references: {\n            model:'flats',\n            key: 'id'\n        }\n    },\n    city: {\n        type: Sequelize.STRING(50) //post_town\n    },\n    location: {\n        type: Sequelize.GEOMETRY('POINT')\n    }\n});\n\nFlat.hasOne(FlatAddress, { as: 'Address', foreignKey: 'flat_id', otherKey: 'id', onDelete: 'cascade' });\n\nFlatAddress.belongsTo(Flat, { foreignKey: 'id', otherKey: 'flat_id', onDelete: 'cascade' });\n```\n\n```text\nvar POINT = {lat, lng} ?? \nFlats.findAndCountAll({\n        where: filter,\n        order:  [\n                [ { model: FlatAddresses, as: 'Address' },\n '//here should be something like distance from POINT//', 'ACS']\n        ],\n        include: [\n            { model: FlatAddresses, as: 'Address'}\n        ],\n        offset,\n        limit\n    })\n```\n\n```text\nconst myDistance = 10000; // e.g. 10 kilometres\nFlats.findAll({\n  attributes: {\n    include: [\n      [\n        Sequelize.fn(\n          'ST_Distance',\n          Sequelize.col('location'),\n          Sequelize.fn('ST_MakePoint', longitude, latitude)\n        ),\n        'distance'\n      ]\n    ]\n  },\n  where: Sequelize.where(\n    Sequelize.fn(\n      'ST_DWithin',\n      Sequelize.col('location'),\n      Sequelize.fn('ST_MakePoint', longitude, latitude),\n      myDistance\n    ),\n    true\n  ),\n  order: Sequelize.literal('distance ASC')\n});\n```\n\n```text\nFlats\n```\n\n```text\ndistance\n```\n\n```text\ndistance\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":163,"estimatedTokens":811}}742{"id":"stack-25891678","source":"stackoverflow","questionId":25891678,"title":"Sequelize.js: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails","tags":["sequelize.js"],"text":"Title: Sequelize.js: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy code is:\n\n```\nDB.sequelize.query('SET FOREIGN_KEY_CHECKS = 0').complete(function(err) {\n if (err) {\n return done(err);\n }\n DB.sequelize.drop();\n return DB.sequelize.sync().complete(function(err) {\n if (err) {\n return done(err);\n }\n });\n});\n```\n\nand I have some foreign key constraints, but I thought that the `SET FOREIGN_KEY_CHECKS = 0` would ignore that and let me drop. Instead, the error that I get is: `ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails`\n\n========================================\n\nTop Answer:\nTry the following.\n\n```\nDB\n .sequelize\n .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})\n .success(function(results) {\n DB.sequelize.sync({force: true});\n });\n```\n\nThe \"force: true\" option for sync will add \"DROP TABLE IF EXISTS\" to the create statements, so this should achieve what you are trying to do with the drop().\n\nIts also worth considering this answer too: Sequelize doesn't create foreign keys as constraints.\n\n========================================\n\nCode:\n```text\nDB.sequelize.query('SET FOREIGN_KEY_CHECKS = 0').complete(function(err) {\n  if (err) {\n    return done(err);\n  }\n  DB.sequelize.drop();\n  return DB.sequelize.sync().complete(function(err) {\n    if (err) {\n      return done(err);\n    }\n  });\n});\n```\n\n```text\nSET FOREIGN_KEY_CHECKS = 0\n```\n\n```text\nER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails\n```\n\n```text\nDB\n    .sequelize\n    .query('SET FOREIGN_KEY_CHECKS = 0', {raw: true})\n    .then(function(results) {\n        DB.sequelize.sync({force: true});\n    });\n```\n\n```text\nDB\n    .sequelize\n    .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})\n    .success(function(results) {\n        DB.sequelize.sync({force: true});\n    });\n```\n\n```js\nconst forceSync = async () => {\n  await db.sequelize.query('SET FOREIGN_KEY_CHECKS = 0');\n  await db.sequelize.sync({ force: true });\n  await db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1'); // setting the flag back for security\n};\n```\n\n========================================\n\nComments:\n- This wouldn't work for me until I set pool to false in the sequelize initialization object.","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":96,"estimatedTokens":583}}743{"id":"stack-64215137","source":"stackoverflow","questionId":64215137,"title":"how to use sequelize specific errors?","tags":["node.js","exception","sequelize.js"],"text":"Title: how to use sequelize specific errors?\nTags: node.js, exception, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow do you import sequelize errors?\nI want to use specific errors like `SequelizeUniqueConstraintError)` for error handling.\n\n```\ntry {\n query...\n} catch(e){\n if (e instanceof SequelizeUniqueConstraintError) { \n next(new ResourceError(e.toString(), 401))\n } else {\n next(new ResourceError(e.toString(), 500))\n }\n}\n```\n\nI'm getting `SequelizeUniqueConstraintError is not defined`, but I can't seem to navigate through the sequelize instance to find any error classes?\n\n========================================\n\nCode:\n```js\ntry {\n  query...\n} catch(e){\n  if (e instanceof SequelizeUniqueConstraintError) { \n    next(new ResourceError(e.toString(), 401))\n  } else {\n    next(new ResourceError(e.toString(), 500))\n  }\n}\n```\n\n```text\nSequelizeUniqueConstraintError)\n```\n\n```text\nSequelizeUniqueConstraintError is not defined\n```\n\n```js\nimport { UniqueConstraintError } from 'sequelize';\n\ntry {\n  throw new UniqueConstraintError({ message: 'test unique constraint' });\n} catch (e) {\n  if (e instanceof UniqueConstraintError) {\n    console.log(401);\n  } else {\n    console.log(500);\n  }\n}\n```\n\n```text\n401\n```\n\n```text\nSequelizeUniqueConstraintError\n```\n\n```text\nUniqueConstraintError\n```\n\n```text\nSequelizeUniqueConstraintError\n```\n\n```text\nname\n```\n\n```text\nUniqueConstraintError\n```\n\n```text\n\"sequelize\": \"^5.21.3\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":86,"estimatedTokens":358}}744{"id":"stack-34483086","source":"stackoverflow","questionId":34483086,"title":"Sequelize include an attribute from junction table","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize include an attribute from junction table\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a shop, where in the database i have orders and items. Here's the code for the models:\n\nItem:\n\n```\nvar Sequelize = require('sequelize')\nvar sequelize = require('./sequelize')\nvar Item = sequelize.define('item', {\n image: {\n type: Sequelize.STRING,\n allowNull: false\n },\n itemName: {\n type: Sequelize.STRING,\n allowNull: false,\n field: 'item_name'\n },\n price: {\n type: Sequelize.INTEGER,\n allowNull: false\n }\n})\n\nmodule.exports = Item\n```\n\nOrder: \n\n```\nvar Sequelize = require('sequelize')\nvar sequelize = require('./sequelize')\nvar Order = sequelize.define('order', {\n orderNumber: {\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4\n },\n shop: {\n type: Sequelize.INTEGER\n },\n location: {\n type: Sequelize.STRING\n }\n})\n\nmodule.exports = Order\n```\n\nThey are related through belongs to many:\n\n```\nItem.belongsToMany(Order, {through: OrderItem})\nOrder.belongsToMany(Item, {through: OrderItem})\n```\n\nThe OrderItem has an additional field, 'count', which i need to return:\n\n```\nvar Sequelize = require('sequelize')\nvar sequelize = require('./sequelize')\n\nvar OrderItem = sequelize.define('OrderItem', {\n count: Sequelize.INTEGER\n})\n\nmodule.exports = OrderItem\n```\n\nHowever, when i try to include the OrderItem model, it doesn't work. No errors, nothing. The query just doesn't return:\n\n```\nOrder.findAll({\n where: {\n userId: userId\n },\n include: [{\n model: Item,\n include: [OrderItem]\n }]\n }).then(orders => {\n console.log(orders)\n res.status(200).json(orders)\n })\n```\n\nHow to get what i need from sequeilize?\n\n========================================\n\nTop Answer:\nTurns out that the OrderItem is already nested inside the Item object. However, this doesn't make a nice return format , so the question is still open.\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize')\nvar sequelize = require('./sequelize')\nvar Item = sequelize.define('item', {\n  image: {\n    type: Sequelize.STRING,\n    allowNull: false\n  },\n  itemName: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    field: 'item_name'\n  },\n  price: {\n    type: Sequelize.INTEGER,\n    allowNull: false\n  }\n})\n\nmodule.exports = Item\n```\n\n```text\nvar Sequelize = require('sequelize')\nvar sequelize = require('./sequelize')\nvar Order = sequelize.define('order', {\n  orderNumber: {\n    primaryKey: true,\n    type: Sequelize.UUID,\n    defaultValue: Sequelize.UUIDV4\n  },\n  shop: {\n    type: Sequelize.INTEGER\n  },\n  location: {\n    type: Sequelize.STRING\n  }\n})\n\nmodule.exports = Order\n```\n\n```text\nItem.belongsToMany(Order, {through: OrderItem})\nOrder.belongsToMany(Item, {through: OrderItem})\n```\n\n```text\nvar Sequelize = require('sequelize')\nvar sequelize = require('./sequelize')\n\nvar OrderItem = sequelize.define('OrderItem', {\n  count: Sequelize.INTEGER\n})\n\nmodule.exports = OrderItem\n```\n\n```text\nOrder.findAll({\n      where: {\n        userId: userId\n      },\n      include: [{\n        model: Item,\n        include: [OrderItem]\n      }]\n    }).then(orders => {\n      console.log(orders)\n      res.status(200).json(orders)\n    })\n```\n\n```text\nOrder.findAll({\n      where: {\n        userId: userId\n      },\n      include: [{ model: Item, \n        as:'item', \n        through:{attributes:['count']} // this may not be needed\n      }]\n  }).then(orders => {\n    console.log(orders)\n    res.status(200).json(orders)\n  })\n```\n\n```text\nvar OrderItem = sequelize.define('OrderItem', {\n  orderId: Sequelize.INTEGER,\n  itemId: Sequelize.INTEGER,\n  count: Sequelize.INTEGER\n})\n```\n\n```text\nOrder.findAll({\n  where: {\n    userId: userId\n  },\n  joinTableAttributes: ['count'],\n  include: [{\n    model: Item,\n  }]\n}).then(orders => {\n  console.log(orders)\n  res.status(200).json(orders)\n})\n```\n\n```text\njoinTableAttributes\n```\n\n```text\nlet orders = await Order.findAll({\n    where: {\n      userId: userId\n    },\n    include: [{ model: Item, \n      as:'item', \n      through:{attributes:['count']} \n    }]\n  });\n \n  let ordersWithCount = orders.map((o) => {\n     let orderWithCount = {};\n     orderWithCount = o;\n     orderWithCount.count = o.OrderItem.count;\n     return orderWithCount;\n  });\n```\n\n========================================\n\nComments:\n- why you want to include OrderItem in the model Item. This is the third table and you can use that table to enter the value of the oderId and ItemId.","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":238,"estimatedTokens":1114}}745{"id":"stack-28772570","source":"stackoverflow","questionId":28772570,"title":"Polygon insertion issue (due to SRID) on Postgres","tags":["postgresql","geolocation","geospatial","postgis","sequelize.js"],"text":"Title: Polygon insertion issue (due to SRID) on Postgres\nTags: postgresql, geolocation, geospatial, postgis, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble inserting a polygon into my table structure. I'm relatively new to PostGIS, so I may be making a pretty amateur mistake on this.\n\nMy table is setup as \"Regions\" and I'm adding a column for my geometry:\n\n```\n\"SELECT AddGeometryColumn(\" +\n\"'public', 'Regions', 'geom', 4326, 'POLYGON', 2\" +\n\");\"\n```\n\nFrom what I've read this sets the column geometry to accept WGS-83 as my projection standard. I'm using GeoJSON to insert my polygon because it's the easiest option for me. Here's an example of my update statement:\n\n```\nUPDATE \"Regions\"\n SET geom = ST_GeomFromGeoJSON(\n '{\"type\":\"Polygon\",\"coordinates\":[[[-114.017347,51.048005],[-114.014433,51.047927],[-114.005899,51.045381],[-114.001598,51.04509],[-114.001631,51.055109],[-114.01618,51.055062],[-114.016949,51.056508],[-114.016181,51.056511],[-114.01659,51.057251],[-114.017318,51.057237],[-114.018672,51.059928],[-114.020528,51.0593],[-114.023615,51.059311],[-114.021148,51.055829],[-114.018807,51.052583],[-114.017347,51.048005]]]}'\n )\n WHERE id = 'ab8326c0-beb3-11e4-89eb-b3372c283c42'\n```\n\nThe response I'm getting from my query is:\n\n```\n{ [SequelizeDatabaseError: Geometry SRID (0) does not match column SRID (4326)]\n name: 'SequelizeDatabaseError',\n message: 'Geometry SRID (0) does not match column SRID (4326)',\n parent: \n { [error: Geometry SRID (0) does not match column SRID (4326)]\n name: 'error',\n length: 121,\n severity: 'ERROR',\n code: '22023',\n detail: undefined,\n hint: undefined,\n position: undefined,\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'gserialized_typmod.c',\n line: '128',\n routine: 'postgis_valid_typmod',\n```\n\nI've had the coordinates verified as WGS84, but now I'm thinking that the issue is unrelated to the SRID type I'm using.\n\nThanks for your help.\n\n========================================\n\nCode:\n```text\n\"SELECT AddGeometryColumn(\" +\n\"'public', 'Regions', 'geom', 4326, 'POLYGON', 2\" +\n\");\"\n```\n\n```text\nUPDATE \"Regions\"\n    SET geom = ST_GeomFromGeoJSON(\n        '{\"type\":\"Polygon\",\"coordinates\":[[[-114.017347,51.048005],[-114.014433,51.047927],[-114.005899,51.045381],[-114.001598,51.04509],[-114.001631,51.055109],[-114.01618,51.055062],[-114.016949,51.056508],[-114.016181,51.056511],[-114.01659,51.057251],[-114.017318,51.057237],[-114.018672,51.059928],[-114.020528,51.0593],[-114.023615,51.059311],[-114.021148,51.055829],[-114.018807,51.052583],[-114.017347,51.048005]]]}'\n    )\n    WHERE id = 'ab8326c0-beb3-11e4-89eb-b3372c283c42'\n```\n\n```text\n{ [SequelizeDatabaseError: Geometry SRID (0) does not match column SRID (4326)]\n  name: 'SequelizeDatabaseError',\n  message: 'Geometry SRID (0) does not match column SRID (4326)',\n  parent: \n   { [error: Geometry SRID (0) does not match column SRID (4326)]\n     name: 'error',\n     length: 121,\n     severity: 'ERROR',\n     code: '22023',\n     detail: undefined,\n     hint: undefined,\n     position: undefined,\n     internalPosition: undefined,\n     internalQuery: undefined,\n     where: undefined,\n     schema: undefined,\n     table: undefined,\n     column: undefined,\n     dataType: undefined,\n     constraint: undefined,\n     file: 'gserialized_typmod.c',\n     line: '128',\n     routine: 'postgis_valid_typmod',\n```\n\n```text\nALTER TABLE\n```\n\n```text\nALTER TABLE foo ADD COLUMN geom Geometry(Polygon,4326)\n```\n\n```text\nST_SetSrid\n```\n\n```text\nUPDATE foo SET geom = ST_SetSRID(ST_GeomFromGeoJSON(...),4326)\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":115,"estimatedTokens":919}}746{"id":"stack-40682025","source":"stackoverflow","questionId":40682025,"title":"X is not associated to Y","tags":["sequelize.js"],"text":"Title: X is not associated to Y\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've been following the documentation of sequelize quite heavily and I've run into a problem when I got to relations. Here's my very simple code creating two extremely basic 1:1 relations using `belongsTo`\n\n```\nimport Sequelize, { STRING, INTEGER, TEXT } from 'sequelize';\n\nconst sequelize = new Sequelize('dbname', '', '');\n\nconst User = sequelize.define('user', {\n name: STRING,\n age: INTEGER\n});\n\nconst Item = sequelize.define('item', {\n name: STRING,\n price: INTEGER\n});\n\nItem.belongsTo(User);\n\nsequelize.sync({ force: true }).then(() => {\n User.create({\n name: 'Hobbyist',\n age: 22,\n Item: {\n name: 'Phone',\n price: 199\n }\n }, {\n include: [ Item ]\n });\n});\n```\n\nError that I'm getting:\n\n```\nUnhandled rejection Error: item is not associated to user!\n```\n\n========================================\n\nCode:\n```text\nimport Sequelize, { STRING, INTEGER, TEXT } from 'sequelize';\n\nconst sequelize = new Sequelize('dbname', '', '');\n\nconst User = sequelize.define('user', {\n    name: STRING,\n    age: INTEGER\n});\n\nconst Item = sequelize.define('item', {\n    name: STRING,\n    price: INTEGER\n});\n\nItem.belongsTo(User);\n\nsequelize.sync({ force: true }).then(() => {\n    User.create({\n        name: 'Hobbyist',\n        age: 22,\n        Item: {\n            name: 'Phone',\n            price: 199\n        }\n    }, {\n        include: [ Item ]\n    });\n});\n```\n\n```text\nUnhandled rejection Error: item is not associated to user!\n```\n\n```text\nbelongsTo\n```\n\n```text\nItem.belongsTo(User);\nUser.hasOne(Item); // this line\n```\n\n```text\nUser.create({\n    name: 'Hobbyist',\n    age: 22,\n    item: {\n // ^ item, not Items\n        name: 'Phone',\n        price: 199\n    }\n}, {\n    include: [ Item ]\n});\n```\n\n```text\nItems belong to User\n```\n\n```text\nUser has one Item\n```\n\n```text\nJOIN\n```\n\n```text\nItem\n```\n\n```text\nitem\n```\n\n========================================\n\nComments:\n- Thanks, I wasn't aware of the 'Item -> item\" thing, and started to abuse alias'. Sequelize is becoming amazing.","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":129,"estimatedTokens":514}}747{"id":"stack-60833520","source":"stackoverflow","questionId":60833520,"title":"How can I use raw SQL in NestJS instead of TypeOrm or Sequelize?","tags":["sql","orm","sequelize.js","nestjs","typeorm"],"text":"Title: How can I use raw SQL in NestJS instead of TypeOrm or Sequelize?\nTags: sql, orm, sequelize.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAs of today TypeOrm has 1.493 issues over 282.102 weekly downloads and Sequelize 783 issues over 571.781 weekly downloads in Github. \n\nAs I read over the TypeOrm and Sequelize Github issues, I want to avoid those major problemas by coding raw SQL instead of dealing with major issues like losing data, columns being dropped when you synchronize entities or types being changed due to default ORM types. \n\nI use NestJs 7.0.3 with TypeGraphQL, PostgreSQL v12.2 and TypeScript.\nSince 2019, I've had two issues raised with TypeOrm. \n\nI understand the advantages of using an ORM but I wonder if NestJS can work efficiently if I use raw SQL in order to replace TypeORM or Sequelize entirely?\n\nThanks so much for your insights.\nRon\n\n========================================\n\nComments:\n- I cheched your github repo and the zeldaPlay source code is amazing. You created your own Dynamic Module. After all you have done with the node-pg package, would you replace in your developments an ORM in order to avoid those issues I mentioned above or would you rather deal with the trade off and use Typeorm/Sequelize ?\n- There's a lot of refactoring going on behind the scenes. Gonna be removing the transient scope and instead working with all singletons, just by creating new provider tokens instead of using the same class name (similar to how the TypeOrm package for Nest works). It should make testing easier, but it'll be a while before I get to that\n- I usually avoid ORMs as I don't feel they bring as many advantages as they do negatives in the end of things. Plus, this way, I **know** what is being executed on my SQL server.\n- Thanks so much for sharing your experience. As a summary, in order to go this \"raw-sql\" route I should start (1) reading the manual for node-pg (2) reading nestjs Dynamic Module (3) creating my own Dynamic Module (4) Compare my code with your working code. Would you suggest any additional readings before I enter this unplanned journey?\n- You don't necessarily have to use my code as a comparison, I do use a few helper packages to make things easier; however, this article is really well written and starts getting into some of the working of Dynamic Modules. John has a lot of good Nest articles so find some stuff that interests you from him if you want as well. Here's another of his\n- All these related pieces were the direction I was looking for: Thank you for sharing so much information Best regards.","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":26,"estimatedTokens":646}}748{"id":"stack-38895259","source":"stackoverflow","questionId":38895259,"title":"How can i define a column as tinyint(4) using sequelize ORM","tags":["mysql","sql","node.js","sequelize.js"],"text":"Title: How can i define a column as tinyint(4) using sequelize ORM\nTags: mysql, sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to define my table as \n\n```\nCREATE TABLE `test` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `o_id` int(11) unsigned NOT NULL,\n `m_name` varchar(45) NOT NULL,\n `o_name` varchar(45) NOT NULL,\n `customer_id` int(11) unsigned NOT NULL,\n `client_id` tinyint(4) unsigned DEFAULT '1',\n `set_id` tinyint(4) unsigned DEFAULT NULL,\n `s1` tinyint(4) unsigned DEFAULT NULL,\n `s2` tinyint(4) unsigned DEFAULT NULL,\n `s3` tinyint(4) unsigned DEFAULT NULL,\n `review` varchar(2045) DEFAULT NULL,\n `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `br_o_id_idx` (`order_id`),\n KEY `br_date_idx` (`created_at`),\n KEY `br_on_idx` (`operator_name`),\n KEY `br_mn_idx` (`merchant_name`)\n)\n```\n\nbut as i am looking on sequelize documentation , it does not have support for tiny int with its size.\n\n========================================\n\nTop Answer:\nFor MySQL, the Sequelize.BOOLEAN data type maps to TINYINT(1). See\n\nhttps://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/data-types.js#L397\n\nand\n\nhttp://docs.sequelizejs.com/en/v3/api/datatypes/\n\nAs noted by @user866762, the number in parentheses only affects how the data is displayed, not how it is stored. So, TINYINT(1) vs. TINYINT(4) should have no effect on your data.\n\n========================================\n\nCode:\n```text\nCREATE TABLE `test` (\n  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n  `o_id` int(11) unsigned NOT NULL,\n  `m_name` varchar(45) NOT NULL,\n  `o_name` varchar(45) NOT NULL,\n  `customer_id` int(11) unsigned NOT NULL,\n  `client_id` tinyint(4) unsigned DEFAULT '1',\n  `set_id` tinyint(4) unsigned DEFAULT NULL,\n  `s1` tinyint(4) unsigned DEFAULT NULL,\n  `s2` tinyint(4) unsigned DEFAULT NULL,\n  `s3` tinyint(4) unsigned DEFAULT NULL,\n  `review` varchar(2045) DEFAULT NULL,\n  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `br_o_id_idx` (`order_id`),\n  KEY `br_date_idx` (`created_at`),\n  KEY `br_on_idx` (`operator_name`),\n  KEY `br_mn_idx` (`merchant_name`)\n)\n```\n\n```text\nZERO_FILL\n```\n\n```text\ntinyint(4)\n```\n\n```text\nTINYINT\n```\n\n```text\nSequelize.INTEGER(4).ZEROFILL\n```\n\n```text\nDataTypes.TINYINT.UNSIGNED\n```\n\n```text\nTINYINT(1)\n```\n\n========================================\n\nComments:\n- so how it actually matters. I just want to limit my value between 0-255 because i have a column in my db as tinyint . it doesn't matter weather i am filling it with 0 or not\n- That's my point; the number in parenthesis after an integer type *doesn't* do that. And since the `sequelize` authors don't provide the correct way to do what you want, you can't do it. You might try using the sequelize boolean type to make a `tinyint` field in your schema, but I imagine that would wreak havoc with the way the ORM handles that type JS side.\n- Actually, thinking about how `sequelize` handles this, if you're saying that you're creating the schema outside of sequelize, so it already is a tinyint, you could use `min` and `max` validations to get what you want, and just tell sequelize that it's an integer field.\n- Sequelize.INTEGER(4).ZEROFILL , <-- this thing helped me!\n- Hi, just to add more info. This works type: DataTypes.TINYINT(4).ZEROFILL\n- Sorry, just realized that you have `tinyint unsigned` and I don't believe you can add the UNSIGNED flag to the Sequelize.BOOLEAN type. If you really need values between 128 and 255, you may be forced to use Sequelize.INTEGER... You could always create the table with `tinyint unsigned` fields and use the Sequelize.INTEGER type in your model along with validation to ensure the value stays between 0 and 255. However, you wouldn't be able to `sync()` your model to the database.\n- I don't need a BOOLEAN type\n- I know you don't need a BOOLEAN type. If you look at the docs and the code that I linked to, you'll see that Sequelize translates BOOLEAN to TINYINT for MySQL. It's the only way to effectively use TINYINT with Sequelize. You're only other option is to use INTEGER along with validations, as I previously stated.","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":104,"estimatedTokens":1049}}749{"id":"stack-62098817","source":"stackoverflow","questionId":62098817,"title":"Is it a good practice to close my connection after Sequelize operations?","tags":["node.js","database","sequelize.js","pool"],"text":"Title: Is it a good practice to close my connection after Sequelize operations?\nTags: node.js, database, sequelize.js, pool\nSource: Stack Overflow\n\nQuestion:\ncurrently I'm designing an app on top of Sequelize using NodeJS/TypeScript, and I'm wondering if it can cause performance issues not closing a connection.\n\nFor instance, in a micro service, I need data from 1 entity.\n\n```\nconst resolver = async (,,{db}) => {\n const entity1 = await db.models.Entity1.findOne()\n return entity1\n}\n```\n\nIs it required to close the connection after having called `findOne`?\n\nMy understanding is that the following config defines a number of concurrent connections and idle is a parameter making the connection manager closing the connection of idle ones:\n\n```\nmodule.exports = {\n development: {\n host: 'db.sqlite',\n dialect: 'sqlite',\n pool: {\n max:5,\n min:0,\n idle:10000\n }\n },\n test: {\n host: 'test.sqlite',\n dialect: 'sqlite',\n pool: {\n max:5,\n min:0,\n idle:10000\n }\n }\n}\n```\n\nAny advice is welcome\n\n========================================\n\nTop Answer:\nIf you don't close the Sequelize connection, the micro-service will still run until the connection got timed out (idle time pool parameter).. I suggest to close Sequelize connection, at least in micro-services..\n\n========================================\n\nCode:\n```js\nconst resolver = async (,,{db}) => {\n  const entity1 = await db.models.Entity1.findOne()\n  return entity1\n}\n```\n\n```js\nmodule.exports = {\n  development: {\n    host: 'db.sqlite',\n    dialect: 'sqlite',\n    pool: {\n        max:5,\n        min:0,\n        idle:10000\n    }\n  },\n  test: {\n    host: 'test.sqlite',\n    dialect: 'sqlite',\n    pool: {\n        max:5,\n        min:0,\n        idle:10000\n    }\n  }\n}\n```\n\n```text\nfindOne\n```\n\n```text\npool\n```\n\n========================================\n\nComments:\n- is the same applicable for lambda function as well ? stackoverflow.com/questions/74264495/&hellip;\n- and that will incur more costs (eg: lambda executing time).. and may cause a timeout of lambda service..\n- but I'm wondering if the connection isn't automatically closed by sequelize after the operation is done, I didn't notice timeouts for that specific use case","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":97,"estimatedTokens":545}}750{"id":"stack-30620092","source":"stackoverflow","questionId":30620092,"title":"Using sequelize.js to interface against existing database?","tags":["node.js","sequelize.js"],"text":"Title: Using sequelize.js to interface against existing database?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently working in a project where our Node.js server will perform a lot of interactions against an existing MySQL database. Thus I'm wondering if Sequelize is a good library to interface the database. From what I've read about it, it is most often used as a master of the database. But in my case it will only have select,insert,delete access and not access to modify and create tables and so on. Does Sequelize support this method of interaction with a database?\n\nIf Sequelize does indeed work good for this, what settings do i need to disable to not run into much trouble? After reading their documentation i could not find any global settings to turn it into a simple interface tool. Timestamps and such could be disabled on table definition but not globally what I saw. Any input is greatly appreciated.\n\n========================================\n\nCode:\n```text\nnew Sequelize(... ,{\n  define: {\n    timestamps: false\n  }\n});\n```\n\n```text\nsequelize.define('name of model', attributes, {\n   tableName: 'name of table'\n});\n```\n\n```text\nsequelize.define('name of model', {\n  name_of_attribute_in_model: {\n    type: ...\n    field: 'name of field in table'\n  }\n});\n```\n\n```text\nsequelize.define('name of model', {\n  a_field_totally_not_called_id: {\n     primaryKey: true // also allows for composite primary keys, even though the support for composite keys accross associations is spotty\n     autoIncrement: true\n  }\n});\n```\n\n```text\nX.belongsTo(Y, { foreignKey: 'something_bla' });\n```\n\n```text\ndefine\n```\n\n```text\nsequelize.define\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":55,"estimatedTokens":417}}751{"id":"stack-59766628","source":"stackoverflow","questionId":59766628,"title":"TypeORM: Define relation in migration","tags":["node.js","sequelize.js","typeorm","typeorm-datamapper"],"text":"Title: TypeORM: Define relation in migration\nTags: node.js, sequelize.js, typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nHi I'm reading TypeORM docs, and trying to implement relations like showed here\nIm trying to have History model that relates to every User, so that each user has multiple history \n\nIm reading this & using that example:\n\nhttps://github.com/typeorm/typeorm/blob/master/docs/many-to-one-one-to-many-relations.md\n\nBut after try to implement it I get column userId on History model does not exist ??\n\nDoes anyone know what could be the problem ?\n\nIm assuming I should add relation in migration file for my Model but I do not see any of that in documentation ?\n\n========================================\n\nCode:\n```js\nexport class ExampleMigration implements MigrationInterface {\n  public async up(queryRunner: QueryRunner): Promise<any> {\n    await queryRunner.createTable(\n      new Table({\n        name: 'stuff',\n        columns: [\n          {\n            name: 'id',\n            type: 'uuid',\n            isPrimary: true\n          },\n          {\n            name: 'userId',\n            type: 'uuid'\n          }\n        ]\n      })\n    );\n\n    await queryRunner.createForeignKey(\n      'stuff',\n      new TableForeignKey({\n        columnNames: ['userId'],\n        referencedTableName: 'users',\n        referencedColumnNames: ['id']\n      })\n    );\n  }\n\n  public async down(queryRunner: QueryRunner): Promise<any> {\n    await queryRunner.dropTable('userSessions');\n  }\n}\n```\n\n```text\ncreateForeignKey\n```\n\n========================================\n\nComments:\n- Have you tried to let TypeORM generate the migration file for you? That should add the needed columns and foreign key constraints to the migration.\n- Yes I checked found solution by looking at the docs thank you :)","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":66,"estimatedTokens":451}}752{"id":"stack-52987837","source":"stackoverflow","questionId":52987837,"title":"NodeJS unable to import Sequelize.js model (ES6)","tags":["node.js","express","ecmascript-6","sequelize.js"],"text":"Title: NodeJS unable to import Sequelize.js model (ES6)\nTags: node.js, express, ecmascript-6, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm running NodeJS with Express and Seqeulize and I have a file `controllers/rooms.js` importing Room from `models/room.js`.\n\n```\nimport Room from '../models'\n\nexport function list(req, res) {\n return Room\n .findAll()\n .then((rooms) => res.status(200).send(rooms))\n .catch((error) => res.status(400).send(error))\n}\n```\n\nBellow is `models/room.js` (There is also `index.js` file generate by sequelize-cli in the same directory)\n\n```\n'use strict'\n\nexport default (sequelize, DataTypes) => {\n\n const Room = sequelize.define('Room', {\n name: DataTypes.STRING\n })\n\n return Room\n}\n```\n\nAnd I have a route `app.get('/rooms', list)`, but when I access this route I get this error:\n\n```\nTypeError: _models2.default.findAll is not a function\n at list (/Users/matis/Documents/apps/node-docker-test/app/database/controllers/rooms.js:21:10)\n at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/route.js:137:13)\n at Route.dispatch (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/route.js:112:3)\n at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n at /Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:281:22\n at Function.process_params (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:335:12)\n at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:275:10)\n at expressInit (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/middleware/init.js:40:5)\n at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n at trim_prefix (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:317:13)\n at /Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:284:7\n at Function.process_params (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:335:12)\n at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:275:10)\n at query (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/middleware/query.js:45:5)\n at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n at trim_prefix (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:317:13)\n at /Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:284:7\n at Function.process_params (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:335:12)\n at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:275:10)\n at Function.handle (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:174:3)\n at Function.handle (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/application.js:174:10)\n```\n\nI'm sure I have my imports/exports messed up but I don't know how.\n\n`models/index.js` file bellow\n\n```\n'use strict'\n\nimport { readdirSync } from 'fs'\nimport { basename as _basename, join } from 'path'\nimport Sequelize from 'sequelize'\nconst basename = _basename(__filename)\nconst env = process.env.NODE_ENV || 'development'\nconst config = require(__dirname + '/../config/config.json')[env]\nconst db = {}\n\nlet sequelize\nif (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config)\n} else {\n sequelize = new Sequelize(config.database, config.username, config.password, config)\n}\n\nreaddirSync(__dirname)\n .filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')\n })\n .forEach(file => {\n const model = sequelize['import'](join(__dirname, file))\n db[model.name] = model\n })\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db)\n }\n})\n\ndb.sequelize = sequelize\ndb.Sequelize = Sequelize\n\nexport default db\n```\n\n**It works when I call it like this:**\n`return Room.Room.findAll()...`\nTherefore i can rename the import to this:\n`import models from '../models'`\nand call it this way:\n`return models.Room.findAll()...`\n\nHowever why can't I just call it `return Room.findAll()...`, how should the import be formulated ??\n\n========================================\n\nTop Answer:\nLast time when I worked with Sequelize it was not working well with ES6 features. My guess is that `models/room.js` is not exporting model properly due to `export default`. You can try changing that line to old style `module.exports`;\n\n```\nexport default (sequelize, DataTypes) => {\n.....\nTo\n.....\nmodule.exports = (sequelize, DataTypes) => {\n```\n\nand see if that solves the import problem.\n\nWhen importing in controller you can do this;\n\n```\nconst Room = require('../models').Room;\n```\n\nthis is old way to do imports and now your code should work. :)\n\nIf you want to try with ES6 you can do something like;\n\n```\nimport {Room} from '../models'\n```\n\nI'm not sure if this ES6 import works here!\n\n========================================\n\nCode:\n```text\nimport Room from '../models'\n\nexport function list(req, res) {\n    return Room\n        .findAll()\n        .then((rooms) => res.status(200).send(rooms))\n        .catch((error) => res.status(400).send(error))\n}\n```\n\n```text\n'use strict'\n\nexport default (sequelize, DataTypes) => {\n\n    const Room = sequelize.define('Room', {\n        name: DataTypes.STRING\n    })\n\n    return Room\n}\n```\n\n```text\nTypeError: _models2.default.findAll is not a function\n    at list (/Users/matis/Documents/apps/node-docker-test/app/database/controllers/rooms.js:21:10)\n    at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n    at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/route.js:137:13)\n    at Route.dispatch (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/route.js:112:3)\n    at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n    at /Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:281:22\n    at Function.process_params (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:335:12)\n    at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:275:10)\n    at expressInit (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/middleware/init.js:40:5)\n    at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n    at trim_prefix (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:317:13)\n    at /Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:284:7\n    at Function.process_params (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:335:12)\n    at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:275:10)\n    at query (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/middleware/query.js:45:5)\n    at Layer.handle [as handle_request] (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/layer.js:95:5)\n    at trim_prefix (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:317:13)\n    at /Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:284:7\n    at Function.process_params (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:335:12)\n    at next (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:275:10)\n    at Function.handle (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/router/index.js:174:3)\n    at Function.handle (/Users/matis/Documents/apps/node-docker-test/node_modules/express/lib/application.js:174:10)\n```\n\n```text\n'use strict'\n\nimport { readdirSync } from 'fs'\nimport { basename as _basename, join } from 'path'\nimport Sequelize from 'sequelize'\nconst basename = _basename(__filename)\nconst env = process.env.NODE_ENV || 'development'\nconst config = require(__dirname + '/../config/config.json')[env]\nconst db = {}\n\nlet sequelize\nif (config.use_env_variable) {\n    sequelize = new Sequelize(process.env[config.use_env_variable], config)\n} else {\n    sequelize = new Sequelize(config.database, config.username, config.password, config)\n}\n\nreaddirSync(__dirname)\n    .filter(file => {\n        return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')\n    })\n    .forEach(file => {\n        const model = sequelize['import'](join(__dirname, file))\n        db[model.name] = model\n    })\n\nObject.keys(db).forEach(modelName => {\n    if (db[modelName].associate) {\n        db[modelName].associate(db)\n    }\n})\n\ndb.sequelize = sequelize\ndb.Sequelize = Sequelize\n\nexport default db\n```\n\n```text\ncontrollers/rooms.js\n```\n\n```text\nmodels/room.js\n```\n\n```text\nmodels/room.js\n```\n\n```text\nindex.js\n```\n\n```text\napp.get('/rooms', list)\n```\n\n```text\nmodels/index.js\n```\n\n```text\nreturn Room.Room.findAll()...\n```\n\n```text\nimport models from '../models'\n```\n\n```text\nreturn models.Room.findAll()...\n```\n\n```text\nreturn Room.findAll()...\n```\n\n```js\nimport Sequelize from 'sequelize';\n\nexport const sequelize = new Sequelize(\n  config.database.name,\n  config.database.user,\n  config.database.password,\n  {\n    host: config.database.host,\n    dialect: config.database.dialect,\n    pool: config.database.pool,\n    operatorsAliases: false\n  }\n);\n```\n\n```js\nimport Sequelize from 'sequelize';\nimport { sequelize } from '../database/db';\n\nconst User = sequelize.define(\n  'table_name',\n  {\n    id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    email: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    password: {\n      type: Sequelize.STRING,\n      allowNull: false\n    }\n  },\n  { freezeTableName: true }\n);\n\nexport default User;\n```\n\n```text\nexport default (sequelize, DataTypes) => {\n.....\nTo\n.....\nmodule.exports = (sequelize, DataTypes) => {\n```\n\n```text\nconst Room = require('../models').Room;\n```\n\n```text\nimport {Room} from '../models'\n```\n\n```text\nmodels/room.js\n```\n\n```text\nexport default\n```\n\n```text\nmodule.exports\n```\n\n========================================\n\nComments:\n- can you please your database connection file . you might have problem with that file. because you are trying with the .defualt key you can try directly model.findAll() method\n- I don't think there is a problem there, but do you want the `config.json` or `index.js` in models folder ?\n- try module.exports = db.\n- on the controller try with `import {Room} from '..&#47;models'` or `import {room} from '..&#47;models'`\n- @VassilisPallas that didn't work, I tried that earlier, but I edited my question with working code, but I'm not satisfied with it\n- Updated the answer.\n- Same Error :/ Do you have a better suggestion for different ORM ?\n- can you upload index.js file?\n- Have you tried without 'use-restrict'? remove that and try. And remember to restart server.\n- Tried without `'user-strict'` didn't help, attached `index.js` file\n- From error I can only see that when you import your model it somehow imports `default` keyword and then tries to call .findAll on that which doesn't exist. I think it should work with updated export in model.\n- small typo in comments, 'use-strict'.\n- @tahirwaseer Your updated answer doesn't work, I'm getting this error now: `Cannot read property 'findAll' of undefined`. However I updated my question with working code, but I'm not satisfied with it.\n- Have you changed your import to `const Room = require('..&#47;models').Room;`\n- @tahirwaseer Yes I did\n- Then I can't see why it is not working. In working state when you can use models.Room.findAll without issue then it only comes to one thing; index.js in models/ returns and object with all models and we need to extract Room model which can be done in two ways I've listed in answer, 1) using `require` old way 2) using destructuring (ES6) way. Then you sould be able to call `return Room.findAll`.","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":370,"estimatedTokens":3202}}753{"id":"stack-29585061","source":"stackoverflow","questionId":29585061,"title":"How do I return a string from a Buffer from a mysql blob field in my Express API?","tags":["node.js","express","sequelize.js"],"text":"Title: How do I return a string from a Buffer from a mysql blob field in my Express API?\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a restful API on Express and using Sequelize. I have a Blob field in my mysql table, but in the `get` response it's returning a Buffer object. How should I return the string value of any of my response data's properties which are Buffer objects?\n\nI'll be consuming this API with PHP but I'm using Postman to test it.\n\nHere's what my model definition looks like:\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n return sequelize.define('submissions', {\n comments: {\n type: DataTypes.BLOB,\n allowNull: true,\n defaultValue: ''\n },\n // Other fields...\n }, {tableName: 'submission', timestamps: false});\n};\n```\n\nHere's an example of one of my routes:\n\n```\nrouter.get('/:model', function(req, res) {\n var where = req.query;\n models[req.params.model].findAll({ where: where}).then(function(results){\n var status = models.utils._.isNull(results) ? 404 : 200;\n res.status(status).json(results);\n });\n});\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function (sequelize, DataTypes) {\n  return sequelize.define('submissions', {\n    comments: {\n      type: DataTypes.BLOB,\n      allowNull: true,\n      defaultValue: ''\n    },\n    // Other fields...\n  }, {tableName: 'submission', timestamps: false});\n};\n```\n\n```text\nrouter.get('/:model', function(req, res) {\n  var where = req.query;\n    models[req.params.model].findAll({ where: where}).then(function(results){\n        var status = models.utils._.isNull(results) ? 404 : 200;\n        res.status(status).json(results);\n    });\n});\n```\n\n```text\nget\n```\n\n```text\nbuffer.toString('utf8')\n```\n\n```text\ncomments\n```\n\n```text\nComment\n```\n\n```text\ncomments\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":452}}754{"id":"stack-51916911","source":"stackoverflow","questionId":51916911,"title":"How to get MAX(id) GROUP BY other_field with Sequalize.js?","tags":["javascript","mysql","sql","node.js","sequelize.js"],"text":"Title: How to get MAX(id) GROUP BY other_field with Sequalize.js?\nTags: javascript, mysql, sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got a MySQL database which stores prices for certain products which are represented by symbols. I now want to get the latest price for each symbol. In pure MySQL I can run the following:\n\n```\nSELECT *\nFROM prices\nWHERE id IN (SELECT MAX(id) FROM prices GROUP BY symbol);\n```\n\nI now want to do the same using Sequelize.js. So I tried several variations of the following:\n\n```\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('mmjs', 'root', 'xxx', {host: 'localhost', dialect: 'mysql', logging: false, pool: {max: 5, min: 1, idle: 20000, acquire: 30000, handleDisconnects: true}, operatorsAliases: false,});\n\nconst Price = sequelize.define('price', {\n createdAt: {type: Sequelize.DATE(6), allowNull: false},\n symbol: {type: Sequelize.STRING, allowNull: false},\n bid: {type: Sequelize.FLOAT},\n ask: {type: Sequelize.FLOAT},\n});\n\nPrice.findAll({\n attributes: [Sequelize.fn('max', Sequelize.col('id'))],\n group: [\"symbol\"]\n}).then((maxIds) => {\n console.log(maxIds);\n console.log(maxIds.length); // logs the correct length of 82\n return Price.findAll({\n where: {\n id: {\n [Sequelize.Op.in]: maxIds\n }\n }\n });\n}).then(maxPrices => {\n console.log(maxPrices);\n});\n```\n\nAs said in the comment the `maxIds.length` logs the correct length of 82. But after that I get an error saying `Unhandled rejection Error: Invalid value price`. Furthermore, the `console.log(maxIds);` gives me some objects which seem to be empty of the expected max id value which I'm expecting. Below is an example of one such an object.\n\nWhat am I doing wrong here? Why doesn't it give me the max ids just like the query `SELECT MAX(id) FROM prices GROUP BY symbol`?\n\n```\nprice {\n dataValues: {},\n _previousDataValues: {},\n _changed: {},\n _modelOptions:\n { timestamps: true,\n validate: {},\n freezeTableName: false,\n underscored: false,\n underscoredAll: false,\n paranoid: false,\n rejectOnEmpty: false,\n whereCollection: null,\n schema: null,\n schemaDelimiter: '',\n defaultScope: {},\n scopes: [],\n indexes: [],\n name: [Object],\n omitNull: false,\n sequelize: [Object],\n hooks: {},\n uniqueKeys: {} },\n _options:\n { isNewRecord: false,\n _schema: null,\n _schemaDelimiter: '',\n raw: true,\n attributes: [Array] },\n __eagerlyLoadedAssociations: [],\n isNewRecord: false },\n```\n\n========================================\n\nCode:\n```text\nSELECT *\nFROM prices\nWHERE id IN (SELECT MAX(id) FROM prices GROUP BY symbol);\n```\n\n```text\nconst Sequelize = require('sequelize');\n\nconst sequelize = new Sequelize('mmjs', 'root', 'xxx', {host: 'localhost', dialect: 'mysql', logging: false, pool: {max: 5, min: 1, idle: 20000, acquire: 30000, handleDisconnects: true}, operatorsAliases: false,});\n\nconst Price = sequelize.define('price', {\n    createdAt: {type: Sequelize.DATE(6), allowNull: false},\n    symbol: {type: Sequelize.STRING, allowNull: false},\n    bid: {type: Sequelize.FLOAT},\n    ask: {type: Sequelize.FLOAT},\n});\n\nPrice.findAll({\n    attributes: [Sequelize.fn('max', Sequelize.col('id'))],\n    group: [\"symbol\"]\n}).then((maxIds) => {\n    console.log(maxIds);\n    console.log(maxIds.length);  // logs the correct length of 82\n    return Price.findAll({\n        where: {\n            id: {\n                [Sequelize.Op.in]: maxIds\n            }\n        }\n    });\n}).then(maxPrices => {\n    console.log(maxPrices);\n});\n```\n\n```text\nprice {\n    dataValues: {},\n    _previousDataValues: {},\n    _changed: {},\n    _modelOptions:\n     { timestamps: true,\n       validate: {},\n       freezeTableName: false,\n       underscored: false,\n       underscoredAll: false,\n       paranoid: false,\n       rejectOnEmpty: false,\n       whereCollection: null,\n       schema: null,\n       schemaDelimiter: '',\n       defaultScope: {},\n       scopes: [],\n       indexes: [],\n       name: [Object],\n       omitNull: false,\n       sequelize: [Object],\n       hooks: {},\n       uniqueKeys: {} },\n    _options:\n     { isNewRecord: false,\n       _schema: null,\n       _schemaDelimiter: '',\n       raw: true,\n       attributes: [Array] },\n    __eagerlyLoadedAssociations: [],\n    isNewRecord: false },\n```\n\n```text\nmaxIds.length\n```\n\n```text\nUnhandled rejection Error: Invalid value price\n```\n\n```text\nconsole.log(maxIds);\n```\n\n```text\nSELECT MAX(id) FROM prices GROUP BY symbol\n```\n\n```text\nPrice.findAll({\n    attributes: [Sequelize.fn('max', Sequelize.col('id'))],\n    group: [\"symbol\"],\n    raw: true,\n})\n```\n\n```text\nraw: true\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":183,"estimatedTokens":1135}}755{"id":"stack-52034955","source":"stackoverflow","questionId":52034955,"title":"sequelize group by fn count becomes undefined","tags":["javascript","node.js","sequelize.js"],"text":"Title: sequelize group by fn count becomes undefined\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy query is as shown below : \n\n```\ndb.test.findAll({\n group: ['source'],\n attributes: ['source', [Sequelize.fn('COUNT', 'source'), 'count']],\n order: [\n [Sequelize.literal('count'), 'DESC']\n ]\n}).then((sources) => {\n sources.forEach((info) => {\n console.log('sorce name :' + info.source + \" count : \" + info.count);\n })\n}).catch((err) => {\n console.log(err);\n})\n```\n\nSo, here what happens is `info.source` name is printed perfectly. But `info.count` is `undefined` even if it is shown in the response ?\n\n========================================\n\nTop Answer:\nJust came across this issue myself. Instead of having to use `raw: true`, you can use `instance.get('attribute')`, so in your case \n\n```\nsources.forEach((info) => {\n console.log('source name :' + info.source + \" count : \" + info.get('count');\n})\n```\n\nYou could also do `info.dataValues.count`\n\n========================================\n\nCode:\n```text\ndb.test.findAll({\n  group: ['source'],\n  attributes: ['source', [Sequelize.fn('COUNT', 'source'), 'count']],\n  order: [\n    [Sequelize.literal('count'), 'DESC']\n  ]\n}).then((sources) => {\n  sources.forEach((info) => {\n    console.log('sorce name :' + info.source + \" count : \" + info.count);\n  })\n}).catch((err) => {\n  console.log(err);\n})\n```\n\n```text\ninfo.source\n```\n\n```text\ninfo.count\n```\n\n```text\nundefined\n```\n\n```text\ndb.test.findAll({\n  group: ['source'],\n  attributes: ['source', [Sequelize.fn('COUNT', 'source'), 'count']],\n  order: [\n    [Sequelize.literal('count'), 'DESC']\n  ],\n  raw: true, // <-- HERE\n})\n```\n\n```text\ntest\n```\n\n```text\nraw: true\n```\n\n```text\nsources.forEach((info) => {\n  console.log('source name :' + info.source + \" count : \" + info.get('count');\n})\n```\n\n```text\nraw: true\n```\n\n```text\ninstance.get('attribute')\n```\n\n```text\ninfo.dataValues.count\n```\n\n========================================\n\nComments:\n- I have not used sequelize.js for a while, but shouldn't it be `Sequelize.col('source')`, instead of just `'source'`: `Sequelize.fn('COUNT', Sequelize.col('source'))`?\n- @t.niese i even wrote `Sequelize.fn('COUNT', sequelize.col('source'))` , the result is the same and `count` is still undefined","metadata":{"transformedAt":"2026-08-18T18:33:34.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":111,"estimatedTokens":568}}756{"id":"stack-62697282","source":"stackoverflow","questionId":62697282,"title":"Sequelize: find entries with no association","tags":["sequelize.js"],"text":"Title: Sequelize: find entries with no association\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nGiven the following simple models:\n\n```\nclass A extends Model {}\nA.init({\n aField: DataTypes.STRING,\n}, { sequelize });\n\nclass B extends Model {}\nB.init({\n bField: DataTypes.STRING,\n}, { sequelize });\n\nA.hasMany(B); // this creates the B.AId column\n\n// populate\n\nawait A.create({\n aField: 'fooA',\n Bs: [{ bField: 'fooB' }]\n}, { include: [B] });\n\nawait A.create({ aField: 'barA' });\nawait A.create({ aField: 'bazA' });\n```\n\nI cannot figure out how to select the first A model instance that has no B entries.\n\nThe the previous case, return just `barA` and `bazA`.\n\nThe following does not work, it returns `foo`:\n\n```\nawait A.findOne({\n include: [{\n model: B,\n required: false,\n where: {\n 'AId': null,\n }\n }],\n});\n```\n\nGenerated query is: `SELECT A.*, Bs.id AS Bs.id, Bs.bField AS Bs.bField, Bs.AId AS Bs.AId FROM (SELECT A.id, A.aField FROM As AS A LIMIT 1) AS A LEFT OUTER JOIN Bs AS Bs ON A.id = Bs.AId AND Bs.AId IS NULL`\n\n========================================\n\nCode:\n```text\nclass A extends Model {}\nA.init({\n    aField: DataTypes.STRING,\n}, { sequelize });\n\nclass B extends Model {}\nB.init({\n    bField: DataTypes.STRING,\n}, { sequelize });\n\nA.hasMany(B); // this creates the B.AId column\n\n\n// populate\n\nawait A.create({\n    aField: 'fooA',\n    Bs: [{ bField: 'fooB' }]\n}, { include: [B] });\n\nawait A.create({ aField: 'barA' });\nawait A.create({ aField: 'bazA' });\n```\n\n```text\nawait A.findOne({\n    include: [{\n        model: B,\n        required: false,\n        where: {\n            'AId': null,\n        }\n    }],\n});\n```\n\n```text\nbarA\n```\n\n```text\nbazA\n```\n\n```text\nfoo\n```\n\n```text\nSELECT A.*, Bs.id AS Bs.id, Bs.bField AS Bs.bField, Bs.AId AS Bs.AId FROM (SELECT A.id, A.aField FROM As AS A LIMIT 1) AS A LEFT OUTER JOIN Bs AS Bs ON A.id = Bs.AId AND Bs.AId IS NULL\n```\n\n```js\nawait A.findOne({\n    include: [{\n        model: B,\n        required: false,\n        where: {\n            'AId': null,\n        }\n    }],\n    subQuery: false\n});\n```\n\n```sql\nSELECT `A`.`id`, `A`.`aField`, `A`.`createdAt`, `A`.`updatedAt`, `Bs`.`id` AS `Bs.id`, \n    `Bs`.`bField` AS `Bs.bField`, `Bs`.`createdAt` AS `Bs.createdAt`, \n    `Bs`.`updatedAt` AS `Bs.updatedAt`, `Bs`.`AId` AS `Bs.AId` \nFROM `As` AS `A` \nLEFT OUTER JOIN `Bs` AS `Bs` ON `A`.`id` = `Bs`.`AId` AND `Bs`.`AId` IS NULL \nLIMIT 1;\n```\n\n```sql\n...\n... ON `A`.`id` = `Bs`.`AId` WHERE `Bs`.`AId` IS NULL \nLIMIT 1;\n```\n\n```js\nawait A.findOne({\n    include: [{\n        model: B,\n        required: false\n    }],\n    where: {\n        '$Bs.AId$': null\n    },\n    subQuery: false\n});\n```\n\n```text\nsubQuery: false\n```\n\n```text\nwhere\n```\n\n```text\ninclude\n```\n\n```text\nAND\n```\n\n```text\nON\n```\n\n```text\nWHERE\n```\n\n```text\nwhere\n```\n\n```text\nA\n```\n\n========================================\n\nComments:\n- Do you expect returning both barA and bazA? or only barA?\n- yes, using findAll(), but here I just expect to get one entry\n- Thank a lot, this work well! I fail to find documentations for subQuery, do you have any pointer ?\n- I cannot find a good doc either. I just knew `subQuery` from some github issues or stackoverflow. sorry... but glad to hear that worked.\n- Thankyou for your answer. But I am having a hardtime understanding it. Say I have model Artist that has many albums. How would I do a findAall query to return all Artists without albums\n- Changing A to Artist and B to Album does work? otherwise, could you post a new question including the descriptive information and model association and your current code if you have?","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":189,"estimatedTokens":896}}757{"id":"stack-48649759","source":"stackoverflow","questionId":48649759,"title":"manipulate data object sequelize ORM (nodejs)","tags":["node.js","express","sequelize.js"],"text":"Title: manipulate data object sequelize ORM (nodejs)\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni have code like :\n\n```\ndata = await photo.findOne({\n where : {id}\n})\n```\n\nthat return data\n\n```\n{\n \"a\" : 2,\n \"b\" : 5\n}\n```\n\ni want to manipulate the data like insert some field\n\nso i add properties :\n\n```\ndata.c = data.a * data.b\n```\n\ni check in console.log the data added\n\n```\n{\n \"a\" : 2,\n \"b\" : 5,\n \"c\" \" 10\n}\n```\n\nbut when i return to json\n\n```\nreturn res.status(200).json({message: \"success\", data })\n```\n\nthe data still like first\n {\n \"a\" : 2,\n \"b\" : 5\n }\n\n========================================\n\nTop Answer:\nFinally I found answer after searching a lot. you should do something like this\n\n```\nconst users = await db.users.findAll({})\n.map(el => el.get({ plain: true })) // add this line to code\n```\n\nsource :Github issue\n\n========================================\n\nCode:\n```text\ndata = await photo.findOne({\n    where : {id}\n})\n```\n\n```text\n{\n     \"a\" : 2,\n     \"b\" : 5\n}\n```\n\n```text\ndata.c = data.a * data.b\n```\n\n```text\n{\n     \"a\" : 2,\n     \"b\" : 5,\n     \"c\" \" 10\n}\n```\n\n```text\nreturn res.status(200).json({message: \"success\", data })\n```\n\n```text\ndataInstance = await photo.findOne({\n    where : {id}\n})\ndata = dataInstance.get({\n   plain: true // Important\n})\ndata.c = data.a * data.b;\n```\n\n```text\ndata.c = data.a * data.b\n```\n\n```text\nconst users = await db.users.findAll({})\n.map(el => el.get({ plain: true })) // add this line to code\n```\n\n========================================\n\nComments:\n- When you use sequelize, you write to a table. So the first thing is to check the table structure. Do you have a column 'c'? Also how is the ORM schema and how do save the data?\n- no i dont have column 'c', but i wanna add some properties \"c\" to object \"data\"\n- I understand now what you are trying to do. I guess your problem is a timing issue. Something with asynchronous code that is not executed in the order you think.\n- wow i see, i'm misunterstanding for the model, but when i try , why return \"dataInstance.get is not a function\"\n- the answer is correct, thanks the reason i got error \"dataInstance.get is not a function\", because the data still in array and i use .findAll()","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":123,"estimatedTokens":555}}758{"id":"stack-45314883","source":"stackoverflow","questionId":45314883,"title":"hash password on create and update","tags":["sequelize.js"],"text":"Title: hash password on create and update\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to hash a password for users when the record is created and when the user updates their password. On creation, I can do something like\n\n```\nUser.beforeCreate((user, options) => {\n user.password = encryptPassword(user.password)\n})\n```\n\nWhich will be easily executed and hash the password for new users. But I have an issue when updating the password. If I just do\n\n```\nUser.beforeUpdate((user, options) => {\n user.password = encryptPassword(user.password)\n})\n```\n\nthen everytime users updating their record (i.e update name, address, etc) it triggers the hook and re-hash the password.\n\nHow can I tell when the password is changed so that I can trigger the hook? Also instead of having those 2 hooks, how can I just use `beforeSave` to achieve the same result?\n\n**UPDATE**\n\nAs per requested my User definition is as simple as\n\n```\nsequelize.define(\n 'user',\n {\n id: {\n type: Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true,\n },\n emailAddress: {\n field: 'email_address',\n type: Sequelize.STRING,\n allowNull: false,\n unique: true,\n validate: {\n isEmail: {\n args: true,\n msg: \"Email is not valid\"\n }\n },\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n min: {\n args: 6,\n msg: \"Password must be more than 6 characters\"\n }\n }\n }\n }\n)\n```\n\n========================================\n\nCode:\n```text\nUser.beforeCreate((user, options) => {\n  user.password = encryptPassword(user.password)\n})\n```\n\n```text\nUser.beforeUpdate((user, options) => {\n  user.password = encryptPassword(user.password)\n})\n```\n\n```text\nsequelize.define(\n  'user',\n  {\n    id: {\n      type:          Sequelize.INTEGER,\n      autoIncrement: true,\n      primaryKey:    true,\n    },\n    emailAddress: {\n      field:        'email_address',\n      type:         Sequelize.STRING,\n      allowNull:    false,\n      unique:       true,\n      validate: {\n        isEmail: {\n          args:     true,\n          msg:      \"Email is not valid\"\n        }\n      },\n    },\n    password: {\n      type:         Sequelize.STRING,\n      allowNull:    false,\n      validate: {\n        min: {\n          args:     6,\n          msg:      \"Password must be more than 6 characters\"\n        }\n      }\n    }\n  }\n)\n```\n\n```text\nbeforeSave\n```\n\n```text\nfunction encryptPasswordIfChanged(user, options) {\n  if (user.changed('password')) {\n    encryptPassword(user.get('password'));\n  }\n}\n\nUser.beforeCreate(encryptPasswordIfChanged);\nUser.beforeUpdate(encryptPasswordIfChanged);\n```\n\n```text\nuser.set('password', somePasswordString);\n```\n\n```text\n.changed\n```\n\n```text\ntrue\n```\n\n```text\n_previousDataValues\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Hey that looks alright. With `.changed()` I can tell when the password is changed. But another issue is the hook does not trigger validation. So if my validation says minimum password is 6 characters, I can still pass 3 digits password.\n- Did you check sequelize.readthedocs.io/en/v3/docs/hooks ? It implies that the validation hook would run before those two hooks. I may be able to give you some insight if you post your Sequelize definition for the user table you're working on.\n- I understand with the hook order and it is still relevant with v4 I am using docs.sequelizejs.com/manual/tutorial/&hellip;. But I still don't understand why the validation is not applied when update/create hook is triggered. I have added my User definition.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":155,"estimatedTokens":876}}759{"id":"stack-49102889","source":"stackoverflow","questionId":49102889,"title":"How can I use datediff of mysql with sequelizejs","tags":["javascript","node.js","sequelize.js"],"text":"Title: How can I use datediff of mysql with sequelizejs\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement this SQL to my Sequelize \n\n```\nSELECT file_id FROM table WHERE datediff(curdate(),create_date) > 5;\n\n Here is my Sequelize\n\n findOverPeriodFile: function () {\n return table.findAll({\n where:{\n 60: {lt: Sequelize.fn('')}\n }\n });\n}\n```\n\nIm new to Seuelize and I have tried to search Google, but it doesn't help. Does anyone have an answer to this question? I don't know what to put in the `WHERE` statement. Sorry for my bad English.\n\n========================================\n\nTop Answer:\n```\nsequelize.where(\n sequelize.fn(\n 'timestampdiff', \n sequelize.literal(\"minute\"),\n sequelize.col('updatedAt'),\n sequelize.literal('CURRENT_TIMESTAMP')\n ), \n {\n [Op.gte] : ACCEPTION_TIMEOUT\n }\n)\n```\n\nIf someone like me will be searching for a way to find date or time difference in sequelize (not only in days), **timestampdiff** is a working way to do that.\n\n`sequelize.literal(\"minute\")` — is a unit of time. More on that here\n\n`sequelize.col('updatedAt')` — column in the database (datetime)\n\n`sequelize.literal('CURRENT_TIMESTAMP')` — sequelize literal for current time\n\n```\n{\n [Op.gte] : ACCEPTION_TIMEOUT\n}\n```\n\nAnd this one is your SELECT condition for time matters\n\n========================================\n\nCode:\n```text\nSELECT file_id FROM table WHERE datediff(curdate(),create_date) > 5;\n\n   Here is my Sequelize\n\n   findOverPeriodFile: function () {\n    return table.findAll({\n        where:{\n            60: {lt: Sequelize.fn('')}\n        }\n    });\n}\n```\n\n```text\nWHERE\n```\n\n```text\n{ \n    where: sequelize.where(sequelize.fn('datediff', sequelize.fn(\"NOW\") , sequelize.col('create_date')), {\n        $gt : 5 // OR [Op.gt] : 5\n    })\n}\n```\n\n```text\n{\n    where: {\n        $and : [\n            sequelize.where(sequelize.fn('datediff', sequelize.fn(\"NOW\") , sequelize.col('create_date')), {\n                $gt : 5 // OR [Op.gt] : 5\n            }) ,\n            { status : 'mystatus' }\n        ]\n    }\n}\n```\n\n```text\nWHERE datediff(curdate(),create_date) > 5;\n```\n\n```text\nsequelize.where(sequelize.fn('datediff', sequelize.literal(\"day\"), sequelize.col('Your Column date'), sequelize.fn(\"getdate\")), {\n          [Op.gt]: 0\n        })\n```\n\n```text\nsequelize.where(\n    sequelize.fn(\n        'timestampdiff', \n         sequelize.literal(\"minute\"),\n         sequelize.col('updatedAt'),\n         sequelize.literal('CURRENT_TIMESTAMP')\n    ), \n    {\n        [Op.gte] : ACCEPTION_TIMEOUT\n    }\n)\n```\n\n```text\n{\n   [Op.gte] : ACCEPTION_TIMEOUT\n}\n```\n\n```text\nsequelize.literal(\"minute\")\n```\n\n```text\nsequelize.col('updatedAt')\n```\n\n```text\nsequelize.literal('CURRENT_TIMESTAMP')\n```\n\n```text\nlet pending = await Table.findAll({\n        where: {\n            [Op.and] : [\n                Sequelize.where(Sequelize.fn('datediff',  Sequelize.col('DD'), Sequelize.col('createdAt'), Sequelize.fn(\"GETDATE\")), {\n                    [Op.lt] : 1 \n                }) ,\n                { is_processed : '0' }\n            ]\n        }\n    } );\n```\n\n```text\nSELECT * FROM [table] AS [table] \nWHERE (datediff(DD, [createdAt], GETDATE()) < 1 AND [table].[is_processed] = 0);\n```\n\n```text\nwhere: {\n        [Op.and]: [\n          sequelize.where(\n            sequelize.fn(\n              \"datediff\",\n              sequelize.fn(\"NOW\"),\n              sequelize.col(\"lastSubmitted\") // your column name \n            ),\n            {\n              [Op.gt]: 1,\n            }\n          ),\n          {status:\"active\"},\n        ],\n}\n```\n\n========================================\n\nComments:\n- But I tried using [Op.gt] :5 and it worked. Btw, thanks for your help :D\n- How do you add more where clauses to this ? eg. ` AND status = 'mystatus'`\n- Thanks @VivekDoshi for the quick reply :) I was just about to comment about one of the solution I found at github.com/sequelize/sequelize/issues/&hellip;.\n- Also the above \"adding more condition\" seems to be throwing me syntax errors. Maybe the `$and` should be after `sequelize.where` ?\n- @NikhilNanjappa, yeah, my mistake , check now.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":184,"estimatedTokens":1025}}760{"id":"stack-42503020","source":"stackoverflow","questionId":42503020,"title":"Sequelize hasOne through another table","tags":["node.js","sequelize.js"],"text":"Title: Sequelize hasOne through another table\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following three models\n\n**User**\n\n```\nuser_id\nuser_email\n```\n\n**Group**\n\n```\ngroup_id\ngroup_name\n```\n\n**GroupUser**\n\n```\ngroup_user_id\nuser_id\ngroup_id\n```\n\nHow can I get group details(if it mapped with user ) while fetch User data ?\nIs there any Sequelize hasOne association through another table ?\n\n========================================\n\nCode:\n```text\nuser_id\nuser_email\n```\n\n```text\ngroup_id\ngroup_name\n```\n\n```text\ngroup_user_id\nuser_id\ngroup_id\n```\n\n```text\nGroup.belongsTo(GroupUser)\nUser.belongsTo(GroupUser)\nGroupUser.hasOne(Group)\nGroupUser.hasOne(User)\n```\n\n```text\nUser.findAll({include : [{model:GroupUser, include :[{model : Group}]}]})\n```\n\n========================================\n\nComments:\n- Thanks bro , let me try your solution.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":66,"estimatedTokens":218}}761{"id":"stack-47439822","source":"stackoverflow","questionId":47439822,"title":"Unit Testing with SQLite3","tags":["node.js","sqlite","sequelize.js","knex.js","bookshelf.js"],"text":"Title: Unit Testing with SQLite3\nTags: node.js, sqlite, sequelize.js, knex.js, bookshelf.js\nSource: Stack Overflow\n\nQuestion:\nI am writing unit tests and use SQLite3 with his inmemory mode.\n\nI am doing this because i need is a fresh database for each test so i can run tests in parallel without affecting each other. \n\nBut this gets, off course, slower and slower the more tests i have.\n\n**Are there any optimisations i can do with sqlite3, another better workflow (e.g. a good mocking library) or another solution do this problem? I need to run raw queries.**\n\nCurrently i use knexjs but this is related to allmost every data access library.\n\n========================================\n\nComments:\n- Why do you run your tests against a real database? Wouldn't it suffice to assume that you get certain data from a database, in a mocked form, and unit test your business logic based on that? What you are trying to do sounds more like integration testing to me.\n- Yes for queries this is true. But what about inserts and updates? Simulating database references etc..\n- For unit tests, I would trust that my persistence layer actually is able to store data, and I would only cover edge cases -- e.g. proper exception handling through unit tests.I am not saying that it is bad to have the queries run against a proper test database, yet those tests are by design slower and all you can do to speed them up is to run them in parallel to a certain degree.\n- Thats true. I guess iam switching to some kind of mocking library. Thanks! @k0pernikus\n- @dknaack Unit testing DB queries is usually pretty much waste of time, so doing integration tests sounds like a good idea. How many tests are you doing if inmemory sqlite is getting too slow? That way you should be able to do hundreds of tests per second... probably its not the sqlite that is the slow part in your tests.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":23,"estimatedTokens":466}}762{"id":"stack-49639153","source":"stackoverflow","questionId":49639153,"title":"Sequelize create database schema from model","tags":["sequelize.js","database-schema"],"text":"Title: Sequelize create database schema from model\nTags: sequelize.js, database-schema\nSource: Stack Overflow\n\nQuestion:\nCan I use sequelize to create the database schema from the available model? I work on a project that has many migrations missing and no tests. To run tests I need to create a new db (sqlite3) but I cannot initialize its schema using migration (because they are missing). Is it possible to use the models to create the schema?\n\n========================================\n\nTop Answer:\nIs it possible to use the models to create the schema? ... Because I want to do this in Mocha config so whenever any test runs, I'm sure that it runs on an up to date test db. But because sync is async I have no idea how to do this\n\nAssuming Sequelize CLI was used, Here's a way to ensure you have an updated db in any mocha test:\n\n```\n// Force sync without migrations\n // This can be run at the top of every individual test suite\n before(function () {\n return require('../../models').sequelize.sync({ force: true })\n })\n```\n\nThe path `'../../models'` points to `models/index.js` which Sequelize CLI creates for you.\n\n========================================\n\nCode:\n```text\n// Force sync without migrations\n  // This can be run at the top of every individual test suite\n  before(function () {\n    return require('../../models').sequelize.sync({ force: true })\n  })\n```\n\n```text\n'../../models'\n```\n\n```text\nmodels/index.js\n```\n\n========================================\n\nComments:\n- Is there any way to do this from the cli, or in a synchronous manner? Because I want to do this in Mocha config so whenever any test runs, I'm sure that it runs on an up to date test db. But because `sync` is async I have no idea how to do this\n- Thanks for a more detailed answer. I've already thought about using the `before` helper, but I prefer to have a global synchronization whenever mocha runs\n- @Uko do add an answer if you figure that method out, I'd love to utilize that as well. I currently do not have a global solution, unfortunately.\n- I discovered that you can use the `mocha-prepare` npm module. The docs are quite clear and here is the code that I have in the synchronization file that I require in mocha.opts: `prepare((done) => { db.sequelize.sync({ force: true }).then(() => done()); });`","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":573}}763{"id":"stack-63335865","source":"stackoverflow","questionId":63335865,"title":"Sequelize Error on DataTypes.ARRAY(DataTypes.STRING)","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize Error on DataTypes.ARRAY(DataTypes.STRING)\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to NodeJs development\nI am using NodeJs with mysql and Sequelize to create a Batch model with these properties.\n\n```\nconst Batch = sequelize.define(\n \"Batch\",\n {\n title: { type: DataTypes.STRING, allowNull: false },\n studentIds: { type: DataTypes.STRING },\n teacherId: { type: DataTypes.STRING, allowNull: true }\n },\n {\n timestamps: false\n }\n);\n```\n\nOn async method call it is working fine.\n\n```\nBatch.sync().then((res) => {\n console.log(\"Batch model sync : \", Batch === sequelize.models.Batch);\n});\n```\n\nBut I need to change\n\n```\nstudentIds: { type: DataTypes.ARRAY(DataTypes.STRING)}\n```\n\nWhenever I make this change it gives error\n\nhttps://i.sstatic.net/kXqpz.png\n\nI am using node 14.5.0 MySql 8.0.21 and Sequelize 6.3.4\n\n========================================\n\nTop Answer:\nWith a small workaround you can use your string data as an array.\nOverwrite the getter and setter of the property of the model\n\n```\nstudentIds: {\n type: Sequelize.STRING,\n get() {\n const stringValue = this.getDataValue('studentIds');\n return stringValue ? rawValue.split(',') : null;\n },\n set(value) {\n const arrayValue = value ? value.join(',') : '';\n this.setDataValue('studentIds', arrayValue);\n },\n },\n```\n\n========================================\n\nCode:\n```text\nconst Batch = sequelize.define(\n  \"Batch\",\n  {\n    title: { type: DataTypes.STRING, allowNull: false },\n    studentIds: { type: DataTypes.STRING },\n    teacherId: { type: DataTypes.STRING, allowNull: true }\n  },\n  {\n    timestamps: false\n  }\n);\n```\n\n```text\nBatch.sync().then((res) => {\n  console.log(\"Batch model sync : \", Batch === sequelize.models.Batch);\n});\n```\n\n```text\nstudentIds: { type: DataTypes.ARRAY(DataTypes.STRING)}\n```\n\n```text\nDataTypes.ARRAY\n```\n\n```text\nstudentIds: {\n    type: Sequelize.STRING,\n    get() {\n      const stringValue = this.getDataValue('studentIds');\n      return stringValue ? rawValue.split(',') : null;\n    },\n    set(value) {\n      const arrayValue = value ? value.join(',') : '';\n      this.setDataValue('studentIds', arrayValue);\n    },\n  },\n```\n\n========================================\n\nComments:\n- so on mysql , it should be what when I need array","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":111,"estimatedTokens":572}}764{"id":"stack-48730477","source":"stackoverflow","questionId":48730477,"title":"Sequelize migration queryInterface.removeColum fails to work","tags":["postgresql","sequelize.js","sequelize-cli"],"text":"Title: Sequelize migration queryInterface.removeColum fails to work\nTags: postgresql, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI created a migration file to add a column as an `up` and then delete it under `down`.\n\nHere's the migration file code:\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) =>\n queryInterface.addColumn('Books', 'Rating', {\n allowNull: false,\n type: Sequelize.ENUM('like', 'dislike'),\n }),\n\n down: (queryInterface, Sequelize) => {\n queryInterface.removeColumn('Books', 'Rating');\n },\n};\n```\n\nWhen I ran it for the first time using `db:migrate`, it successfully added the column but when I did a `db:migrate:undo:all` and then ran the migrations again, it threw me an error sqying\n\n```\n======= 20180211100937-AddedRatingIntoBooks: migrating \n======= 2018-02-11 15:42:46.076 IST \n[64531] ERROR: type \"enum_Books_Rating\" already exists 2018-02-11 15:42:46.076 IST \n[64531] STATEMENT: CREATE TYPE \"public\".\"enum_Books_Rating\" AS ENUM('like', 'dislike');\nALTER TABLE \"public\".\"Boo ks\" ADD COLUMN \"Rating\" \"public\".\"enum_Books_Rating\";\n\n ERROR: type \"enum_Books_Rating\" already exists\n```\n\nThe issue is still live here.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) =>\n    queryInterface.addColumn('Books', 'Rating', {\n      allowNull: false,\n      type: Sequelize.ENUM('like', 'dislike'),\n    }),\n\n  down: (queryInterface, Sequelize) => {\n    queryInterface.removeColumn('Books', 'Rating');\n  },\n};\n```\n\n```text\n======= 20180211100937-AddedRatingIntoBooks: migrating \n======= 2018-02-11 15:42:46.076 IST \n[64531] ERROR:  type \"enum_Books_Rating\" already exists 2018-02-11 15:42:46.076 IST \n[64531] STATEMENT:  CREATE TYPE \"public\".\"enum_Books_Rating\" AS ENUM('like', 'dislike');\nALTER TABLE \"public\".\"Boo ks\" ADD COLUMN \"Rating\" \"public\".\"enum_Books_Rating\";\n\n    ERROR: type \"enum_Books_Rating\" already exists\n```\n\n```text\nup\n```\n\n```text\ndown\n```\n\n```text\ndb:migrate\n```\n\n```text\ndb:migrate:undo:all\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) =>\n    queryInterface.addColumn('Books', 'Rating', {\n      allowNull: false,\n      type: Sequelize.ENUM('like', 'dislike')\n  }),\n\n  down: (queryInterface, Sequelize) =>  \n    queryInterface.removeColumn('Books', 'Rating')\n      .then(() => queryInterface.sequelize.query('DROP TYPE \"enum_Books_Rating\";'));\n  };\n```\n\n```text\nenum_Books_Rating\n```\n\n```text\nENUM\n```\n\n========================================\n\nComments:\n- Just a note - If the error exists before one uses this code, he or she needs to go execute `DROP TYPE enum_tableName_attributeName` at the database first before he runs any kind of up or down migrations.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":106,"estimatedTokens":676}}765{"id":"stack-26421713","source":"stackoverflow","questionId":26421713,"title":"Sequelize doesn't create foreign keys as constraints","tags":["postgresql","sequelize.js"],"text":"Title: Sequelize doesn't create foreign keys as constraints\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWe're trying to create tables automatically inside PostgreSQL using Sequelize. Unfortunately, it doesn't create the foreign keys as constraints. Here is an example of one of my models:\n\n```\nmodule.exports = function(schema, DataTypes) {\n\n var definition = {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n deal_id: {\n type: DataTypes.INTEGER\n },\n image: DataTypes.STRING,\n };\n\n var image = schema.define('Image', definition, {\n tableName: 'images', // this will define the table's name\n timestamps: false, // this will deactivate the timestamp columns\n syncOnAssociation: true,\n\n classMethods: {\n getDefinition: function() {\n return definition;\n },\n associate: function(_models) {\n image.belongsTo(_models.Product, {\n foreignKey: 'deal_id'\n });\n }\n }\n });\n\n return image;\n};\n```\n\nAm I doing something wrong?\n\n========================================\n\nCode:\n```text\nmodule.exports = function(schema, DataTypes) {\n\n    var definition = {\n        id: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        deal_id: {\n            type: DataTypes.INTEGER\n        },\n        image: DataTypes.STRING,\n    };\n\n\n    var image = schema.define('Image', definition, {\n        tableName: 'images', // this will define the table's name\n        timestamps: false, // this will deactivate the timestamp columns\n        syncOnAssociation: true,\n\n        classMethods: {\n            getDefinition: function() {\n                return definition;\n            },\n            associate: function(_models) {\n                image.belongsTo(_models.Product, {\n                    foreignKey: 'deal_id'\n                });\n            }\n        }\n    });\n\n    return image;\n};\n```\n\n```text\nvar Task = this.sequelize.define('Task', { title: Sequelize.STRING })\n  , User = this.sequelize.define('User', { username: Sequelize.STRING })\n\nUser.hasMany(Task)\nTask.belongsTo(User)\n```\n\n```text\nUser.hasMany(Task, { onDelete: 'SET NULL', onUpdate: 'CASCADE' })\n\nCREATE TABLE IF NOT EXISTS `Task` (\n  `id` INTEGER PRIMARY KEY, \n  `title` VARCHAR(255), \n  `user_id` INTEGER REFERENCES `User` (`id`) ON DELETE SET NULL ON UPDATE CASCADE\n);\n```\n\n```text\nonUpdate\n```\n\n```text\nonDelete\n```\n\n========================================\n\nComments:\n- Thanks, clear answer. Didn't read that part in the documentation, my mistake. Thanks!\n- One problem left: how to define the foreignkey? If I add the foreignkey inside the object it doesn't create the constraints, if I don't it creates a camelCase foreignkey itself.\n- As I understand it, you don't define the foreign key in Sequelize. Instead, you set onDelete or on Update options in the association.\n- @Charlie: Thanks for catching the dead link. I think it just documents where I copied the last code block from. I couldn't find it on their current web site, and archive.org didn't seem to have a copy. I'll think about deleting it, but I'm also thinking about leaving the dead link in place as kind of documentation that Sequelize is indifferent to redirection and the effect of updating web pages.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":118,"estimatedTokens":808}}766{"id":"stack-49307788","source":"stackoverflow","questionId":49307788,"title":"Sequelize (or clear SQL) query for selecting rows what includes value in JSON field?","tags":["mysql","json","node.js","sequelize.js"],"text":"Title: Sequelize (or clear SQL) query for selecting rows what includes value in JSON field?\nTags: mysql, json, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have rows in my MYSQL and I Need Sequelize.js query.\n\nEvery row have col of type JSON what include this for example:\n\n```\n[\n {id: 1234, blah: \"test\"},\n {id: 3210, blah: \"test\"},\n {id: 5897, blah: \"test\"}\n]\n```\n\nI have `id` and I need to select row what include this `id` in at least one object in array.\n\n========================================\n\nCode:\n```text\n[\n  {id: 1234, blah: \"test\"},\n  {id: 3210, blah: \"test\"},\n  {id: 5897, blah: \"test\"}\n]\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nSELECT * FROM `user` WHERE JSON_CONTAINS(`comments`, '{\"id\": 1234}');\n```\n\n```text\nconst { fn, col, cast } = this.sequelize;\n\nconst User = this.sequelize.define('user', {  \n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  comments: DataTypes.JSON,\n  defaultValue: [],\n})\n\nUser.findAll({\n  where: fn('JSON_CONTAINS', col('comments'), cast('{\"id\": 1234}', 'CHAR CHARACTER SET utf8')),\n})\n.then(users => console.log('result', users.map(u => u.get())))\n.catch(err => console.log('error', err));\n```\n\n```text\nSELECT * FROM `user` WHERE JSON_CONTAINS(`comments`, '{\\\"id\\\": 1234}');\n```\n\n```text\nSELECT * FROM `user` WHERE `comments` LIKE '%\"id\": 1234%';\n```\n\n========================================\n\nComments:\n- docs.sequelizejs.com/manual/tutorial/querying.html#json may be this help you\n- How Can I use OR condition also with JSON_CONTAINS? Query is like `SELECT * FROM projects WHERE JSON_CONTAINS(`stackholders`, 2) OR owner = 1`","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":408}}767{"id":"stack-47379702","source":"stackoverflow","questionId":47379702,"title":"Sequelize invalid value Symbol(ne)","tags":["javascript","node.js","postgresql","express","sequelize.js"],"text":"Title: Sequelize invalid value Symbol(ne)\nTags: javascript, node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following two files running on an Express Node.js server:\n\nhome.js\n\n```\nvar express = require('express')\nvar sequelize = require('sequelize')\nvar db = require('../../shared/db.js')\n\nvar op = sequelize.Op\n\nvar router = express.Router()\n\nrouter.get('/home', function(req, res, next) {\n db.shared.person.findAll({\n where: {\n email: {\n [op.ne]: null\n }\n },\n order: ['id']\n }).then(function (person) {\n res.locals = {\n person: person\n }\n res.render('home')\n })\n})\n\nmodule.exports = router\n```\n\ndb.js\n\n```\nvar sequelize = require('sequelize')\n\nvar config = {\n host: 'localhost',\n port: 5432,\n username: '...',\n password: '...',\n database: 'postgres',\n dialect: 'postgres',\n operatorsAliases: false\n}\nvar db = new sequelize(config)\n\nmodule.exports = {\n shared: {\n person: db.define('person', {\n id: {\n type: sequelize.INTEGER,\n primaryKey: true\n },\n name: sequelize.STRING,\n email: sequelize.INTEGER\n }, { freezeTableName: true , timestamps: false, schema: 'shared' }),\n }\n}\n```\n\nWhen I try to run this query, I get an error claiming `Unhandled rejection Error: Invalid value { [Symbol(ne)]: null }`\n\nWhat am I doing wrong? I can use `$ne` and even `ne` just fine but they've been deprecated and are not entirely safe to use. Furthermore, it's not just `[op.ne]` - I get this error when I use any conditional like this.\n\nI'm basing this all on this guide so I'm not really sure what I could be doing wrong here.\n\n========================================\n\nTop Answer:\n`Unhandled rejection Error: Invalid value` might also appear if you didn't setup string aliases like this:\n\n\r\n\r\n\n```\nconst Op = Sequelize.Op;\r\nconst operatorsAliases = {\r\n $eq: Op.eq,\r\n $ne: Op.ne,\r\n ...\r\n $any: Op.any,\r\n $all: Op.all,\r\n $values: Op.values,\r\n $col: Op.col\r\n};\r\n\r\nconst connection = new Sequelize(db, user, pass, { operatorsAliases });\n```\n\n\r\n\r\n\r\n\nBut, better to remove String based aliases from code and use [Op.ne] for example, Sequlize is planning to deprecate them soon.\n\n========================================\n\nCode:\n```text\nvar express = require('express')\nvar sequelize = require('sequelize')\nvar db = require('../../shared/db.js')\n\nvar op = sequelize.Op\n\nvar router = express.Router()\n\nrouter.get('/home', function(req, res, next) {\n    db.shared.person.findAll({\n        where: {\n            email: {\n                [op.ne]: null\n            }\n        },\n        order: ['id']\n    }).then(function (person) {\n        res.locals = {\n            person: person\n        }\n        res.render('home')\n    })\n})\n\nmodule.exports = router\n```\n\n```text\nvar sequelize = require('sequelize')\n\nvar config = {\n  host: 'localhost',\n  port: 5432,\n  username: '...',\n  password: '...',\n  database: 'postgres',\n  dialect: 'postgres',\n  operatorsAliases: false\n}\nvar db = new sequelize(config)\n\nmodule.exports = {\n  shared: {\n    person: db.define('person', {\n      id: {\n        type: sequelize.INTEGER,\n        primaryKey: true\n      },\n      name: sequelize.STRING,\n      email: sequelize.INTEGER\n    }, { freezeTableName: true , timestamps: false, schema: 'shared' }),\n  }\n}\n```\n\n```text\nUnhandled rejection Error: Invalid value { [Symbol(ne)]: null }\n```\n\n```text\n$ne\n```\n\n```text\nne\n```\n\n```text\n[op.ne]\n```\n\n```text\nmodule.exports = {\n  shared: {\n    person: db.define('person', {\n      id: {\n        type: sequelize.INTEGER,\n        primaryKey: true\n      },\n      name: sequelize.STRING,\n      email: sequelize.INTEGER\n    }, { freezeTableName: true , timestamps: false, schema: 'shared' }),\n  },\n  db: db\n}\n```\n\n```text\nvar express = require('express')\nvar sequelize = require('sequelize')\nvar db = require('../../shared/db.js')\n\nvar op = db.db.Op;\n\nvar router = express.Router()\n\nrouter.get('/home', function(req, res, next) {\n    db.shared.person.findAll({\n        where: {\n            email: {\n                [op.ne]: null\n            }\n        },\n        order: ['id']\n    }).then(function (person) {\n        res.locals = {\n            person: person\n        }\n        res.render('home')\n    })\n})\n\nmodule.exports = router\n```\n\n```text\ndb.js\n```\n\n```text\nhome.js\n```\n\n```text\ndb.js\n```\n\n```js\nconst Op = Sequelize.Op;\nconst operatorsAliases = {\n  $eq: Op.eq,\n  $ne: Op.ne,\n  ...\n  $any: Op.any,\n  $all: Op.all,\n  $values: Op.values,\n  $col: Op.col\n};\n\nconst connection = new Sequelize(db, user, pass, { operatorsAliases });\n```\n\n```text\nUnhandled rejection Error: Invalid value\n```\n\n========================================\n\nComments:\n- This was super helpful, thank you very much! One question though: how do I sanitise user inputs with Node.js/Express?","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":256,"estimatedTokens":1172}}768{"id":"stack-48438938","source":"stackoverflow","questionId":48438938,"title":"Achieve Single Table Inheritance with Sequelize","tags":["node.js","sequelize.js","sti"],"text":"Title: Achieve Single Table Inheritance with Sequelize\nTags: node.js, sequelize.js, sti\nSource: Stack Overflow\n\nQuestion:\nIs there a way to use sequelize to create single table inheritance?\n\nI would like to have a STI for a Purchase and PartialPurchase model where I would have a type field which would be \"Purchase\" or \"PartialPurchase\" and classes Purchase and PartialPurchase which would each inherit from an Operation class.\n\nI don't see this as supported by sequelize, but is an implementation possible?\n\n========================================\n\nTop Answer:\nI think this functionality is not supported yet (09/2021). But, I am working now in a solution for this. The following example resolves two needs:\n\n- We have two entities in the same table (inheriting and adding new attributes) and;\n\n- There's a way for we have common attributes for all models:\n\n```\nconst ModelDiscriminators = {\n Dish: 1,\n Item: 2,\n ItemWithEmail: 3\n}\n\n//Basic field attributes for all entities\nconst BasicModelAttributes = { \n id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true } \n};\n\n//Table dish have id, name, veg, discriminator attributes\nconst Dish = sequelize.define('dish', Object.assign( {}, BasicModelAttributes, { \n name: { type: DataTypes.STRING },\n veg: { type: DataTypes.BOOLEAN },\n discriminator: { type: DataTypes.INTEGER, defaultValue: () => ModelDiscriminators.Dish }\n} ) );\n\n//Two entities sharing same table. Table Item has id, name, type, discriminator e email(see model ItemWithEmail) atributes\n//Model Item\nconst Item = sequelize.define('item', Object.assign( {}, BasicModelAttributes, { \n name: { type: DataTypes.STRING },\n type: { type: DataTypes.STRING },\n discriminator: { type: DataTypes.INTEGER, defaultValue: () => ModelDiscriminators.Item }\n} ) );\n\n//Model ItemWithEmail inherits all Item attributes and define a new one: e-mail\n//We use the discriminator attribute to query the right records when we make a query or .findAll(+where)\nconst ItemWithEmail = sequelize.define('item', Object.assign({}, Item.rawAttributes, { \n email: { type: DataTypes.STRING },\n discriminator: { type: DataTypes.INTEGER, defaultValue: () => ModelDiscriminators.ItemWithEmail }\n} ) );\n```\n\nI think that this approach could be a default way supported by Sequelize. We could have a inherits relation, so we could write:\n\n```\nItemWithEmail.inherits( Item )\n```\n\nAny doubt, I would be glad to help you again. heltongoncalves@gmail.com\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var Message = sequelize.define('Message', {\n    id: {\n      allowNull: false,\n      autoIncrement: true,\n      primaryKey: true,\n      type: DataTypes.INTEGER,\n    },\n    type: {\n      type: DataTypes.ENUM('REQUEST', 'RESPONSE', 'FILE'),\n      allowNull: false\n    },\n    text: {\n      type: DataTypes.TEXT,\n      allowNull: false,\n    },\n    state: {\n      type: DataTypes.JSONB,\n      allowNull: true,\n    },\n    userTeamId: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n    }\n  }, );\n  Message.associate = (models) => {\n    Message.belongsTo(models.UserTeam, { foreignKey: 'userTeamId', targetKey: 'tag'})\n  }\n  return Message;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var UserTeam = sequelize.define('UserTeam', {\n    tag: { type: DataTypes.UUID, allowNull: false, unique: true},\n    active: { type: DataTypes.BOOLEAN, defaultValue: false },\n    activationNonce: { type: DataTypes.STRING },\n    UserId: { type: DataTypes.INTEGER, },\n    TeamId: { type: DataTypes.INTEGER, },\n    type: DataTypes.ENUM('OWNER', 'ADMIN', 'MEMBER', 'GUEST'),\n  },);\n  UserTeam.associate = (models) => {\n    UserTeam.hasMany(models.Message, { as: 'responses', foreignKey: 'userTeamId', sourceKey: 'tag', scope: {type: 'RESPONSE'}})\n    UserTeam.hasMany(models.Message, { as: 'requests', foreignKey: 'userTeamId', sourceKey: 'tag', scope: {type: 'REQUEST'}})\n    UserTeam.hasMany(models.Message, { as: 'files', foreignKey: 'userTeamId', sourceKey: 'tag', scope: {type: 'FILE'}})\n    UserTeam.hasOne(models.Team, {foreignKey: 'id', sourceKey: 'TeamId'})\n    UserTeam.belongsTo(models.User, {foreignKey: 'UserId', sourceKey: 'id'})\n  }\n  return UserTeam;\n};\n```\n\n```text\nconst ModelDiscriminators = {\n  Dish: 1,\n  Item: 2,\n  ItemWithEmail: 3\n}\n\n//Basic field attributes for all entities\nconst BasicModelAttributes = { \n  id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true } \n};\n\n//Table dish have id, name, veg, discriminator attributes\nconst Dish = sequelize.define('dish', Object.assign( {}, BasicModelAttributes, {   \n  name: { type: DataTypes.STRING },\n  veg: { type: DataTypes.BOOLEAN },\n  discriminator: { type: DataTypes.INTEGER, defaultValue: () => ModelDiscriminators.Dish }\n} ) );\n\n//Two entities sharing same table. Table Item has id, name, type, discriminator e email(see model ItemWithEmail) atributes\n//Model Item\nconst Item = sequelize.define('item', Object.assign( {}, BasicModelAttributes, {   \n  name: { type: DataTypes.STRING },\n  type: { type: DataTypes.STRING },\n  discriminator: { type: DataTypes.INTEGER, defaultValue: () => ModelDiscriminators.Item }\n} ) );\n\n//Model ItemWithEmail inherits all Item attributes and define a new one: e-mail\n//We use the discriminator attribute to query the right records when we make a query or .findAll(+where)\nconst ItemWithEmail = sequelize.define('item', Object.assign({}, Item.rawAttributes, { \n  email: { type: DataTypes.STRING },\n  discriminator: { type: DataTypes.INTEGER, defaultValue: () => ModelDiscriminators.ItemWithEmail }\n} ) );\n```\n\n```text\nItemWithEmail.inherits( Item )\n```\n\n========================================\n\nComments:\n- Sweet. Thanks for the nice example. I Was wondering if this could then be subclassed. It would be a bit contrived for messages, but ex. UserMessage, SystemMessage etc. assuming that they had different functional domains.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":163,"estimatedTokens":1478}}769{"id":"stack-69053635","source":"stackoverflow","questionId":69053635,"title":"In sequelize bulkCreate timestamps are not updating","tags":["mysql","node.js","sequelize.js"],"text":"Title: In sequelize bulkCreate timestamps are not updating\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using bulkCreate and uupdate\n\n`const item = await models.Gsdatatab.bulkCreate(gsdatamodel,{updateOnDuplicate: [\"SCRIP\",\"LTP\",\"OHL\",\"ORB15\",\"ORB30\",\"PRB\",\"CAMARILLA\"]});`\n\nI see the timestamps(createdAt and updatedAt) are not getting updated in DB after the the update. Do I need to explicitly pass those two in the bulKCreate to get them updated each time there is an update or is there any option I am missing. Also the id is getting incremented while rows are getting updated. I dont want the id column to auto increment in case of update.\n\nI am using the extended model creation for defining the model\n\n========================================\n\nCode:\n```text\nconst item = await models.Gsdatatab.bulkCreate(gsdatamodel,{updateOnDuplicate: [\"SCRIP\",\"LTP\",\"OHL\",\"ORB15\",\"ORB30\",\"PRB\",\"CAMARILLA\"]});\n```\n\n```text\nlet {\n        Sequelize,\n        DataTypes,\n    } = require('sequelize')\n\nasync function run () {\n    let sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASSWORD, {\n            host:       'localhost',\n            dialect:    'mysql',\n            logging:    console.log\n        })\n\n    let Item = sequelize.define('item', {\n            name: DataTypes.STRING,\n            age: DataTypes.INTEGER\n        }, {\n            tableName: 'items',\n            schema: 'agw_queries'\n        })\n\n    await sequelize.sync({ force: true })\n\n    let wait = sec => new Promise( res => setTimeout(res, sec * 1000));\n\n    let items = await Item.bulkCreate([{ name: 'mickey', age: 32 }, { name: 'minnie', age: 30 }])\n    console.log()\n    console.log('These values are returned upon creation.')\n    console.log()\n    console.log(JSON.stringify(items, null, 2))\n\n    console.log()\n    console.log('These values are returned after a subsequent query.')\n    console.log()\n    let r = await Item.findAll({})\n    console.log(JSON.stringify(r, null, 2))\n\n    console.log()\n    console.log('Waiting two seconds ...')\n    console.log()\n    await wait(2)\n\n    console.log('These values are returned after an update.')\n    console.log()\n    items = await Item.bulkCreate(\n            [\n                { id: 1, name: 'mickey mouse', age: 33 },\n                { id: 2, name: 'minnie mouse', age: 31 },\n                { name: 'goofy', age: 37 }\n            ],\n            { updateOnDuplicate: [ 'name', 'updatedAt' ] })\n    console.log(JSON.stringify(items, null, 2))\n\n    console.log()\n    console.log('These values are returned after another subsequent query.')\n    console.log()\n    r = await Item.findAll({})\n    console.log(JSON.stringify(r, null, 2))\n\n    console.log()\n    console.log('Waiting two seconds ...')\n    console.log()\n    await wait(2)\n\n    console.log('These values are returned after an update.')\n    console.log()\n    items = await Item.bulkCreate(\n            [\n                { id: 1, name: 'mickey t. mouse', age: 33 },\n                { id: 2, name: 'minerva mouse', age: 31 },\n                { name: 'donald duck', age: 32 }\n            ],\n            { updateOnDuplicate: [ 'name', 'updatedAt' ] })\n    console.log(JSON.stringify(items, null, 2))\n\n    console.log()\n    console.log('These values are returned after another subsequent query.')\n    console.log()\n    r = await Item.findAll({})\n    console.log(JSON.stringify(r, null, 2))\n\n    await sequelize.close()\n}\n\nrun()\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS `items`;\nExecuting (default): DROP TABLE IF EXISTS `items`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `items` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255), `age` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `items`\nExecuting (default): INSERT INTO `items` (`id`,`name`,`age`,`createdAt`,`updatedAt`) VALUES (NULL,'mickey',32,'2021-09-06 12:17:44','2021-09-06 12:17:44'),(NULL,'minnie',30,'2021-09-06 12:17:44','2021-09-06 12:17:44');\n\nThese values are returned upon creation.\n\n[\n  {\n    \"id\": 1,\n    \"name\": \"mickey\",\n    \"age\": 32,\n    \"createdAt\": \"2021-09-06T12:17:44.042Z\",\n    \"updatedAt\": \"2021-09-06T12:17:44.042Z\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"minnie\",\n    \"age\": 30,\n    \"createdAt\": \"2021-09-06T12:17:44.042Z\",\n    \"updatedAt\": \"2021-09-06T12:17:44.042Z\"\n  }\n]\n\nThese values are returned after a subsequent query.\n\nExecuting (default): SELECT `id`, `name`, `age`, `createdAt`, `updatedAt` FROM `items` AS `item`;\n[\n  {\n    \"id\": 1,\n    \"name\": \"mickey\",\n    \"age\": 32,\n    \"createdAt\": \"2021-09-06T12:17:44.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:44.000Z\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"minnie\",\n    \"age\": 30,\n    \"createdAt\": \"2021-09-06T12:17:44.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:44.000Z\"\n  }\n]\n\nWaiting two seconds ...\n\nThese values are returned after an update.\n\nExecuting (default): INSERT INTO `items` (`id`,`name`,`age`,`createdAt`,`updatedAt`) VALUES (1,'mickey mouse',33,'2021-09-06 12:17:46','2021-09-06 12:17:46'),(2,'minnie mouse',31,'2021-09-06 12:17:46','2021-09-06 12:17:46'),(NULL,'goofy',37,'2021-09-06 12:17:46','2021-09-06 12:17:46') ON DUPLICATE KEY UPDATE `name`=VALUES(`name`),`updatedAt`=VALUES(`updatedAt`);\n[\n  {\n    \"id\": 1,\n    \"name\": \"mickey mouse\",\n    \"age\": 33,\n    \"createdAt\": \"2021-09-06T12:17:46.174Z\",\n    \"updatedAt\": \"2021-09-06T12:17:46.174Z\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"minnie mouse\",\n    \"age\": 31,\n    \"createdAt\": \"2021-09-06T12:17:46.174Z\",\n    \"updatedAt\": \"2021-09-06T12:17:46.174Z\"\n  },\n  {\n    \"id\": 5,\n    \"name\": \"goofy\",\n    \"age\": 37,\n    \"createdAt\": \"2021-09-06T12:17:46.174Z\",\n    \"updatedAt\": \"2021-09-06T12:17:46.174Z\"\n  }\n]\n\nThese values are returned after another subsequent query.\n\nExecuting (default): SELECT `id`, `name`, `age`, `createdAt`, `updatedAt` FROM `items` AS `item`;\n[\n  {\n    \"id\": 1,\n    \"name\": \"mickey mouse\",\n    \"age\": 32,\n    \"createdAt\": \"2021-09-06T12:17:44.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:46.000Z\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"minnie mouse\",\n    \"age\": 30,\n    \"createdAt\": \"2021-09-06T12:17:44.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:46.000Z\"\n  },\n  {\n    \"id\": 3,\n    \"name\": \"goofy\",\n    \"age\": 37,\n    \"createdAt\": \"2021-09-06T12:17:46.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:46.000Z\"\n  }\n]\n\nWaiting two seconds ...\n\nThese values are returned after an update.\n\nExecuting (default): INSERT INTO `items` (`id`,`name`,`age`,`createdAt`,`updatedAt`) VALUES (1,'mickey t. mouse',33,'2021-09-06 12:17:48','2021-09-06 12:17:48'),(2,'minerva mouse',31,'2021-09-06 12:17:48','2021-09-06 12:17:48'),(NULL,'donald duck',32,'2021-09-06 12:17:48','2021-09-06 12:17:48') ON DUPLICATE KEY UPDATE `name`=VALUES(`name`),`updatedAt`=VALUES(`updatedAt`);\n[\n  {\n    \"id\": 1,\n    \"name\": \"mickey t. mouse\",\n    \"age\": 33,\n    \"createdAt\": \"2021-09-06T12:17:48.258Z\",\n    \"updatedAt\": \"2021-09-06T12:17:48.258Z\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"minerva mouse\",\n    \"age\": 31,\n    \"createdAt\": \"2021-09-06T12:17:48.258Z\",\n    \"updatedAt\": \"2021-09-06T12:17:48.258Z\"\n  },\n  {\n    \"id\": 8,\n    \"name\": \"donald duck\",\n    \"age\": 32,\n    \"createdAt\": \"2021-09-06T12:17:48.258Z\",\n    \"updatedAt\": \"2021-09-06T12:17:48.258Z\"\n  }\n]\n\nThese values are returned after another subsequent query.\n\nExecuting (default): SELECT `id`, `name`, `age`, `createdAt`, `updatedAt` FROM `items` AS `item`;\n[\n  {\n    \"id\": 1,\n    \"name\": \"mickey t. mouse\",\n    \"age\": 32,\n    \"createdAt\": \"2021-09-06T12:17:44.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:48.000Z\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"minerva mouse\",\n    \"age\": 30,\n    \"createdAt\": \"2021-09-06T12:17:44.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:48.000Z\"\n  },\n  {\n    \"id\": 3,\n    \"name\": \"goofy\",\n    \"age\": 37,\n    \"createdAt\": \"2021-09-06T12:17:46.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:46.000Z\"\n  },\n  {\n    \"id\": 6,\n    \"name\": \"donald duck\",\n    \"age\": 32,\n    \"createdAt\": \"2021-09-06T12:17:48.000Z\",\n    \"updatedAt\": \"2021-09-06T12:17:48.000Z\"\n  }\n]\n```\n\n```text\n.bulkCreate\n```\n\n```text\nbulkUpdate\n```\n\n```text\nupdatedAt\n```\n\n```text\nupdateOnDuplicate\n```\n\n```text\nbulkCreate\n```\n\n```text\nsequelize\n```\n\n========================================\n\nComments:\n- Thanks Andrew for the detailed example. Sequelize seems to be increasing the id field by one every time its doing an update. I think instead sequelize handle the id field I will take care of the id field by getting the record count and increment in case there are new record and keep it as it is when there is an update to any row\n- @SibaSwain You're right Siba, I don't know how I missed that. I've updated my answer to include what you've observed about the primary keys. To be honest, I don't really have a good solution. I put a couple of ideas into the answer, though. Hope this helps.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":302,"estimatedTokens":2214}}770{"id":"stack-36122896","source":"stackoverflow","questionId":36122896,"title":"Sequelize is not updated when I added new column in table","tags":["node.js","postgresql","express","sequelize.js"],"text":"Title: Sequelize is not updated when I added new column in table\nTags: node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI cannot convince why my sequelize models is not updated when I add new column in table.\n\nI've added new column 'status INTEGER' in my table and updated as in Models of my table in sequelize. When I retrieve value from my table, it coming nothing.\n\nhttps://i.sstatic.net/kkLdx.png\n\n```\n},\n status: {\n type: DataTypes.INTEGER,\n default: 0\n }\n```\n\nPlease help me how to solve that issue. And even I've run migration as .\n\n```\nmodule.exports = {\n up: function (migration, DataTypes, done) {\n\n function addDisabledColumn() {\n return migration.addColumn('applications', 'status',\n {\n type: DataTypes.INTEGER,\n default: 0\n }\n )\n }\n\n addDisabledColumn().then(function () {\n done();\n }, function (err) {\n done(err);\n });\n\n },\n down: function (migration, DataTypes, done) {\n done()\n }\n};\n```\n\n========================================\n\nTop Answer:\nWhen I retrieve value from my table, it coming nothing.\n\nThe same thing happened to me. I created a migration that added a column to a table. When I would use `.findAll`, `.findOne`, `findAllAndCount`, etc. the column wouldn't be present.\n\nYou can get the new column in two ways:\n\nAdd the new column to the model definition. This is needed not only to get the new column with `.find` queries but to also be able to save the column when calling `.create`. If that doesn't work:\n\nUse `attributes` and explicitly define the new column to be retrieved:\n\n```\nconst employee = await Employee.findOne({\n where: { id: id },\n attributes: ['id', 'name', 'NEW_COLUMN'],\n });\n```\n\nIf you're going to query the table in several places, it's best to create an alias with the fields you want to query and use it everywhere you run find queries:\n\n```\nconst Employee = sequelize.define('employee', {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n }, \n // DONT FORGET TO ADD THE NEW COLUMN TO YOUR MODEL\n NEW_COLUMN: {\n type: DataTypes.STRING,\n allowNull: true,\n }\n // ...\n });\n\n Employee.basicAttributes = (alias = 'employee') => [\n 'id', \n 'name',\n 'NEW_COLUMN',\n // ...\n ];\n\n const employee = await Employee.findOne({\n where: { id: id },\n attributes: Employee.basicAttributes(),\n });\n```\n\nIt's not ideal, but it works, and it doesn't require to run `sequalize.sync({force:true})`.\n\n========================================\n\nCode:\n```text\n},\n            status: {\n                type: DataTypes.INTEGER,\n                default: 0\n            }\n```\n\n```text\nmodule.exports = {\n    up: function (migration, DataTypes, done) {\n\n        function addDisabledColumn() {\n            return migration.addColumn('applications', 'status',\n                {\n                    type: DataTypes.INTEGER,\n                    default: 0\n                }\n            )\n        }\n\n        addDisabledColumn().then(function () {\n            done();\n        }, function (err) {\n            done(err);\n        });\n\n    },\n    down: function (migration, DataTypes, done) {\n        done()\n    }\n};\n```\n\n```text\nsequalize.sync({force:true})\n```\n\n```text\nconst employee = await Employee.findOne({\n     where: { id: id },\n     attributes: ['id', 'name', 'NEW_COLUMN'],\n });\n```\n\n```text\nconst Employee = sequelize.define('employee', {\n     id: {\n         type: DataTypes.INTEGER,\n         primaryKey: true,\n         autoIncrement: true\n     }, \n     // DONT FORGET TO ADD THE NEW COLUMN TO YOUR MODEL\n     NEW_COLUMN: {\n         type: DataTypes.STRING,\n         allowNull: true,\n     }\n     // ...\n });\n\n Employee.basicAttributes = (alias = 'employee') => [\n     'id', \n     'name',\n     'NEW_COLUMN',\n     // ...\n ];\n\n const employee = await Employee.findOne({\n     where: { id: id },\n     attributes: Employee.basicAttributes(),\n });\n```\n\n```text\n.findAll\n```\n\n```text\n.findOne\n```\n\n```text\nfindAllAndCount\n```\n\n```text\n.find\n```\n\n```text\n.create\n```\n\n```text\nattributes\n```\n\n```text\nsequalize.sync({force:true})\n```\n\n```text\npublic async sync\n```\n\n```text\nalter\n```\n\n```text\ndrop\n```\n\n```text\nsequalize.sync({alter:true, drop: false})\n```\n\n========================================\n\nComments:\n- where do I need to put 'sequalize.sync({force:true})' and when do I need to run that script?\n- when you first created your tables you must have synced the database. show me your code, then i will tell you. you can also see in the documentation here under 'Your first model' sequelize.readthedocs.org/en/latest/docs/getting-started\n- if you are using migrations you should run migrations for changes to take effect read this post should clear your doubts sequelize.readthedocs.org/en/latest/docs/migrations and i recomend you read sequalize documentation\n- Yap, I've read that documentation. Even migration is run, new column is added in my table but 'Sequelize' does not recognise that new column even it's in table.\n- WARNING: This deletes every record in the table\n- I am in same problem @ppshein\n- Try other name than \"status\", thats a tricky name for sequelize to deal with.\n- I am facing the same issue.\n- On the updated API reference it says: \"options.alter\tAlters tables to fit models. Provide an object for additional configuration. Not recommended for production use. If not further configured deletes data in columns that were removed or had their type changed in the model.\"","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":231,"estimatedTokens":1340}}771{"id":"stack-36402704","source":"stackoverflow","questionId":36402704,"title":"ExpressJs with sequelize","tags":["express","sequelize.js"],"text":"Title: ExpressJs with sequelize\nTags: express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have successfully integrated **Sequelize** ORM with Express Js but i am having troble to migrate db in sequelize. Any help?\n\n```\nvar express = require('express');\nvar Sequelize = require('sequelize');\nvar bodyParser = require('body-parser');\nvar app = express();\n\napp.use(bodyParser.urlencoded({extended: false}));\napp.use(bodyParser.json());\n\nvar router = express.Router();\nvar sequelize = new Sequelize('tousif', 'root', 'root', {\n host: 'localhost',\n dialect: 'mysql'\n});\n```\n\n========================================\n\nTop Answer:\nHave you loaded your model and synced the database? Your code doesn't really show me the rest of your configuration just the connection string.\n\nI suggest after installing sequelize-cli that your use\n\n`$ sequelize help:model:create`\n\nIt will tell you how to create a model.\n\nYou'll have to import the model files, associate methods, sync those models with the database. \n\n```\n// Expose the connection function\n db.connect = function(database, username, password, options) {\n if (typeof db.logger === 'function')\n console.log(\"Connecting to: \" + database + \" as: \" + username);\n\n // Instantiate a new sequelize instance\n var sequelize = new db.Sequelize(database, username, password, options);\n\n db.discover.forEach(function(location) {\n var model = sequelize[\"import\"](location);\n if (model)\n db.models[model.name] = model;\n });\n\n // Execute the associate methods for each Model\n Object.keys(db.models).forEach(function(modelName) {\n if (db.models[modelName].options.hasOwnProperty('associate')) {\n db.models[modelName].options.associate(db.models);\n winston.info(\"Associating Model: \" + modelName);\n }\n });\n\n if (config.db.sync) {\n // Synchronizing any model changes with database.\n sequelize.sync(\n //{ force: true } // use to drop before create\n ).then(function() {\n console.log(\"Database synchronized\");\n }).catch(function(err) {\n console.log(err);\n });\n }\n}\n```\n\n========================================\n\nCode:\n```text\nvar express = require('express');\nvar Sequelize = require('sequelize');\nvar bodyParser =  require('body-parser');\nvar app = express();\n\napp.use(bodyParser.urlencoded({extended: false}));\napp.use(bodyParser.json());\n\nvar router = express.Router();\nvar sequelize = new Sequelize('tousif', 'root', 'root', {\n  host: 'localhost',\n  dialect: 'mysql'\n});\n```\n\n```text\nnpm install --save sequelize-cli\n```\n\n```text\n$ sequelize help:init\n$ sequelize help:db:migrate\n$ sequelize help:db:migrate:undo\n```\n\n```text\n// Expose the connection function\n  db.connect = function(database, username, password, options) {\n  if (typeof db.logger === 'function')\n    console.log(\"Connecting to: \" + database + \" as: \" + username);\n\n  // Instantiate a new sequelize instance\n  var sequelize = new db.Sequelize(database, username, password, options);\n\n  db.discover.forEach(function(location) {\n    var model = sequelize[\"import\"](location);\n    if (model)\n      db.models[model.name] = model;\n  });\n\n  // Execute the associate methods for each Model\n  Object.keys(db.models).forEach(function(modelName) {\n    if (db.models[modelName].options.hasOwnProperty('associate')) {\n      db.models[modelName].options.associate(db.models);\n      winston.info(\"Associating Model: \" + modelName);\n    }\n  });\n\n  if (config.db.sync) {\n    // Synchronizing any model changes with database.\n    sequelize.sync(\n      //{ force: true } // use to drop before create\n      ).then(function() {\n        console.log(\"Database synchronized\");\n      }).catch(function(err) {\n        console.log(err);\n      });\n  }\n}\n```\n\n```text\n$ sequelize help:model:create\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":140,"estimatedTokens":918}}772{"id":"stack-70504747","source":"stackoverflow","questionId":70504747,"title":"How to use postgres pgcrypto with Nodejs and Sequelize?","tags":["node.js","postgresql","encryption","sequelize.js","pgcrypto"],"text":"Title: How to use postgres pgcrypto with Nodejs and Sequelize?\nTags: node.js, postgresql, encryption, sequelize.js, pgcrypto\nSource: Stack Overflow\n\nQuestion:\n- How to use sequelize with pgcrypto plugin in postgres.\n\n- How to encrypt and decrypt the values of a column using sequelize\n\n- How to use PGP_SYM_ENCRYPT and PGP_SYM_DECRYPT using nodejs and sequelize\n\n========================================\n\nTop Answer:\nI don't have enough reputation to comment on the accepted answer so posting here to help those who might try it and give up because of something quite small.\n\n***The accepted answer has a typo that will keep the solution from working.***\n\n**Step 4** should have \"*attributes*\" instead of \"*attribute*\"\n\n```\nsequelize.findAll({\n attributes: [\n [\n sequelize.fn(\n 'PGP_SYM_DECRYPT',\n sequelize.cast(sequelize.col('column_name'), 'bytea'), \n 'secret_key'\n ), \n \"column_name\"\n ]\n ]\n}).then(data => console.log(data))\n```\n\n========================================\n\nCode:\n```sql\nselect * from pg_available_extensions\n```\n\n```sql\nselect * from pg_extension\n```\n\n```sql\ncreate extension pgcrypto\n```\n\n```js\nquery: sequelize.fn(\"PGP_SYM_ENCRYPT\", \"data_to_encrypt\", \"secret_key\")\n```\n\n```sql\nselect PGP_SYM_DECRYPT(colum_name::bytea, 'secret_key') FROM table where PGP_SYM_DECRYPT(column_name::bytea, 'secret_key' LIKE '%search_string%';\n```\n\n```js\nsequelize.findAll({\n  attributes: [\n    [\n      sequelize.fn(\n        'PGP_SYM_DECRYPT',\n        sequelize.cast(sequelize.col('column_name'), 'bytea'), \n        'secret_key'\n      ), \n      \"column_name\"\n    ]\n  ]\n}).then(data => console.log(data))\n```\n\n```sql\nCREATE EXTENSION IF NOT EXISTS pgcrypto;\n```\n\n```text\npgcrypto\n```\n\n```text\npgadmin\n```\n\n```text\nQuery Tool\n```\n\n```text\npgcrypto\n```\n\n```text\npgcrypto\n```\n\n```text\npgcrypto\n```\n\n```text\npgcrypto\n```\n\n```text\npgcrypto\n```\n\n```text\npgcrypto\n```\n\n```text\nsequelize\n```\n\n```text\ncreate\n```\n\n```text\nPGP_SYM_ENCRYPT\n```\n\n```text\npgcrypto\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize.findAll({\n  attributes: [\n    [\n      sequelize.fn(\n        'PGP_SYM_DECRYPT',\n        sequelize.cast(sequelize.col('column_name'), 'bytea'), \n        'secret_key'\n      ), \n      \"column_name\"\n    ]\n  ]\n}).then(data => console.log(data))\n```\n\n========================================\n\nComments:\n- Do you have an example with findOne and a where clause where you need to send the encrypted field to search for it in the database?\n- Thanks for pointing out this typo! I made an edit to that answer which includes this fix. For future reference, you can also suggest edits to posts to fix things like typos, grammar, formatting issues, etc by clicking the \"Edit\" button under a post","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":153,"estimatedTokens":670}}773{"id":"stack-33663579","source":"stackoverflow","questionId":33663579,"title":"ExpressJS + Sequelize er_bad_field_error: Unknown column in fieldlist","tags":["node.js","express","database-schema","sequelize.js"],"text":"Title: ExpressJS + Sequelize er_bad_field_error: Unknown column in fieldlist\nTags: node.js, express, database-schema, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing the following model file in conjunction with Sequelize, this code runs without error and allows me to perform an insert:\n\n```\nvar crypto = require('crypto');\n\nmodule.exports = function(sequelize, DataTypes) {\n\nvar User = sequelize.define('User', \n {\n title: DataTypes.STRING,\n name: DataTypes.STRING,\n email: DataTypes.STRING,\n username: DataTypes.STRING,\n hashedPassword: DataTypes.STRING,\n provider: DataTypes.STRING,\n salt: DataTypes.STRING, \n facebookUserId: DataTypes.INTEGER,\n twitterUserId: DataTypes.INTEGER,\n twitterKey: DataTypes.STRING,\n twitterSecret: DataTypes.STRING,\n github: DataTypes.STRING,\n openID: DataTypes.STRING\n },\n...\n)\n```\n\nHowever, when I try to manually add my own fields of interest, i.e. adding a ZIP code field as below:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\nvar User = sequelize.define('User', \n {\n title: DataTypes.STRING,\n name: DataTypes.STRING,\n email: DataTypes.STRING,\n username: DataTypes.STRING,\n hashedPassword: DataTypes.STRING,\n provider: DataTypes.STRING,\n salt: DataTypes.STRING, \n facebookUserId: DataTypes.INTEGER,\n twitterUserId: DataTypes.INTEGER,\n twitterKey: DataTypes.STRING,\n twitterSecret: DataTypes.STRING,\n github: DataTypes.STRING,\n openID: DataTypes.STRING,\n ZIP: DataTypes.INT\n },\n```\n\nthe following error propagates:\n\n```\nSequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'title' in 'field list'\n```\n\nWhy am I not allowed to add fields within the models to be able to access them from the controller?\n\n========================================\n\nTop Answer:\nAdding `sync({ force: true })` will recreate the table while deleting all entries that is if you have the db in production. You can try using the same but with an alter option `sync({ alter: true })`. It will try and update the new or remove the old values without much harm. I would try it first in dev mode before pushing to production.\n\n========================================\n\nCode:\n```text\nvar crypto = require('crypto');\n\nmodule.exports = function(sequelize, DataTypes) {\n\nvar User = sequelize.define('User', \n    {\n        title: DataTypes.STRING,\n        name: DataTypes.STRING,\n        email: DataTypes.STRING,\n        username: DataTypes.STRING,\n        hashedPassword: DataTypes.STRING,\n        provider: DataTypes.STRING,\n        salt: DataTypes.STRING, \n        facebookUserId: DataTypes.INTEGER,\n        twitterUserId: DataTypes.INTEGER,\n        twitterKey: DataTypes.STRING,\n        twitterSecret: DataTypes.STRING,\n        github: DataTypes.STRING,\n        openID: DataTypes.STRING\n    },\n...\n)\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\nvar User = sequelize.define('User', \n    {\n        title: DataTypes.STRING,\n        name: DataTypes.STRING,\n        email: DataTypes.STRING,\n        username: DataTypes.STRING,\n        hashedPassword: DataTypes.STRING,\n        provider: DataTypes.STRING,\n        salt: DataTypes.STRING, \n        facebookUserId: DataTypes.INTEGER,\n        twitterUserId: DataTypes.INTEGER,\n        twitterKey: DataTypes.STRING,\n        twitterSecret: DataTypes.STRING,\n        github: DataTypes.STRING,\n        openID: DataTypes.STRING,\n        ZIP: DataTypes.INT\n    },\n```\n\n```text\nSequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'title' in 'field list'\n```\n\n```text\nsequelize \n.sync({ force: true })\n.then(function(err) {\n    console.log('It worked!');\n  }, function (err) { \n         console.log('An error occurred while creating the table:', err);\n  });\n```\n\n```text\nsync({ force: true })\n```\n\n```text\nsync({ alter: true })\n```\n\n========================================\n\nComments:\n- Are you syncing your model with database ? , make sure u are doing it , about your ZIP field there is no datatype INT , there is INTEGER , docs.sequelizejs.com/en/latest/api/datatypes/#integer\n- The syncing of the model with database occurs after an insert, correct? Also, I changed the ZIP type to INTEGER and the exact same error was propagated\n- You have to sync your model schema , this will change your table in database , so if u could check that there is a ZIP column in your table its all ok.","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":147,"estimatedTokens":1068}}774{"id":"stack-55508289","source":"stackoverflow","questionId":55508289,"title":"Why did I get an error when running migration, I tried to change typedatas text to JSONB (PosgreesSql+sequelize)","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: Why did I get an error when running migration, I tried to change typedatas text to JSONB (PosgreesSql+sequelize)\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI got an error when I was running a migration in sequelize,\nbefore I set typedatas text and i tried to change to json I got some error...\n\n`ERROR: column \"value\" cannot be cast automatically to type jsonb`\n\nThis is the new code:\n\n```\nup: (queryInterface, Sequelize) => Promise.resolve()\n .then(async () => {\n await queryInterface.changeColumn('Action', 'value', {\n type: Sequelize.JSONB,\n allowNull: false,\n defaultValue: {},\n })\n }),\n```\n\nand this is my migration code that I want to change:\n\n```\nup: (queryInterface, Sequelize) => queryInterface.createTable('Action', {\n ....\n value: {\n type: Sequelize.TEXT,\n allowNull: false,\n defaultValue: '',\n },\n ....\n}\n```\n\nWhat's wrong?\n\n========================================\n\nTop Answer:\nthe accepted answer doesn't work for me.\n\nI use this one and it works.\n\n```\ntype: `${Sequelize.JSONB} using to_jsonb(col_name)`\n```\n\n========================================\n\nCode:\n```text\nup: (queryInterface, Sequelize) => Promise.resolve()\n    .then(async () => {\n      await queryInterface.changeColumn('Action', 'value', {\n        type: Sequelize.JSONB,\n        allowNull: false,\n        defaultValue: {},\n      })\n    }),\n```\n\n```text\nup: (queryInterface, Sequelize) => queryInterface.createTable('Action', {\n    ....\n    value: {\n      type: Sequelize.TEXT,\n      allowNull: false,\n      defaultValue: '',\n    },\n    ....\n}\n```\n\n```text\nERROR: column \"value\" cannot be cast automatically to type jsonb\n```\n\n```text\ntype: 'JSONB USING CAST (\"value\" as JSONB)'`\n```\n\n```text\ntype: `${Sequelize.JSONB} using to_jsonb(col_name)`\n```\n\n========================================\n\nComments:\n- Does the column contain valid JSON? If so, `type: `${Sequelize.JSONB} using value::jsonb`` might work (see github.com/sequelize/sequelize/issues/2471).\n- thanks , based your code i change to `${Sequelize.ARRAY(Sequelize.JSONB)} USING CAST (\"value\" as ${Sequelize.ARRAY(Sequelize.JSONB)}` its work\n- This is the one that worked for us. Though the data doesn't get transformed to jsonb. Do you know how to do that?","metadata":{"transformedAt":"2026-08-18T18:33:34.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":94,"estimatedTokens":561}}775{"id":"stack-29019676","source":"stackoverflow","questionId":29019676,"title":"Sequelize multiple databases on different servers","tags":["angularjs","node.js","express","orm","sequelize.js"],"text":"Title: Sequelize multiple databases on different servers\nTags: angularjs, node.js, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Node, Express, Angular and Sequelize for database ORM. Everything is working great so far, but I just got a requirement to add an additional datasource to the sequelize/node backend.\n\nHow would I go about setting up two different databases (db1 on one server and db2 on a different one) in Sequelize and using them side by side?\n\nIs this even supported, do I need to write up something of my own for it? I have looked around everywhere, but cannot find any mention of doing something like this.\n\nThanks in advance for any help.\n\n========================================\n\nCode:\n```text\nvar db1sequelize = new Sequelize('db1', 'db1user', 'db1pass'...);\n\ndb1sequelize.define('User', {...})\ndb1sequelize.define('Group', {...})\n\nvar db2sequelize = new Sequelize('db2', 'db2user', 'db2pass'...);\n\ndb2sequelize.define('Order', {...})\n\nUser.findAll(...)  // queries db1\nOrder.findAll(...) // queries db2\n```\n\n```text\nUser.hasMany(Group);\n```\n\n```text\ndb2sequelize.define('Order', {\n  userId: Sequelize.INTEGER,\n  ...\n})\n\nUser.create({...}).then(function(createdUser) {      // inserts in db1\n  return Order.create({userId: createdUser.id, ...}) // inserts in db2\n});\n```\n\n========================================\n\nComments:\n- When you say two different databases, do you mean completely different databases with separate schemas, or just two instances of the same schema (possibly replicated?)\n- I'm not sure how invested you are in Sequelize, but the **sails.js** ORM supports cross-datasource joins, even if they are different types (e.g. you can join MongoDB against PostgreSQL) or whatever.\n- Thanks man, the way you did it works. I actually ended up creating two different folders of models for two different databases because i wanted to keep keep collecting all models and associating them if need be without having to worry about importing each new model every time i need to use it. Associations do not work, but for the project i'm working on they don't really need to so it's all good. Thanks again\n- How to do this, if you have the same models in each of the databases?","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":557}}776{"id":"stack-33884744","source":"stackoverflow","questionId":33884744,"title":"return last inserted id sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: return last inserted id sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow could I send the last inserted id when creating a new entry in sequlize?\n\nCurrently this is the model way of creating a new value:\n\n```\nfunction post( request, response ) {\n\n models.xxx.create( {\n\n field1: request.body.field1,\n field2: request.body.field2\n\n } )\n .then( function ( x ) {\n\n //x = 0 || 1;\n response.json( x );\n //What I would like to send is the `id` of the new row\n\n } );\n\n}\n```\n\nIs that possible with sequelize, or do I have to query the table?\n\n========================================\n\nTop Answer:\nI am using MSSQL dialect and the return result is a row of new created data. Access object key \"id\" will show you the last increment id used.\n\n```\n.then( function ( x ) {\n\n //x = new created row\n response.json( x.id );\n\n} );\n```\n\n========================================\n\nCode:\n```text\nfunction post( request, response ) {\n\n    models.xxx.create( {\n\n            field1: request.body.field1,\n            field2: request.body.field2\n\n        } )\n        .then( function ( x ) {\n\n            //x = 0 || 1;\n            response.json( x );\n            //What I would like to send is the `id` of the new row\n\n        } );\n\n}\n```\n\n```text\n.then( function ( x ) {\n\n    //x = new created row\n    response.json( x );\n\n} );\n```\n\n```text\n[1]\n```\n\n```text\n.then( function ( x ) {\n\n    //x = new created row\n    response.json( x.id );\n\n} );\n```\n\n========================================\n\nComments:\n- x should be your newly created row so it has the id no ? x.getId()\n- I don't know why, but when I was testing i just saw a `[1]` logged, now i see the full object, thanks\n- So when you used `create`, it returned the autoincremented primary key on the table? Sequelize keeps returning `'0'` for all my inserts.\n- Did you add `autoIncrement: true` to your id attribute\n- you can also use `.then (anything => {sequelize.query('SELECT LAST_INSERT_ID() AS lastId', {type: Sequelize.QueryTypes.SELECT}) .then(id => {res.json({id: id[0].lastId}) })`\n- I edited the github answer, now you have a standard res.json() to understand how. `router.post(\"&#47;link\", (req, res) => { const rowData = { autoincrementId: req.body.id, name: req.body.name } yourModel.create(rowData) .then(row => { sequelize.query('SELECT @@IDENTITY', {type: Sequelize.QueryTypes.SELECT}) .then(id => console.log(id); res.json({id: id[0]['@@IDENTITY'] }) })); ...`\n- Works for MySQL as well.","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":100,"estimatedTokens":618}}777{"id":"stack-71044842","source":"stackoverflow","questionId":71044842,"title":"How to structure seqeulize migration files for many-to-many association","tags":["sequelize.js","sequelize-cli"],"text":"Title: How to structure seqeulize migration files for many-to-many association\nTags: sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nWhat do you have to put in your migration files (and model files) to create a M:N association in sequelize? I suspect I specifically mean, what `references` need to be set, and what do the required keys in those objects mean, but I'm not 100% sure that's what I mean.\n\nI'm trying to create a usersrolls association, similar to what was asked here.\n\nInitially, I added `references` to my `user` and `roll` migration files. Then I realised that the `userrolls` join table migration file probably needed `references` the other direction as well. I suspect I'm nearing every possible combination of settings, but somehow still haven't gotten this to work :)\n\nThe associations from my model files:\n\n**role.js**\n\n```\nstatic associate(models) {\n models.Role.belongsToMany(models.User, {\n through: models.UserRole\n })\n}\n```\n\n**user.js**\n\n```\nstatic associate(models) {\n models.User.belongsToMany(models.Role, {\n through: models.UserRole\n })\n}\n```\n\n**userrole.js**\n\n```\nstatic associate(models) {\n UserRole.belongsTo(models.User, { foreignKey: 'id' });\n UserRole.belongsTo(models.Role, { foreignKey: 'id' }); \n // UserRole.belongsTo(models.User, { foreignKey: 'userId' }); // ***** Here, and below, commented out lines are various things I've tried, though they probably don't account for all attempts.\n\nMy migration files:\n\n**create-user**\n\n```\n'use strict';\nmodule.exports = {\n async up(queryInterface, Sequelize) {\n await queryInterface.createTable('Users', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER,\n /*\n references: {\n model: 'UserRoles',\n key: 'id',\n as: 'userId'\n }\n */\n references: {\n model: 'UserRoles',\n key: 'userId'\n }\n }, \n username: {\n type: Sequelize.STRING\n },\n ...\n });\n },\n async down(queryInterface, Sequelize) {\n await queryInterface.dropTable('Users');\n }\n};\n```\n\nThe `create-role.js` file is congruent to the above.\n\n**create-user-role.js**\n\n```\n'use strict';\nmodule.exports = {\n async up(queryInterface, Sequelize) {\n await queryInterface.createTable('UserRoles', {\n /*\n userId: {\n // allowNull: false,\n primaryKey: true,\n type: Sequelize.INTEGER,\n references: {\n model: 'Users',\n key: 'id'\n }\n },\n */\n userId: {\n // allowNull: false,\n primaryKey: true,\n type: Sequelize.INTEGER,\n references: {\n model: 'Users',\n key: 'id',\n as: 'userId'\n }\n },\n /*\n roleId: {\n // allowNull: false,\n primaryKey: true,\n type: Sequelize.INTEGER,\n references: {\n model: 'Roles',\n key: 'id'\n }\n },\n */\n roleId: {\n // allowNull: false,\n primaryKey: true,\n type: Sequelize.INTEGER,\n references: {\n model: 'Roles',\n key: 'id',\n as: 'roleId'\n }\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n async down(queryInterface, Sequelize) {\n await queryInterface.dropTable('UserRoles');\n }\n};\n```\n\nI had/have this working, using the standard, documented method where you use `sequelize.define` and rely on `sync` to create the tables, but it seems I can't find the right incantation to get it to work with the `seqeulize-cli` migration method that autoloads all the models. To my (rather untrained) eye, the tables that are generated look right:\n\n```\nsqlite> .schema\nCREATE TABLE `Users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT REFERENCES `UserRoles` (`userId`), `username` VARCHAR(255), `email` VARCHAR(255), `password` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nCREATE TABLE `Roles` (`id` INTEGER PRIMARY KEY AUTOINCREMENT REFERENCES `UserRoles` (`roleId`), `name` VARCHAR(255), `createdAt` DATETIME, `updatedAt` DATETIME NOT NULL);\nCREATE TABLE `UserRoles` (`userId` INTEGER NOT NULL REFERENCES `Users` (`id`), `roleId` INTEGER NOT NULL REFERENCES `Roles` (`id`), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`userId`, `roleId`));\n```\n\nAt least that last entry looks analogous to the PostgreSQL example they give in the docs, but they don't seem to provide examples of the main tables.\n\nBut, no matter what I do, if I go to insert a user, it complains about a foreign key mismatch:\n\n```\nExecuting (default): INSERT INTO `Users` (`id`,`username`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4,$5);\nSQLITE_ERROR: foreign key mismatch - \"Users\" referencing \"UserRoles\"\n```\n\nI'd take a simple \"change this in your code\" answer, but, as I mentioned in the beginning, I suspect this is a fundamental misunderstand of what needs to be set and why, so ... some explanation of what I'm supposed to be doing would be greatly appreciated.\n\n========================================\n\nCode:\n```text\nstatic associate(models) {\n  models.Role.belongsToMany(models.User, {\n    through: models.UserRole\n  })\n}\n```\n\n```text\nstatic associate(models) {\n  models.User.belongsToMany(models.Role, {\n    through: models.UserRole\n  })\n}\n```\n\n```text\nstatic associate(models) {\n  UserRole.belongsTo(models.User, { foreignKey: 'id' });\n  UserRole.belongsTo(models.Role, { foreignKey: 'id' }); \n  // UserRole.belongsTo(models.User, { foreignKey: 'userId' }); // <- *\n  // UserRole.belongsTo(models.Role, { foreignKey: 'roleId' });\n}\n```\n\n```text\n'use strict';\nmodule.exports = {\n  async up(queryInterface, Sequelize) {\n    await queryInterface.createTable('Users', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n        /*\n        references: {\n          model: 'UserRoles',\n          key: 'id',\n          as: 'userId'\n        }\n        */\n        references: {\n          model: 'UserRoles',\n          key: 'userId'\n        }\n      },  \n      username: {\n        type: Sequelize.STRING\n      },\n      ...\n    });\n  },\n  async down(queryInterface, Sequelize) {\n    await queryInterface.dropTable('Users');\n  }\n};\n```\n\n```text\n'use strict';\nmodule.exports = {\n  async up(queryInterface, Sequelize) {\n    await queryInterface.createTable('UserRoles', {\n      /*\n      userId: {\n        // allowNull: false,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'Users',\n          key: 'id'\n        }\n      },\n      */\n      userId: {\n        // allowNull: false,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'Users',\n          key: 'id',\n          as: 'userId'\n        }\n      },\n      /*\n      roleId: {\n        // allowNull: false,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'Roles',\n          key: 'id'\n        }\n      },\n      */\n      roleId: {\n        // allowNull: false,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'Roles',\n          key: 'id',\n          as: 'roleId'\n        }\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  async down(queryInterface, Sequelize) {\n    await queryInterface.dropTable('UserRoles');\n  }\n};\n```\n\n```text\nsqlite> .schema\nCREATE TABLE `Users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT REFERENCES `UserRoles` (`userId`), `username` VARCHAR(255), `email` VARCHAR(255), `password` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nCREATE TABLE `Roles` (`id` INTEGER PRIMARY KEY AUTOINCREMENT REFERENCES `UserRoles` (`roleId`), `name` VARCHAR(255), `createdAt` DATETIME, `updatedAt` DATETIME NOT NULL);\nCREATE TABLE `UserRoles` (`userId` INTEGER NOT NULL REFERENCES `Users` (`id`), `roleId` INTEGER NOT NULL REFERENCES `Roles` (`id`), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`userId`, `roleId`));\n```\n\n```text\nExecuting (default): INSERT INTO `Users` (`id`,`username`,`email`,`password`,`createdAt`,`updatedAt`) VALUES (NULL,$1,$2,$3,$4,$5);\nSQLITE_ERROR: foreign key mismatch - \"Users\" referencing \"UserRoles\"\n```\n\n```text\nreferences\n```\n\n```text\nreferences\n```\n\n```text\nuser\n```\n\n```text\nroll\n```\n\n```text\nuserrolls\n```\n\n```text\nreferences\n```\n\n```text\ncreate-role.js\n```\n\n```text\nsequelize.define\n```\n\n```text\nsync\n```\n\n```text\nseqeulize-cli\n```\n\n```js\nmodels.Role.belongsToMany(models.User, {\n    through: models.UserRole,\n    foreignKey: 'roleId',\n    otherKey: 'userId'\n  })\n```\n\n```js\nmodels.User.belongsToMany(models.Role, {\n    through: models.UserRole,\n    foreignKey: 'userId',\n    otherKey: 'roleId'\n  })\n```\n\n```js\nstatic associate(models) {\n  UserRole.belongsTo(models.User, { foreignKey: 'userId' });\n  UserRole.belongsTo(models.Role, { foreignKey: 'roleId' });\n}\n```\n\n```js\n'use strict';\nmodule.exports = {\n  async up(queryInterface, Sequelize) {\n    await queryInterface.createTable('Users', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n      },  \n      username: {\n        type: Sequelize.STRING\n      },\n      ...\n    });\n  },\n  async down(queryInterface, Sequelize) {\n    await queryInterface.dropTable('Users');\n  }\n};\n```\n\n```js\n'use strict';\nmodule.exports = {\n  async up(queryInterface, Sequelize) {\n    await queryInterface.createTable('UserRoles', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n      },  \n      userId: {\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'Users',\n          key: 'id'\n        }\n      },\n      roleId: {\n        type: Sequelize.INTEGER,\n        references: {\n          model: 'Roles',\n          key: 'id'\n        }\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE\n      }\n    });\n  },\n  async down(queryInterface, Sequelize) {\n    await queryInterface.dropTable('UserRoles');\n  }\n};\n```\n\n```text\nUser\n```\n\n```text\nRole\n```\n\n```text\nUserRole\n```\n\n```text\nreferences\n```\n\n```text\nUserRole\n```\n\n```text\nUser\n```\n\n```text\nRole\n```\n\n```text\nbelongsToMany\n```\n\n```text\nbelongsTo\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- OK, I think I get it. And this all seems to work. But, it also seems to work if I leave out the `id` field from **create-user-role**, and use the compound key, as they seem to suggest in the docs. Why do you recommend the separate primary key as a single column?\n- AFAIK Sequelize does not support composite keys in associations so it's better to use a surrogate primary key column. If you need to add uniqueness for a pair `userid`-`roleId` you can add a unique index.","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":32,"totalLines":475,"estimatedTokens":2680}}778{"id":"stack-56903706","source":"stackoverflow","questionId":56903706,"title":"How to set application name in sequelize connection object?","tags":["node.js","sequelize.js","tedious"],"text":"Title: How to set application name in sequelize connection object?\nTags: node.js, sequelize.js, tedious\nSource: Stack Overflow\n\nQuestion:\n**Summary:**\n\nI want to change the `application name` of the `connection string` when initialize a new sequalize object. based on this stackoverflow question, I set the appName of dialectOptions as follows:\n\n```\nlet conn = new Sequelize(this.models.sequelize.config.database, this.models.sequelize.config.username,\n this.models.sequelize.config.password, {\n host: this.models.sequelize.config.host,\n dialect: this.models.sequelize.getDialect(),\n dialectOptions: {\n appName: \"userid=-2@gid=\" + gid\n }\n });\n```\n\n**Question:**\n\nWhen I execute a transaction like the following code, the `application name` does not pass to the SQL server. When I monitor the execution of SQL queries, the following picture shows that `Tedious` was sent to the application name.\n\ntransaction code:\n\n```\nawait conn.transaction(async t => {\n for(let i in this.collect){\n let queryBuilder = this.collect[i];\n let options = {replacements: queryBuilder.replacement, transaction: t};\n if(queryBuilder.type === 'insert'){\n options.type = conn.QueryTypes.INSERT;\n }\n let row = await conn.query(queryBuilder.query + ';select @@IDENTITY as id', options);\n progressBar.update(parseInt(i) + 1);\n }\n```\n\nand the SQL Profiler picture is:\n\nhttps://i.sstatic.net/bWvU6.png\n\nHow can I set the `Application Name` properly?\n\n========================================\n\nTop Answer:\nOn PostgreSQL, you need to set the property `application_name` in the `dialectOptions` object like that:\n\n```\nlet conn = new Sequelize(this.models.sequelize.config.database, this.models.sequelize.config.username,\n this.models.sequelize.config.password, {\n host: this.models.sequelize.config.host,\n dialect: \"postgres\",\n dialectOptions: {\n application_name: \"yourApp\"\n }\n });\n```\n\n========================================\n\nCode:\n```text\nlet conn = new Sequelize(this.models.sequelize.config.database, this.models.sequelize.config.username,\n                this.models.sequelize.config.password, {\n                host: this.models.sequelize.config.host,\n                dialect: this.models.sequelize.getDialect(),\n                dialectOptions: {\n                    appName: \"userid=-2@gid=\" + gid\n                }\n            });\n```\n\n```text\nawait conn.transaction(async t => {\n                for(let i in this.collect){\n                    let queryBuilder = this.collect[i];\n                    let options = {replacements: queryBuilder.replacement, transaction: t};\n                    if(queryBuilder.type === 'insert'){\n                        options.type = conn.QueryTypes.INSERT;\n                    }\n                    let row = await conn.query(queryBuilder.query + ';select @@IDENTITY as id', options);\n                    progressBar.update(parseInt(i) + 1);\n                }\n```\n\n```text\napplication name\n```\n\n```text\nconnection string\n```\n\n```text\napplication name\n```\n\n```text\nTedious\n```\n\n```text\nApplication Name\n```\n\n```text\nlet conn = new Sequelize(this.models.sequelize.config.database, this.models.sequelize.config.username,\n            this.models.sequelize.config.password, {\n            host: this.models.sequelize.config.host,\n            dialect: this.models.sequelize.getDialect(),\n            dialectOptions: {\n               options: {\n                  appName: \"userid=-2@gid=\" + gid\n               }\n            }\n        });\n```\n\n```text\nlet conn = new Sequelize(this.models.sequelize.config.database, this.models.sequelize.config.username,\n            this.models.sequelize.config.password, {\n            host: this.models.sequelize.config.host,\n            dialect: \"postgres\",\n            dialectOptions: {\n               application_name: \"yourApp\"\n            }\n        });\n```\n\n```text\napplication_name\n```\n\n```text\ndialectOptions\n```\n\n========================================\n\nComments:\n- It's been awhile since I used Sequelize, but can you use a hard coded value for your dialect such as 'mssql' instead of what you have `dialect: this.models.sequelize.getDialect()` So you would have `dialect: 'mssql'` or use postgres, mysql or whatever your dialect is?\n- It is still the same. the `application name` is still Tedious.","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":145,"estimatedTokens":1062}}779{"id":"stack-53386132","source":"stackoverflow","questionId":53386132,"title":"Hooks not triggering when inserting raw queries via sequelize.query()","tags":["mysql","node.js","sequelize.js"],"text":"Title: Hooks not triggering when inserting raw queries via sequelize.query()\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following `Employee` model for a MySQL database:\n\n```\nvar bcrypt = require('bcrypt');\n\nmodule.exports = (sequelize, DataTypes) => {\n const Employee = sequelize.define(\n \"Employee\",\n {\n username: DataTypes.STRING,\n password: DataTypes.STRING,\n }, {}\n );\n return Employee;\n};\n```\n\nSeeding the database is done by reading a `.sql` file containing 10,000+ employees via raw queries:\n\n`sequelize.query(mySeedingSqlFileHere);`\n\nThe problem is that the passwords in the SQL file are plain text and I'd like to use `bcrypt` to hash them before inserting into the database. I've never done bulk inserts before so I was looking into Sequelize docs for adding a hook to the `Employee` model, like so:\n\n```\nhooks: {\n beforeBulkCreate: (employees, options) => {\n for (employee in employees) {\n if (employee.password) {\n employee.password = await bcrypt.hash(employee.password, 10);\n }\n }\n }\n}\n```\n\nThis isn't working as I'm still getting the plain text values after reseeding - should I be looking into another way? I was looking into sequelize capitalize name before saving in database - instance hook\n\n========================================\n\nCode:\n```text\nvar bcrypt = require('bcrypt');\n\nmodule.exports = (sequelize, DataTypes) => {\n    const Employee = sequelize.define(\n        \"Employee\",\n        {\n            username: DataTypes.STRING,\n            password: DataTypes.STRING,\n        }, {}\n    );\n    return Employee;\n};\n```\n\n```text\nhooks: {\n  beforeBulkCreate: (employees, options) => {\n    for (employee in employees) {\n      if (employee.password) {\n        employee.password = await bcrypt.hash(employee.password, 10);\n      }\n     }\n  }\n}\n```\n\n```text\nEmployee\n```\n\n```text\n.sql\n```\n\n```text\nsequelize.query(mySeedingSqlFileHere);\n```\n\n```text\nbcrypt\n```\n\n```text\nEmployee\n```\n\n```text\nModel.create();\nModel.bulkCreate();\nModel.update();\nModel.destroy;\n```\n\n========================================\n\nComments:\n- Upvoted but what are the workarounds for this ? Let's say sequelize cannot perform what I want through model (i.e. non raw) sql queries (for example : an upsert operation, github.com/sequelize/sequelize/issues/11656) , there's no way to use an afterSave hook after a raw query that does this ? That seems restrictive. :( Let's say I have complex code being re-used through hooks across all our projects, I don't want to duplicate this code elsewhere and not use hooks. :(\n- Perhaps specifying the queryType (sequelize.org/api/v6/class/src/&hellip;) would help in ensuring those hooks are working properly.","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":104,"estimatedTokens":670}}780{"id":"stack-69051499","source":"stackoverflow","questionId":69051499,"title":"TypeScript - Repository pattern with Sequelize","tags":["node.js","typescript","sequelize.js","typescript-generics","sequelize-typescript"],"text":"Title: TypeScript - Repository pattern with Sequelize\nTags: node.js, typescript, sequelize.js, typescript-generics, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI'm converting my Express API Template to TypeScript and I'm having some issues with the repositories.\n\nWith JavaScript, I would do something like this:\n\n```\nexport default class BaseRepository {\n async all() {\n return this.model.findAll();\n }\n\n // other common methods\n}\n```\n\n```\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository {\n constructor() {\n super();\n this.model = User;\n }\n\n async findByEmail(email) {\n return this.model.findOne({\n where: {\n email,\n },\n });\n }\n\n // other methods\n```\n\nNow, with TypeScript, the problem is that it doesn't know the type of `this.model`, and I can't pass a concrete model to `BaseRepository`, because, well, it is an abstraction. I've found that `sequelize-typescript` exports a `ModelCtor` which declares all the static model methods like findAll, create, etc., and I also could use another `sequelize-typescript` export which is `Model` to properly annotate the return type.\n\nSo, I ended up doing this:\n\n```\nimport { Model, ModelCtor } from 'sequelize-typescript';\n\nexport default abstract class BaseRepository {\n protected model: ModelCtor;\n\n constructor(model: ModelCtor) {\n this.model = model;\n }\n\n public async all(): Promise {\n return this.model.findAll();\n }\n\n // other common methods\n}\n```\n\n```\nimport { Model } from 'sequelize-typescript';\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository {\n constructor() {\n super(User);\n }\n\n public async findByEmail(email: string): Promise {\n return this.model.findOne({\n where: {\n email,\n },\n });\n }\n\n // other methods\n}\n```\n\nOk, this works, TypeScript doesn't complain about methods like `findOne` or `create` not existing, but that generates another problem.\n\nNow, for example, whenever I get a `User` from the repository, if I try to access one of its properties, like `user.email`, TypeScript will complain that this property does not exist. Of course, because the type `Model` does not know about the specifics of each model.\n\nOk, it's treason generics then.\n\nNow `BaseRepository` uses a generic `Model` type which the methods also use:\n\n```\nexport default abstract class BaseRepository {\n public async all(): Promise {\n return Model.findAll();\n }\n\n // other common methods\n}\n```\n\nAnd the concrete classes pass the appropriate model to the generic type:\n\n```\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository {\n public async findByEmail(email: string): Promise {\n return User.findOne({\n where: {\n email,\n },\n });\n }\n\n // other methods\n}\n```\n\nNow IntelliSense lights up correctly, it shows both abstract and concrete classes methods and the model properties (e.g. `user.email`).\n\nBut, as you have imagined, that leads to more problems.\n\nInside `BaseRepository`, where the methods use the `Model` generic type, TypeScript complains that `'Model' only refers to a type, but is being used as a value here`. Not only that, but TypeScript also doesn't know (again) that the static methods from the model exist, like `findAll`, `create`, etc.\n\nAnother problem is that in both abstract and concrete classes, as the methods don't use `this` anymore, ESLint expects the methods to be static: `Expected 'this' to be used by class async method 'all'`. Ok, I can just ignore this rule in the whole file and the error is gone. It would be even nicer to have all the methods set to static, so I don't have to instantiate the repository, but maybe I'm dreaming too much.\n\nWorth mentioning that although I can just silence those errors with `// @ts-ignore`, when I execute this, it doesn't work: `TypeError: Cannot read property 'create' of undefined\\n at UserRepository.`\n\nI researched a lot, tried to make all methods static, but static methods can't reference the generic type (because it is considered an instance property), tried some workarounds, tried to pass the concrete model in the constructor of `BaseRepository` along with the class using the generic type, but nothing seems to work so far.\n\nIn case you want to check the code: https://github.com/andresilva-cc/express-api-template/tree/main/src/App/Repositories\n\nEDIT:\n\nFound this: Sequelize-Typescript typeof model\n\nOk, I removed some unnecessary code from that post and that kinda works:\n\n```\nimport { Model } from 'sequelize-typescript';\n\nexport default abstract class BaseRepository {\n constructor(protected model: typeof Model) {}\n\n public async all(attributes?: string[]): Promise {\n // Type 'Model[]' is not assignable to type 'M[]'.\n // Type 'Model' is not assignable to type 'M'.\n // 'Model' is assignable to the constraint of type 'M', but 'M' could be instantiated with a different subtype of constraint 'Model'.\n return this.model.findAll({\n attributes,\n });\n }\n```\n\n```\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository {\n constructor() {\n super(User);\n }\n}\n```\n\nI mean, if I put some `// @ts-ignore` it at least executes, and IntelliSense lights up perfectly, but TypeScript complains.\n\n========================================\n\nCode:\n```js\nexport default class BaseRepository {\n  async all() {\n    return this.model.findAll();\n  }\n\n  // other common methods\n}\n```\n\n```js\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository {\n  constructor() {\n    super();\n    this.model = User;\n  }\n\n  async findByEmail(email) {\n    return this.model.findOne({\n      where: {\n        email,\n      },\n    });\n  }\n\n  // other methods\n```\n\n```js\nimport { Model, ModelCtor } from 'sequelize-typescript';\n\nexport default abstract class BaseRepository {\n  protected model: ModelCtor;\n\n  constructor(model: ModelCtor) {\n    this.model = model;\n  }\n\n  public async all(): Promise<Model[]> {\n    return this.model.findAll();\n  }\n\n  // other common methods\n}\n```\n\n```js\nimport { Model } from 'sequelize-typescript';\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository {\n  constructor() {\n    super(User);\n  }\n\n  public async findByEmail(email: string): Promise<Model | null> {\n    return this.model.findOne({\n      where: {\n        email,\n      },\n    });\n  }\n\n  // other methods\n}\n```\n\n```js\nexport default abstract class BaseRepository<Model> {\n  public async all(): Promise<Model[]> {\n    return Model.findAll();\n  }\n\n  // other common methods\n}\n```\n\n```js\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository<User> {\n  public async findByEmail(email: string): Promise<User | null> {\n    return User.findOne({\n      where: {\n        email,\n      },\n    });\n  }\n\n  // other methods\n}\n```\n\n```js\nimport { Model } from 'sequelize-typescript';\n\nexport default abstract class BaseRepository<M extends Model> {\n  constructor(protected model: typeof Model) {}\n\n  public async all(attributes?: string[]): Promise<M[]> {\n    // Type 'Model<{}, {}>[]' is not assignable to type 'M[]'.\n    // Type 'Model<{}, {}>' is not assignable to type 'M'.\n    // 'Model<{}, {}>' is assignable to the constraint of type 'M', but 'M' could be instantiated with a different subtype of constraint 'Model<any, any>'.\n    return this.model.findAll({\n      attributes,\n    });\n  }\n```\n\n```js\nimport BaseRepository from './BaseRepository';\nimport { User } from '../Models';\n\nexport default class UserRepository extends BaseRepository<User> {\n  constructor() {\n    super(User);\n  }\n}\n```\n\n```text\nthis.model\n```\n\n```text\nBaseRepository\n```\n\n```text\nsequelize-typescript\n```\n\n```text\nModelCtor\n```\n\n```text\nsequelize-typescript\n```\n\n```text\nModel\n```\n\n```text\nfindOne\n```\n\n```text\ncreate\n```\n\n```text\nUser\n```\n\n```text\nuser.email\n```\n\n```text\nModel\n```\n\n```text\nBaseRepository\n```\n\n```text\nModel\n```\n\n```text\nuser.email\n```\n\n```text\nBaseRepository\n```\n\n```text\nModel\n```\n\n```text\n'Model' only refers to a type, but is being used as a value here\n```\n\n```text\nfindAll\n```\n\n```text\ncreate\n```\n\n```text\nthis\n```\n\n```text\nExpected 'this' to be used by class async method 'all'\n```\n\n```text\n// @ts-ignore\n```\n\n```text\nTypeError: Cannot read property 'create' of undefined\\n    at UserRepository.<anonymous>\n```\n\n```text\nBaseRepository\n```\n\n```text\n// @ts-ignore\n```\n\n```js\nexport type RepoResult<M> = Promise<Result<M | undefined, RepoError | undefined>>;\n    \nexport interface IRepo<M> {\n  save(model: M): RepoResult<M>;\n  findById(id: string): RepoResult<M>;\n  search(parameterName: string, parameterValue: string, sortBy: string, order: number, pageSize: number, pageNumber: number): RepoResult<M[]>;\n  getAll(): RepoResult<M[]>;\n  deleteById(id: string): RepoResult<M>;\n  findByIds(ids: string[]): RepoResult<M[]>;\n  deleteByIds(ids: string[]): RepoResult<any>;\n};\n```\n\n```js\nexport abstract class Repo<M extends sequelize.Model> implements IRepo<M> {\n  protected Model!: sequelize.ModelCtor<M>;\n  constructor(Model: sequelize.ModelCtor<M>) {\n    this.Model = Model;\n  }\n\n  public async save(doc: M) {\n    try {\n      const savedDoc = await doc.save();\n      return Result.ok(savedDoc);\n    } catch (ex: any) {\n      logger.error(ex);\n      return Result.fail(new RepoError(ex.message, 500));\n    }\n  }\n\n  public async findById(id: string) {\n    try {\n      const doc = await this.Model.findOne({\n        where: {\n          id: id\n        }\n      });\n      if (!doc) {\n        return Result.fail(new RepoError('Not found', 404));\n      }\n\n      return Result.ok(doc);\n    } catch (ex: any) {\n      return Result.fail(new RepoError(ex.message, 500));\n    }\n  }\n}\n```\n\n```js\nexport class Result<V, E> {\n  public isSuccess: boolean;\n  public isFailure: boolean;\n  private error: E;\n  private value: V;\n\n  private constructor(isSuccess: boolean, value: V, error: E) {\n    if (isSuccess && error) {\n      throw new Error('Successful result must not contain an error');\n    } else if (!isSuccess && value) {\n      throw new Error('Unsuccessful error must not contain a value');\n    }\n\n    this.isSuccess = isSuccess;\n    this.isFailure = !isSuccess;\n    this.value = value;\n    this.error = error;\n  }\n\n  public static ok<V>(value: V): Result<V, undefined> {\n    return new Result(true, value, undefined);\n  }\n\n  public static fail<E>(error: E): Result<undefined, E> {\n    return new Result(false, undefined, error);\n  }\n\n  public getError(): E {\n    if (this.isSuccess) {\n      throw new Error('Successful result does not contain an error');\n    }\n\n    return this.error;\n  }\n\n  public getValue(): V {\n    if (this.isFailure) {\n      throw new Error('Unsuccessful result does not contain a value');\n    }\n\n    return this.value;\n  }\n}\n\ntype RepoErrorCode = 404 | 500;\n\nexport class RepoError extends Error {\n  public code: RepoErrorCode;\n  constructor(message: string, code: RepoErrorCode) {\n    super(message);\n    this.code = code;\n  }\n}\n```\n\n```text\nexport type RepoResult<M> = Promise<Result<M | undefined, RepoError | undefined>>;\n```\n\n========================================\n\nComments:\n- what is repoError and result here? Could you please add those imports in interface?\n- Done! Glad if it helps:)","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":37,"totalLines":513,"estimatedTokens":2875}}781{"id":"stack-51275802","source":"stackoverflow","questionId":51275802,"title":"Sequelize bulk update with inner join","tags":["postgresql","sequelize.js"],"text":"Title: Sequelize bulk update with inner join\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am currently working with Sequelize and can not figure out how to update bulk when im associating two tables together. I have the :\n\nTables:\n\n```\nmembers\n user_id\n channel_id\n all\n\nactivities\n user_id\n channel_id\n```\n\nI am trying to update `members.all` when the user_ids match, `members.channel_id` is 2 and `activities.channel_id` is not 2. \n\nHere is working Postgresql:\n\n```\nUPDATE members AS m \n SET \"all\" = true \n FROM activities AS a \n WHERE m.user_id = a.user_id \n AND m.channel_id = 2 \n AND a.current_channel != 2;\n```\n\nIs this possible to do is sequelize? How do include `a.current_channel != 2` into my current update?\n\n```\nMember.update(\n { all: true },\n { where: { channel_id: channelId } },\n)\n```\n\nWhen I try to add an include it does not work.\n\n========================================\n\nTop Answer:\nGenerally, i use this hack\n\n```\nmodels.findAll({\n where: {\n // which models to update\n }\n}).then(targets => {\n models.target.update({\n // your updates\n},{\n where : {\n target_primary_key: targets.map(t => t.primary_key)\n }\n})\n\n})\n```\n\n========================================\n\nCode:\n```text\nmembers\n   user_id\n   channel_id\n   all\n\nactivities\n   user_id\n   channel_id\n```\n\n```text\nUPDATE members AS m \n   SET    \"all\" = true \n   FROM   activities AS a \n   WHERE  m.user_id = a.user_id \n      AND m.channel_id = 2 \n      AND a.current_channel != 2;\n```\n\n```text\nMember.update(\n        { all: true },\n        { where: { channel_id: channelId } },\n)\n```\n\n```text\nmembers.all\n```\n\n```text\nmembers.channel_id\n```\n\n```text\nactivities.channel_id\n```\n\n```text\na.current_channel != 2\n```\n\n```text\nsequelize.query(\"UPDATE members AS m SET \"all\" = true FROM activities AS a WHERE m.user_id = a.user_id AND m.channel_id = 2 AND a.current_channel != 2\").spread((results, metadata) => {\n  // Results will be an empty array and metadata will contain the number of affected rows.\n});\n```\n\n```text\nupdate\n```\n\n```text\nfindAll\n```\n\n```text\nupdate\n```\n\n```text\nmodels.findAll({\n where: {\n // which models to update\n }\n}).then(targets => {\n models.target.update({\n // your updates\n},{\n where : {\n  target_primary_key: targets.map(t => t.primary_key)\n }\n})\n\n})\n```\n\n```text\nconst foundMembers = await Member.findAll({\n  include: {\n    model: Activity,\n    where: { channel_id: { [Op.not]: 2 } }\n    attributes: []\n  },\n  where: { channel_id: 2 }\n  attributes: ['id']\n});\n\nconst foundMemberIds = foundMembers.map(m=>m.id);\n\nawait Member.update(\n  { all: true }, \n  { where: { id: { [Op.in]: foundMemberIds } }\n);\n```\n\n========================================\n\nComments:\n- Feature request: github.com/sequelize/sequelize/issues/3957\n- Thank you. That is currently how I have it but was wondering if there was a way with sequelize and I missed it in the docs. Guess not\n- you can optimize this further by adding the attributes option and only select the primary key attribute in query 1.\n- Does this scale well? Would the bulk update be better in that aspect?\n- @user081608 its not infinitely scalable, the primary keys array is loaded into memory.\n- this is not bulk update. Question is about bulk update.","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":175,"estimatedTokens":802}}782{"id":"stack-60784618","source":"stackoverflow","questionId":60784618,"title":"Sequelize ORDER BY","tags":["node.js","sequelize.js"],"text":"Title: Sequelize ORDER BY\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHello I want to query a company and list all the users ordered by name\nThis is what I have. Relationship works fine is just the ordering that´s not working.\nI don´t see the ORDER BY name when I debug the generated query.\n\n```\nconst user = {\n model: models.User,\n as: \"Users\",\n order: [[\"name\", \"asc\"]]\n};\n\nconst options = {\n where: { id: 1 },\n include: [user]\n};\n\nmodels.Company.findOne(options)\n .then(company => console.log(company))\n .catch(error => console.log(error.message));\n```\n\n========================================\n\nCode:\n```text\nconst user = {\n    model: models.User,\n    as: \"Users\",\n    order: [[\"name\", \"asc\"]]\n};\n\nconst options = {\n    where: { id: 1 },\n    include: [user]\n};\n\nmodels.Company.findOne(options)\n    .then(company => console.log(company))\n    .catch(error => console.log(error.message));\n```\n\n```text\n/**\n   * Order include. Only available when setting `separate` to true.\n   */\n  order?: Order;\n```\n\n```js\nimport { sequelize } from '../../db';\nimport { Model, DataTypes } from 'sequelize';\n\nclass Company extends Model {}\nCompany.init({}, { sequelize, modelName: 'companies' });\n\nclass User extends Model {}\nUser.init(\n  {\n    name: DataTypes.STRING,\n  },\n  { sequelize, modelName: 'users' },\n);\n\nCompany.hasMany(User, { as: 'Users' });\n\n(async function test() {\n  try {\n    await sequelize.sync({ force: true });\n    // seed\n    await Company.create(\n      { Users: [{ name: 'tim' }, { name: 'elsa' }, { name: 'james' }] },\n      { include: [{ model: User, as: 'Users' }] },\n    );\n    // test\n    const company = await Company.findOne({\n      where: { id: 1 },\n      include: [\n        {\n          model: User,\n          as: 'Users',\n          separate: true,\n          order: [['name', 'asc']],\n        },\n      ],\n    });\n    console.log(company.Users);\n  } catch (error) {\n    console.log(error);\n  } finally {\n    await sequelize.close();\n  }\n})();\n```\n\n```sh\nExecuting (default): SELECT \"companies\".\"id\" FROM \"companies\" AS \"companies\" WHERE \"companies\".\"id\" = 1;\nExecuting (default): SELECT \"id\", \"name\", \"companyId\" FROM \"users\" AS \"users\" WHERE \"users\".\"companyId\" IN (1) ORDER BY \"users\".\"name\" ASC;\n[ users {\n    dataValues: { id: 2, name: 'elsa', companyId: 1 },\n    _previousDataValues: { id: 2, name: 'elsa', companyId: 1 },\n    _changed: {},\n    _modelOptions:\n     { timestamps: false,\n       validate: {},\n       freezeTableName: true,\n       underscored: false,\n       paranoid: false,\n       rejectOnEmpty: false,\n       whereCollection: [Object],\n       schema: null,\n       schemaDelimiter: '',\n       defaultScope: {},\n       scopes: {},\n       indexes: [],\n       name: [Object],\n       omitNull: false,\n       sequelize: [Sequelize],\n       hooks: {} },\n    _options:\n     { isNewRecord: false,\n       _schema: null,\n       _schemaDelimiter: '',\n       include: undefined,\n       includeNames: undefined,\n       includeMap: undefined,\n       includeValidated: true,\n       raw: true,\n       attributes: undefined },\n    isNewRecord: false },\n  users {\n    dataValues: { id: 3, name: 'james', companyId: 1 },\n    _previousDataValues: { id: 3, name: 'james', companyId: 1 },\n    _changed: {},\n    _modelOptions:\n     { timestamps: false,\n       validate: {},\n       freezeTableName: true,\n       underscored: false,\n       paranoid: false,\n       rejectOnEmpty: false,\n       whereCollection: [Object],\n       schema: null,\n       schemaDelimiter: '',\n       defaultScope: {},\n       scopes: {},\n       indexes: [],\n       name: [Object],\n       omitNull: false,\n       sequelize: [Sequelize],\n       hooks: {} },\n    _options:\n     { isNewRecord: false,\n       _schema: null,\n       _schemaDelimiter: '',\n       include: undefined,\n       includeNames: undefined,\n       includeMap: undefined,\n       includeValidated: true,\n       raw: true,\n       attributes: undefined },\n    isNewRecord: false },\n  users {\n    dataValues: { id: 1, name: 'tim', companyId: 1 },\n    _previousDataValues: { id: 1, name: 'tim', companyId: 1 },\n    _changed: {},\n    _modelOptions:\n     { timestamps: false,\n       validate: {},\n       freezeTableName: true,\n       underscored: false,\n       paranoid: false,\n       rejectOnEmpty: false,\n       whereCollection: [Object],\n       schema: null,\n       schemaDelimiter: '',\n       defaultScope: {},\n       scopes: {},\n       indexes: [],\n       name: [Object],\n       omitNull: false,\n       sequelize: [Sequelize],\n       hooks: {} },\n    _options:\n     { isNewRecord: false,\n       _schema: null,\n       _schemaDelimiter: '',\n       include: undefined,\n       includeNames: undefined,\n       includeMap: undefined,\n       includeValidated: true,\n       raw: true,\n       attributes: undefined },\n    isNewRecord: false } ]\n```\n\n```sh\nnode-sequelize-examples=# select * from \"users\";\n id | name  | companyId\n----+-------+-----------\n  1 | tim   |         1\n  2 | elsa  |         1\n  3 | james |         1\n(3 rows)\n\nnode-sequelize-examples=# select * from \"companies\";\n id\n----\n  1\n(1 row)\n```\n\n```text\nIncludeOptions.order\n```\n\n```text\nseparate\n```\n\n```text\nCompany\n```\n\n```text\nUser\n```\n\n```text\n\"sequelize\": \"^5.21.3\"\n```\n\n========================================\n\nComments:\n- Does this generate the expected query?\n- It's also time to investigate if `async`/`await` is something you can be using here to eliminate the old `then` dance.\n- @tadman nope. I don&#180;t see the ORDER BY name ASC in the generated query. also what&#180;s the problem with then? that&#180;s not causing any issues I believe","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":242,"estimatedTokens":1395}}783{"id":"stack-56571134","source":"stackoverflow","questionId":56571134,"title":"Sequelize - map fields to field alias in model definition","tags":["javascript","node.js","model","sequelize.js"],"text":"Title: Sequelize - map fields to field alias in model definition\nTags: javascript, node.js, model, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am defining a Sequelize model to map fields from existing tables in my database. However, the field names in the table are long and not developer-friendly. \n\nIs it possible to map the database field names to aliases in the model definition so that my service has more developer-friendly model property names to work with?\n\n**Example:**\n\nThis...\n\n```\n// Horrible field names\nmodule.exports = (sequelize, DataTypes) =>\n sequelize.define('Transaction', {\n f_curr_finaccount__amount: DataTypes.DECIMAL,\n f_curr_finaccount__tx_type: DataTypes.STRING,\n f_finaccount__currency_iso_id: DataTypes.STRING,\n f_lex_finaccount__tx_atomic_status: DataTypes.STRING\n }, {\n schema: 'fins',\n tableName: 'fins_financialaccounttransaction',\n timestamps: false\n })\n```\n\n...becomes...\n\n```\n// Developer-friendly field names\nmodule.exports = (sequelize, DataTypes) =>\n sequelize.define('Transaction', {\n amount: {\n type: DataTypes.DECIMAL,\n fieldName: 'f_curr_finaccount__amount'\n },\n type: {\n type: DataTypes.STRING,\n fieldName: 'f_curr_finaccount__tx_type'\n },\n currency: {\n type: DataTypes.STRING,\n fieldName: 'f_finaccount__currency_iso_id'\n },\n status: {\n type: DataTypes.STRING,\n fieldName: 'f_lex_finaccount__tx_atomic_status'\n }\n }, {\n schema: 'fins',\n tableName: 'fins_financialaccounttransaction',\n timestamps: false\n })\n```\n\n========================================\n\nCode:\n```text\n// Horrible field names\nmodule.exports = (sequelize, DataTypes) =>\n  sequelize.define('Transaction', {\n    f_curr_finaccount__amount: DataTypes.DECIMAL,\n    f_curr_finaccount__tx_type: DataTypes.STRING,\n    f_finaccount__currency_iso_id: DataTypes.STRING,\n    f_lex_finaccount__tx_atomic_status: DataTypes.STRING\n  }, {\n    schema: 'fins',\n    tableName: 'fins_financialaccounttransaction',\n    timestamps: false\n  })\n```\n\n```text\n// Developer-friendly field names\nmodule.exports = (sequelize, DataTypes) =>\n  sequelize.define('Transaction', {\n    amount: {\n      type: DataTypes.DECIMAL,\n      fieldName: 'f_curr_finaccount__amount'\n    },\n    type: {\n      type: DataTypes.STRING,\n      fieldName: 'f_curr_finaccount__tx_type'\n    },\n    currency: {\n      type: DataTypes.STRING,\n      fieldName: 'f_finaccount__currency_iso_id'\n    },\n    status: {\n      type: DataTypes.STRING,\n      fieldName: 'f_lex_finaccount__tx_atomic_status'\n    }\n  }, {\n    schema: 'fins',\n    tableName: 'fins_financialaccounttransaction',\n    timestamps: false\n  })\n```\n\n```text\n// Developer-friendly field names\nmodule.exports = (sequelize, DataTypes) =>\n  sequelize.define('Transaction', {\n    amount: {\n      type: DataTypes.DECIMAL,\n      field: 'f_curr_finaccount__amount'\n    },\n    type: {\n      type: DataTypes.STRING,\n      field: 'f_curr_finaccount__tx_type'\n    },\n    currency: {\n      type: DataTypes.STRING,\n      field: 'f_finaccount__currency_iso_id'\n    },\n    status: {\n      type: DataTypes.STRING,\n      field: 'f_lex_finaccount__tx_atomic_status'\n    }\n  }, {\n    schema: 'fins',\n    tableName: 'fins_financialaccounttransaction',\n    timestamps: false\n  })\n```\n\n```text\nfield\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":132,"estimatedTokens":800}}784{"id":"stack-51653620","source":"stackoverflow","questionId":51653620,"title":"MariaDB connection with Sequelize","tags":["javascript","mysql","node.js","mariadb","sequelize.js"],"text":"Title: MariaDB connection with Sequelize\nTags: javascript, mysql, node.js, mariadb, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have been checking for the connectivity of MariaDB, with Sequelize.\n\n```\nconst Sequelize = require('sequelize');\n\n// Setting up database (MariaDB) connection\nconst sequelize = new Sequelize('dbName', 'usr', 'pass', {\n host: 'localhost',\n dialect: 'mariadb'\n});\n```\n\nBut I am getting the following error:\n\n```\n/home/lt-196/api/node_modules/sequelize/lib/sequelize.js:236\n throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.');\n ^\n\nError: The dialect mariadb is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.\n at new Sequelize (/home/lt-196/api/node_modules/sequelize/lib/sequelize.js:236:15)\n at Object. (/home/lt-196/api/app.js:21:19)\n at Module._compile (module.js:652:30)\n at Object.Module._extensions..js (module.js:663:10)\n at Module.load (module.js:565:32)\n at tryModuleLoad (module.js:505:12)\n at Function.Module._load (module.js:497:3)\n at Function.Module.runMain (module.js:693:10)\n at startup (bootstrap_node.js:191:16)\n at bootstrap_node.js:612:3\n```\n\n========================================\n\nTop Answer:\nhttps://github.com/MariaDB/mariadb-connector-nodejs\n\nNPM\n\n```\nnpm install --save mariadb\n npm install --save sequelize@next\n```\n\nYarn\n\n```\nyarn add mariadb\n yarn add sequelize@next\n```\n\n```\nconst Sequelize = require('sequelize'),\n sequelize = new Sequelize(process.env.db_name, process.env.db_user, process.env.db_pass, {\n dialect: 'mariadb',\n dialectOptions: {\n socketPath: process.env.db_socket,\n timezone: process.env.db_timezone\n },\n pool: {\n min: 0,\n max: 5,\n idle: 10000\n },\n define: {\n charset: 'utf8',\n timestamps: false\n },\n benchmark: false,\n logging: false\n })\n```\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\n\n// Setting up database (MariaDB) connection\nconst sequelize = new Sequelize('dbName', 'usr', 'pass', {\n  host: 'localhost',\n  dialect: 'mariadb'\n});\n```\n\n```text\n/home/lt-196/api/node_modules/sequelize/lib/sequelize.js:236\n        throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.');\n        ^\n\nError: The dialect mariadb is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.\n    at new Sequelize (/home/lt-196/api/node_modules/sequelize/lib/sequelize.js:236:15)\n    at Object.<anonymous> (/home/lt-196/api/app.js:21:19)\n    at Module._compile (module.js:652:30)\n    at Object.Module._extensions..js (module.js:663:10)\n    at Module.load (module.js:565:32)\n    at tryModuleLoad (module.js:505:12)\n    at Function.Module._load (module.js:497:3)\n    at Function.Module.runMain (module.js:693:10)\n    at startup (bootstrap_node.js:191:16)\n    at bootstrap_node.js:612:3\n```\n\n```text\nvar sequelize = new Sequelize('database', 'username', 'password', {\n  dialect: 'mariadb'\n})\n```\n\n```text\nvar Client = require('mariasql');\n\nvar c = new Client({\n  host: '127.0.0.1',\n  user: 'foo',\n  password: 'bar'\n});\n\nc.query('SHOW DATABASES', function(err, rows) {\n  if (err)\n    throw err;\n  console.dir(rows);\n});\n\nc.end();\n```\n\n```text\nnpm install --save mariadb\n    npm install --save sequelize@next\n```\n\n```text\nyarn add mariadb\n    yarn add sequelize@next\n```\n\n```text\nconst Sequelize = require('sequelize'),\n    sequelize = new Sequelize(process.env.db_name, process.env.db_user, process.env.db_pass, {\n    dialect: 'mariadb',\n    dialectOptions: {\n      socketPath: process.env.db_socket,\n      timezone: process.env.db_timezone\n    },\n    pool: {\n      min: 0,\n      max: 5,\n      idle: 10000\n    },\n    define: {\n      charset: 'utf8',\n      timestamps: false\n    },\n    benchmark: false,\n    logging: false\n  })\n```\n\n========================================\n\nComments:\n- MariaSQL is working thanks, but 1st option would be better and it is not working.\n- You can use 'mysql' as dialect.","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":170,"estimatedTokens":1001}}785{"id":"stack-38778482","source":"stackoverflow","questionId":38778482,"title":"Sequelize DataTypes TypeError: Cannot read property 'INTEGER' of undefined","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize DataTypes TypeError: Cannot read property 'INTEGER' of undefined\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a Sequelize `DataTypes.INTEGER` issue when defining a model. I'm following an example in ebook titled \"Building APIs with Node.js\". I'm a beginner trying to grasp Express and Sequelize.\n\nError details:\n\n```\n> /home/xxx/workspace/ntask-api/models/tasks.js:9\n> type: DataTypes.INTEGER,\n> ^ TypeError: Cannot read property 'INTEGER' of undefined\n> at Function.module.exports (/home/xxx/workspace/ntask-api/models/tasks.js:9:21)\n> at Consign.into (/home/xxx/workspace/ntask-api/node_modules/consign/lib/consign.js:239:17)\n> at Object. (/home/xxx/workspace/ntask-api/index.js:13:5)\n> at Module._compile (module.js:456:26)\n> at Object.Module._extensions..js (module.js:474:10)\n> at Module.load (module.js:356:32)\n> at Function.Module._load (module.js:312:12)\n> at Function.Module.runMain (module.js:497:10)\n> at startup (node.js:119:16)\n> at node.js:902:3\n```\n\nCode sample below in `/models/tasks.js`:\n\n```\n> module.exports = function(sequelize, DataTypes){\n> //console.log(DataTypes.INTEGER);\n> const Tasks = sequelize.define(\"Tasks\", { id: {\n> type: DataTypes.INTEGER,\n> primaryKey: true,\n> autoIncrement: true }, title: {\n> type: DataTypes.STRING,\n> allowNull: false,\n> validate: { notEmpty: true\n> } }, done: {\n> type: DataTypes.BOOLEAN,\n> allowNull: false,\n> defaultValue: false }\n> }, \n> { classMethods:{\n> associate: function(models){ Tasks.belongsTo(models.Users, {\n> onDelete: \"CASCADE\",\n> foreignKey: { allowNull: false\n> } }); \n> } }\n> });\n> return Tasks; };\n```\n\nI also tried the suggestion from TypeError: object is not a function when defining models in NodeJs using Sequelize by adding this to the top of models/tasks.js file but same error.\n\n```\nvar DataTypes = require('sequelize/lib/data-types');\n```\n\n========================================\n\nCode:\n```text\n> /home/xxx/workspace/ntask-api/models/tasks.js:9\n>       type: DataTypes.INTEGER,\n>                      ^ TypeError: Cannot read property 'INTEGER' of undefined\n>     at Function.module.exports (/home/xxx/workspace/ntask-api/models/tasks.js:9:21)\n>     at Consign.into (/home/xxx/workspace/ntask-api/node_modules/consign/lib/consign.js:239:17)\n>     at Object.<anonymous> (/home/xxx/workspace/ntask-api/index.js:13:5)\n>     at Module._compile (module.js:456:26)\n>     at Object.Module._extensions..js (module.js:474:10)\n>     at Module.load (module.js:356:32)\n>     at Function.Module._load (module.js:312:12)\n>     at Function.Module.runMain (module.js:497:10)\n>     at startup (node.js:119:16)\n>     at node.js:902:3\n```\n\n```text\n> module.exports = function(sequelize, DataTypes){\n>     //console.log(DataTypes.INTEGER);\n>     const Tasks = sequelize.define(\"Tasks\", {     id: {\n>       type: DataTypes.INTEGER,\n>       primaryKey: true,\n>       autoIncrement: true     },  title: {\n>       type: DataTypes.STRING,\n>       allowNull: false,\n>       validate: {         notEmpty: true\n>       }   },  done: {\n>       type: DataTypes.BOOLEAN,\n>       allowNull: false,\n>       defaultValue: false     }\n>     }, \n>     {     classMethods:{\n>       associate: function(models){        Tasks.belongsTo(models.Users, {\n>           onDelete: \"CASCADE\",\n>           foreignKey: {           allowNull: false\n>           }       }); \n>       }   }\n>     });\n>     return Tasks; };\n```\n\n```text\nvar DataTypes = require('sequelize/lib/data-types');\n```\n\n```text\nDataTypes.INTEGER\n```\n\n```text\n/models/tasks.js\n```\n\n```text\nvar Project = sequelize.define('project', {\n  title: Sequelize.STRING,\n  description: Sequelize.TEXT\n})\n\nvar Task = sequelize.define('task', {\n  title: Sequelize.STRING,\n  description: Sequelize.TEXT,\n  deadline: Sequelize.DATE\n})\n```\n\n```text\nSequelize.XXXX\n```\n\n```text\nrequire('sequelize')\n```\n\n```text\nrequire('sequelize')\n```\n\n```text\nindex\n```\n\n========================================\n\nComments:\n- Thanks @hiEven, will try it out.\n- It worked like a charm! ...just stuck with 1. but will try 2. later. Thanks again.","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":148,"estimatedTokens":1017}}786{"id":"stack-48652374","source":"stackoverflow","questionId":48652374,"title":"Add array element if it's not contained already","tags":["arrays","node.js","mongodb","postgresql","sequelize.js"],"text":"Title: Add array element if it's not contained already\nTags: arrays, node.js, mongodb, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to add integer to an array if does not exist in the array, yet. But the following creates duplicate values:\n\n```\nUser.update(\n{\n 'topics': sequelize.fn('array_append', sequelize.col('topics'), topicId),\n},\n{where: {uuid: id}})\n```\n\nIs there an equivalent function in PostgreSQL/sequelize to MongoDB $addToSet?\n\n========================================\n\nTop Answer:\nI had the same problem and this is how I solved.\n\n```\nconst user = User.findOne({where: {id}})\nUser.update({topics: (user.topics.indexOf('topicId') > -1) ? user.topics : Sequelize.fn('array_append', Sequelize.col('topics'), topicId) }, {where: {id}})\n```\n\nThough it definitely feels like there is a better way.\n\n========================================\n\nCode:\n```text\nUser.update(\n{\n    'topics': sequelize.fn('array_append', sequelize.col('topics'), topicId),\n},\n{where: {uuid: id}})\n```\n\n```sql\nUPDATE \"user\"\nSET    topics = topics || topicId\nWHERE  uuid = id\nAND    NOT (topics @> ARRAY[topicId]);\n```\n\n```sql\nCREATE OR REPLACE FUNCTION f_array_append_uniq (anyarray, anyelement)\n  RETURNS anyarray\n  LANGUAGE sql IMMUTABLE PARALLEL SAFE AS\n 'SELECT CASE WHEN array_position($1,$2) IS NULL THEN $1 || $2 ELSE $1 END;'\n```\n\n```text\n...\nSET    topics = f_array_append_uniq (topics, topicId)\n...\n```\n\n```sql\nUPDATE \"user\"\nSET    topics = topics || topicId\nWHERE  uuid = id\nAND    array_position(topics,topicId) IS NOT NULL;\n```\n\n```text\n$addToSet\n```\n\n```text\n@>\n```\n\n```text\n||\n```\n\n```text\nnull\n```\n\n```text\narray_position(topics, topicId) IS NULL\n```\n\n```text\nconst user = User.findOne({where: {id}})\nUser.update({topics: (user.topics.indexOf('topicId') > -1) ? user.topics : Sequelize.fn('array_append', Sequelize.col('topics'), topicId) }, {where: {id}})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":91,"estimatedTokens":472}}787{"id":"stack-37947290","source":"stackoverflow","questionId":37947290,"title":"Sequelize updating nested associations","tags":["node.js","sequelize.js"],"text":"Title: Sequelize updating nested associations\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an instance where I have **Users** and **Roles**. I have the following:\n\n```\nvar User = sequelize.define(\"Users\", {\n username: DataTypes.STRING,\n password: DataTypes.STRING,\n });\n\n var Role = sequelize.define(\"Role\", {\n role: DataTypes.STRING\n });\n\n var UsersRole = sequelize.define(\"UsersRole\");\n\n User.belongsToMany(Role, {through: UsersRole});\n```\n\nWhich creates a **UsersRoles** table in the DB for me with a UserId and RoleId column. This is all working fine, but now I want to be able to update a users role, I can't work out quite how to do this! I've tried the following with no luck so far:\n\n```\nmodels.Users.findAll({\n where: { id: req.params.id },\n include: [{ all: true }]\n}).then(function(dbUser){\n dbUser[0].Roles[0].updateAttributes({\n RoleId: req.body.role,\n },\n {\n where: { UserId : req.params.id }\n }\n ).then(function (result) {...\n```\n\nIn summary, all I want to do is be able to change a users role, so update the '**UsersRoles**' table and change the **RoleId** for a given **UserId**. I can't quite seem to figure out how to get to the **UsersRoles** table via any sequelize syntax!\n\nI could write some raw SQL but that doesn't feel right?\n\n**EDIT**\n\nI just want to update a users role, if the table has:\n\n| UserId | RoleId |\n-------------------\n| 1 | 1 |\n\nI would like to be able to change it to:\n\n| UserId | RoleId |\n-------------------\n| 1 | 2 |\n\nbut I can't quite figure out the code to do this!\n\n========================================\n\nTop Answer:\nyou are updating `RoleId` but you have not defined it. If you don't define a primary key on a table the by default Sequelize defines a primary key by name if `id`, so you should do `id: req.body.role`.\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define(\"Users\", {\n    username: DataTypes.STRING,\n    password: DataTypes.STRING,\n  });\n\n  var Role = sequelize.define(\"Role\", {\n    role: DataTypes.STRING\n  });\n\n  var UsersRole = sequelize.define(\"UsersRole\");\n\n  User.belongsToMany(Role, {through: UsersRole});\n```\n\n```text\nmodels.Users.findAll({\n    where: { id: req.params.id },\n    include: [{ all: true }]\n}).then(function(dbUser){\n    dbUser[0].Roles[0].updateAttributes({\n            RoleId: req.body.role,\n        },\n        {\n            where: { UserId : req.params.id }\n        }\n    ).then(function (result) {...\n```\n\n```text\n| UserId | RoleId |\n-------------------\n|    1   |    1   |\n```\n\n```text\n| UserId | RoleId |\n-------------------\n|    1   |    2   |\n```\n\n```text\nuser.setRoles([newRole]);\n```\n\n```text\nuser.addRole(newRole);\n```\n\n```text\nset\n```\n\n```text\nRoleId\n```\n\n```text\nid\n```\n\n```text\nid: req.body.role\n```\n\n========================================\n\nComments:\n- Actually 'RoleId' gets created in the table as part of the association and this is the one I do want to update, sequelize created the table for me and there is no 'id' column\n- Another way of updating the role is like this `dbUser[0].Roles[0].RoleId = req.body.role; dbUser[0].Roles[0].save();` . Also why do you need the second where condiion first where condition will take care of filtering the user.\n- Thanks for the answer, I tried this and it still isn't working, I'm concerned that I'm trying to hack this a bit and actually there is a 'sequelize' way of doing this I should be trying instead?\n- Apologies, I don't think I've explained this well enough...its not the Role I want to update, is the UserRoles table, so which user is associated to which Role.\n- A couple of side-note: If you only need one user, use `findOne` or `findById` instead. Also, no need to `include: all` if you aren't going to use them","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":139,"estimatedTokens":932}}788{"id":"stack-50381235","source":"stackoverflow","questionId":50381235,"title":"Sequelize optional relation","tags":["sql","node.js","sequelize.js"],"text":"Title: Sequelize optional relation\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to create optional relation? for ex.\n\nI have 2 tables:\n- User (id, siteId, email, ...), can have multiple users with same email\n- Wallet (id, email, ...), one Wallet per email address\n\nI want to be able find all Users by Wallet object (by its email)\nI want to be able find the Wallet by User record\n\nNot every email address has Wallet, so that means that sometimes users has Wallet, and sometimes no.\n\nWhat are the relation that I have to set on Sequelize in order to achive that goal?\n\nThanks!\n\n========================================\n\nTop Answer:\nSettings `constraints: false` works but it doesn't create the foreign key so you lose the relation between two tables.\n\nPlease see the answer below for better way of handling this requirement\nhttps://stackoverflow.com/a/68068079/5219165\n\n========================================\n\nCode:\n```text\nconstraints: false\n```\n\n```text\nconstraints: false\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":38,"estimatedTokens":254}}789{"id":"stack-47173231","source":"stackoverflow","questionId":47173231,"title":"Define Sequelize model such as all inserted entries should be in lowercase","tags":["mysql","node.js","sequelize.js"],"text":"Title: Define Sequelize model such as all inserted entries should be in lowercase\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to insert `first_name` and `last_name` in a lower case using sequelize and NodeJS.\nHow do I define a model where all entries should be in lower case?\n\n```\nconst Users = sequelize.define('users', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n },\n mobile : {\n type: Sequelize.STRING,\n }\n first_name: {\n type: Sequelize.STRING,\n\n },\n last_name :{\n type: Sequelize.STRING,\n },\n email :{\n type: Sequelize.STRING,\n }\n },\n {\n freezeTableName: true // Model tableName will be the same as the model name\n },\n {\n where: { \n $and: [\n sequelize.where(sequelize.fn('lower', sequelize.col('first_name'))),\n sequelize.where(sequelize.fn('lower', sequelize.col('last_name')))\n ]\n }\n }\n);\n```\n\n========================================\n\nCode:\n```text\nconst Users = sequelize.define('users', {\n        id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n        },\n        mobile : {\n             type: Sequelize.STRING,\n        }\n        first_name: {\n            type: Sequelize.STRING,\n\n        },\n        last_name :{\n            type: Sequelize.STRING,\n            },\n        email :{\n            type: Sequelize.STRING,\n        }\n    },\n    {\n        freezeTableName: true // Model tableName will be the same as the model name\n    },\n    {\n         where: { \n             $and: [\n                 sequelize.where(sequelize.fn('lower', sequelize.col('first_name'))),\n                  sequelize.where(sequelize.fn('lower', sequelize.col('last_name')))\n                ]\n            }\n    }\n);\n```\n\n```text\nfirst_name\n```\n\n```text\nlast_name\n```\n\n```text\nconst Users = sequelize.define('users', {\n        id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n        },\n        mobile : {\n            type: Sequelize.STRING,\n        }\n        first_name: {\n            type: Sequelize.STRING,\n\n        },\n        last_name :{\n            type: Sequelize.STRING,\n        },\n        email :{\n            type: Sequelize.STRING,\n        }\n    },\n    {\n        freezeTableName: true\n    },\n    hooks: {\n        beforeCreate: function(user){\n\n            user.first_name = user.first_name.toLowerCase();\n            user.last_name  = user.last_name.toLowerCase();\n\n            return user;\n\n        }\n    }\n\n);\n```\n\n```text\nbeforeCreate()\n```\n\n========================================\n\nComments:\n- Does your question actually have anything to do with MySQL?\n- i used sequelize for mysql database","metadata":{"transformedAt":"2026-08-18T18:33:34.402Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":133,"estimatedTokens":645}}790{"id":"stack-41968028","source":"stackoverflow","questionId":41968028,"title":"NodeJS Sequelize - Cannot read property '_isSequelizeMethod' of undefined","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: NodeJS Sequelize - Cannot read property '_isSequelizeMethod' of undefined\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a NodeJS server using Express.\nFor my database I use Sequelize, and I defined my models like on the Sequelize documentation:\n\nmodels/index.js\n\n```\n\"use strict\";\n\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize('mydb', 'root', '', {\n host: 'localhost',\n dialect: 'mysql',\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n }\n});\nvar db = {};\n\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n })\n .forEach(function(file) {\n var model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function(modelName) {\n if (\"associate\" in db[modelName]) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nmodels/server.js\n\n```\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n var Server = sequelize.define('Server', {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n unique: true,\n allowNull: false\n },\n reference: DataTypes.STRING,\n name: DataTypes.STRING\n },\n {\n timestamps: false,\n paranoid: false,\n underscored: true,\n freezeTableName: true,\n tableName: 'server'\n });\n\n return Server;\n};\n```\n\nmodels/subscriber.js\n\n```\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n var Subscriber = sequelize.define('Subscriber', {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n unique: true,\n allowNull: false\n },\n type: {\n type: DataTypes.ENUM,\n values: ['email', 'phone']\n },\n contact: DataTypes.STRING,\n server_id: DataTypes.INTEGER,\n notified: DataTypes.INTEGER,\n last_notified: DataTypes.DATE\n },\n {\n timestamps: false,\n paranoid: false,\n underscored: true,\n freezeTableName: true,\n tableName: 'subscriber',\n classMethods: {\n associate: function(models) {\n Subscriber.belongsTo(models.Server, { foreignKey: 'server_id', targetKey: 'id' });\n }\n }\n });\n\n return Subscriber;\n};\n```\n\nAnd here my route :\n\n```\nvar models = require('../models');\n\napp.get('/subscribe/:type/:contact/:ref', function(req, res) {\n var type = req.params.type;\n var contact = req.params.contact;\n var ref = req.params.ref;\n\n models.Subscriber.findAll().then(function(result) {\n console.log(result);\n });\n\n res.render('full/subscribed.twig', {\n type: type,\n contact: contact,\n server : server\n });\n });\n```\n\nAnd when I access my route I have this error message :\n\n```\nUnhandled rejection TypeError: Cannot read property '_isSequelizeMethod' of undefined\nat /Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1077:20\nat Array.map (native)\nat Object.QueryGenerator.selectQuery (/Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1067:55)\nat QueryInterface.select (/Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/query-interface.js:669:25)\nat null. (/Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/model.js:1398:32)\nat tryCatcher (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/util.js:16:23)\nat Promise._settlePromiseFromHandler (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:510:31)\nat Promise._settlePromise (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:567:18)\nat Promise._settlePromise0 (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:612:10)\nat Promise._settlePromises (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:691:18)\nat Async._drainQueue (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/async.js:133:16)\nat Async._drainQueues (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/async.js:143:10)\nat Immediate.Async.drainQueues [as _onImmediate] (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/async.js:17:14)\nat processImmediate [as _immediateCallback] (timers.js:383:17)\n```\n\nI tried to do some experiences on an independent NodeJS file and everything work fine, I just launch my standalone js file with some actions on database and everything is ok. By when I do the exact same things on my Express route I have this error...\n\nSomeone have an idea of why ?\n\nThanks in advance,\nSteve\n\n========================================\n\nTop Answer:\nWhen you import a table, it's already added to the `sequelize.models` array so you don't need to explicity added again. The sequelize docs need to be updated to the following:\n\n```\nreaddirSync(__dirname)\n.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))\n.forEach(file => {\n sequelize.import(path.join(__dirname, file))\n})\n\nObject\n.keys(sequelize.models)\n.forEach(modelName => {\n if ('associate' in sequelize.models[modelName]) {\n sequelize.models[modelName].associate(sequelize.models)\n }\n})\n```\n\n========================================\n\nCode:\n```text\n\"use strict\";\n\nvar fs        = require(\"fs\");\nvar path      = require(\"path\");\nvar Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize('mydb', 'root', '', {\n  host: 'localhost',\n  dialect: 'mysql',\n\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  }\n});\nvar db        = {};\n\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n  })\n  .forEach(function(file) {\n    var model = sequelize.import(path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(function(modelName) {\n  if (\"associate\" in db[modelName]) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n  var Server = sequelize.define('Server', {\n    id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true,\n        unique: true,\n        allowNull: false\n    },\n    reference: DataTypes.STRING,\n    name: DataTypes.STRING\n  },\n  {\n    timestamps: false,\n    paranoid: false,\n    underscored: true,\n    freezeTableName: true,\n    tableName: 'server'\n  });\n\n  return Server;\n};\n```\n\n```text\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n  var Subscriber = sequelize.define('Subscriber', {\n    id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true,\n        unique: true,\n        allowNull: false\n    },\n    type: {\n      type: DataTypes.ENUM,\n      values: ['email', 'phone']\n    },\n    contact: DataTypes.STRING,\n    server_id: DataTypes.INTEGER,\n    notified: DataTypes.INTEGER,\n    last_notified: DataTypes.DATE\n  },\n  {\n    timestamps: false,\n    paranoid: false,\n    underscored: true,\n    freezeTableName: true,\n    tableName: 'subscriber',\n    classMethods: {\n      associate: function(models) {\n        Subscriber.belongsTo(models.Server, { foreignKey: 'server_id', targetKey: 'id' });\n      }\n    }\n  });\n\n  return Subscriber;\n};\n```\n\n```text\nvar models  = require('../models');\n\napp.get('/subscribe/:type/:contact/:ref', function(req, res) {\n        var type = req.params.type;\n        var contact = req.params.contact;\n        var ref = req.params.ref;\n\n        models.Subscriber.findAll().then(function(result) {\n            console.log(result);\n        });\n\n        res.render('full/subscribed.twig', {\n            type: type,\n            contact: contact,\n            server : server\n        });\n    });\n```\n\n```text\nUnhandled rejection TypeError: Cannot read property '_isSequelizeMethod' of undefined\nat /Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1077:20\nat Array.map (native)\nat Object.QueryGenerator.selectQuery (/Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1067:55)\nat QueryInterface.select (/Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/query-interface.js:669:25)\nat null.<anonymous> (/Users/me/Projects/nodejs/myproject/node_modules/sequelize/lib/model.js:1398:32)\nat tryCatcher (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/util.js:16:23)\nat Promise._settlePromiseFromHandler (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:510:31)\nat Promise._settlePromise (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:567:18)\nat Promise._settlePromise0 (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:612:10)\nat Promise._settlePromises (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/promise.js:691:18)\nat Async._drainQueue (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/async.js:133:16)\nat Async._drainQueues (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/async.js:143:10)\nat Immediate.Async.drainQueues [as _onImmediate] (/Users/me/Projects/nodejs/myproject/node_modules/bluebird/js/release/async.js:17:14)\nat processImmediate [as _immediateCallback] (timers.js:383:17)\n```\n\n```text\nmainAttributes = mainAttributes && mainAttributes.map(function(attr) {\n```\n\n```text\n[ 'id',\n  'reference',\n  'name',\n  [ undefined, 'join' ],\n  [ undefined, 'getKeyByValue' ] ]\n```\n\n```js\nreaddirSync(__dirname)\n.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))\n.forEach(file => {\n    sequelize.import(path.join(__dirname, file))\n})\n\nObject\n.keys(sequelize.models)\n.forEach(modelName => {\n    if ('associate' in sequelize.models[modelName]) {\n        sequelize.models[modelName].associate(sequelize.models)\n    }\n})\n```\n\n```text\nsequelize.models\n```\n\n========================================\n\nComments:\n- apologies but could not understand what you are trying to communicate.. could you pls elaborate where i have to make changes to remove this error. i am facing similar issue with exact same stack trace\n- Hi Amritpal, in my code I had something like \"Object.prototype.join = function(){};\" this line was generating my error. Try to console.log node_modules/sequelize/lib/dialects/abstract/query-generator&zwnj;&#8203;.js (line 1067) the variable \"mainAttributes\", you will see.","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":374,"estimatedTokens":2587}}791{"id":"stack-45733730","source":"stackoverflow","questionId":45733730,"title":"Order by date a list with multiple dates","tags":["node.js","sql-order-by","sequelize.js"],"text":"Title: Order by date a list with multiple dates\nTags: node.js, sql-order-by, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am building a page where I display a list of events. Each of the events takes place in one or two consecutive dates. The issue is that these events should be order by these dates.\nI use Sequelize.js.\n\nFor example: \nevent1 - in 13th and 14th of July should be displayed before the event2- in 10th and 11th of July because it the most recent one.\n\nI have two tables: Events and EventDates with a one-to-many relationship.\n\n```\nEvent.findAll({ \n include: [\n { model:EventDates, order: [ [ 'date', 'DESC' ]] }, \n ],\n\n })\n```\n\nThis will only order the two dates of one event, but will not compare the dates of different events.\n\nHow can I perform the operation of order?\n\nEventDates model:\n\n```\nvar EventDates= sequelize.define('eventdates', { \n date: {\n type: Sequelize.DATE\n },\n availabletickets: {\n type: Sequelize.INTEGER\n },\n},\n{\n freezeTableName: true\n});\n```\n\nAnd the Events model:\n\n```\nvar Event = sequelize.define('event', {\n title: {\n type: Sequelize.STRING,\n },\n slug: {\n type: Sequelize.STRING\n },\n description: {\n type: Sequelize.STRING\n },\n isDeleted:{\n type: Sequelize. BOOLEAN,\n defaultValue: false\n },\n\n}\n});\n```\n\n========================================\n\nCode:\n```text\nEvent.findAll({ \n        include: [\n            { model:EventDates, order: [ [ 'date', 'DESC' ]] },                  \n        ],\n\n    })\n```\n\n```text\nvar EventDates= sequelize.define('eventdates', {    \n  date: {\n    type: Sequelize.DATE\n  },\n  availabletickets: {\n   type: Sequelize.INTEGER\n  },\n},\n{\n  freezeTableName: true\n});\n```\n\n```text\nvar Event = sequelize.define('event', {\n  title: {\n    type: Sequelize.STRING,\n  },\n  slug: {\n    type: Sequelize.STRING\n  },\n   description: {\n    type: Sequelize.STRING\n  },\n  isDeleted:{\n   type: Sequelize. BOOLEAN,\n   defaultValue: false\n  },\n\n}\n});\n```\n\n```text\nEvent.findAll({ \n        include: [\n            { model:EventDates, order: [ [ 'date', 'DESC' ]] },                  \n        ],\n        order: [[ EventDates , 'date', 'DESC']]\n\n    })\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":119,"estimatedTokens":527}}792{"id":"stack-43729063","source":"stackoverflow","questionId":43729063,"title":"Node and sequelize -> .catch(...) isn't working as expected","tags":["node.js","try-catch","sequelize.js"],"text":"Title: Node and sequelize -> .catch(...) isn't working as expected\nTags: node.js, try-catch, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got a really simple example here. In this case, 'token' is a read-only property on the model, and throws an error when you try to write it. This is just present to force an error to show how .catch(...) isn't ever being called. The very simple example code is below (name, description, uptime are all variables set to static values before we get to this code):\n\n```\nmodels.TANServer.create({\n name : name,\n description : description,\n defaultUpTime : defaultUpTime,\n token : \"apple\"\n})\n.then( function( server ){\n\n if( !server ){\n res.statusCode = 400;\n res.end( \"unknown error creating new server entry\" );\n return;\n }\n\n res.statusCode = 200;\n res.end( JSON.stringify( server ) );\n return;\n\n}).catch( function( reason ){\n res.statusCode = 500;\n res.end( \"This should print out \" + reason + \" but is never called as the error stack goes to console, and nothing ever is caught.\" );\n return;\n});\n```\n\nThe catch is never called, the http request just sits there spinning, and the console output pretty clearly displays that the exception just bubbled up without being caught. \n\nWhat am I missing about .catch(...) in Sequelize calls?\n\nThanks. \n\nThe pertinent info from the exception stack output follows. The text \"This is a read only property\" is the error message I generate and toss when you try to write to that property.\n\n```\nUnhandled rejection Error: This is a read-only property\n```\n\n========================================\n\nCode:\n```text\nmodels.TANServer.create({\n    name : name,\n    description : description,\n    defaultUpTime : defaultUpTime,\n    token : \"apple\"\n})\n.then( function( server ){\n\n    if( !server ){\n        res.statusCode = 400;\n        res.end( \"unknown error creating new server entry\" );\n        return;\n    }\n\n    res.statusCode = 200;\n    res.end( JSON.stringify( server ) );\n    return;\n\n}).catch( function( reason ){\n    res.statusCode = 500;\n    res.end( \"This should print out \" + reason + \" but is never called as the error stack goes to console, and nothing ever is caught.\" );\n    return;\n});\n```\n\n```text\nUnhandled rejection Error: This is a read-only property\n```\n\n```text\nmodels.TANServer.create({\n  name : name,\n  description : description,\n  defaultUpTime : defaultUpTime,\n  token : \"apple\"\n})\n```\n\n```text\ntry {\n  models.TANServer.create(...).then(...).catch(...);\ncatch (e) {\n  // A synchronous exception happened here\n}\n\n// Alternatively (and much better IMO):\nPromise.resolve().then(() => {\n  // Any synchronous errors here will fail the promise chain\n  // triggering the .catch\n  return models.TANServer.create(...);\n}).then(server => {\n  // Use server here\n}).catch(reason => {\n  // All errors show up here\n});\n```\n\n```text\n.catch\n```\n\n```text\n.then\n```\n\n```text\n.then\n```\n\n```text\n.catch\n```\n\n```text\n.create\n```\n\n```text\nPromise.reject\n```\n\n```text\n.create\n```\n\n```text\n.create\n```\n\n```text\ntry / catch\n```\n\n```text\nPromise.resolve\n```\n\n========================================\n\nComments:\n- There's nothing in here that looks like a write to a read-only property. Are you sure the rejection error is coming from this code?\n- Yes, in my model I'm throwing an exception on writes to that property. I didn't show the model because it's just a super simple model at the moment, and literally has a name, description, the uptime and the token properties. Token is generated in the model when a new record is generated, and lives in that record forever as a read-only value, akin to db id. Specifically, it's just a UUID. To be fair/clear, I could easily remove it and just use the record id, but that wouldn't really change the issue I'm having.\n- In short, shouldn't *ANY* exception generated calling TANServer.Create({...}) bubble out to the .catch(...) block as listed?\n- Makes an odd bit of sense. Thanks. The .Create is absolutely under my control, so I can do that. Thanks much! Appreciate it. The Sequelize docs are, IMO, a bit lacking for certain bits of clarity. I'm not sure I read anything quite so succinct and direct as you pointed out in hours of reading, testing, recoding, experimenting, etc. Thanks, man!","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":153,"estimatedTokens":1053}}793{"id":"stack-31606373","source":"stackoverflow","questionId":31606373,"title":"breeze-sequelize with MSSQL possible?","tags":["javascript","sql-server","node.js","breeze","sequelize.js"],"text":"Title: breeze-sequelize with MSSQL possible?\nTags: javascript, sql-server, node.js, breeze, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it currently possible to connect breeze-sequelize with a MS SQL server?\n\nAccording to the doc of Sequelize, Sequelize does support MSSQL Server.\nThough in the breeze doc there is no MS SQL server listed.\n\nI am a bit confused now. And if it is not possible, is the breeze dev team planning to impl that? Or are there alternatives to use breeze in nodejs with an MSSQL server?\n\n========================================\n\nCode:\n```text\nvar dbConfig = {\n    user: 'username',\n    password: 'secret',\n    dbName: 'myDatabase'\n};\n\nvar sequelizeOptions = {\n    host: 'hostname',\n    dialect: 'mssql',\n    port: 1433\n};\n\n\nfunction createSequelizeManager() {\n    var metadata = readMetadata();\n    var sm = new SequelizeManager(dbConfig, sequelizeOptions);\n    sm.importMetadata(metadata);\n\n    return sm;\n}\n```\n\n```text\nvar sequelizeOptions = {\n    host: 'localhost',\n    dialect: 'mssql',\n    dialectOptions: {\n        instanceName: 'MY_MSSQL_INSTANCE'\n    }\n};\n```\n\n```text\nlocalhost\\MY_MSSQL_INSTANCE\n```\n\n```text\nlocalhost\\MY_MSSQL_INSTANCE\n```\n\n```text\nsequelizeOptions\n```\n\n========================================\n\nComments:\n- in the getting started section there is a reference to MSSQL. did you try to use that syntax?\n- with breeze i need to work with the lib `breeze-sequelize`. I need to create a SequelizeManager described in the breeze-sequelize-docs\n- i tried to set the dialect to `mssql` though i always get the following mySql error `[Breeze] Unable to connect to mySql:Error: getaddrinfo ENOTFOUND (LocalDb)♂11.0`\n- Wow! I am surprised that no one else is trying to get this to work. I love Breeze and needed to strip down an API to run on Node.js using a MSSQL backend. There is little documentation out there and your answer saved by butt. Thank you!\n- Yep... this answer saved the day! :-)","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":68,"estimatedTokens":486}}794{"id":"stack-69498954","source":"stackoverflow","questionId":69498954,"title":"Sequelize query to find all records that fall between a date range and time range","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize query to find all records that fall between a date range and time range\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a column **time_scheduled** of type **Sequelize.DATE** which stores the scheduled time of **events**.\n\nI am tying to create a Sequelize query where I can find all **events** that fall between a date range and time range. The SQL query for the same is below.\n\n`SELECT * FROM events where time_scheduled between '2021/10/01' and '2021/10/10' and time_scheduled::timestamp::time between '12:00' and '15:00';`\n\nSample output for the same\n\n`id`\n`time_scheduled`\n\n`4d543320-4d23-46d2-8a54-fbb13a1251d0`\n`2021-10-05 14:30:00+00`\n\n`d6640e70-f873-436c-a59d-5a4c4fc655b7`\n`2021-10-06 12:02:49.441+00`\n\n`b11481b2-ffdd-413e-81af-f83df756bcc9`\n`2021-10-06 13:55:36.62+00`\n\n`53447517-f226-407f-94f4-63ddc8c17d9c`\n`2021-10-07 13:59:48.123+00`\n\n`f0344678-11eb-4422-9d23-43e8d5320f55`\n`2021-10-07 14:14:13.647+00`\n\n========================================\n\nCode:\n```text\nSELECT * FROM events where time_scheduled between '2021/10/01' and '2021/10/10' and time_scheduled::timestamp::time between '12:00' and '15:00';\n```\n\n```text\nid\n```\n\n```text\ntime_scheduled\n```\n\n```text\n4d543320-4d23-46d2-8a54-fbb13a1251d0\n```\n\n```text\n2021-10-05 14:30:00+00\n```\n\n```text\nd6640e70-f873-436c-a59d-5a4c4fc655b7\n```\n\n```text\n2021-10-06 12:02:49.441+00\n```\n\n```text\nb11481b2-ffdd-413e-81af-f83df756bcc9\n```\n\n```text\n2021-10-06 13:55:36.62+00\n```\n\n```text\n53447517-f226-407f-94f4-63ddc8c17d9c\n```\n\n```text\n2021-10-07 13:59:48.123+00\n```\n\n```text\nf0344678-11eb-4422-9d23-43e8d5320f55\n```\n\n```text\n2021-10-07 14:14:13.647+00\n```\n\n```js\nconst records = await Events.findAll({\n  where: {\n    [Op.and]: [{\n      time_scheduled: {\n        [Op.between]: ['2021/10/01', '2021/10/10']\n      }\n    }, \n    Sequelize.where(Sequelize.cast(Sequelize.col('time_scheduled'), 'time'), '>=', '12:00'),\n    Sequelize.where(Sequelize.cast(Sequelize.col('time_scheduled'), 'time'), '<=', '15:00')\n]\n  }\n});\n```\n\n```text\nOp.between\n```\n\n```text\nSequelize.where\n```\n\n```text\nSequelize.cast\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":112,"estimatedTokens":527}}795{"id":"stack-64207295","source":"stackoverflow","questionId":64207295,"title":"What Type does sequelize.define() return in TypeScript?","tags":["node.js","typescript","sequelize.js"],"text":"Title: What Type does sequelize.define() return in TypeScript?\nTags: node.js, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo I finally decided to try out TypeScript, because of everything I've heard about it and how having static types is good for me. I decided to test it out by creating a simple web API with sequelize, but I am having trouble understanding the types returned from sequelize. So I have the following imports (note that I've also installed the @types/sequelize npm module:\n\n```\nimport sequelize = require('sequelize');\nimport {DataTypes} from 'sequelize';\n```\n\nI am creating my model like this:\n\n```\nconst User:sequelize.Model= db.define('User',{\n id: {type:DataTypes.INTEGER, primaryKey:true},\n email:{type:DataTypes.STRING, allowNull:false},\n hashedPassword:{type:DataTypes.STRING,allowNull:false}\n });\n```\n\nBut I am getting this error:\n\n```\nType 'ModelCtor>' is missing the following properties from type 'Model': _attributes, _creationAttributes, isNewRecord, where, and 16 more.\n```\n\nBut if I do this:\n\n```\nconst User:any= db.define('User',{\n id: {type:DataTypes.INTEGER, primaryKey:true},\n email:{type:DataTypes.STRING, allowNull:false},\n hashedPassword:{type:DataTypes.STRING,allowNull:false}\n});\n```\n\nIt works fine. But of course, because this is TypeScript, I want to take advantage of Types. Using \"any\" defeats the purpose. How can I know which type I should use for my model? Unfortunately, most of sequelize's documentation is regular javascript, so I can't find examples of this. Any help is appreciated.\n\n========================================\n\nCode:\n```text\nimport sequelize = require('sequelize');\nimport  {DataTypes} from 'sequelize';\n```\n\n```text\nconst User:sequelize.Model= db.define('User',{\n        id: {type:DataTypes.INTEGER, primaryKey:true},\n        email:{type:DataTypes.STRING, allowNull:false},\n        hashedPassword:{type:DataTypes.STRING,allowNull:false}\n    });\n```\n\n```text\nType 'ModelCtor<Model<any, any>>' is missing the following properties from type 'Model<any,any>': _attributes, _creationAttributes, isNewRecord, where, and 16 more.\n```\n\n```text\nconst User:any= db.define('User',{\n    id: {type:DataTypes.INTEGER, primaryKey:true},\n    email:{type:DataTypes.STRING, allowNull:false},\n    hashedPassword:{type:DataTypes.STRING,allowNull:false}\n});\n```\n\n```js\nimport { Sequelize, DataTypes, Model, BuildOptions } from 'sequelize';\n\nconst db = new Sequelize('mysql://root:asd123@localhost:3306/mydb');\n\ninterface UserAttributes {\n  readonly id: number;\n  readonly email: string;\n  readonly hashedPassword: string;\n}\ninterface UserInstance extends Model<UserAttributes>, UserAttributes {}\ntype UserModelStatic = typeof Model & {\n  new (values?: object, options?: BuildOptions): UserInstance;\n};\n\nconst User = db.define('User', {\n  id: { type: DataTypes.INTEGER, primaryKey: true },\n  email: { type: DataTypes.STRING, allowNull: false },\n  hashedPassword: { type: DataTypes.STRING, allowNull: false },\n}) as UserModelStatic;\n\n(async function test() {\n  const user: UserInstance = await User.create({\n    id: 1,\n    hashedPassword: '123',\n    email: 'test@gmail.com',\n  });\n  user.getDataValue('email');\n})();\n```\n\n```text\nsequelize.define\n```\n\n```text\nTypeScript\n```\n\n```text\n\"sequelize\": \"^5.21.3\"\n```\n\n```text\nuser.ts\n```\n\n========================================\n\nComments:\n- Can you explain what is going on on this line: interface UserInstance extends Model, UserAttributes {} As far as I know, TypeScript does not support multiple inheritance. What does the , do here?\n- @tutiplain This is an interface, NOT a class. An interface can extend multiple interfaces in TypeScript.\n- This really sucks that you need to define it twice. With TypeGoose for example you get the types out of the box.","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":121,"estimatedTokens":942}}796{"id":"stack-63122018","source":"stackoverflow","questionId":63122018,"title":"Sequelize operation hanging when returning the result but working when no returning it","tags":["node.js","promise","sequelize.js"],"text":"Title: Sequelize operation hanging when returning the result but working when no returning it\nTags: node.js, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've been working with Node for about 3 years, but what is happening to me right now is driving me crazy.\n\nMy project uses Sequelize for the last 6 months and it's all working perfectly.\n\nIf I try to update the *myModelObject* instance with the following code, it works as expected.(*I've change the real code in order to show the behavior in a more cleaner way*)\n\n```\n...\n.then(parameters => { \n myModelObject.update({parameters}, { where: { id: myObjectId }})\n .then(() => {\n console.log(\"Sequelize update resolved !\") \n })\n})\n.then( () => {\n console.log(\"Promise resolved !\")\n})\n```\n\nThis will make my myModelObject updated in the DB and the console will display:\n\nPromise resolved !\n\n1 second later...\n\nSequelize update resolved !\n\n**But**, the strange behavior happens when I add a **return** before the update of myModelObject:\n\n```\n...\n.then(parameters => { \n return myModelObject.update({parameters}, { where: { id: myObjectId }})\n .then(() => {\n console.log(\"Sequelize update resolved !\")\n })\n})\n.then( () => {\n console.log(\"Promise resolved !\")\n})\n```\n\nThis makes my code to hung.. the update is never done and a timeout happens. What I mean is that the Sequelize update is never resolved if I want to return it !\nAll my other Sequelize code is working perfectly !\n\nAny hep will be very appreciate it :)\n\n*Node: 12.16.0 || Sequelize: 5.21.6 || pg: 7.18.2*\n\n========================================\n\nTop Answer:\n@oriuken, maybe you should try something like this below.\n\n```\n.then(parameters => { \n return new Promise(async (resolve, reject) => {\n try {\n await myModelObject.update({parameters}, { where: { id: myObjectId }});\n console.log(\"Sequelize update resolved !\")\n return resolve('Promise resolved')\n }catch(e) {\n return reject(e.message);\n }\n });\n})\n```\n\n========================================\n\nCode:\n```text\n...\n.then(parameters => {                                    \n   myModelObject.update({parameters}, { where: { id: myObjectId }})\n   .then(() => {\n      console.log(\"Sequelize update resolved !\")      \n   })\n})\n.then( () => {\n   console.log(\"Promise resolved !\")\n})\n```\n\n```text\n...\n.then(parameters => {                                    \n   return myModelObject.update({parameters}, { where: { id: myObjectId }})\n   .then(() => {\n      console.log(\"Sequelize update resolved !\")\n   })\n})\n.then( () => {\n   console.log(\"Promise resolved !\")\n})\n```\n\n```text\n.then(parameters => {   \n  return new Promise(async (resolve, reject) => {\n    try {\n      await myModelObject.update({parameters}, { where: { id: myObjectId }});\n      console.log(\"Sequelize update resolved !\")\n      return resolve('Promise resolved')\n    }catch(e) {\n      return reject(e.message);\n    }\n  });\n})\n```\n\n========================================\n\nComments:\n- What do you want to return? A promise object or just a string \"Sequelize update resolved !\"\n- I just want to return the Promise of the Update so I can make an action once it is resolved, but if I add the return before the 'update', it hangs and doesn't ever resolve\n- suprised to see that your code is not working with `return` !!\n- Exactly.. is driving me crazy\n- What you are describing here is not possible, given the code you show. There must be something else going on that you omitted in your example.\n- Yes, but that is happening.... it took me to the point where I really doubted if I understood the use of promises, because if the 'Update' hangs, then it should hang always independently if is returning the promise or not\n- I tried something similar but no luck. I also tried this code of yours too but no luck neither.. the code hungs when making the 'update'\n- Bad use of promises. Creating extra needless promises, plus `return resolve` and `return reject` do nothing, see Promise spec.\n- Extra needless promise? please read the actual question again and the comment section. The reason i have used return, it should ideally be your last statement within your function. Also, do nothing? you will see the \"Promise resolved\" if you log it. with or without return keyword because resolve and reject are callback functions.\n- Wow I had the exact same problem. This probably saved me hours of debugging.","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":129,"estimatedTokens":1085}}797{"id":"stack-36898526","source":"stackoverflow","questionId":36898526,"title":"How do I get sequelize to create id for join table?","tags":["sequelize.js"],"text":"Title: How do I get sequelize to create id for join table?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSee these models and relationships:\n\n```\nvar User = sequelize.define('user', {\n name: {type: Sequelize.STRING, unique: true},\n password: Sequelize.STRING,\n email: Sequelize.STRING\n});\n\nvar Group = sequelize.define('group', {\n name: Sequelize.STRING,\n});\n\nvar Membership = sequelize.define('membership', {\n foo: Sequelize.STRING\n});\n\nvar Query = sequelize.define('query', {\n text: Sequelize.STRING,\n});\n\nUser.belongsToMany(Group, {through: Membership});\nGroup.belongsToMany(User, {through: Membership});\n\nQuery.belongsTo(Membership);\nMembership.hasMany(Query);\n```\n\nWhy doesn't sequelize create an id column for Membership? How can i make it create it? Why does it create a column called `membershipGroupId`?\n\nTo answer @denisazevedo, i am using `sync` with `force`. Below is the output from the sync\n\n```\nExecuting (default): DROP TABLE IF EXISTS `memberships`;\nExecuting (default): DROP TABLE IF EXISTS `groups`;\nExecuting (default): DROP TABLE IF EXISTS `cookies`;\nExecuting (default): DROP TABLE IF EXISTS `events`;\nExecuting (default): DROP TABLE IF EXISTS `clients`;\nExecuting (default): DROP TABLE IF EXISTS `users`;\nExecuting (default): DROP TABLE IF EXISTS `results`;\nExecuting (default): DROP TABLE IF EXISTS `queries`;\nExecuting (default): DROP TABLE IF EXISTS `queries`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `queries` (`id` INTEGER NOT NULL auto_increment , `text` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `membershipGroupId` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `queries`\nExecuting (default): DROP TABLE IF EXISTS `results`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `results` (`id` INTEGER NOT NULL auto_increment , `link` VARCHAR(2048), `description` TEXT, `result_order` FLOAT(5,2), `title` VARCHAR(255), `result_relevance` ENUM('up', 'down', 'none'), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `queryId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`queryId`) REFERENCES `queries` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `results`\nExecuting (default): DROP TABLE IF EXISTS `users`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) UNIQUE, `password` VARCHAR(255), `email` VARCHAR(255), `role` ENUM('facilitator', 'participant'), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `users`\nExecuting (default): DROP TABLE IF EXISTS `clients`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `clients` (`id` INTEGER NOT NULL auto_increment , `socketid` VARCHAR(255), `connected` DATETIME, `disconnected` DATETIME, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `userId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `clients`\nExecuting (default): DROP TABLE IF EXISTS `events`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `events` (`id` INTEGER NOT NULL auto_increment , `description` TEXT, `type` ENUM('vote_up', 'vote_down', 'critisort', 'originalsort', 'logout', 'login', '', 'search'), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `clientId` INTEGER, `resultId` INTEGER, `queryId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`clientId`) REFERENCES `clients` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (`resultId`) REFERENCES `results` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (`queryId`) REFERENCES `queries` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `events`\nExecuting (default): DROP TABLE IF EXISTS `cookies`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `cookies` (`id` INTEGER NOT NULL auto_increment , `key` VARCHAR(255), `uid` VARCHAR(255) UNIQUE, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `cookies`\nExecuting (default): DROP TABLE IF EXISTS `groups`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `groups` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `ownerId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`ownerId`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `groups`\nExecuting (default): DROP TABLE IF EXISTS `memberships`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `memberships` (`foo` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `groupId` INTEGER , `userId` INTEGER , PRIMARY KEY (`groupId`, `userId`), FOREIGN KEY (`groupId`) REFERENCES `groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `memberships`\n```\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('user', {\n  name: {type: Sequelize.STRING, unique: true},\n  password: Sequelize.STRING,\n  email: Sequelize.STRING\n});\n\nvar Group = sequelize.define('group', {\n  name: Sequelize.STRING,\n});\n\nvar Membership = sequelize.define('membership', {\n  foo: Sequelize.STRING\n});\n\nvar Query = sequelize.define('query', {\n  text: Sequelize.STRING,\n});\n\nUser.belongsToMany(Group, {through: Membership});\nGroup.belongsToMany(User, {through: Membership});\n\nQuery.belongsTo(Membership);\nMembership.hasMany(Query);\n```\n\n```text\nExecuting (default): DROP TABLE IF EXISTS `memberships`;\nExecuting (default): DROP TABLE IF EXISTS `groups`;\nExecuting (default): DROP TABLE IF EXISTS `cookies`;\nExecuting (default): DROP TABLE IF EXISTS `events`;\nExecuting (default): DROP TABLE IF EXISTS `clients`;\nExecuting (default): DROP TABLE IF EXISTS `users`;\nExecuting (default): DROP TABLE IF EXISTS `results`;\nExecuting (default): DROP TABLE IF EXISTS `queries`;\nExecuting (default): DROP TABLE IF EXISTS `queries`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `queries` (`id` INTEGER NOT NULL auto_increment , `text` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `membershipGroupId` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `queries`\nExecuting (default): DROP TABLE IF EXISTS `results`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `results` (`id` INTEGER NOT NULL auto_increment , `link` VARCHAR(2048), `description` TEXT, `result_order` FLOAT(5,2), `title` VARCHAR(255), `result_relevance` ENUM('up', 'down', 'none'), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `queryId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`queryId`) REFERENCES `queries` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `results`\nExecuting (default): DROP TABLE IF EXISTS `users`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) UNIQUE, `password` VARCHAR(255), `email` VARCHAR(255), `role` ENUM('facilitator', 'participant'), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `users`\nExecuting (default): DROP TABLE IF EXISTS `clients`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `clients` (`id` INTEGER NOT NULL auto_increment , `socketid` VARCHAR(255), `connected` DATETIME, `disconnected` DATETIME, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `userId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `clients`\nExecuting (default): DROP TABLE IF EXISTS `events`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `events` (`id` INTEGER NOT NULL auto_increment , `description` TEXT, `type` ENUM('vote_up', 'vote_down', 'critisort', 'originalsort', 'logout', 'login', 'follow', 'search'), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `clientId` INTEGER, `resultId` INTEGER, `queryId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`clientId`) REFERENCES `clients` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (`resultId`) REFERENCES `results` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, FOREIGN KEY (`queryId`) REFERENCES `queries` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `events`\nExecuting (default): DROP TABLE IF EXISTS `cookies`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `cookies` (`id` INTEGER NOT NULL auto_increment , `key` VARCHAR(255), `uid` VARCHAR(255) UNIQUE, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `cookies`\nExecuting (default): DROP TABLE IF EXISTS `groups`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `groups` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `ownerId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`ownerId`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `groups`\nExecuting (default): DROP TABLE IF EXISTS `memberships`;\nExecuting (default): CREATE TABLE IF NOT EXISTS `memberships` (`foo` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `groupId` INTEGER , `userId` INTEGER , PRIMARY KEY (`groupId`, `userId`), FOREIGN KEY (`groupId`) REFERENCES `groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `memberships`\n```\n\n```text\nmembershipGroupId\n```\n\n```text\nsync\n```\n\n```text\nforce\n```\n\n```text\nUserProjects = sequelize.define('userProjects', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  status: DataTypes.STRING\n})\n```\n\n```text\nMembership\n```\n\n```text\ngroupId\n```\n\n```text\nuserId\n```\n\n```text\nMembership\n```\n\n========================================\n\nComments:\n- What is the generated SQL in the logs when you call `sync` method? Are you forcing the tables creation?\n- I think because you are defining the relationship through a certain attribute - `{through: Membership}`\n- just searched for this again, couldn't remember where i found the q/a, which i had more votes to upvote you @denisazevedo thanks again","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":181,"estimatedTokens":2672}}798{"id":"stack-60843078","source":"stackoverflow","questionId":60843078,"title":"How to modify virtual fields from sequelize findAll result?","tags":["javascript","sequelize.js"],"text":"Title: How to modify virtual fields from sequelize findAll result?\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have looked everywhere and couldn't find any clear answers for this.\nI have a complex findAll() with many inclusions and each with their own virtual fields.\nWhat I want is to modify the virtual fields of the result, however as it is returning the model instance trying to access the virtual fields returns undefined as they are not in the result yet.\nI have tried 'raw: true' but this removes all virtual fields and as my data has nested tables which also have their own virtual fields which I need, I cannot do that.\n\nExample models \n\n```\nvar Book = sequelize.define('Book', {\n\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n autoIncrement: true,\n primaryKey: true\n },\n title: {\n type: DataTypes.STRING\n },\n author: {\n type: DataTypes.STRING\n }\n //....other columns,\n myField: {\n type: DataTypes.Virtual,\n get() {\n return this.getDataValue('title:') + this.getDataValue('author');\n })\n```\n\nGetting the data\n\n```\nmodel.Book.findAll({\n limit: 100\n})\n.then((result) => {\n\n const newBook = result.map(row => {\n return {...row, myField: 'setMyOwnValueHere'}\n }\n\n return newBook\n}\n```\n\n========================================\n\nCode:\n```text\nvar Book = sequelize.define('Book', {\n\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        title: {\n            type: DataTypes.STRING\n        },\n        author: {\n            type: DataTypes.STRING\n        }\n        //....other columns,\n        myField: {\n            type: DataTypes.Virtual,\n            get() {\n                return this.getDataValue('title:') + this.getDataValue('author');\n    })\n```\n\n```text\nmodel.Book.findAll({\n  limit: 100\n})\n.then((result) => {\n\n  const newBook = result.map(row => {\n    return {...row, myField: 'setMyOwnValueHere'}\n  }\n\n  return newBook\n}\n```\n\n```text\nmodel.Book.findAll({\n    limit: 100\n}).then(result => {\n    const books = result.map(row => {\n        //this returns all values of the instance, \n        //also invoking virtual getters\n        const book = row.get();\n        book.myField = 'setMyOwnValueHere';\n        return book;\n    });\n    return books;\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":105,"estimatedTokens":576}}799{"id":"stack-19368025","source":"stackoverflow","questionId":19368025,"title":"How to work with associations in Sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: How to work with associations in Sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to understand Sequelize and I have small problem with associations. Please take a look at code below:\n\nUser model:\n\n```\nvar Sequelize = require(\"sequelize\");\n\nmodule.exports = function (sequelize) {\n var User = sequelize.define('user', {\n id:{ type:Sequelize.INTEGER.UNSIGNED, autoIncrement:true, allowNull:false, primaryKey:true},\n name:{ type:Sequelize.STRING(50), defaultValue:''},\n email:Sequelize.STRING(50),\n password:Sequelize.STRING(256)\n });\n\n return User;\n};\n```\n\nDeadline model:\n\n```\nvar Sequelize = require(\"sequelize\");\n\nmodule.exports = function (sequelize) {\n var User = require(\"./user\")(sequelize),\n Deadline = sequelize.define('deadline', {\n id:{ type:Sequelize.INTEGER.UNSIGNED, autoIncrement:true, allowNull:false, primaryKey:true},\n name:{ type:Sequelize.STRING(255)}\n });\n\n User.hasMany(Deadline);\n\n return Deadline;\n};\n```\n\nand code which does not let me sleep well:\n\n```\nvar sequelize = require('./app/mysqlConnection'),\n User = require(\"./app/models/user\")(sequelize),\n Deadline = require(\"./app/models/deadline\")(sequelize);\n\nsequelize.drop().success(function () {\n sequelize.sync().success(function () {\n\n var user = User.build({password:'bar', email:'ser'}),\n dead = Deadline.build({name:'learn js'});\n\n user.addDeadline(dead);\n```\n\nin last line I got \n\n```\nTypeError: Object [object Object] has no method 'addDeadline'\n at null. (C:\\projects\\deadline\\dbsynch.js:11:14)\n at EventEmitter.emit (events.js:106:17)\n at module.exports.finish (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:138:30)\n at exec (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:92:16)\n at onSuccess (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:65:11)\n at null. (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:86:15)\n at EventEmitter.emit (events.js:95:17)\n at null. (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\dao-factory.js:195:41)\n at EventEmitter.emit (events.js:95:17)\n at null. (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-interface.js:162:19)\n```\n\nAccording documentation when I inform User about User.hasMany(Deadline) then User prototype should automatically get setDeadlines, getDeadlines, add/removeDeadline methods. Could you help me? \n\nBTW\n\"sequelize\": \"~2.0.0-beta.0\",\n\n========================================\n\nCode:\n```text\nvar Sequelize = require(\"sequelize\");\n\nmodule.exports = function (sequelize) {\n    var User = sequelize.define('user', {\n        id:{ type:Sequelize.INTEGER.UNSIGNED, autoIncrement:true, allowNull:false, primaryKey:true},\n        name:{ type:Sequelize.STRING(50), defaultValue:''},\n        email:Sequelize.STRING(50),\n        password:Sequelize.STRING(256)\n    });\n\n    return User;\n};\n```\n\n```text\nvar Sequelize = require(\"sequelize\");\n\nmodule.exports = function (sequelize) {\n    var User = require(\"./user\")(sequelize),\n        Deadline = sequelize.define('deadline', {\n            id:{ type:Sequelize.INTEGER.UNSIGNED, autoIncrement:true, allowNull:false, primaryKey:true},\n            name:{ type:Sequelize.STRING(255)}\n        });\n\n    User.hasMany(Deadline);\n\n    return Deadline;\n};\n```\n\n```text\nvar sequelize = require('./app/mysqlConnection'),\n    User = require(\"./app/models/user\")(sequelize),\n    Deadline = require(\"./app/models/deadline\")(sequelize);\n\nsequelize.drop().success(function () {\n    sequelize.sync().success(function () {\n\n        var user = User.build({password:'bar', email:'ser'}),\n            dead = Deadline.build({name:'learn js'});\n\n        user.addDeadline(dead);\n```\n\n```text\nTypeError: Object [object Object] has no method 'addDeadline'\n    at null.<anonymous> (C:\\projects\\deadline\\dbsynch.js:11:14)\n    at EventEmitter.emit (events.js:106:17)\n    at module.exports.finish (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:138:30)\n    at exec (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:92:16)\n    at onSuccess (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:65:11)\n    at null.<anonymous> (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-chainer.js:86:15)\n    at EventEmitter.emit (events.js:95:17)\n    at null.<anonymous> (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\dao-factory.js:195:41)\n    at EventEmitter.emit (events.js:95:17)\n    at null.<anonymous> (C:\\projects\\deadline\\node_modules\\sequelize\\lib\\query-interface.js:162:19)\n```\n\n```text\nsequelize.drop().success(function () {\n    sequelize.sync().success(function () {\n\n        User.create({password:'bar', email:'ser'}).success(function(user) {\n            Deadline.create({name:'learn js'}).success(function(deadline) {\n                user.addDeadline(deadline).success(function() {\n                    console.log('coolio!')\n                })\n            })\n        })\n    })\n})\n```\n\n========================================\n\nComments:\n- Hi sdepold, Unfortunately it still does not work. Please take a look at pastebin.com/gmJ0uzLk\n- Can you try this? gist.github.com/sdepold/d452d9bfb65c2a33c88e It perfectly works for me.\n- Hi, Thanks a lot, now is working. I don't know why I had problem before.","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":162,"estimatedTokens":1309}}800{"id":"stack-51028899","source":"stackoverflow","questionId":51028899,"title":"Build instance, save and associate with one query","tags":["sequelize.js"],"text":"Title: Build instance, save and associate with one query\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using `.build` to create a model instance, which is later saved.\n\n```\nconst modelInstance = sequelize.models.SomeModel.build({\n someKey: 'someValue',\n // ...\n});\n```\n\nLater on after conditionally adding various properties, I'm calling `.save()`, followed by associating the record with another model.\n\n```\nmodelInstance.save().then((modelInstance) => {\n modelInstance.setParent(parentInstance);\n});\n```\n\nI've found that if I call `.setParent()` before `.save()`, that an empty `SomeModel` record is placed into the database. Therefore, I have to call `.save()` first. However, this requires two queries.\n\nHow can I use `.build()`/`.save()` with `.set` in a single query?\n\n========================================\n\nCode:\n```text\nconst modelInstance = sequelize.models.SomeModel.build({\n  someKey: 'someValue',\n  // ...\n});\n```\n\n```text\nmodelInstance.save().then((modelInstance) => {\n  modelInstance.setParent(parentInstance);\n});\n```\n\n```text\n.build\n```\n\n```text\n.save()\n```\n\n```text\n.setParent()\n```\n\n```text\n.save()\n```\n\n```text\nSomeModel\n```\n\n```text\n.save()\n```\n\n```text\n.build()\n```\n\n```text\n.save()\n```\n\n```text\n.set<x>\n```\n\n```text\nreturn SomeModel.create({\n  someKey: 'someValue',\n  parent: {\n    parentKey: 'parentValue'\n  }\n}, {\n  include: [{\n    association: ParentModel\n  }]\n});\n```\n\n```text\nmodelInstance.save().then((modelInstance) => {\n  return modelInstance.setParent(parentInstance);\n});\n```\n\n```text\nreturn SomeModel.create({\n  someKey: 'someValue',\n  parentId: parentInstance.id\n});\n```\n\n```text\ngetParent()\n```\n\n========================================\n\nComments:\n- Why are you building model ? is that also included in part of checking conditions ?","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":112,"estimatedTokens":446}}801{"id":"stack-64537487","source":"stackoverflow","questionId":64537487,"title":"Sequelize upsert is always creating/inserting a new entry on post request, instead of updating data on matching username. MySQL database","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize upsert is always creating/inserting a new entry on post request, instead of updating data on matching username. MySQL database\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a survey for a specific amount of users.\nWhen a user first submits their answers I want to create a new entry in the database, this part works fine. If the same user wants to retake the survey I want to update their answers instead of creating a new entry for the same user.\n\nI'm trying to use sequelize upsert but it keeps creating new entries for the same \"testuser\" every time I make a new post request.\n\nNone of the answers found online seemed to work. Any help on what I might be doing wrong is appreciated.\n\n```\n// parts of the code that might not be relevant to the problem have been omitted\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst Sequelize = require('sequelize');\n\nconst app = express();\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\n\nconst sequelize = new Sequelize({\n database: 'database',\n username: 'user',\n password: 'password',\n dialect: 'mysql',\n});\n\nsequelize\n .authenticate()\n .then(() => console.log('Connection has been established successfully.'))\n .catch(err => console.log('error: ', err));\n\nconst SurveyResults = sequelize.define('results', {\n name: {\n type: Sequelize.STRING,\n primaryKey: true,\n unique: true,\n },\n results: {\n type: Sequelize.JSON,\n },\n});\n\nSurveyResults.sync()\n .then(() => console.log('Survey results table created'))\n .catch(err => console.log(err));\n\napp.post('/dashboard', (req, res) => {\n let { username, surveyData } = req.body;\n\n SurveyResults.upsert(\n {\n name: username,\n results: surveyData,\n },\n { name: username }\n )\n .then(data => console.log(data))\n .catch(err => console.log(err));\n});\n\nconst PORT = process.env.PORT || 5050;\n\napp.listen(PORT, () => console.log('Server is running on port ' + PORT));\n```\n\n========================================\n\nTop Answer:\nUpsert on mysql work only if the same primary key is given in not this will create a new one .\n\nyou can refer to : https://sequelize.org/master/class/lib/model.js~Model.html#static-method-upsert\n\n========================================\n\nCode:\n```text\n// parts of the code that might not be relevant to the problem have been omitted\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst Sequelize = require('sequelize');\n\nconst app = express();\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\n\nconst sequelize = new Sequelize({\n  database: 'database',\n  username: 'user',\n  password: 'password',\n  dialect: 'mysql',\n});\n\nsequelize\n  .authenticate()\n  .then(() => console.log('Connection has been established successfully.'))\n  .catch(err => console.log('error: ', err));\n\nconst SurveyResults = sequelize.define('results', {\n  name: {\n    type: Sequelize.STRING,\n    primaryKey: true,\n    unique: true,\n  },\n  results: {\n    type: Sequelize.JSON,\n  },\n});\n\nSurveyResults.sync()\n  .then(() => console.log('Survey results table created'))\n  .catch(err => console.log(err));\n\n\napp.post('/dashboard', (req, res) => {\n  let { username, surveyData } = req.body;\n\n  SurveyResults.upsert(\n    {\n      name: username,\n      results: surveyData,\n    },\n    { name: username }\n  )\n    .then(data => console.log(data))\n    .catch(err => console.log(err));\n});\n\nconst PORT = process.env.PORT || 5050;\n\napp.listen(PORT, () => console.log('Server is running on port ' + PORT));\n```\n\n========================================\n\nComments:\n- I don't know this language, but I doubt that a pk *also* needs to be defined as unique.\n- Setting it to unique might have been redundant, I made the change. Ty for your answer but the problem still persists.\n- If you try to insert a row with the same `name` using `INSERT ... ON DUPLICATE KEY UPDATE` the issue is not shown?\n- @Anatoly using INSERT ... ON DUPLICATE KEY UPDATE with the same name created new entries.\n- Ok, check PK and an unique index definitions in a DB\n- Isn't `sequelize.define` setting `name` as pk?\n- Check if `name` has uniqueness set in database manually first, if not make it `unique` by adding unique index on it.\n- This seems to have solved the issue even though the console.log is showing ` _previousDataValues: { name: undefined, results: undefined, id: null },` on the second entry. I might be misunderstanding the console.log and expecting to see the previous values there, I hope that's not important. Thank you for your help!","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":148,"estimatedTokens":1143}}802{"id":"stack-36038820","source":"stackoverflow","questionId":36038820,"title":"Sequelize attributes in findOne returning all fields","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize attributes in findOne returning all fields\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have\n\n```\ndb.User.findOne({\n attributes: ['id', 'firstName', 'lastName', 'email', 'phoneNumber', 'createdAt', 'type', 'status'],\n where: {\n id: id\n }\n}).then(function(dbUser) {\n console.log(dbUser);\n});\n```\n\nAnd it's returning all of the fields, not just the ones I specify in `attributes`. What am I doing wrong?\n\n========================================\n\nTop Answer:\nAccording to the docs, you're doing absolutely nothing wrong. I'm seeing similar behavior. Sequelize seems to be going through some growing pains. :\\\n\n========================================\n\nCode:\n```text\ndb.User.findOne({\n  attributes: ['id', 'firstName', 'lastName', 'email', 'phoneNumber', 'createdAt', 'type', 'status'],\n  where: {\n    id: id\n  }\n}).then(function(dbUser) {\n  console.log(dbUser);\n});\n```\n\n```text\nattributes\n```\n\n```text\ndb.animals.findOne({ },{_id:0, numlegs:1,class:1, name:1})\n```\n\n```text\nconst user = await User.findOne({\n    attributes : ['id','name','email','contact'],\n    where: {email:req.body.email}\n});\n```\n\n```text\n{\n\"status\": \"success\",\n\"user\": {\n    \"id\": 1,\n    \"name\": \"admin\",\n    \"email\": \"admin@eatanddrink.io\",\n    \"contact\": \"0724466628\"\n },\n}\n```\n\n```js\nimport { sql } from '@sequelize/core';\n\ninterface Data {\n  authorId: number;\n  postCount: number;\n}\n\n// this will return an array of plain objects with the shape of the \"Data\" interface\nconst data: Data[] = await Post.findAll<Data>({\n  attributes: [\n    [sql`COUNT(${sql.attribute('id')})`, 'postCount'],\n  ],\n  group: ['authorId'],\n  raw: true,\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":415}}803{"id":"stack-54927493","source":"stackoverflow","questionId":54927493,"title":"Maximum call stack size exceeded in react-admin with ra_data_graphql_simple when schema with nested object","tags":["reactjs","sequelize.js","graphql","introspection","react-admin"],"text":"Title: Maximum call stack size exceeded in react-admin with ra_data_graphql_simple when schema with nested object\nTags: reactjs, sequelize.js, graphql, introspection, react-admin\nSource: Stack Overflow\n\nQuestion:\nI dove in head first to try react-admin as the admin solution for some simple data entry for an application but i find the docs lacking and i have searched for a solution to this online after many hours of debugging.\n\nMy Problem:\n\nWhen nested objects are present in my schema as follows..\n\n```\ntype Country {\ncountry_id: ID!\nname: String\nabbr2: String\nabbr3: String\nprovincesOrStates: [ProvinceState]}\n```\n\nreact-admin will fail with the error: Maximimum call stack size exceeded.. it does not even make a call to my graphql server in that case after the introspection, i can see that in my developer tools. My back end is Apollo Server with Sequelize as my ORM and my dependencies are as follows there:\n\n```\n\"dependencies\": {\n\"apollo-server\": \"^2.4.2\",\n\"dataloader-sequelize\": \"^1.7.9\",\n\"dotenv\": \"^6.2.0\",\n\"graphql\": \"^14.1.1\",\n\"graphql-import\": \"^0.7.1\",\n\"graphql-list-fields\": \"^2.0.2\",\n\"graphql-tools\": \"^4.0.4\",\n\"lodash\": \"^4.17.11\",\n\"merge-graphql-schemas\": \"^1.5.8\",\n\"pg\": \"^7.8.0\",\n\"pg-hstore\": \"^2.3.2\",\n\"save\": \"^2.3.3\",\n\"sequelize\": \"^4.42.0\"}\n```\n\nI should note that GraphiQL works just fine with the nested objects and returns the expected data.. The schema is modeled exactly the way the simple data provider from marmelabs suggested\n\nMy react-admin is nothing special... it is set up exactly the same as the examples they list in the readme... my App.js code is as follows\n\n```\nimport React, { Component } from 'react';\nimport { Admin, Resource, ListGuesser } from 'react-admin';\nimport buildGraphQLProvider from 'ra-data-graphql-simple';\n\nclass App extends Component {\n constructor() {\n super();\n this.state = { dataProvider: null };\n }\n componentDidMount() {\n\n buildGraphQLProvider({ clientOptions: { uri: 'http://localhost:3030/graphql' }})\n .then(dataProvider => this.setState({ dataProvider }));\n }\n\n render() {\n const { dataProvider } = this.state;\n\n if (!dataProvider) {\n return Loading;\n }\n\n return (\n \n \n \n );\n }\n}\n\nexport default App;\n```\n\nand my dependencies in that project are:\n\n```\n\"dependencies\": {\n \"graphql\": \"^14.1.1\",\n \"prop-types\": \"^15.7.1\",\n \"ra-data-graphql-simple\": \"^2.7.1\",\n \"ra-data-json-server\": \"^2.7.1\",\n \"ra-data-simple-rest\": \"^2.7.1\",\n \"react\": \"^16.8.1\",\n \"react-admin\": \"^2.7.1\",\n \"react-dom\": \"^16.8.1\",\n \"react-scripts\": \"2.1.5\"\n }\n```\n\nThe only way it will even send the call to the graphql server for allCountries is if there is no nesting in the Country object when the introspection query runs. I tested with it in and out multiple times to be sure. Obviously i need it in. I also thought maybe the ListGuesser was being a problem so i took that out and put in a simple CountryList component that only wanted the name... That did not help.\n\nI also looked at other related questions based around maximum call stack exceeded but i'm not sure that message is not just a red herring since whether or not the schema object was nested should be neither here nor there to the UI if it is ignoring it. i put console logs in to make sure i was not getting some endless loop (not knowing react well) and indeed i am not, and obviously since this sample code would be most peoples landing point, it must work for most.\n\nCan someone point me in the right direction here?\n\n========================================\n\nCode:\n```text\ntype Country {\ncountry_id: ID!\nname: String\nabbr2: String\nabbr3: String\nprovincesOrStates: [ProvinceState]}\n```\n\n```text\n\"dependencies\": {\n\"apollo-server\": \"^2.4.2\",\n\"dataloader-sequelize\": \"^1.7.9\",\n\"dotenv\": \"^6.2.0\",\n\"graphql\": \"^14.1.1\",\n\"graphql-import\": \"^0.7.1\",\n\"graphql-list-fields\": \"^2.0.2\",\n\"graphql-tools\": \"^4.0.4\",\n\"lodash\": \"^4.17.11\",\n\"merge-graphql-schemas\": \"^1.5.8\",\n\"pg\": \"^7.8.0\",\n\"pg-hstore\": \"^2.3.2\",\n\"save\": \"^2.3.3\",\n\"sequelize\": \"^4.42.0\"}\n```\n\n```text\nimport React, { Component } from 'react';\nimport { Admin, Resource, ListGuesser } from 'react-admin';\nimport buildGraphQLProvider from 'ra-data-graphql-simple';\n\n\nclass App extends Component {\n    constructor() {\n        super();\n        this.state = { dataProvider: null };\n    }\n    componentDidMount() {\n\n        buildGraphQLProvider({ clientOptions: { uri: 'http://localhost:3030/graphql' }})\n            .then(dataProvider => this.setState({ dataProvider }));\n    }\n\n    render() {\n        const { dataProvider } = this.state;\n\n        if (!dataProvider) {\n            return <div>Loading</div>;\n        }\n\n        return (\n            <Admin dataProvider={dataProvider}>\n                <Resource name=\"Country\" options={{ label: 'Countries' }} list={ListGuesser}/>\n            </Admin>\n        );\n    }\n}\n\nexport default App;\n```\n\n```text\n\"dependencies\": {\n    \"graphql\": \"^14.1.1\",\n    \"prop-types\": \"^15.7.1\",\n    \"ra-data-graphql-simple\": \"^2.7.1\",\n    \"ra-data-json-server\": \"^2.7.1\",\n    \"ra-data-simple-rest\": \"^2.7.1\",\n    \"react\": \"^16.8.1\",\n    \"react-admin\": \"^2.7.1\",\n    \"react-dom\": \"^16.8.1\",\n    \"react-scripts\": \"2.1.5\"\n  }\n```\n\n========================================\n\nComments:\n- Hi Greg, Thank you for sharing your experience. My company is looking at using react admin with Apollo Graph QL. I was wondering if you were able to use it or if you found something else. Thank you.\n- I absolutely did use it, for two different companies and it worked great.. if you have questions about it, go ahead and inbox me.. I’m also looking for some new work so if you have openings let me know, I spent three years working with these.. Cheers","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":182,"estimatedTokens":1406}}804{"id":"stack-47538043","source":"stackoverflow","questionId":47538043,"title":"Sequelize: TypeError: User.hasMany is not a function","tags":["javascript","node.js","postgresql","express","sequelize.js"],"text":"Title: Sequelize: TypeError: User.hasMany is not a function\nTags: javascript, node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am having this weird behavior.\nI have a User model, and a Client model. User has many Clients.\nI am using this docs: http://docs.sequelizejs.com/manual/tutorial/associations.html \n\nWhen I run the server, Sequelize throws *TypeError: User.hasMany is not a function*\n\n**Node version:** 8.9.1\n\n**Dialect:** postgres\n\n**Database version:** Postgres 10\n\n**Sequelize version:** 4.22.15 \n\nThe following files are all in the same folder \n\nuser.js model\n\n```\nconst Sequelize = require('sequelize');\nconst db = require('../index.js'); //This is an instance of new Sequelize(...)\n\nconst tableName = 'users';\n\nconst User = db.define('user', {\n firstName: {\n type: Sequelize.STRING(50),\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n lastName: {\n type: Sequelize.STRING(50),\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n username: { //Username will be the email\n type: Sequelize.STRING(80),\n allowNull: false,\n unique: true,\n validate: {\n isEmail: true\n }\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n isAdmin: {\n type: Sequelize.BOOLEAN,\n allowNull: false,\n defaultValue: false\n },\n isActive: {\n type: Sequelize.BOOLEAN,\n allowNull: false,\n defaultValue: false\n }\n\n}, { tableName });\n\nmodule.exports = User;\n```\n\nclient.js model\n\n```\n'use strict'\n\nconst Sequelize = require('sequelize');\nconst db = require('../index.js');\n\nconst instanceMethods = {\n toJSON() {\n const values = Object.assign({}, this.get());\n\n return values;\n },\n};\n\nconst Client = db.define('clients', {\n ibid: {\n type: Sequelize.BIGINT,\n allowNull: true,\n defaultValue: null\n },\n firstName: {\n type: Sequelize.STRING(50),\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n lastName: {\n type: Sequelize.STRING(50),\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n agreementSigned: {\n type: Sequelize.BOOLEAN,\n allowNull: false,\n defaultValue: false\n },\n totalBalance: {\n type: Sequelize.DECIMAL(11,2),\n allowNull: true,\n defaultValue: null\n },\n currentAllocation: {\n type: Sequelize.STRING,\n allowNull: true,\n defaultValue: null\n }\n\n}, { instanceMethods });\n\nmodule.exports = Client;\n```\n\nindex.js models\n\n```\n'use strict';\n\nconst User = require('./user')\nconst Client = require('./client');\n\nUser.hasMany(Client);\nClient.belongsTo(User);\n\nmodule.exports = {User, Client};\n```\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\nconst db = require('../index.js'); //This is an instance of new Sequelize(...)\n\nconst tableName = 'users';\n\nconst User = db.define('user', {\n  firstName: {\n    type: Sequelize.STRING(50),\n    allowNull: false,\n    validate: {\n      notEmpty: true\n    }\n  },\n  lastName: {\n    type: Sequelize.STRING(50),\n    allowNull: false,\n    validate: {\n      notEmpty: true\n    }\n  },\n  username: { //Username will be the email\n    type: Sequelize.STRING(80),\n    allowNull: false,\n    unique: true,\n    validate: {\n      isEmail: true\n    }\n  },\n  password: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    validate: {\n      notEmpty: true\n    }\n  },\n  isAdmin: {\n    type: Sequelize.BOOLEAN,\n    allowNull: false,\n    defaultValue: false\n  },\n  isActive: {\n    type: Sequelize.BOOLEAN,\n    allowNull: false,\n    defaultValue: false\n  }\n\n}, { tableName });\n\nmodule.exports = User;\n```\n\n```text\n'use strict'\n\nconst Sequelize = require('sequelize');\nconst db = require('../index.js');\n\nconst instanceMethods = {\n  toJSON() {\n    const values = Object.assign({}, this.get());\n\n    return values;\n  },\n};\n\nconst Client = db.define('clients', {\n  ibid: {\n    type: Sequelize.BIGINT,\n    allowNull: true,\n    defaultValue: null\n  },\n  firstName: {\n    type: Sequelize.STRING(50),\n    allowNull: false,\n    validate: {\n      notEmpty: true\n    }\n  },\n  lastName: {\n    type: Sequelize.STRING(50),\n    allowNull: false,\n    validate: {\n      notEmpty: true\n    }\n  },\n  agreementSigned: {\n    type: Sequelize.BOOLEAN,\n    allowNull: false,\n    defaultValue: false\n  },\n  totalBalance: {\n    type: Sequelize.DECIMAL(11,2),\n    allowNull: true,\n    defaultValue: null\n  },\n  currentAllocation: {\n    type: Sequelize.STRING,\n    allowNull: true,\n    defaultValue: null\n  }\n\n}, { instanceMethods });\n\nmodule.exports = Client;\n```\n\n```text\n'use strict';\n\nconst User = require('./user')\nconst Client = require('./client');\n\nUser.hasMany(Client);\nClient.belongsTo(User);\n\nmodule.exports = {User, Client};\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst dbconfig=require('./dbconfig.json');\n\nconst sequelize = new Sequelize('postgres://' + dbconfig.USER + \":\" +     dbconfig.PASSWORD + \"@\" + dbconfig.HOST + \":5432/\" + dbconfig.DB, {\nhost: dbconfig.HOST,\ndialect: dbconfig.DIALECT,\npool: {\n    min: 0,\n    max: 5,\n    idle: 1000\n     }\n});\n\n module.exports={sequelize};\n```\n\n```text\n'use strict'\nconst Sequelize = require('sequelize');\n\nconst sequelize=require('./sequelize_index').sequelize;\nconst db = require('./index.js');\n\nconst instanceMethods = {\n    toJSON() {\n        const values = Object.assign({}, this.get());\n\n        return values;\n    },\n};\n\nconst Client = sequelize.define('clients', {\n    ibid: {\n        type: Sequelize.BIGINT,\n        allowNull: true,\n        defaultValue: null\n    },\n    firstName: {\n        type: Sequelize.STRING(50),\n        allowNull: false,\n        validate: {\n            notEmpty: true\n        }\n    },\n    lastName: {\n        type: Sequelize.STRING(50),\n        allowNull: false,\n        validate: {\n            notEmpty: true\n        }\n    },\n    agreementSigned: {\n        type: Sequelize.BOOLEAN,\n        allowNull: false,\n        defaultValue: false\n    },\n    totalBalance: {\n        type: Sequelize.DECIMAL(11,2),\n        allowNull: true,\n        defaultValue: null\n    },\n    currentAllocation: {\n        type: Sequelize.STRING,\n        allowNull: true,\n        defaultValue: null\n    }\n\n}, { instanceMethods });\n\nmodule.exports = Client;\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst sequelize=require('./sequelize_index').sequelize;\nconst db = require('./index.js'); //This is an instance of new Sequelize(...)\n\nconst tableName = 'users';\n\nconst User = sequelize.define('user', {\n    firstName: {\n        type: Sequelize.STRING(50),\n        allowNull: false,\n        validate: {\n            notEmpty: true\n        }\n    },\n    lastName: {\n        type: Sequelize.STRING(50),\n        allowNull: false,\n        validate: {\n            notEmpty: true\n        }\n    },\n    username: { //Username will be the email\n        type: Sequelize.STRING(80),\n        allowNull: false,\n        unique: true,\n        validate: {\n            isEmail: true\n        }\n    },\n    password: {\n        type: Sequelize.STRING,\n        allowNull: false,\n        validate: {\n            notEmpty: true\n        }\n    },\n    isAdmin: {\n        type: Sequelize.BOOLEAN,\n        allowNull: false,\n        defaultValue: false\n    },\n    isActive: {\n        type: Sequelize.BOOLEAN,\n        allowNull: false,\n        defaultValue: false\n    }\n\n}, { tableName });\n\nmodule.exports = User;\n```\n\n```text\n'use strict';\nconst sequelize = require('./sequelize_index').sequelize;\nconst User = require('./user')\nconst Client = require('./client');\n\n\nUser.hasMany(Client);\nClient.belongsTo(User);\n\nsequelize.sync({force: false}).then(function () {\n    console.log(\"Database Configured\");\n});\nmodule.exports = {User, Client};\n```\n\n========================================\n\nComments:\n- In the user.js you are not exporting user `module.exports = User;`\n- @Molda I am sorry, I didn't copy the final of the file but yes, I am exporting the User model correctly\n- I would love to know any other structures to remove the circular dependency! Thanks! :)\n- @Abhisek Yadav Thanks for your reply! I can resolve this before. I realized I have to require my db before use some model (I had one auth file that uses User, and I was not including the db before). I don'l like so much that way so tomorrow I will try your way, it looks nice. Greetings!","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":417,"estimatedTokens":2032}}805{"id":"stack-60388225","source":"stackoverflow","questionId":60388225,"title":"How can I count inside nested associations in Sequelize?","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: How can I count inside nested associations in Sequelize?\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI try to count product reviews in nested associations. With the following query.\n\n```\nconst user = await User.findOne({\n where: {\n id: req.query.user\n },\n attributes: [\"id\", \"name\"],\n include: [\n {\n model: Category,\n as: \"interests\",\n attributes: [\"category_name\"],\n through: {\n attributes: []\n },\n include: [\n {\n model: Product,\n as: \"products\",\n attributes: {\n include: [\n [\n // How to count product_reviews here?\n sequelize.literal(`\n (SELECT COUNT(*) FROM product_reviews WHERE productId = Product.id)\n `),\n \"num_reviews\"\n ]\n ] \n },\n include: [\n {\n model: User,\n as: \"userReviews\",\n attributes: []\n }\n ]\n }\n ]\n }\n ]\n});\n```\n\nIn the model definitions I have a belongsTo/haveMany association set up e.g.:\n\nInside my models\n\n```\n// User model\nUser.belongsToMany(models.Category, {\n through: \"user_categories\",\n as: \"interests\",\n foreignKey: \"userId\"\n});\nUser.belongsToMany(models.Product, {\n through: \"user_reviews\",\n as: \"reviews\",\n foreignKey: \"userId\"\n});\n\n// Category model\nCategory.hasMany(models.Product, {\n foreignKey: \"categoryId\",\n as: \"products\"\n});\n\n// Product model\nProduct.belongsToMany(models.User, {\n through: \"product_reviews\",\n as: \"userReviews\",\n foreignKey: \"productId\"\n});\n\n// Product_reviews model\nproduct_review.belongsTo(models.User, { foreignKey: \"userId\" });\nproduct_review.belongsTo(models.Product, { foreignKey: \"productId\" });\n```\n\n **How to count product reviews?**\n Here the result I want.\n\n```\n{\n \"id\": 1,\n \"name\": \"John Doe\",\n \"interests\": [\n {\n \"category_name\": \"Toys\",\n \"products\": [\n {\n \"id\": 1,\n \"name\": \"Lorem Ipsum\",\n \"num_reviews\": 20 // I need to count # of reviews here\n },\n ...\n ]\n }\n ]\n}\n```\n\nCan anyone explain how to get counting inside nested associated in this case?\n\n========================================\n\nCode:\n```text\nconst user = await User.findOne({\n  where: {\n    id: req.query.user\n  },\n  attributes: [\"id\", \"name\"],\n  include: [\n    {\n      model: Category,\n      as: \"interests\",\n      attributes: [\"category_name\"],\n      through: {\n        attributes: []\n      },\n      include: [\n        {\n          model: Product,\n          as: \"products\",\n          attributes: {\n            include: [\n              [\n                // How to count product_reviews here?\n                sequelize.literal(`\n                (SELECT COUNT(*) FROM product_reviews WHERE productId = Product.id)\n                `),\n                \"num_reviews\"\n              ]\n            ] \n          },\n          include: [\n            {\n              model: User,\n              as: \"userReviews\",\n              attributes: []\n            }\n          ]\n        }\n      ]\n    }\n  ]\n});\n```\n\n```text\n// User model\nUser.belongsToMany(models.Category, {\n  through: \"user_categories\",\n  as: \"interests\",\n  foreignKey: \"userId\"\n});\nUser.belongsToMany(models.Product, {\n  through: \"user_reviews\",\n  as: \"reviews\",\n  foreignKey: \"userId\"\n});\n\n// Category model\nCategory.hasMany(models.Product, {\n  foreignKey: \"categoryId\",\n  as: \"products\"\n});\n\n// Product model\nProduct.belongsToMany(models.User, {\n  through: \"product_reviews\",\n  as: \"userReviews\",\n  foreignKey: \"productId\"\n});\n\n// Product_reviews model\nproduct_review.belongsTo(models.User, { foreignKey: \"userId\" });\nproduct_review.belongsTo(models.Product, { foreignKey: \"productId\" });\n```\n\n```text\n{\n  \"id\": 1,\n  \"name\": \"John Doe\",\n  \"interests\": [\n    {\n      \"category_name\": \"Toys\",\n      \"products\": [\n        {\n          \"id\": 1,\n          \"name\": \"Lorem Ipsum\",\n          \"num_reviews\": 20 // I need to count # of reviews here\n        },\n        ...\n      ]\n    }\n  ]\n}\n```\n\n```text\nsequelize.literal(`\n                (SELECT COUNT(*) FROM product_reviews WHERE productId = \\`products\\`.\\`id\\`)\n                `)\n```\n\n========================================\n\nComments:\n- Thanks for your time. But I got \"error\": \"Unknown column 'products.id' in 'where clause'\"\n- Big thanks!! I solved by change `Product`.`id` instead of `products`.`id`","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":218,"estimatedTokens":1021}}806{"id":"stack-45613807","source":"stackoverflow","questionId":45613807,"title":"Alter sequence in a postgreSQL DB using Sequelize","tags":["node.js","postgresql","sequelize.js","auto-increment"],"text":"Title: Alter sequence in a postgreSQL DB using Sequelize\nTags: node.js, postgresql, sequelize.js, auto-increment\nSource: Stack Overflow\n\nQuestion:\nI have a postgresql database that I need to first seed and use predetermine id, then when I create new items to the DB I want the id to auto increment. This was trivial when I was using a SQLite database. When I tried the same code with an PostgreSQL DB I find that the sequelize created IDs have started from zero and \n have ignored the seedcreated indices, resulting in a unique constraint error. \n\nI figure that this because postgresql uses a separate sequence to keep track of the increment. My approch from here was to use a raw query from sequelize to alter the sequence. But when I try to run an alter sequence query sequelize can't find sequence. I run:\n\n```\ndb.query(\"ALTER SEQUENCE COMPOUND_CPCD_seq RESTART WITH 100;\");\n```\n\nBut a error is generated and in the error message it states \"Unhandled rejection SequelizeDatabaseError: relation \"compound_cpcd_seq\" does not exist\". Is this a problem with upper and lower case letters since COMPOUND_CPCD_seq is not equal to compound_cpcd.seq? And if that is the case how do you work around that (since I have no control over how COMPOUND_CPCD_seq is created)?\n\nWhat have I missed?\n\nThe model:\n\n```\nconst COMPOUND= db.define('COMPOUND', {\n CPCD: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n unique: true,\n },\n Name: {\n type: Sequelize.STRING,\n }\n})\n```\n\n========================================\n\nTop Answer:\nI was stupid; the sequence need to be double quoted like:\n\n```\ndb.query(\"ALTER SEQUENCE \"COMPOUND_CPCD_seq\" RESTART WITH 100;\");\n```\n\n========================================\n\nCode:\n```text\ndb.query(\"ALTER SEQUENCE COMPOUND_CPCD_seq RESTART WITH 100;\");\n```\n\n```text\nconst COMPOUND= db.define('COMPOUND', {\n  CPCD: {\n  type: Sequelize.INTEGER,\n  primaryKey: true,\n  autoIncrement: true,\n  unique: true,\n },\n  Name: {\n  type: Sequelize.STRING,\n }\n})\n```\n\n```text\n''\n```\n\n```text\ndb.query(\"ALTER SEQUENCE \"COMPOUND_CPCD_seq\" RESTART WITH 100;\");\n```\n\n```js\nconst tableName = 'YourTable';\nconst sequenceColumn = 'id';\n\nmodule.exports = {\n    up: (queryInterface) => queryInterface.sequelize.transaction(async (transaction) => {\n        // Get current highest value from the table\n        const [[{ max }]] = await queryInterface.sequelize.query(`SELECT MAX(\"${sequenceColumn}\") AS max FROM public.\"${tableName}\";`, { transaction });\n        // Set the autoincrement current value to highest value + 1\n        await queryInterface.sequelize.query(`ALTER SEQUENCE public.\"${tableName}_${sequenceColumn}_seq\" RESTART WITH ${max + 1};`, { transaction });\n    }),\n    down: () => Promise.resolve(),\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":86,"estimatedTokens":683}}807{"id":"stack-52922010","source":"stackoverflow","questionId":52922010,"title":"Sequelize running migration results Cannot read property 'key' of undefined","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize running migration results Cannot read property 'key' of undefined\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI wanted to update column to set not null to false, however running db:migration fails with this error message:\n\n Cannot read property 'key' of undefined\n\nHere's the code of migration:\n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.changeColumn('Notes', 'title', {\n allowNull: false\n });\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.changeColumn('Notes', 'title', {\n allowNull: true\n });\n }\n};\n```\n\nAs followed document, it seems nothing wrong with my code.\n\nTable and field are exists, what am I wrong?\n\n========================================\n\nTop Answer:\nJust had this problem myself. From what I see in the source code Sequelize assumes you always provide the type when changing the column. I see it's also in the documentation you linked: \"Please make sure, that you are completely describing the new data type.\"\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n   return queryInterface.changeColumn('Notes', 'title', {\n     allowNull: false\n   });\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.changeColumn('Notes', 'title', {\n      allowNull: true\n    });\n  }\n};\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n  return queryInterface.changeColumn('Notes', 'title', {\n    type: Sequelize.STRING,\n    allowNull: false\n  });\n },\n\n down: (queryInterface, Sequelize) => {\n   return queryInterface.changeColumn('Notes', 'title', {\n     type: Sequelize.STRING,\n     allowNull: true\n   });\n }\n};\n```\n\n========================================\n\nComments:\n- Can you please a little detailed code? with at least handler function where you're executing this and the line/file that shows that error.\n- @RahulYadav Actually there's no more code for this. All I do is running $ sequelize db:migrate and got that error.","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":84,"estimatedTokens":524}}808{"id":"stack-29936007","source":"stackoverflow","questionId":29936007,"title":"Adding limit to sequelize findAll destroys the query?","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Adding limit to sequelize findAll destroys the query?\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to return a group of `Model`s, paginated using `limit` and `offset`, including the grouped count of that model's favorites. A fairly trivial thing to attempt.\n\nHere's my basic query setup with sequelize:\n\n```\nvar perPage = 12;\nvar page = 1;\n\nreturn Model.findAll({\n\n group: [ 'model.id', 'favorites.id' ],\n attributes: [\n '*',\n [ Sequelize.fn('count', Sequelize.col('favorites.id')), 'favorites_count' ]\n ],\n include: [\n { attributes: [], model: Favorite },\n ],\n offset: perPage * page\n```\n\nThis generates the (fairly) expected query:\n\n```\nSELECT \"model\".\"id\",\n \"model\".*,\n Count(\"favorites\".\"id\") AS \"favorites_count\",\n \"favorites\".\"id\" AS \"favorites.id\"\nFROM \"model\" AS \"model\"\nLEFT OUTER JOIN \"favorite\" AS \"favorites\"\nON \"model\".\"id\" = \"favorites\".\"model_id\"\nGROUP BY \"model\".\"id\",\n \"favorites\".\"id\" offset 12;\n```\n\nIgnoring the fact that it quotes the tables, and that it selects `favorites.id` (forcing me to add it to the group by clause), and that it has randomly aliased things to their exact name or to a nonsensical name like `\"favorites.id\"` (all undesired), it seems to have worked. But now let's complete the pagination and add the limit to the query:\n\n```\n...\noffset: perPage * page\nlimit: perPage\n```\n\nIt now generates this query:\n\n```\nSELECT \"model\".*,\n \"favorites\".\"id\" AS \"favorites.id\"\nFROM (SELECT \"model\".\"id\",\n \"model\".*,\n Count(\"favorites\".\"id\") AS \"favorites_count\"\n FROM \"model\" AS \"model\"\n GROUP BY \"model\".\"id\",\n \"favorites\".\"id\"\n LIMIT 12 offset 12) AS \"model\"\n LEFT OUTER JOIN \"favorite\" AS \"favorites\"\n ON \"model\".\"id\" = \"favorites\".\"model\";\n```\n\nIn completely baffling behavior, it has generated an inner query and applied the limit only to that, then aliased that as `\"model\"`.\n\nAs a sanity check I looked in the docs for findAll, but the docs do not seem to think that command exists.\n\nI suspect I am doing something wrong, but I can't figure out what it is. This behavior is quite bizzarre, and I'm hoping my sleep deprivation is the cause of my confusion. \n\nI'm using version `2.0.6`\n\n========================================\n\nCode:\n```text\nvar perPage = 12;\nvar page = 1;\n\nreturn Model.findAll({\n\n    group: [ 'model.id', 'favorites.id' ],\n    attributes: [\n        '*',\n        [ Sequelize.fn('count', Sequelize.col('favorites.id')), 'favorites_count' ]\n    ],\n    include: [\n        { attributes: [], model: Favorite },\n    ],\n    offset: perPage * page\n```\n\n```text\nSELECT          \"model\".\"id\",\n                \"model\".*,\n                Count(\"favorites\".\"id\") AS \"favorites_count\",\n                \"favorites\".\"id\"        AS \"favorites.id\"\nFROM            \"model\"                 AS \"model\"\nLEFT OUTER JOIN \"favorite\"              AS \"favorites\"\nON              \"model\".\"id\" = \"favorites\".\"model_id\"\nGROUP BY        \"model\".\"id\",\n                \"favorites\".\"id\" offset 12;\n```\n\n```text\n...\noffset: perPage * page\nlimit: perPage\n```\n\n```text\nSELECT \"model\".*,\n    \"favorites\".\"id\" AS \"favorites.id\"\nFROM   (SELECT \"model\".\"id\",\n            \"model\".*,\n            Count(\"favorites\".\"id\") AS \"favorites_count\"\n        FROM   \"model\" AS \"model\"\n        GROUP  BY \"model\".\"id\",\n                \"favorites\".\"id\"\n        LIMIT  12 offset 12) AS \"model\"\n    LEFT OUTER JOIN \"favorite\" AS \"favorites\"\n                    ON \"model\".\"id\" = \"favorites\".\"model\";\n```\n\n```text\nModel\n```\n\n```text\nlimit\n```\n\n```text\noffset\n```\n\n```text\nfavorites.id\n```\n\n```text\n\"favorites.id\"\n```\n\n```text\n\"model\"\n```\n\n```text\n2.0.6\n```\n\n========================================\n\nComments:\n- The command does exist in docs docs.sequelizejs.com/en/latest/docs/models/ but in readthedocs.org\n- Note: that the search in docs seems to be case-sensitive","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":157,"estimatedTokens":952}}809{"id":"stack-30005751","source":"stackoverflow","questionId":30005751,"title":"sequelize belongsToMany giving TypeError: undefined is not a function","tags":["node.js","express","sequelize.js"],"text":"Title: sequelize belongsToMany giving TypeError: undefined is not a function\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize with express, I have defined my model like this\n\n```\n\"use strict\";\n\nvar Sequelize = require('sequelize');\nmodule.exports = function(sequelize, DataTypes) {\n var Order = sequelize.define(\"Order\",\n {\n status: {\n type: Sequelize.INTEGER\n },\n notes: {\n type: Sequelize.STRING\n }\n },\n {\n classMethods: {\n associate: function(models) {\n Order.belongsTo(models.User);\n Order.belongsTo(models.Address);\n\n Order.belongsToMany(models.Items);\n }\n }\n }\n\n );\n return Order;\n}\n```\n\nI am getting following error message when trying to run my app\n\n```\nOrder.belongsToMany(models.Items );\n ^\nTypeError: undefined is not a function\nat sequelize.define.classMethods.associate (models/order.js:18:7)\nat models/index.js:24:19\nat Array.forEach (native)\nat Object. (models/index.js:22:17)\nat Module._compile (module.js:460:26)\nat Object.Module._extensions..js (module.js:478:10)\nat Module.load (module.js:355:32)\nat Function.Module._load (module.js:310:12)\nat Module.require (module.js:365:17)\nat require (module.js:384:17)\n```\n\nMy index.js file is same as one given is express example here: https://github.com/sequelize/express-example/blob/master/models/index.js\n\nMy item model looks like this:\n\n```\n\"use strict\";\n\nvar Sequelize = require('sequelize');\nmodule.exports = function(sequelize, DataTypes) {\n var Item = sequelize.define(\"Item\", {\n title: {\n type: Sequelize.STRING\n },\n mrp: {\n type: Sequelize.DECIMAL,\n allowNull: false\n },\n sp: {\n type: Sequelize.DECIMAL,\n allowNull: false\n },\n desc: {\n type: Sequelize.STRING\n },\n skuId: {\n type: Sequelize.STRING,\n allowNull: false\n },\n type: {\n type: Sequelize.STRING\n },\n merchantId: {\n type: Sequelize.STRING,\n allowNull: false\n },\n categoryId: {\n type: Sequelize.STRING,\n allowNull: false\n }\n }\n );\n return Item;\n}\n```\n\nI have also tried giving belongsToMany in app.js but it does not work. All other associations are working correctly.\nPlease help.\n\n========================================\n\nCode:\n```text\n\"use strict\";\n\nvar Sequelize = require('sequelize');\nmodule.exports = function(sequelize, DataTypes) {\n    var Order = sequelize.define(\"Order\",\n        {\n            status: {\n                type: Sequelize.INTEGER\n            },\n            notes: {\n                type: Sequelize.STRING\n            }\n        },\n        {\n            classMethods: {\n                associate: function(models) {\n                    Order.belongsTo(models.User);\n                    Order.belongsTo(models.Address);\n\n                    Order.belongsToMany(models.Items);\n                }\n            }\n        }\n\n    );\n    return Order;\n}\n```\n\n```text\nOrder.belongsToMany(models.Items );\n     ^\nTypeError: undefined is not a function\nat sequelize.define.classMethods.associate (models/order.js:18:7)\nat models/index.js:24:19\nat Array.forEach (native)\nat Object. (models/index.js:22:17)\nat Module._compile (module.js:460:26)\nat Object.Module._extensions..js (module.js:478:10)\nat Module.load (module.js:355:32)\nat Function.Module._load (module.js:310:12)\nat Module.require (module.js:365:17)\nat require (module.js:384:17)\n```\n\n```text\n\"use strict\";\n\nvar Sequelize = require('sequelize');\nmodule.exports = function(sequelize, DataTypes) {\n  var Item = sequelize.define(\"Item\", {\n      title: {\n        type: Sequelize.STRING\n      },\n      mrp: {\n        type: Sequelize.DECIMAL,\n        allowNull: false\n      },\n      sp: {\n        type: Sequelize.DECIMAL,\n        allowNull: false\n      },\n      desc: {\n        type: Sequelize.STRING\n      },\n      skuId: {\n        type: Sequelize.STRING,\n        allowNull: false\n      },\n      type: {\n        type: Sequelize.STRING\n      },\n      merchantId: {\n        type: Sequelize.STRING,\n        allowNull: false\n      },\n      categoryId: {\n        type: Sequelize.STRING,\n        allowNull: false\n      }\n    }\n  );\n  return Item;\n}\n```\n\n```text\nOrder.belongsToMany(models.Item);\n```\n\n```text\nOrder.belongsToMany(models.Item, {\n    through: 'OrderItems'\n});\n```\n\n```text\nItem\n```\n\n```text\nItems\n```\n\n```text\nthrough\n```\n\n```text\nbelongsToMany\n```\n\n```text\nbelongsToMany\n```\n\n========================================\n\nComments:\n- What version of sequelize are you using? How are you calling `associate` ?\n- Version is sequelize@2.0.0-rc1, associate gets called from index.js which is same as github.com/sequelize/express-example/blob/master/models/&hellip;\n- Hmm, orders.js looks fine to me. Can you post your code for `Items`?\n- added item model code\n- Still the same error :( .. I dont know why just belongsToMany doesn't work while all other associations are working.\n- I've actually cloned the repo and gotten your code to work on my end with the typo fix. I'm not sure what to say. You could try attaching a debugger (eg `node-inspector`) to confirm that the line number of the reported error is correct, and also verify that `Order` and `Order.belongsToMany` are defined as expected.\n- Note also that in the sample there's a `Task.belongsToMany(models.User);` that appears to work. I'd recommend also trying to understand where the differences are between your `Order` and the sample's `Task` model.\n- Incidentally my version of sequelize is older than the current version that gets downloaded through npm. I upgraded sequelize and it worked. Thanks ..","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":234,"estimatedTokens":1351}}810{"id":"stack-18291476","source":"stackoverflow","questionId":18291476,"title":"connect sequelize.js to node-webkit desktop app using sqlite","tags":["javascript","angularjs","sqlite","sequelize.js","node-webkit"],"text":"Title: connect sequelize.js to node-webkit desktop app using sqlite\nTags: javascript, angularjs, sqlite, sequelize.js, node-webkit\nSource: Stack Overflow\n\nQuestion:\ncurrently I am using node-sqlite3 sqlite binding on my node-webkit desktop app and using it as\n\n```\nvar sqlite3 = require('node_sqlite3').verbose();\nvar db = new sqlite3.Database('file:data.db');\ndb.run(query);\n```\n\nand on my knowledge this natively compiled node-sqlite3 is the only way to use sqlite db with node-webkit.\n\nnow I want to use sequelize on the app which is normally used as:\n\n```\nvar Sequelize = require('sequelize-sqlite').sequelize\nvar sqlite = require('sequelize-sqlite').sqlite\nvar sequelize = new Sequelize('database', 'username', 'password', {\ndialect: 'sqlite',\nstorage: 'path/to/database.sqlite'\n})\nsequelize.query(\"SELECT * FROM myTable\").success(function(myTableRows) {\nconsole.log(myTableRows)\n})\n```\n\nhow can I achieve this ? (ie. use sequelize on node-webkit app with sqlite)\n\nthe goal is to make the database life easier by running migrations , use models to manipulate database , or suggest if there are any other javascript libraries (mvc is prefered) , which can work through node-webkit+sqlite (and how to make them work) .\n\nis angularjs an option ? if yes how to do this. \n\nthank yous.\n\n========================================\n\nTop Answer:\nI also had a problem connecting to SQLite database from `node-webkit` using `sequelize`. By trial and error, I have come with the following solution.\n\n```\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('sqlite:mydb.sqlite3', {\n dialect: 'sqlite',\n storage: './mydb.sqlite3'\n});\n\nsequelize.query(\"SELECT * FROM tableName\", { type: db.QueryTypes.SELECT })\n.then(function(result) {\n console.log(result);\n})\n.catch(function (e) {\n console.log(e);\n});\n```\n\nNote that for SQLite database you have to specify\n\n```\nstorage: './mydb.sqlite3'\n```\n\nThis is the path to your db file. It can be either absolute path or relative. `./` means project root folder where `package.json` is located.\n\nAlso, the connection string must contain the `sqlite:` prefix. Otherwise, it will raise an exception: `Cannot read property 'replace' of null`. The part after `sqlite:` prefix is irrevelant and can even be omitted because the actual db location is specified in `storage` option. `dialect` option can be omitted as well, since db type is mentioned in the connection string prefix. So you can connect simply using\n\n```\nvar sequelize = new Sequelize('sqlite:', {\n storage: './mydb.sqlite3'\n});\n```\n\nIt is also worth noting that `.success` and `.error` methods are deprecated. At the time of writing this post, the latest version of Sequelize (3.21) uses `.then` method to handle operations if the promise is fulfilled and `.catch` method if the promise is rejected.\n\n========================================\n\nCode:\n```text\nvar sqlite3 = require('node_sqlite3').verbose();\nvar db = new sqlite3.Database('file:data.db');\ndb.run(query);\n```\n\n```text\nvar Sequelize = require('sequelize-sqlite').sequelize\nvar sqlite    = require('sequelize-sqlite').sqlite\nvar sequelize = new Sequelize('database', 'username', 'password', {\ndialect: 'sqlite',\nstorage: 'path/to/database.sqlite'\n})\nsequelize.query(\"SELECT * FROM myTable\").success(function(myTableRows) {\nconsole.log(myTableRows)\n})\n```\n\n```text\nvar Sequelize = require('sequelize-sqlite').sequelize\nvar sqlite    = require('sequelize-sqlite').sqlite\n\nvar sequelize = new Sequelize('database', 'username', '', {\ndialect: 'sqlite',\nstorage: 'file:data.db'\n})\n\nvar Record = sequelize.define('Record', {\nname: Sequelize.STRING,\nquantity: Sequelize.INTEGER\n})\n\nsequelize.sync()\n.success(function(){\nconsole.log('synced')\n})\n\nvar rec = Record.build({ name: \"sunny\", quantity: 3 });\nrec.save()\n.error(function(err) {\n// error callback\nalert('somethings wrong')\n})\n.success(function() {\n// success callback\nconsole.log('inserted')\n});\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('sqlite:mydb.sqlite3', {\n  dialect: 'sqlite',\n  storage: './mydb.sqlite3'\n});\n\nsequelize.query(\"SELECT * FROM tableName\", { type: db.QueryTypes.SELECT })\n.then(function(result) {\n  console.log(result);\n})\n.catch(function (e) {\n  console.log(e);\n});\n```\n\n```text\nstorage: './mydb.sqlite3'\n```\n\n```text\nvar sequelize = new Sequelize('sqlite:', {\n  storage: './mydb.sqlite3'\n});\n```\n\n```text\nnode-webkit\n```\n\n```text\nsequelize\n```\n\n```text\n./\n```\n\n```text\npackage.json\n```\n\n```text\nsqlite:\n```\n\n```text\nCannot read property 'replace' of null\n```\n\n```text\nsqlite:\n```\n\n```text\nstorage\n```\n\n```text\ndialect\n```\n\n```text\n.success\n```\n\n```text\n.error\n```\n\n```text\n.then\n```\n\n```text\n.catch\n```\n\n========================================\n\nComments:\n- I can use node-sqlite3 only because I already have build it by node-gyp and I am already using sequelize-sqlite as says the question . thank you for the answer anyway .\n- I'm doing a similar project, using Sequelize+sqlite3 in a node-webkit application. In regards to defining the `sequelize` instance, what's the relative path for the `storage` option? Where, relative to the app root (`package.json` and `index.html`) does the database go?\n- @MikeTrpcic I am still developing the app so currently sqlite db is inside the app folder but it must go outside the compressed app once it is complete , couldn't figure it out yet , will surely if i find a way.\n- I did what you said and I'm getting this error =S `\"Uncaught Error: Cannot find module '.&#47;binding&#47;Release&#47;node-v11-darwin-ia32&#47;node_sqlite3.node'\", source: module.js (343)`Any ideas?","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":213,"estimatedTokens":1398}}811{"id":"stack-36899235","source":"stackoverflow","questionId":36899235,"title":"Sequelize: Error trying to nested association","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize: Error trying to nested association\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHello i'm new with Sequelize and i'm really lost about how to manage relations. I want to set 1:N relation but when I see the results I'm not receiving the relation data. I'm working with 2 tables at this moment, `medicos` and `hospitals` where `hospitals` can have many `doctors` but `doctors` only has one `hospital`. \n\nThis is my `doctors` table: `models/doctors.js`\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('doctors', {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n lastName: {\n type: DataTypes.STRING,\n allowNull: false\n },\n SSN: {\n type: DataTypes.STRING,\n allowNull: false\n },\n speciality: {\n type: DataTypes.ENUM('Doctor','Geriatrician'),\n allowNull: false\n },\n idHospital: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n },\n }, {\n tableName: 'doctors',\n freezeTableName: true,\n classMethods: {\n associate: models => {\n models.doctors.belongsTo(models.hospitals, {\n foreignKey: \"idHospital\"\n })\n }\n }\n });\n });\n };\n```\n\nand this one is `hospitals` one: `models/hospitals.js`\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('hospitals', {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n idData: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'data',\n key: 'id'\n }\n },\n }, {\n tableName: 'hospitals',\n freezeTableName: true,\n classMethods: {\n associate: models => {\n models.hospitals.hasMany(models.doctors, {\n foreignKey: \"idHospital\"\n })\n }\n }\n });\n};\n```\n\nIm managing my models with this file `models/index.js`\n\n'use strict'\n\n```\nmodule.exports = (connection) => {\n const Users = connection.import('users'),\n States = connection.import('states'),\n Cities = connection.import('cities'),\n Data = connection.import('data'),\n Patient = connection.import('patients'),\n Hospitals = connection.import('hospitals'),\n Doctors = connection.import('doctors'),\n\n Doctors.belongsTo(Hospitals)\n Hospitals.hasMany(Doctors)\n require('../controllers/patients')(Users)\n require('../controllers/personal')(Doctors, Hospitals)\n}\n```\n\nthis one is my `controller` `/controllers/personal.js`\n\n```\n'use strict'\n\nmodule.exports = (Doctors) => {\n\n const express = require('express'),\n router = express.Router()\n router\n .get('/', (req, res) => {\n Doctors.findAll({ include: [{ model: Hospitals, include: [Doctors], }], }).then((Doctors) => console.log(Doctors));\n })\n```\n\nand my main `index`\n\n```\n'use strict'\n\nconst express = require('express'),\n path = require('path'),\n bodyParser = require('body-parser'),\n Sequelize = require('sequelize'),\n port = process.env.PORT || 3000,\n app = express(),\n connection = new Sequelize('Matadero', 'root', 'root');\n\napp.use(bodyParser.json())\napp.use(bodyParser.urlencoded({extended:true}))\n\napp.set('view engine', 'ejs')\napp.set('views', path.resolve(__dirname, 'client', 'views'))\n\napp.use(express.static(path.resolve(__dirname, 'client')))\n\napp.get('/', (req, res) => {\n res.render('admin/index.ejs')\n})\n\nconst onListening = () => console.log(`Successful connection at port: ${port}`)\n\nrequire('./models')(connection)\n\napp.listen(port, onListening)\n\nconst patients = require('./controllers/patients'),\n personal = require('./controllers/personal')\n\napp.use('/api/patients', patients)\napp.use('/api/personal', personal)\n```\n\nThe error i'm getting: `Unhandled rejection Error: hospitals is not associated to doctors!`\n\n========================================\n\nTop Answer:\nDid you try this?\n\n```\nDoctors.findAll({ include: Hospitals, });\n```\n\nTo fetch medicos as well:\n\n```\nDoctors.findAll({ include: [{ model: Hospitals, include: [Medicos], }], });\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n      return sequelize.define('doctors', {\n        id: {\n          type: DataTypes.INTEGER(11),\n          allowNull: false,\n          primaryKey: true,\n          autoIncrement: true\n        },\n        name: {\n          type: DataTypes.STRING,\n          allowNull: false\n        },\n        lastName: {\n          type: DataTypes.STRING,\n          allowNull: false\n        },\n        SSN: {\n          type: DataTypes.STRING,\n          allowNull: false\n        },\n        speciality: {\n          type: DataTypes.ENUM('Doctor','Geriatrician'),\n          allowNull: false\n        },\n        idHospital: {\n          type: DataTypes.INTEGER(11),\n          allowNull: false,\n        },\n      }, {\n        tableName: 'doctors',\n        freezeTableName: true,\n        classMethods: {\n          associate: models =>  {\n            models.doctors.belongsTo(models.hospitals,  {\n              foreignKey: \"idHospital\"\n            })\n         }\n       }\n  });\n      });\n    };\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('hospitals', {\n    id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    idData: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      references: {\n        model: 'data',\n        key: 'id'\n      }\n    },\n  }, {\n    tableName: 'hospitals',\n    freezeTableName: true,\n    classMethods: {\n      associate: models =>  {\n      models.hospitals.hasMany(models.doctors,  {\n         foreignKey: \"idHospital\"\n      })\n    }\n  }\n  });\n};\n```\n\n```text\nmodule.exports = (connection) => {\n  const Users                     = connection.import('users'),\n        States                    = connection.import('states'),\n        Cities                    = connection.import('cities'),\n        Data                      = connection.import('data'),\n        Patient                   = connection.import('patients'),\n        Hospitals                 = connection.import('hospitals'),\n        Doctors                   = connection.import('doctors'),\n\n\n        Doctors.belongsTo(Hospitals)\n        Hospitals.hasMany(Doctors)\n        require('../controllers/patients')(Users)\n        require('../controllers/personal')(Doctors, Hospitals)\n}\n```\n\n```text\n'use strict'\n\nmodule.exports = (Doctors) =>  {\n\n  const express   = require('express'),\n        router    = express.Router()\n  router\n  .get('/', (req, res) => {\n    Doctors.findAll({ include: [{ model: Hospitals, include: [Doctors], }], }).then((Doctors) => console.log(Doctors));\n  })\n```\n\n```text\n'use strict'\n\nconst express       = require('express'),\n      path          = require('path'),\n      bodyParser    = require('body-parser'),\n      Sequelize     = require('sequelize'),\n      port          = process.env.PORT || 3000,\n      app           = express(),\n      connection    = new Sequelize('Matadero', 'root', 'root');\n\napp.use(bodyParser.json())\napp.use(bodyParser.urlencoded({extended:true}))\n\napp.set('view engine', 'ejs')\napp.set('views', path.resolve(__dirname, 'client', 'views'))\n\napp.use(express.static(path.resolve(__dirname, 'client')))\n\napp.get('/', (req, res) =>  {\n  res.render('admin/index.ejs')\n})\n\nconst onListening = () => console.log(`Successful connection at port: ${port}`)\n\n\n\nrequire('./models')(connection)\n\napp.listen(port, onListening)\n\nconst patients   = require('./controllers/patients'),\n      personal    = require('./controllers/personal')\n\n\napp.use('/api/patients', patients)\napp.use('/api/personal', personal)\n```\n\n```text\nmedicos\n```\n\n```text\nhospitals\n```\n\n```text\nhospitals\n```\n\n```text\ndoctors\n```\n\n```text\ndoctors\n```\n\n```text\nhospital\n```\n\n```text\ndoctors\n```\n\n```text\nmodels/doctors.js\n```\n\n```text\nhospitals\n```\n\n```text\nmodels/hospitals.js\n```\n\n```text\nmodels/index.js\n```\n\n```text\ncontroller\n```\n\n```text\n/controllers/personal.js\n```\n\n```text\nindex\n```\n\n```text\nUnhandled rejection Error: hospitals is not associated to doctors!\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var doctors = sequelize.define('doctors', {\n    id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    lastName: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    SSN: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    idData: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      references: { // I'd recommend using the associate functions instead of creating references on the property, only causes confusion from my experience.\n        model: 'data',\n        key: 'id'\n      }\n    },\n    speciality: {\n      type: DataTypes.ENUM('Doctor','Geriatrician'),\n      allowNull: false\n    },\n    // This is the foreignKey property which is referenced in the associate function on BOTH models.\n    idHospital: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false // Using allowNull makes this relationship required, on your model, a doctor can't exist without a hospital.\n    },\n  }, {\n    tableName: 'doctor',\n    freezeTableName: true,\n    classMethods: {\n      associate: models =>  {\n        doctors.belongsTo(models.hospitals, {\n          foreignKey: \"idHospital\"\n        })\n      }\n    }\n  });\n\n  return doctors;\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n  var hospital = sequelize.define('hospitals', {\n    id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    idData: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      references: {\n        model: 'data',\n        key: 'id'\n      }\n    },\n  }, {\n    tableName: 'hospitals',\n    freezeTableName: true,\n    classMethods: {\n        associate: models => {\n            hospital.hasMany(models.doctors, {\n                foreignKey: 'idHospital'\n            }\n        }\n    }\n  });\n\n  return hospital;\n};\n```\n\n```text\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar Sequelize = require(\"sequelize\");\n\nmodule.exports = (connection) => {\n    var models = {};\n\n    // Here we read in all the model files in your models folder.\n    fs\n        // This assumes this file is in the same folder as all your\n        // models. Then you can simply do require('./modelfoldername')\n        // to get all your models.\n        .readdirSync(__dirname)\n        // We don't want to read this file if it's in the folder. This\n        // assumes it's called index.js and removes any files with    \n        // that name from the array.\n        .filter(function (file) {\n            return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n        })\n        // Go through each file and import it into sequelize.\n        .forEach(function (file) {\n            var model = connection.import(path.join(__dirname, file));\n            models[model.name] = model;\n        });\n\n    // For each model we run the associate function on it so that sequelize\n    // knows that they are associated.\n    Object.keys(models).forEach(function (modelName) {\n        if (\"associate\" in models[modelName]) {\n            models[modelName].associate(models);\n        }\n    });\n\n    models.connection = connection;\n    models.Sequelize = Sequelize;\n\n    return models\n}\n```\n\n```text\nDoctors.findAll({ include: Hospitals, });\n```\n\n```text\nDoctors.findAll({ include: [{ model: Hospitals, include: [Medicos], }], });\n```\n\n========================================\n\nComments:\n- Yeah, but i'm getting this error Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'doctors.hospitaleId' in 'field list' at Query.formatError\n- I think it's because you need to define a relationship from `Hospital` to `Doctor`. In sequelize all relationships should be defined both ways.\n- Still not working. :( I just updated my code. This is the error i'm getting `Unhandled rejection Error: hospitals is not associated to doctors!`\n- Thank you so much, Mr. GrimurD. You helped me a lot! Your answer is correct, I just had to add some stuff `Hospitals.hasMany(Doctors, {foreignKey: \"idHospital\"}) Doctors.belongsTo(Hospitals, {as: \"Hospitals\", foreignKey: \"idHospital\"})` If I no bother you, I would like if you add to your answer and of course, you got the bounty. :)\n- @CanKerDiAlike glad it worked. My code examples combined should have worked though, dont understand why you had to add these extra lines. Oh well it works now either way :)\n- ohhh, because it was looking for another id camp named HospitalID and I had to set manually by writing that. And yeah, I had like a week crying because didnt know how to do that. You saved my life.","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":540,"estimatedTokens":3214}}812{"id":"stack-28546885","source":"stackoverflow","questionId":28546885,"title":"Does sequelize have any change tracking built-in mechanism?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Does sequelize have any change tracking built-in mechanism?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI was wondering whether sequelize implements (or plans to implement) any change tracking mechanism, which goal would be to avoid running unnecessary queries. For example:\n\n```\nvar user = sequelize.User.find { where: { name: 'bob' } };\n\nuser.name = 'john';\nuser.save();\n```\n\nThe sequelize will of course update the username. Now, imagine that the assignment is missing.\n\n```\nvar user = sequelize.User.find { where: { name: 'bob' } };\n\nuser.save();\n```\n\nIs sequelize smart enough to figure it out that no database update is needed (and won't do one)? Is there any flag exposed by the sequelize object to see whether any changes were done to the model?\n\nOr should I simply test by hand each property against the original model?\n\nI have noticed an user._previousDataValues and user.options.isDirty properties on the sequelize model, but I am not sure what is their purpose and whether I should rely my code on those in any way.\n\n========================================\n\nCode:\n```text\nvar user = sequelize.User.find { where: { name: 'bob' } };\n\nuser.name = 'john';\nuser.save();\n```\n\n```text\nvar user = sequelize.User.find { where: { name: 'bob' } };\n\nuser.save();\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":43,"estimatedTokens":326}}813{"id":"stack-20017334","source":"stackoverflow","questionId":20017334,"title":"Node.js sequelize embed hasMany IDs","tags":["node.js","ember.js","ember-data","sequelize.js"],"text":"Title: Node.js sequelize embed hasMany IDs\nTags: node.js, ember.js, ember-data, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am experimenting with a Ember app using ember-data and a node.js backend serving data from MySQL using Sequelize.js.\n\nMy problem:\nIf I have a Comment model associated to a Post model through hasMany the expected JSON by ember-data looks like\n\n```\n{\n \"post\": {\n \"comment_ids\": [1, 2, 3]\n }\n}\n```\n\nWhat would be the best way to query / generate this JSON without expensive loops etc. using sequelize?\n\nThe Comment model has a foreign key with the post_id.\n\n========================================\n\nTop Answer:\nI'd suggest passing the buck to the client. You can set up a custom serializer client side that reformats the data into the expected format for ED. Additionally ED is expecting it in this format:\n\n```\n{\n \"post\": {\n \"comments\": [1, 2, 3]\n }\n}\n\nApp.Post = DS.Model.extend({\n comments = DS.hasMany('comment')\n});\n```\n\nor if you choose to include the comments in the response\n\n```\n{\n \"post\": {\n \"id\": 1\n \"title\": \"Rails is omakase\",\n \"comments\": [\"1\", \"2\"],\n \"_links\": {\n \"user\": \"/people/dhh\"\n },\n },\n\n \"comments\": [{\n \"id\": \"1\",\n \"body\": \"Rails is unagi\"\n }, {\n \"id\": \"2\",\n \"body\": \"Omakase O_o\"\n }]\n}\n```\n\nYou can read more about it here: https://github.com/emberjs/data/blob/master/TRANSITION.md\n\nAt some point, someone is going to have to loop (or iterate) and it isn't an uncommon practice to iterate through your result set to build up your response (or serialize your response client side).\n\n========================================\n\nCode:\n```text\n{\n  \"post\": {\n    \"comment_ids\": [1, 2, 3]\n  }\n}\n```\n\n```text\n// include comments\nPost.all({\n  where: \"..\",\n  include: [Comment]\n}).success(function(posts) {\n  // collect IDs\n  _.each(posts, function(element) {\n    element[\"comments\"] = _.pluck(element.comments, 'id');\n  });\n});\n```\n\n```text\n{\n   \"post\": {\n     \"comments\": [1, 2, 3]\n   }\n}\n\nApp.Post = DS.Model.extend({\n   comments = DS.hasMany('comment')\n});\n```\n\n```text\n{\n \"post\": {\n   \"id\": 1\n   \"title\": \"Rails is omakase\",\n   \"comments\": [\"1\", \"2\"],\n   \"_links\": {\n      \"user\": \"/people/dhh\"\n   },\n },\n\n \"comments\": [{\n   \"id\": \"1\",\n   \"body\": \"Rails is unagi\"\n  }, {\n   \"id\": \"2\",\n   \"body\": \"Omakase O_o\"\n  }]\n}\n```\n\n========================================\n\nComments:\n- Thanks for your answer. What I was looking for is a nice way to utilize sequelize to do some kind of join to add in the comment IDs\n- Where did artists come from?\n- @freakTheMighty edited - should be posts which is passed to the callback","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":129,"estimatedTokens":640}}814{"id":"stack-68565903","source":"stackoverflow","questionId":68565903,"title":"Sequelize findAndCountAll pagination issue","tags":["javascript","sequelize.js"],"text":"Title: Sequelize findAndCountAll pagination issue\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen using `findAndCountAll` with a limit and offset, I get only (for example) 8 rows per page instead of 10.\n\nHere's what I'm using to paginate results (10 per page):\n\n```\nasync function allPlayers(req, res) {\n const page = parseInt(req.query.page);\n const perPage = parseInt(req.query.perPage);\n\n const options = {\n where: {\n [Op.and]: [\n {\n type: \"player\",\n },\n {\n \"$teams.team.type$\": \"club\",\n },\n ],\n },\n include: [\n {\n model: UserTeam,\n duplicating: false,\n required: true,\n include: [\n {\n model: Team,\n include: [{ model: Club }, { model: School }],\n },\n ],\n },\n ],\n };\n\n const { rows, count } = await User.findAndCountAll({\n ...options,\n limit: perPage,\n offset: perPage * (page - 1),\n });\n\n res.json({ data: { rows, count } });\n}\n```\n\nThe issue seems to be Sequelize filtering out the rows when returned from SQL, instead of in the query. This happens because of this segment in the find options query:\n\n```\n{\n model: UserTeam,\n duplicating: false,\n required: true,\n include: [...],\n}\n```\n\nBecause of that, instead of returning 10 per paginated page, it's returning 10 or less (depending if any rows were filtered out).\n\nIs there a fix for this behaviour or a different way to re-structure my data so I don't need this nested query?\n\nI need this because I have a database/model structure like this:\n\n```\nUser (players, coaches, admins, etc.)\n |\n |_ UserTeam (pivot table containing userId and teamId)\n |\n |_ Team\n```\n\n========================================\n\nTop Answer:\nLet try this function bro\n\n```\npaginate: ({\n currentPage,\n pageSize\n }) => {\n const offset = parseInt((currentPage - 1) * pageSize, 10);\n const limit = parseInt(pageSize, 10);\n return {\n offset,\n limit,\n };\n },\n\n // import function here\n const result = await city.findAndCountAll({\n where: conditions,\n order: [\n ['createdAt', 'DESC']\n ],\n ...paginate({\n currentPage: page,\n pageSize: limit\n }),\n })\n```\n\nhttps://i.sstatic.net/ipADt.png\n\n========================================\n\nCode:\n```js\nasync function allPlayers(req, res) {\n  const page = parseInt(req.query.page);\n  const perPage = parseInt(req.query.perPage);\n\n  const options = {\n    where: {\n      [Op.and]: [\n        {\n          type: \"player\",\n        },\n        {\n          \"$teams.team.type$\": \"club\",\n        },\n      ],\n    },\n    include: [\n      {\n        model: UserTeam,\n        duplicating: false,\n        required: true,\n        include: [\n          {\n            model: Team,\n            include: [{ model: Club }, { model: School }],\n          },\n        ],\n      },\n    ],\n  };\n\n  const { rows, count } = await User.findAndCountAll({\n    ...options,\n    limit: perPage,\n    offset: perPage * (page - 1),\n  });\n\n  res.json({ data: { rows, count } });\n}\n```\n\n```js\n{\n  model: UserTeam,\n  duplicating: false,\n  required: true,\n  include: [...],\n}\n```\n\n```text\nUser (players, coaches, admins, etc.)\n  |\n  |_ UserTeam (pivot table containing userId and teamId)\n    |\n    |_ Team\n```\n\n```text\nfindAndCountAll\n```\n\n```js\nconst { DataTypes } = require('sequelize')\n    const sequelize = require('./../config/db')\n    const User = require('./User')\n    const Team = require('./Team')\n    \n    const UserTeam = sequelize.define('userTeam', {\n      id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true,\n        autoIncrement: true,\n        allowNull: false\n      },\n      teamId: {\n        type: DataTypes.UUID,\n        allowNull: false,\n        unique: false,\n        onDelete: 'CASCADE',\n        references: {\n          model: Team,\n          key: 'id'\n        },\n        validate: {\n          isUUID: {\n            args: 4,\n            msg: 'Team ID must be a UUID4 string.'\n          }\n        }\n      },\n      userId: {\n        type: DataTypes.UUID,\n        allowNull: false,\n        unique: false,\n        onDelete: 'CASCADE',\n        references: {\n          model: User,\n          key: 'id'\n        },\n        validate: {\n          isUUID: {\n            args: 4,\n            msg: 'User ID must be a UUID4 string.'\n          }\n        }\n      },\n      deletedAt: {\n        type: DataTypes.DATE,\n        allowNull: true,\n        defaultValue: null\n      }\n    },\n    {\n      paranoid: true,\n      tableName: 'userTeam'\n    })\n```\n\n```js\nconst users = await User.findAll({\n      include: Team\n    })\n```\n\n```js\nUser.belongsToMany(Team, { through: UserTeam, foreignKey: 'userId', onDelete: 'CASCADE' })\nTeam.belongsToMany(User, { through: UserTeam, foreignKey: 'teamId', onDelete: 'CASCADE' })\n```\n\n```json\n{\n    \"fullName\": \"Player One\",\n    \"id\": \"6e8ca258-9daa-4d52-b033-a077d98c29ef\",\n    \"firstName\": \"Player\",\n    \"lastName\": \"One\",\n    \"email\": \"playerone@gmail.com\",\n    \"password\": \"$2a$14$tApwpX9Ld9a1cjZMFzTGZeVEUC01M7n/tSVlldG7OEbm9sEh/k8kW\",\n    \"verified\": 1,\n    \"verifyCode\": \"4f49b5ca-12ed5a2d-1608191096291\",\n    \"resetPasswordToken\": \"bd15eda5097e030988eed5d2d20b3bbb6a06439f6b9907783fc0ea19083d8410\",\n    \"resetPasswordExpire\": 1620266644543,\n    \"passwordChangedAt\": 1608337842942,\n    \"createdFromIp\": \"122.222.10.33\",\n    \"createdAt\": \"2020-12-14T06:33:13.000Z\",\n    \"updatedAt\": \"2021-05-06T01:54:04.000Z\",\n    \"deletedAt\": null,\n    \"teams\": [\n        {\n            \"id\": \"427e9de4-9318-4406-aed9-fcbb3b8a3282\",\n            \"name\": \"Texas Rangers\",\n            \"type\": \"MLB\",\n            \"slug\": \"texas-rangers\",\n            \"createdByUserId\": \"6e8ca258-9daa-4d52-b033-a077d98c29ef\",\n            \"createdAt\": \"2020-12-14T06:33:15.000Z\",\n            \"updatedAt\": \"2020-12-29T06:07:54.000Z\",\n            \"deletedAt\": null,\n            \"userTeams\": {\n                \"id\": 54,\n                \"teamId\": \"427e9de4-9318-4406-aed9-fcbb3b8a3282\",\n                \"userId\": \"6e8ca258-9daa-4d52-b033-a077d98c29ef\",\n                \"deletedAt\": null,\n                \"createdAt\": \"2020-12-14T06:33:15.000Z\",\n                \"updatedAt\": \"2020-12-14T06:33:15.000Z\"\n            }\n        },\n        {\n            \"id\": \"cbff6df7-0e0c-4906-9e1c-54b569079d83\",\n            \"name\": \"New York Yankees\",\n            \"type\": \"MLB\",\n            \"slug\": \"yankees\",\n            \"createdByUserId\": \"16f38fc5-63d1-4285-8773-526720f9a506\",\n            \"createdAt\": \"2020-12-14T23:57:11.000Z\",\n            \"updatedAt\": \"2021-07-06T06:08:35.000Z\",\n            \"deletedAt\": null,\n            \"userTeams\": {\n                \"id\": 55,\n                \"teamId\": \"cbff6df7-0e0c-4906-9e1c-54b569079d83\",\n                \"userId\": \"6e8ca258-9daa-4d52-b033-a077d98c29ef\",\n                \"deletedAt\": null,\n                \"createdAt\": \"2020-12-14T23:57:11.000Z\",\n                \"updatedAt\": \"2020-12-14T23:57:11.000Z\"\n            }\n        }\n    ]\n}\n```\n\n```text\npaginate: ({\n        currentPage,\n        pageSize\n    }) => {\n        const offset = parseInt((currentPage - 1) * pageSize, 10);\n        const limit = parseInt(pageSize, 10);\n        return {\n            offset,\n            limit,\n        };\n    },\n\n    // import function here\n    const result = await city.findAndCountAll({\n        where: conditions,\n        order: [\n            ['createdAt', 'DESC']\n        ],\n        ...paginate({\n            currentPage: page,\n            pageSize: limit\n        }),\n    })\n```\n\n========================================\n\nComments:\n- Actually, I have also faced an issue like this, when using some searching logic with a few includes, and searching by the included models parameters, filters, counting, and so on I have tried a lot of things but no exact result. Some of my changes fixed some problems but created new ones. I have solved that problem by SQL query usage.\n- The query needs to filter based on `user.type` and `team.type`. The `UserTeam` model references `userId` and `teamId`. Are you suggesting to put more columns into the `UserTeam` pivot table? This is not possible for my data structure, since the teams, clubs, and schools are separate models, and need to be linked through a pivot table. Maybe I'm not fully understanding what you're suggesting, but this is how I interpret it...\n- 1/2: The userId and teamId is all a pivot table needs, but if you reference the User and Team models and their `key` in the UserTeam model, you will have access to all the data in every column from both of them (including user.type and team.type) via Sequelize queries. If you query all Users and include Team like in my example above, you will – because of the magical references in the pivot model – get a SQL query that looks something like this:\n- 2/2: `SELECT`users`.`id` (...etc.) FROM `users` AS `users` LEFT OUTER JOIN ( `userTeam` AS `teams->userTeams` INNER JOIN `teams` AS `teams` ON `teams`.`id` = `teams->userTeams`.`orgId` AND (`teams->userTeams`.`deletedAt` IS NULL)) ON `users`.`id` = `teams->userTeams`.`userId` AND (`teams`.`deletedAt` IS NULL) WHERE(`users`.`deletedAt` IS NULL);`\n- Added the api response to my original answer, with the resulti from querying the user table as described above. If you this pattern you should have enough user data to work with in your filter.","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":333,"estimatedTokens":2268}}815{"id":"stack-59767360","source":"stackoverflow","questionId":59767360,"title":"Sequelize - Best way to INSERT a long record","tags":["mysql","angular","sequelize.js"],"text":"Title: Sequelize - Best way to INSERT a long record\nTags: mysql, angular, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table with 20 elements. \n\nIs there a way to avoid this syntax :\n\n```\nSequelize.create({\n elem1: req.body.eleme1,\n elem2: req.body.eleme2,\n elem3: req.body.eleme3,\n elem4: req.body.eleme4,\n elem5: req.body.eleme5,\n ..... \n elem20: req.body.eleme20,\n});\n```\n\nand do something like :\n\n```\nSequelize.create({\n req.body\n});\n```\n\nThanks :)\n\n========================================\n\nTop Answer:\n`Sequelize.create({...req.body})` should work as well, but if it's the only content, why not simply use `Sequelize.create(req.body)`?\n\n========================================\n\nCode:\n```text\nSequelize.create({\n  elem1: req.body.eleme1,\n  elem2: req.body.eleme2,\n  elem3: req.body.eleme3,\n  elem4: req.body.eleme4,\n  elem5: req.body.eleme5,\n  ..... \n  elem20: req.body.eleme20,\n});\n```\n\n```text\nSequelize.create({\n  req.body\n});\n```\n\n```text\nconst data = {}\n    Object.keys(req.body).forEach(function(key, index) {\n        data[key] = req.body[key]\n    //you can perform any other operation on a particular property here\n    })\nSequelize.create(data);\n```\n\n```text\nreq.body\n```\n\n```text\nSequelize.create({...req.body})\n```\n\n```text\nSequelize.create(req.body)\n```\n\n========================================\n\nComments:\n- Thanks a lot ! I hadn't thought of doing that","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":82,"estimatedTokens":346}}816{"id":"stack-47240325","source":"stackoverflow","questionId":47240325,"title":"How to run a sequelize query in the console?","tags":["sequelize.js"],"text":"Title: How to run a sequelize query in the console?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen I run a sequelize query in the console during a debug session, the return is an unresolved promise. But how can I get the outcome of that query/promise instantly?\n\nThe way I do it so far:\n\n```\nAuthor.findOne({})\n .then(function(error, result){\n debugger;\n //now I can work with the outcome in the console\n })\n```\n\nThis approach is extremely time-consuming, simple changes in the query would require a rerun of the whole debug session to see the new outcome.\n\n========================================\n\nCode:\n```text\nAuthor.findOne({})\n      .then(function(error, result){\n               debugger;\n               //now I can work with the outcome in the console\n            })\n```\n\n```text\nawait Author.findOne({})\n```\n\n```text\nnode --inspect-brk\n```\n\n```text\nchrome://inspect\n```\n\n```text\nAuthor\n```\n\n```text\n--inspect\n```\n\n```text\ncopy(JSON.stringify(temp1))\n```\n\n========================================\n\nComments:\n- I think the approach I would take is to write tests against it. That way you could run the tests quickly one after the other and it wouldn't be such a time-consuming thing to do what you're doing now.\n- Any suggestion how such a setup script could look like? Would be super helpful!","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":59,"estimatedTokens":328}}817{"id":"stack-24431213","source":"stackoverflow","questionId":24431213,"title":"Get only values from rows and associations with Sequelize","tags":["mysql","node.js","associations","sequelize.js"],"text":"Title: Get only values from rows and associations with Sequelize\nTags: mysql, node.js, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize, MySQL and Node to write a web application.\n\nFor most of my DB needs, I usually do some verification, then fetch my models (eagerly with associations) and send them back to the client, almost always as-is (at least, up to now).\n\nI wrote a little utility function `getValuesFromRows` to extract the values from a returned row array:\n\n```\ngetValuesFromRows: function(rows, valuesProp) {\n // get POD (plain old data) values\n valuesProp = valuesProp || 'values';\n if (rows instanceof Array) {\n var allValues = [];\n for (var i = 0; i However, I am adding more and more complex relations to my DB models. As a result, I get more associations that I have to fetch. Now, I don't only have to call above function to get the `values` from each row, but also I need more complicated utilities to get the `values` from all included (eagerly loaded) associations. Is there a way to only get values from Sequelize queries (and not the Sequelize model instance) that also includes all associated values from the instance?\n\nElse, I would have to manually \"get all `values` from each `Project` and add one item to that `values` object for the `values` property of each entry of `Project.members`\" (for example). Note that things get worse fast if you nest associations (e.g. members have `tasks` and `tasks` have this and that etc.).\n\nI am guessing that I have to write such utility myself?\n\n========================================\n\nCode:\n```text\ngetValuesFromRows: function(rows, valuesProp) {\n    // get POD (plain old data) values\n    valuesProp = valuesProp || 'values';\n    if (rows instanceof Array) {\n        var allValues = [];\n        for (var i = 0; i < rows.length; ++i) {\n            allValues[i] = rows[i][valuesProp];\n        }\n        return allValues;\n    }\n    else if (rows) {\n        // only one object\n        return rows[valuesProp];\n    }\n    return null;\n}\n\n// ...\n\n...findAll(...)...complete(function(err, rows) {\n     var allValues = getValuesFromRows(rows);\n     sendToClient(errToString(err, user), allValues);\n});\n```\n\n```text\ngetValuesFromRows\n```\n\n```text\nvalues\n```\n\n```text\nvalues\n```\n\n```text\nvalues\n```\n\n```text\nProject\n```\n\n```text\nvalues\n```\n\n```text\nvalues\n```\n\n```text\nProject.members\n```\n\n```text\ntasks\n```\n\n```text\ntasks\n```\n\n```text\n/**\n * Get POD (plain old data) values from Sequelize results.\n *\n * @param rows The result object or array from a Sequelize query's `success` or `complete` operation.\n * @param associations The `include` parameter of the Sequelize query.\n */\ngetValuesFromRows: function(rows, associations) {\n    // get POD (plain old data) values\n    var values;\n    if (rows instanceof Array) {\n        // call this method on every element of the given array of rows\n        values = [];\n        for (var i = 0; i < rows.length; ++i) {\n            // recurse\n            values[i] = this.getValuesFromRows(rows[i], associations);\n        }\n    }\n    else if (rows) {\n        // only one row\n        values = rows.dataValues;\n\n        // get values from associated rows\n        if (values && associations) {\n            for (var i = 0; i < associations.length; ++i) {\n                var association = associations[i];\n                var propName = association.as;\n\n                // recurse\n                values[propName] = this.getValuesFromRows(values[propName], association.include);\n            };\n        }\n    }\n\n    return values;\n}\n```\n\n```text\nvar postAssociations = [\n// poster association\n{\n    model: User,\n    as: 'author'\n},\n\n// comments association\n{\n    model: Comment,\n    as: 'comments',\n    include: [\n    {\n        // author association\n        model: User,\n        as: 'author'\n    }\n    ]\n}\n];\n\n// ...\n\nvar query = {\n    where: ...\n    include: postAssociations;\n};\n\n// query post data from DB\nreturn Post.findAll(query)\n\n// convert Sequelize result to POD\n.then(function(posts) {\n    return getValuesFromRows(posts, postAssociations);\n})\n\n// send POD back to client\n.then(client.sendPosts);\n```\n\n```text\ninclude\n```\n\n```text\nfind\n```\n\n```text\nfindAll\n```\n\n```text\nall\n```\n\n```text\nclient.sendPosts\n```\n\n```text\nauthor\n```\n\n```text\ncomments\n```\n\n```text\ncomments\n```\n\n```text\nauthor\n```\n\n========================================\n\nComments:\n- Currently `.get()` will return all values of the toplevel object but return instances for the included objects, it's in the works to provide a easy way to get just a plain object when calling `.get()` (it will probably be the default unless you're doing `.get(key)`). As a temporary hack you can use `JSON.parse(JSON.stringify(instance))` to get a POJO.\n- @MickHansen 1. `findAll` returns an array. You are saying that array has an added `get()` method? 2. Stringifying the entire complex object will include all kinds of things that you don't want in there. It is not desirable at all. I will wait and hope for a more complete solution :)\n- no the array is just an array, but each instance has a `.get()`. No stringifying will not, it uses `toJSON` which maps to `get()` which gives you the base values.\n- I don't get it. I can already get the POD values by simply getting the `values` property. Why use `get()` or JSON?\n- `values` simply maps to `get`, and no `get()` will give you the included instances aswell, so they will have more properties than just values (if you have used prefetching).\n- @MickHansen Yeah, it makes no sense. I expected, if I use `get()` (or `values`, or `dataValues`), that it's all POD, but the included relation objects are non-POD sequelize model instances. That is pretty sad.\n- No software is perfect. Provide a pull request or voice your support on the existing feature request on GH.\n- @MickHansen Thank you for your help and support! I came up with a solution below. Feel free to check it out :)","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":218,"estimatedTokens":1479}}818{"id":"stack-20433592","source":"stackoverflow","questionId":20433592,"title":"Using sequelize to store and retrieve JSON objects within a Model/Instance","tags":["json","node.js","sequelize.js"],"text":"Title: Using sequelize to store and retrieve JSON objects within a Model/Instance\nTags: json, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm looking to leverage sequelize on a big project, and was hoping I could use it to store a JSON Object as a property in a Model.\n\nI feel like I'm struggling with this, but perhaps I'm missing something simple?\n\nI'm defining a model (`Context`) as follows:\n\n```\nvar contextProperties = {\n\n contextName: { type: Sequelize.STRING, validate: { is: [\"[a-z]\",'i'], notEmpty: true } },\n\n _trackList: {type: Sequelize.TEXT}, \n trackList: {type: Sequelize.TEXT}\n\n}\n\nvar contextGetSet = {\n\n getterMethods: {\n trackList: function(){\n return JSON.parse(this._trackList);\n }\n },\n\n setterMethods: {\n trackList: function(v){\n this._trackList = JSON.stringify(v);\n }\n }\n\n};\n\nvar Context = sequelize.define('Context', contextProperties, contextGetSet);\n```\n\nNow when I create my `Context`, it seems to work before I save.\n\n```\nvar contextMain;\n\nContext.create({contextName: \"Whatever\"}).success(function (context){\n\n contextMain = context;\n\n contextMain.trackList = { atrackList: \"1111\", anotherTrackList: 2872 };\n console.log(constextMain.trackList);\n //logs { atrackList: \"1111\", anotherTrackList: 2872 } as expected\n\n contextMain.save().success(function (contextSaved){\n console.log(contextSaved.values);\n //all values are null except for the contextName\n });\n\n});\n```\n\nSo the JSON IS setting right, but the object returned by the `save().success()` method does not seem to have the proper values of what I set it to.\n\nWhen I log the object returned by the `save().success()` method (ie. `contextSaved.values`) the object looks like this:\n\n```\n{ contextName: 'Whatever',\n _trackList: 'null',\n trackList: null,\n id: 6,\n createdAt: Fri Dec 06 2013 15:57:39 GMT-0500 (EST),\n updatedAt: Fri Dec 06 2013 15:57:39 GMT-0500 (EST)\n}\n```\n\nEverything is null!!\n\nEven more weird is that when I look at the save SQL query made to save `contextMain`, it seems to be saving right!\n\n```\nExecuting: UPDATE \"Contexts\" SET \"contextName\"='Whatever', \"_trackList\"='{\"atrackList\":\"1111\",\"anotherTrackList\":2872}', \"trackList\"=NULL,\"id\"=7, \"createdAt\"='2013-12-06 20:59:39.278 +00:00', \"updatedAt\"='2013\n-12-06 20:59:39.294 +00:00' WHERE \"id\"=7 RETURNING *\n```\n\nNotice that: `\"_trackList\"='{\"atrackList\":\"1111\",\"anotherTrackList\":2872}'`\n\nAlso when I look at the actual SQL row for it, **it does have the stringified JSON object in there**!\n\nIf I load the Context using sequelize though...\n\n```\nContext.findAll().success(function(contexts) {\n console.log(JSON.stringify(contexts))\n // also displays null for _trackList and trackList\n});\n```\n\nSo very strange. Any help greatly greatly appreciated!!\nThanks so much! Sorry this post is so long!\n\n========================================\n\nTop Answer:\nCan you check if the setterMethod that is running JSON.stringify is getting called? Maybe its trying to insert as an object not a string?\n\nMore broadly, have you considered MongoDb? There may be other reasons why it isn't appealing for you, but just from this glimpse into the project, it looks like it would have real advantages--chiefly not having to parse json in both directions... but beyond that you'd be able to do things like query with the values inside that object, which might prove useful later on.\n\n========================================\n\nCode:\n```text\nvar contextProperties = {\n\n  contextName: { type: Sequelize.STRING, validate: { is: [\"[a-z]\",'i'], notEmpty: true } },\n\n  _trackList: {type: Sequelize.TEXT},    \n  trackList: {type: Sequelize.TEXT}\n\n}\n\nvar contextGetSet = {\n\n  getterMethods: {\n    trackList: function(){\n      return JSON.parse(this._trackList);\n    }\n  },\n\n  setterMethods: {\n    trackList: function(v){\n      this._trackList = JSON.stringify(v);\n    }\n  }\n\n};\n\nvar Context = sequelize.define('Context', contextProperties, contextGetSet);\n```\n\n```text\nvar contextMain;\n\nContext.create({contextName: \"Whatever\"}).success(function (context){\n\n  contextMain = context;\n\n  contextMain.trackList = { atrackList: \"1111\", anotherTrackList: 2872 };\n  console.log(constextMain.trackList);\n  //logs { atrackList: \"1111\", anotherTrackList: 2872 } as expected\n\n\n  contextMain.save().success(function (contextSaved){\n    console.log(contextSaved.values);\n    //all values are null except for the contextName\n  });\n\n});\n```\n\n```text\n{ contextName: 'Whatever',\n  _trackList: 'null',\n  trackList: null,\n  id: 6,\n  createdAt: Fri Dec 06 2013 15:57:39 GMT-0500 (EST),\n  updatedAt: Fri Dec 06 2013 15:57:39 GMT-0500 (EST)\n}\n```\n\n```text\nExecuting: UPDATE \"Contexts\" SET \"contextName\"='Whatever', \"_trackList\"='{\"atrackList\":\"1111\",\"anotherTrackList\":2872}', \"trackList\"=NULL,\"id\"=7, \"createdAt\"='2013-12-06 20:59:39.278 +00:00', \"updatedAt\"='2013\n-12-06 20:59:39.294 +00:00' WHERE \"id\"=7 RETURNING *\n```\n\n```text\nContext.findAll().success(function(contexts) {\n  console.log(JSON.stringify(contexts))\n  // also displays null for _trackList and trackList\n});\n```\n\n```text\nContext\n```\n\n```text\nContext\n```\n\n```text\nsave().success()\n```\n\n```text\nsave().success()\n```\n\n```text\ncontextSaved.values\n```\n\n```text\ncontextMain\n```\n\n```text\n\"_trackList\"='{\"atrackList\":\"1111\",\"anotherTrackList\":2872}'\n```\n\n========================================\n\nComments:\n- Thanks Zeke, I've tested by logging, and the getters and setters are both being called when the initial setting of the property is done. And the setter is also called when I save the instance.\n- Turn on sequelize debugging and let me know what the actual insert query looks like? Also check the record in the real db?\n- This is likely related to this issue: github.com/sequelize/sequelize/issues/759 Also, I am currently using a NoSQL (CouchDB). I'm excluding a lot of the details of my actual model(s) for this post, but the complexity of the project and the features of sequelize/ORM definitely seem like it's worth exploring it as an option. This is certainly more exploratory anyway. The original post has the UPDATE query (near the bottom of the post), if that's what you mean?\n- Sorry for my comment formatting :/ should have been separate comments there!\n- Weird. Mongoose is a great ORM for mongodb, if you haven't checked it out yet. What if you don't JSON.parse in the getter? Just return the string?","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":217,"estimatedTokens":1573}}819{"id":"stack-39484325","source":"stackoverflow","questionId":39484325,"title":"how to implement clustering in Sequelize?","tags":["mysql","node.js","express","sequelize.js","node-mysql"],"text":"Title: how to implement clustering in Sequelize?\nTags: mysql, node.js, express, sequelize.js, node-mysql\nSource: Stack Overflow\n\nQuestion:\nI have two mysql server both are (MASTER,MASTER). how could we implement clustering in sequelize. if one of sql server has stopped then all request goes to other mysql server without restarting node server.\n\n========================================\n\nCode:\n```text\nvar Sequelize = require(\"sequelize\");\n\nsequelize.connectionManager.connect = function(){\n    return new Promise(function(resolve,reject){\n       // create your connection and return its instance in promise\n       resolve(connection);\n    });\n}\n\nsequelize.connectionManager.disconnect = function(connection){\n   // to disconnect the connection\n   if (!connection._protocol._ended) {\n       connection.release()\n}\nreturn Promise.resolve();\n\n}\n```\n\n========================================\n\nComments:\n- can you please more details on how this works?","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":34,"estimatedTokens":238}}820{"id":"stack-46523077","source":"stackoverflow","questionId":46523077,"title":"Observables and Sequelize promises","tags":["javascript","promise","sequelize.js","observable"],"text":"Title: Observables and Sequelize promises\nTags: javascript, promise, sequelize.js, observable\nSource: Stack Overflow\n\nQuestion:\nGood morning,\n\nI'm having an issue understanding how Sequelize and RxJS work together.\nFrom what I read, Sequelize uses promises. Now, what happens if I want to load a list and render everytime an element is found in my database ?\nI'm using this syntax from sequelize:\n\n```\nUser.findAll().then()\n```\n\nBut what i want is to have this wrapped in an observable and be able to use :\n\n```\nvar getAllUsersObservable = Rx.Observable.create(function (obs) {\n obs.next(user)\n}\n```\n\nThen my observer just want, let's say, to print the new user.\n\n```\nvar getAllUsersObserver = {\n next: console.log(user)\n}\n```\n\nTo me, this will not work because Sequelize will only put the list of all my users in its promise when it's done finding all users. My question is : how do I use these two together to have my users being printed, one at a time?\n\nThanks in advance\n\n========================================\n\nTop Answer:\nThank you very much ! As I am new to stackoverflow, I forgot to come back to explain how I solved my issue. I'll learn to do that more.\n\nAs it turned out, Rx.Observable.fromPromise really did the trick. \nHowever, we chose another solution, which is the use of\n\n```\nRx.Observable.create(obs => { User.findOrCreate(......).spread((user, \ncreated) => obs.onNext({whatever}) )}\n```\n\nAnd it's working great for now. Hope that also helps.\n\n========================================\n\nCode:\n```text\nUser.findAll().then()\n```\n\n```text\nvar getAllUsersObservable = Rx.Observable.create(function (obs) {\n  obs.next(user)\n}\n```\n\n```text\nvar getAllUsersObserver = {\n  next: console.log(user)\n}\n```\n\n```js\nlet observable1 = Rx.Observable.fromPromise(User.findAll());\n\nobservable1.subscribe(...);\n```\n\n```text\nRx.Observable.create(obs => { User.findOrCreate(......).spread((user, \ncreated) => obs.onNext({whatever}) )}\n```\n\n========================================\n\nComments:\n- Doesn't sequelize provide some kind of cursor for results?\n- Update: I was doing something similar with Sequelize and successfully hooked it into RxJS. It's really as simple as doing this: Rx.Observable.fromPromise(User.findAll()).subscribe(...); You can use almost all of the other RxJS methods, as there is great support for promises.","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":85,"estimatedTokens":582}}821{"id":"stack-40709816","source":"stackoverflow","questionId":40709816,"title":"Sequelize Many-to-many table with identical foreign key is overriding the value","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize Many-to-many table with identical foreign key is overriding the value\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following structure:\n\n```\nvar User = sequelize.define('user', {\n name: DataTypes.STRING\n});\n\nvar Post = sequelize.define('post', {\n text: DataTypes.STRING\n});\n\nvar PostComment = sequelize.define('postComment', {\n id: {\n type: DataTypes.BIGINT,\n primaryKey: true,\n autoIncrement: true\n },\n comment: DataTypes.TEXT\n});\n\nPost.belongsToMany(User, { as: 'postUserComment', through: PostComment });\nUser.belongsToMany(Post, { through: PostComment });\n```\n\nThe same user, should be able to make multiples comments to the same post.\nBut when i execute\n\n```\npost.addPostUserComment(currentUserId, {comment: \"teste\"})\n```\n\nIf i already have a comment to this post made by the currentUser, it override it's \"comment\" value in the database when it should create a new row.\n\nDialect: mysql\nSequelize version: ~3.24.2\n\nAm i doing something wrong?\n\n========================================\n\nTop Answer:\nI end up doing \n\n```\nPost.belongsToMany(User, {as: 'postUserComment', through: {model: models.PostComment, unique: false}, foreignKey: 'idPost'});\n\nUser.belongsToMany(Post, {through: {model: models.PostComment, unique: false}, foreignKey: 'idUserComment'});\n```\n\nI am able to create multiples comments now. \nI am having a little trouble to select them all, but it's something to another issue i belive.\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('user', {\n  name: DataTypes.STRING\n});\n\nvar Post = sequelize.define('post', {\n  text: DataTypes.STRING\n});\n\nvar PostComment = sequelize.define('postComment', {\n  id: {\n    type: DataTypes.BIGINT,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  comment: DataTypes.TEXT\n});\n\nPost.belongsToMany(User, { as: 'postUserComment', through: PostComment });\nUser.belongsToMany(Post, { through: PostComment });\n```\n\n```text\npost.addPostUserComment(currentUserId, {comment: \"teste\"})\n```\n\n```text\npost.addPostComment({userId: currentUserId, comment: 'test'})\n```\n\n```text\nbelongsToMany\n```\n\n```text\nPost.hasMany(PostComment);\n```\n\n```text\nUser.hasMany(PostComment);\n```\n\n```text\nPost.belongsToMany(User, {as: 'postUserComment', through: {model: models.PostComment, unique: false}, foreignKey: 'idPost'});\n\nUser.belongsToMany(Post, {through: {model: models.PostComment, unique: false}, foreignKey: 'idUserComment'});\n```\n\n========================================\n\nComments:\n- I have to give up and do it by your way, i was able to create new instances but i was not being able to select them all. your solution worked for me. Thanks\n- I had to do it by @tilov-yrys way because i was able to create new instances but not select them","metadata":{"transformedAt":"2026-08-18T18:33:34.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":113,"estimatedTokens":692}}822{"id":"stack-41204152","source":"stackoverflow","questionId":41204152,"title":"Sequelize.or returns Limit 1 rather than or result","tags":["javascript","node.js","express","passport.js","sequelize.js"],"text":"Title: Sequelize.or returns Limit 1 rather than or result\nTags: javascript, node.js, express, passport.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni'm using SequelizeJS(MySql) with Passportjs for authentication \nwhen i write\n\n```\nUser.find(db.Sequelize.or({ 'username': username }, { 'email': req.body.email }) )\n .then((user) => {console.log(user)}\n```\n\nor\n\n```\nUser.find({$or:[({ 'username': username }, { 'email': req.body.email })]} )\n```\n\nGenerats\n\n Executing (default): SELECT `id`, `name`, `username`, `email`, `password`, `Picture`, `role`, `Description`, `joinedAt`, `Social`, `createdAt`, `updatedAt` FROM `Users` AS `User` LIMIT 1;\n\nI don't understand what happen , i'm using or and it generates query with limit 1 !\n\nmy user Model \n\n```\nconst bcrypt = require('bcrypt-node');\nconst db = require('../Config/db');\n\nmodule.exports = function () {\n let DataType = db.Sequelize;\n let User = db.sequelize.define('User', {\n name: { type: DataType.STRING, allowNull: false },\n username: { type: DataType.STRING, unique: true, allowNull: false },\n email: { type: DataType.STRING, unique: true, allowNull: false, validate: { isEmail: true } },\n password: {\n type: DataType.STRING, allowNull: false, set: function (pass) {\n let newPassword = bcrypt.hashSync(pass);\n this.setDataValue('password', newPassword);\n }\n },\n Picture: { type: DataType.STRING, default: '#' },\n role: { type: DataType.STRING, default: 'user',allowNull: false },\n Description: { type: DataType.TEXT },\n joinedAt: { type: DataType.DATE, defaultValue: DataType.NOW },\n Social: { type: DataType.TEXT }\n }, {\n classMethods: {\n associate: function (models) {\n User.hasMany(models.Post);\n }\n }\n }, {\n instanceMethods: {\n comparePassword: function (password) {\n return bcrypt.compareSync(password, this.password);\n }\n }\n });\n\n return User;\n}\n```\n\n========================================\n\nCode:\n```text\nUser.find(db.Sequelize.or({ 'username': username }, { 'email': req.body.email }) )\n            .then((user) => {console.log(user)}\n```\n\n```text\nUser.find({$or:[({ 'username': username }, { 'email': req.body.email })]} )\n```\n\n```text\nconst bcrypt = require('bcrypt-node');\nconst db = require('../Config/db');\n\nmodule.exports = function () {\n    let DataType = db.Sequelize;\n    let User = db.sequelize.define('User', {\n        name: { type: DataType.STRING, allowNull: false },\n        username: { type: DataType.STRING, unique: true, allowNull: false },\n        email: { type: DataType.STRING, unique: true, allowNull: false, validate: { isEmail: true } },\n        password: {\n            type: DataType.STRING, allowNull: false, set: function (pass) {\n                let newPassword = bcrypt.hashSync(pass);\n                this.setDataValue('password', newPassword);\n            }\n        },\n        Picture: { type: DataType.STRING, default: '#' },\n        role: { type: DataType.STRING, default: 'user',allowNull: false },\n        Description: { type: DataType.TEXT },\n        joinedAt: { type: DataType.DATE, defaultValue: DataType.NOW },\n        Social: { type: DataType.TEXT }\n    }, {\n            classMethods: {\n                associate: function (models) {\n                    User.hasMany(models.Post);\n                }\n            }\n        }, {\n            instanceMethods: {\n                comparePassword: function (password) {\n                    return bcrypt.compareSync(password, this.password);\n                }\n            }\n        });\n\n    return User;\n}\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nusername\n```\n\n```text\nemail\n```\n\n```text\npassword\n```\n\n```text\nPicture\n```\n\n```text\nrole\n```\n\n```text\nDescription\n```\n\n```text\njoinedAt\n```\n\n```text\nSocial\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nUsers\n```\n\n```text\nUser\n```\n\n```js\nUser.findAll({\n  where: {\n    $or: [\n      username: username,\n      email: req.body.email,\n    ],\n  }\n})\n.then(users => console.log(users));\n```\n\n```text\nModel.find()\n```\n\n```text\nModel.findOne()\n```\n\n```text\nLIMIT 1\n```\n\n```text\nModel.findAll()\n```\n\n```text\nwhere\n```\n\n========================================\n\nComments:\n- `find` is an alias for `findOne` , but it works now with where Thank you, the problem docs doesn't offer any kind of examples like this.\n- It must be generated dynamically, you are correct that it's not in the docs and I didn't see it with static analysis either. I would recommend sticking to the methods in the official docs.","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":210,"estimatedTokens":1103}}823{"id":"stack-41883695","source":"stackoverflow","questionId":41883695,"title":"Sequelize: Query same join table with different conditions","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: Sequelize: Query same join table with different conditions\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two models `Contact` and `Thread` with a many to many relationship represented across a join table `ThreadContacts`.\n\nI need to write a query to **find a Thread which has associations with an exact list of Contacts**. For example, I might have a list of `contact_id`'s \n[1,2,3,4], and I need to find a `Thread` that is associated with these exact 4 contacts.\n\nI have tried including `Contact` on a findAll query:\n\n```\nThread.findOne({\n include: [{\n model: Contact,\n where: { id: $in: [1, 2, 3, 4] },\n }],\n})\n```\n\nOf course this doesn't work because it'll return a thread that has a ThreadContact with any of the 4 ids.\n\nI need something like this:\n\n```\nThread.findAll({\n include: contactIds.map(id => ({\n model: Contact,\n where: { id },\n }),\n})\n```\n\nHowever this also doesn't work because it is including duplicates of the same model.\n\nWhat are my options here? I'm having a difficult time finding a solution for this.\n\n========================================\n\nCode:\n```text\nThread.findOne({\n    include: [{\n        model: Contact,\n        where: { id: $in: [1, 2, 3, 4] },\n    }],\n})\n```\n\n```text\nThread.findAll({\n    include: contactIds.map(id => ({\n        model: Contact,\n        where: { id },\n    }),\n})\n```\n\n```text\nContact\n```\n\n```text\nThread\n```\n\n```text\nThreadContacts\n```\n\n```text\ncontact_id\n```\n\n```text\nThread\n```\n\n```text\nContact\n```\n\n```text\nsequelize.query(`\n  SELECT Thread.*\n  FROM Thread\n  INNER JOIN ThreadContact\n    ON Thread.id = ThreadContact.threadId\n  GROUP BY Thread.id\n  HAVING array_agg(ThreadContact.contactId) @> ARRAY[:contactIds];\n`, {\n  model: Thread,\n  mapToModel: true,\n  type: sequelize.QueryTypes.SELECT,\n  replacements: {contactIds: [1, 2, 3, 4]},\n});\n```\n\n```text\nThread.id\n```\n\n```text\narray_agg\n```\n\n```text\n@>\n```\n\n========================================\n\nComments:\n- Useful as alternative, also this is what I use when I need to do `joins`, however still would like to see example of \"sequelize\" way of doing this.\n- Yeah, would be nice to see it in Sequelize...but this works perfectly for my application. Thanks :)\n- Just one thing I had to add, because the array needs to contain the *exact* list of contact ids: `HAVING array_agg(thread_contacts.contact_id) @> ARRAY[:contactIds] AND array_agg(thread_contacts.contact_id) <@ ARRAY[:contactIds];`\n- Great solution! Just note that you don't have to use an entirely raw query for this to work. This could instead be written as: `Thread.findAll({ include: { model: ThreadContact, required: true }, group: ['Thread.id'], having: sequelize.where(sequelize.fn('array_agg', 'ThreadContact.contactId'), '@>', contactIds) })`, or something along those lines. Generally, limiting how raw your queries are can help in terms of security and maintainability.","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":118,"estimatedTokens":726}}824{"id":"stack-55697544","source":"stackoverflow","questionId":55697544,"title":"Express and PassportJs - Google OAuth2.0 strategy not giving me a req.user object","tags":["javascript","node.js","express","sequelize.js","passport.js"],"text":"Title: Express and PassportJs - Google OAuth2.0 strategy not giving me a req.user object\nTags: javascript, node.js, express, sequelize.js, passport.js\nSource: Stack Overflow\n\nQuestion:\nI'm setting up an auth route for our application, and I cannot seem to get the Google oAuth 2.0 strategy for PassportJs to give me a req.user object, using sequelize. Below is my code, I have tried to snip out only the relevant parts :)\n\n**Here's how my app.js is set up:**\n\n```\n//Dependencies\nconst creds = require('./credentials');\nconst express = require('express');\nconst bodyparser = require('body-parser');\nconst passport = require('passport');\nconst flash = require('connect-flash');\nconst Sequelize = require('sequelize');\nconst cookieParser = require('cookie-parser');\nconst session = require('express-session');\nconst SequelizeStore = require('connect-session-sequelize')(session.Store);\nconst sequelize = new Sequelize(creds.mssqlAuth);\n\n//Routes\nconst indexRouter = require('./routes/index');\nconst authRouter = require('./routes/auth');\n\n//Init\nconst app = express\n\n//View engine setup\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'pug');\n\n//Session config\napp.use(session({\n secret: 'this is a super secret session sign in string',\n store: new SequelizeStore({\n db: sequelize,\n checkExpirationInterval: 15 * 60 * 1000,\n expiration: 8 * 60 * 60 * 1000\n }),\n resave: true,\n saveUninitialized: true,\n cookie: { maxAge: 8 * 60 * 60 * 1000, secure : true }\n}));\n\n//Init middlewares\napp.use(passport.initialize());\napp.use(passport.session());\n\n//Init Routes\napp.use('/', indexRouter);\napp.use('/auth', authRouter);\n```\n\n**Here's my auth route:**\n\n```\n'use strict';\n\n// Dependencies\nconst express = require('express');\nconst passport = require('passport');\nconst GoogleStrategy = require('passport-google-oauth20').Strategy;\nconst creds = require('../credentials');\nconst Models = require('../models');\nconst Sequelize = require('sequelize');\nconst sequelize = new Sequelize(creds.mssqlAuth);\n\n//Init router\nconst router = express.Router();\n\n//Winston logging - dev purposes only\nconst winston = require('winston');\n\n//Authenticate with Google and get users data\npassport.use(new GoogleStrategy({\n clientID: creds.googleAuth.clientID,\n clientSecret: creds.googleAuth.clientSecret,\n callbackURL: 'http://localhost:3000/auth/callback'\n },\n function(accessToken, refreshToken, profile, done) {\n Models.users.findOne({\n where: {\n email: profile.emails[0].value,\n }\n }).then( user =>{\n if (user){\n\n Models.user.update({\n **Update existing user here...**\n },\n where: { **Update existing user here...**} })\n\n .then( user =>{\n\n return Models.users.findOne({\n where: { email: profile.emails[0].value }\n });\n\n }).then(user =>{\n return done(null, user);\n\n }).catch(error => { return done(error, null)});\n }\n else if(!user){\n //****For the sake of brevity - Same as above, only create the new user****//\n }\n\n }).catch(error => { return done(error, null)});\n\n//Serialization\npassport.serializeUser(function(user, done) {\n done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done) {\n Models.users.findOne({\n where: { id: id }\n })\n .then(user => done(null, user))\n .catch(error => done(error, null));\n});\n\n//Initial auth call to Google\nrouter.get('/',\n passport.authenticate('google', {\n hd: 'ourDomain.com',\n scope: ['email'],\n prompt: 'select_account'\n })\n);\n\n//Callback - Send user to index or back to auth screen\nrouter.get('/callback', \n passport.authenticate('google', \n { failureRedirect: '/auth',\n successRedirect: '/' }\n));\n```\n\nI seem to be able to authenticate all of that, and I even get a new user written to our users table. But then in my index route I am checking to make sure req.user exists. It is always undefined, and this results in a loop back to the auth route.\n\nI'm wondering if it has something to do with setting this up under //localhost instead of an actual server? This code is intended to be a boilerplate setup for us to quickly get underway on new projects.\n\nCuriously, this code seems to write 3 separate sessions to our sessions table as well, each time it's run. I'm unsure if that's an unrelated issue, or if it's the cause of our issues here.\n\nDoes anyone have some guidance?\n\n========================================\n\nCode:\n```text\n//Dependencies\nconst creds = require('./credentials');\nconst express = require('express');\nconst bodyparser = require('body-parser');\nconst passport = require('passport');\nconst flash = require('connect-flash');\nconst Sequelize = require('sequelize');\nconst cookieParser = require('cookie-parser');\nconst session = require('express-session');\nconst SequelizeStore = require('connect-session-sequelize')(session.Store);\nconst sequelize = new Sequelize(creds.mssqlAuth);\n\n//Routes\nconst indexRouter = require('./routes/index');\nconst authRouter = require('./routes/auth');\n\n//Init\nconst app = express\n\n//View engine setup\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'pug');\n\n//Session config\napp.use(session({\n  secret: 'this is a super secret session sign in string',\n  store:  new SequelizeStore({\n    db: sequelize,\n    checkExpirationInterval: 15 * 60 * 1000,\n    expiration: 8 * 60 * 60 * 1000\n  }),\n  resave: true,\n  saveUninitialized: true,\n  cookie: { maxAge: 8 * 60 * 60 * 1000, secure : true }\n}));\n\n//Init middlewares\napp.use(passport.initialize());\napp.use(passport.session());\n\n//Init Routes\napp.use('/', indexRouter);\napp.use('/auth', authRouter);\n```\n\n```text\n'use strict';\n\n// Dependencies\nconst express = require('express');\nconst passport = require('passport');\nconst GoogleStrategy = require('passport-google-oauth20').Strategy;\nconst creds = require('../credentials');\nconst Models = require('../models');\nconst Sequelize = require('sequelize');\nconst sequelize = new Sequelize(creds.mssqlAuth);\n\n//Init router\nconst router = express.Router();\n\n//Winston logging - dev purposes only\nconst winston = require('winston');\n\n//Authenticate with Google and get users data\npassport.use(new GoogleStrategy({\n    clientID: creds.googleAuth.clientID,\n    clientSecret: creds.googleAuth.clientSecret,\n    callbackURL: 'http://localhost:3000/auth/callback'\n  },\n  function(accessToken, refreshToken, profile, done) {\n    Models.users.findOne({\n      where: {\n        email: profile.emails[0].value,\n      }\n    }).then( user =>{\n      if (user){\n\n        Models.user.update({\n          **Update existing user here...**\n          },\n          where: { **Update existing user here...**} })\n\n        .then( user =>{\n\n          return Models.users.findOne({\n            where: { email: profile.emails[0].value }\n          });\n\n        }).then(user =>{\n          return done(null, user);\n\n        }).catch(error => { return done(error, null)});\n      }\n      else if(!user){\n        //****For the sake of brevity - Same as above, only create the new user****//\n      }\n\n    }).catch(error => { return done(error, null)});\n\n//Serialization\npassport.serializeUser(function(user, done) {\n  done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done) {\n  Models.users.findOne({\n    where: { id: id }\n  })\n    .then(user => done(null, user))\n    .catch(error => done(error, null));\n});\n\n//Initial auth call to Google\nrouter.get('/',\n  passport.authenticate('google', {\n    hd: 'ourDomain.com',\n    scope: ['email'],\n    prompt: 'select_account'\n  })\n);\n\n//Callback - Send user to index or back to auth screen\nrouter.get('/callback', \n  passport.authenticate('google', \n    { failureRedirect: '/auth',\n      successRedirect: '/' }\n));\n```\n\n```text\n//Session config\napp.use(session({\n  secret: 'this is a super secret session sign in string',\n  store:  new SequelizeStore({\n    db: sequelize,\n    checkExpirationInterval: 15 * 60 * 1000,\n    expiration: 8 * 60 * 60 * 1000\n  }),\n  resave: true,\n  saveUninitialized: true,\n  cookie: { maxAge: 8 * 60 * 60 * 1000, secure : true },\n  secure: true\n}));\n```\n\n```text\n//Session config\napp.use(session({\n  secret: 'this is a super secret session sign in string',\n  store:  new SequelizeStore({\n    db: sequelize,\n    checkExpirationInterval: 15 * 60 * 1000,\n    expiration: 8 * 60 * 60 * 1000\n  }),\n  resave: true,\n  saveUninitialized: true,\n  cookie: { maxAge: 8 * 60 * 60 * 1000 }\n}));\n\n//****************************************//\n//***** Note the lack of secure: true ****//\n//****************************************//\n```\n\n========================================\n\nComments:\n- We did end up finding a solution to this, and It was related to running the app on localhost. I will type up an answer shortly","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":321,"estimatedTokens":2143}}825{"id":"stack-68895706","source":"stackoverflow","questionId":68895706,"title":"Why isn't my Sequelize DB syncing with V6?","tags":["javascript","postgresql","sequelize.js"],"text":"Title: Why isn't my Sequelize DB syncing with V6?\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using the setup described here and when I try to:\n\n```\nconst sequelize = require('./db').getConnection()\n....\nawait sequelize.sync()\n console.log(\"sync done\")\n```\n\nI get no error, but it doesn't actually create the tables in my DB. What could I be doing wrong?\n\n========================================\n\nCode:\n```text\nconst sequelize = require('./db').getConnection()\n....\nawait sequelize.sync()\n    console.log(\"sync done\")\n```\n\n```text\nsequelize.sync({alter:true})\n```\n\n========================================\n\nComments:\n- Have you tried using the option `force: true` in the sync function? Had a similar issue when I first started using sequelize and iirc that was how I fixed it. If that doesn't work though, you may need to change the way you initialise your DB.\n- you can take a look at stackoverflow.com/a/69431362/6183464","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":35,"estimatedTokens":241}}826{"id":"stack-67309598","source":"stackoverflow","questionId":67309598,"title":"I'd like to inject Repositories container at Service constructor using typedi","tags":["node.js","typescript","sequelize.js","typedi"],"text":"Title: I'd like to inject Repositories container at Service constructor using typedi\nTags: node.js, typescript, sequelize.js, typedi\nSource: Stack Overflow\n\nQuestion:\nI'd like to inject Repositories at my UserService.\n\nBut i'm not sure how to do that.\nI'm using typescript, typedi and sequelize.\n\nI think, the Service is loaded more fast than loaders.\n\nWhen I try to inject my Repositories which I set at database loader, the error occur.\n\nThe error like this : **ServiceNotFoundError: Service with \"repositories\" identifier was not found in the container. Register it before usage via explicitly calling the \"Container.set\" function or using the \"@Service()\" decorator.**\n\nSo, I checked \"userRepo\" with console.log and the result was undefined.\nI also checked Container.get('repositories') at CreateUser meathod, it loaded collectly. I mean, I can get my Container instance.\n\nI just can't load repositories instance at constructor.\n\nWhat should I do to load repositories at constructor?\nShould I change sequelize to typeorm to load this?\n\n```\n// ** UserService.ts **\nimport { Inject, Service } from 'typedi';\nimport { UserRepository } from '../repositories/user.repository';\nimport { UserCreationAttributes } from '../models/interface/User.interface';\nimport { User, UserModel, UserStatic } from '../models/User';\n\n@Service()\nexport default class UserService {\n constructor(@Inject('repositories') private userRepo: UserRepository) {}\n\n public async CreateUser(userData: UserCreationAttributes): Promise {\n try {\n await this.userRepo.create(userData);\n return true;\n } catch (err) {\n console.log(err);\n return false;\n }\n }\n}\n```\n\n```\n// ** Database Loader **\nimport { Sequelize } from 'sequelize';\nimport config from '../config';\nimport Logger from './logger';\nimport { UserStatic } from '../models/User';\nimport { FeedStatic } from '../models/Feed';\nimport { CommentStatic } from '../models/Comment';\nimport { VerificationStatic } from '../models/Verification';\nimport { initializeModels } from '../models';\nimport { initializeRepositories, Repositories } from '../repositories';\nimport { Container } from 'typedi';\n\nexport interface Models {\n User: UserStatic;\n Feed: FeedStatic;\n Comment: CommentStatic;\n Verification: VerificationStatic;\n}\n\nexport default async function loadSequelize() {\n const sequelize = new Sequelize(\n config.database,\n config.databaseUsername,\n config.databasePassword,\n {\n host: config.databaseHost,\n port: config.databasePort,\n dialect: 'postgres',\n },\n );\n\n try {\n await sequelize.authenticate();\n const models: Models = initializeModels(sequelize);\n const repositories: Repositories = initializeRepositories(models);\n await sequelize.sync({ force: true });\n\n // This part might be loaded after services were loaded\n Container.set('models', models);\n Container.set('repositories', repositories);\n\n console.log('load finish');\n } catch (err) {\n Logger.error(err);\n }\n}\n```\n\n```\n// ** ./repositories/index.ts **\nimport { Models } from '../loaders/database';\nimport { UserRepository } from './user.repository';\n\nexport interface Repositories {\n UserRepository: UserRepository;\n}\nexport const initializeRepositories = (models: Models): Repositories => {\n const usersRepository = new UserRepository(models.User);\n const repositories: Repositories = {\n UserRepository: usersRepository,\n };\n return repositories;\n};\n```\n\n```\n// ** ./repositories/base.repository.ts **\nimport { Model, BuildOptions, FindOptions } from 'sequelize/types';\nimport { IFilter } from './filter/base.filter';\n\nexport type RichModel = typeof Model & {\n new (values?: Record, options?: BuildOptions): Model;\n};\n\nexport interface IMeta {\n globalCount: number;\n countAfterFiltering: number;\n}\n\nexport interface IWithMeta {\n meta: IMeta;\n data: M[];\n}\n\nexport abstract class BaseRepository {\n constructor(public _model: RichModel, private filterFactory: new () => F) {}\n\n private async getCount(where?: Record): Promise {\n const count = await this._model.count({ where });\n return count;\n }\n\n async getAll(params?: FindOptions, filter?: F): Promise> {\n const { from: offset, count: limit } = filter || {};\n const result = await this._model.findAndCountAll({\n order: [['id', 'ASC']],\n offset: offset,\n limit: limit,\n ...params,\n });\n\n const globalCount = await this.getCount();\n const countAfterFiltering = ((result.count as unknown) as Record[]).length;\n\n return {\n meta: { globalCount, countAfterFiltering },\n data: result.rows as M[],\n };\n }\n\n async getById(id: string | number): Promise {\n const result = await this._model.findByPk(id);\n return result as M;\n }\n\n async get(where: Record): Promise {\n const result = await this._model.findOne({ where });\n return result as M;\n }\n\n async updateById(id: string | number, data: C): Promise {\n const result = await this._model.update(data, {\n where: { id },\n returning: true,\n });\n\n const [, models] = result;\n\n return models[0] as M;\n }\n\n async deleteById(id: string | number): Promise {\n await this._model.destroy({\n where: { id },\n });\n }\n\n async create(data: C): Promise {\n const model = await this._model.create(data);\n return (model as unknown) as M;\n }\n}\n```\n\n```\n// ** ./repositories/user.repository.ts\nimport { BaseRepository, IWithMeta, RichModel } from './base.repository';\nimport { UserModel, UserStatic } from '../models/User';\nimport { UserCreationAttributes } from '../models/interface/User.interface';\nimport { IFilter } from './filter/base.filter';\nimport { UserFilter } from './filter/user.filter';\nimport { Service } from 'typedi';\n\n@Service()\nexport class UserRepository extends BaseRepository {\n constructor(private model: UserStatic) {\n super(model, IFilter);\n }\n\n async getAllUsers(): Promise> {\n const users = await this.getAll();\n return users;\n }\n\n async getOneByFilter({\n email,\n password,\n }: UserFilter): Promise {\n const user = await this.model.findOne({\n where: {\n email,\n password,\n },\n });\n return user;\n }\n\n async getAdminOneByFilter({\n email,\n password,\n }: UserFilter): Promise {\n const user = await this.model.findOne({\n where: {\n email,\n password,\n isAdmin: true,\n },\n });\n return user;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// ** UserService.ts **\nimport { Inject, Service } from 'typedi';\nimport { UserRepository } from '../repositories/user.repository';\nimport { UserCreationAttributes } from '../models/interface/User.interface';\nimport { User, UserModel, UserStatic } from '../models/User';\n\n@Service()\nexport default class UserService {\n  constructor(@Inject('repositories') private userRepo: UserRepository) {}\n\n  public async CreateUser(userData: UserCreationAttributes): Promise<boolean> {\n    try {\n      await this.userRepo.create(userData);\n      return true;\n    } catch (err) {\n      console.log(err);\n      return false;\n    }\n  }\n}\n```\n\n```text\n// ** Database Loader **\nimport { Sequelize } from 'sequelize';\nimport config from '../config';\nimport Logger from './logger';\nimport { UserStatic } from '../models/User';\nimport { FeedStatic } from '../models/Feed';\nimport { CommentStatic } from '../models/Comment';\nimport { VerificationStatic } from '../models/Verification';\nimport { initializeModels } from '../models';\nimport { initializeRepositories, Repositories } from '../repositories';\nimport { Container } from 'typedi';\n\nexport interface Models {\n  User: UserStatic;\n  Feed: FeedStatic;\n  Comment: CommentStatic;\n  Verification: VerificationStatic;\n}\n\nexport default async function loadSequelize() {\n  const sequelize = new Sequelize(\n    config.database,\n    config.databaseUsername,\n    config.databasePassword,\n    {\n      host: config.databaseHost,\n      port: config.databasePort,\n      dialect: 'postgres',\n    },\n  );\n\n  try {\n    await sequelize.authenticate();\n    const models: Models = initializeModels(sequelize);\n    const repositories: Repositories = initializeRepositories(models);\n    await sequelize.sync({ force: true });\n\n    // This part might be loaded after services were loaded\n    Container.set('models', models);\n    Container.set('repositories', repositories);\n\n\n    console.log('load finish');\n  } catch (err) {\n    Logger.error(err);\n  }\n}\n```\n\n```text\n// ** ./repositories/index.ts **\nimport { Models } from '../loaders/database';\nimport { UserRepository } from './user.repository';\n\nexport interface Repositories {\n  UserRepository: UserRepository;\n}\nexport const initializeRepositories = (models: Models): Repositories => {\n  const usersRepository = new UserRepository(models.User);\n  const repositories: Repositories = {\n    UserRepository: usersRepository,\n  };\n  return repositories;\n};\n```\n\n```text\n// ** ./repositories/base.repository.ts **\nimport { Model, BuildOptions, FindOptions } from 'sequelize/types';\nimport { IFilter } from './filter/base.filter';\n\nexport type RichModel = typeof Model & {\n  new (values?: Record<string, unknown>, options?: BuildOptions): Model;\n};\n\nexport interface IMeta {\n  globalCount: number;\n  countAfterFiltering: number;\n}\n\nexport interface IWithMeta<M extends Model> {\n  meta: IMeta;\n  data: M[];\n}\n\nexport abstract class BaseRepository<\n  M extends Model,\n  C extends object,\n  F extends IFilter = IFilter\n> {\n  constructor(public _model: RichModel, private filterFactory: new () => F) {}\n\n  private async getCount(where?: Record<string, unknown>): Promise<number> {\n    const count = await this._model.count({ where });\n    return count;\n  }\n\n  async getAll(params?: FindOptions, filter?: F): Promise<IWithMeta<M>> {\n    const { from: offset, count: limit } = filter || {};\n    const result = await this._model.findAndCountAll({\n      order: [['id', 'ASC']],\n      offset: offset,\n      limit: limit,\n      ...params,\n    });\n\n    const globalCount = await this.getCount();\n    const countAfterFiltering = ((result.count as unknown) as Record<\n      string,\n      unknown\n    >[]).length;\n\n    return {\n      meta: { globalCount, countAfterFiltering },\n      data: result.rows as M[],\n    };\n  }\n\n  async getById(id: string | number): Promise<M> {\n    const result = await this._model.findByPk(id);\n    return result as M;\n  }\n\n  async get(where: Record<string, unknown>): Promise<M> {\n    const result = await this._model.findOne({ where });\n    return result as M;\n  }\n\n  async updateById(id: string | number, data: C): Promise<M> {\n    const result = await this._model.update(data, {\n      where: { id },\n      returning: true,\n    });\n\n    const [, models] = result;\n\n    return models[0] as M;\n  }\n\n  async deleteById(id: string | number): Promise<void> {\n    await this._model.destroy({\n      where: { id },\n    });\n  }\n\n  async create(data: C): Promise<M> {\n    const model = await this._model.create(data);\n    return (model as unknown) as M;\n  }\n}\n```\n\n```text\n// ** ./repositories/user.repository.ts\nimport { BaseRepository, IWithMeta, RichModel } from './base.repository';\nimport { UserModel, UserStatic } from '../models/User';\nimport { UserCreationAttributes } from '../models/interface/User.interface';\nimport { IFilter } from './filter/base.filter';\nimport { UserFilter } from './filter/user.filter';\nimport { Service } from 'typedi';\n\n@Service()\nexport class UserRepository extends BaseRepository<\n  UserModel,\n  UserCreationAttributes,\n  IFilter\n> {\n  constructor(private model: UserStatic) {\n    super(<RichModel>model, IFilter);\n  }\n\n  async getAllUsers(): Promise<IWithMeta<UserModel>> {\n    const users = await this.getAll();\n    return users;\n  }\n\n  async getOneByFilter({\n    email,\n    password,\n  }: UserFilter): Promise<UserModel | null> {\n    const user = await this.model.findOne({\n      where: {\n        email,\n        password,\n      },\n    });\n    return user;\n  }\n\n  async getAdminOneByFilter({\n    email,\n    password,\n  }: UserFilter): Promise<UserModel | null> {\n    const user = await this.model.findOne({\n      where: {\n        email,\n        password,\n        isAdmin: true,\n      },\n    });\n    return user;\n  }\n}\n```\n\n```text\n@Inject('repositories') repositories: { UserRepository: UserRepository}; \n\nrepositories.UserRepository\n```\n\n```text\ninitializeRepositories\n```\n\n```text\nreflect-metadata\n```\n\n```text\nContainer.set\n```\n\n```text\nContainer.set([{ id: 'userRepository', value: new UserRepository() }])\n```\n\n```text\nContainer.set('userRepository', new UserRepository())\n```\n\n```text\nContainer.get('userRepository')\n```\n\n```text\nrepositories\n```\n\n```text\ninitializeRepositories\n```\n\n```text\n@Service('userRepository')\n```\n\n```text\nUserRepository\n```\n\n========================================\n\nComments:\n- Did you remember to install and import `reflect-metadata` at the top level of your app?\n- @WitaloBenicio Yes, I already added my app.ts that on top. That's why I don't solve the error :(\n- Can you add your repository code?\n- @WitaloBenio Added.","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":526,"estimatedTokens":3174}}827{"id":"stack-56698348","source":"stackoverflow","questionId":56698348,"title":"Possible to WHERE on nested includes in Sequelize?","tags":["javascript","sql","orm","sequelize.js"],"text":"Title: Possible to WHERE on nested includes in Sequelize?\nTags: javascript, sql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got a problem that I've been stuck on, to no avail - seemingly similar in nature to Where condition for joined table in Sequelize ORM, except that I'd like to query on a previous join. Perhaps code will explain my problem. Happy to provide any extra info.\n\n**Models:**\n\n```\nA.hasMany(B);\nB.belongsTo(A);\nB.hasMany(C);\nC.belongsTo(B);\n```\n\n**This is what I'd like to be able to achieve with Sequelize:**\n\n```\nSELECT *\nFROM `A`AS `A`\nLEFT OUTER JOIN `B` AS `B` ON `A`.`id` = `B`.`a_id`\nLEFT OUTER JOIN `C` AS `B->C` ON `B`.`id` = `B->C`.`b_id`\n AND (`B`.`b_columnName` = `B->C`.`c_columnName`);\n```\n\n**This is how I imagine this working:** *(instead it will create a raw query (2 raw queries, for A-B/C) with `AND ( `C`.`columnName` = '$B.columnName$'))` on the join (second arg is a string). Have tried `sequelize.col`, `sequelize.where(sequelize.col...`, etc..)*\n\n```\nA.findOne({\n where: { id: myId },\n include: [{\n model: B,\n include: [{\n model: C,\n where: { $C.c_columnName$: $B.b_columnName$ }\n }]\n }]\n});\n```\n\n========================================\n\nCode:\n```text\nA.hasMany(B);\nB.belongsTo(A);\nB.hasMany(C);\nC.belongsTo(B);\n```\n\n```sql\nSELECT *\nFROM `A`AS `A`\nLEFT OUTER JOIN `B` AS `B` ON `A`.`id` = `B`.`a_id`\nLEFT OUTER JOIN `C` AS `B->C` ON `B`.`id` = `B->C`.`b_id`\n    AND (`B`.`b_columnName` = `B->C`.`c_columnName`);\n```\n\n```js\nA.findOne({\n    where: { id: myId },\n    include: [{\n        model: B,\n        include: [{\n            model: C,\n            where: { $C.c_columnName$: $B.b_columnName$ }\n        }]\n    }]\n});\n```\n\n```text\nAND ( `C`.`columnName` = '$B.columnName$'))\n```\n\n```text\nsequelize.col\n```\n\n```text\nsequelize.where(sequelize.col...\n```\n\n```js\nconst Op = Sequelize.Op;\n\nconst result = await A.findOne({\n  include: {\n    model: B,\n    include: {\n      model: C,\n      where: {\n        c_columnName: {\n          [Op.col]: 'B.b_columnName',\n        },\n      }\n    },\n  },\n});\n```\n\n```text\nOp.col\n```\n\n========================================\n\nComments:\n- Thanks! This works perfectly. Edit: For anyone reading this in the future, note that using `limit` on an include might break this: github.com/sequelize/sequelize/issues/9869\n- Thanks a lot it took around 5hrs for me to get to this solution :)","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":111,"estimatedTokens":591}}828{"id":"stack-57853624","source":"stackoverflow","questionId":57853624,"title":"Association is using wrong column","tags":["node.js","sequelize.js"],"text":"Title: Association is using wrong column\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using my existing database which has no foreign keys created but I am able to join two tables using sql query but I am not able to join them in sequelize.\n\nThere are two models:\n- User:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n var User = sequelize.define('User', {\n steamid: DataTypes.STRING,\n name: DataTypes.STRING,\n img: DataTypes.STRING,\n tradelink: DataTypes.STRING,\n ban_chat: DataTypes.INTEGER,\n block_sms: DataTypes.INTEGER,\n balance: DataTypes.INTEGER,\n ref: DataTypes.STRING,\n refcode: DataTypes.STRING,\n ip_address: DataTypes.STRING\n }, {\n timestamps: false\n });\n User.associate = function(models) {\n // associations can be defined here\n User.hasMany(models.Order,{\n foreignKey: 'steamid',\n as: 'orders'\n });\n\n };\n return User;\n};\n```\n\n- Order:\n\n```\nconst customDataTypes = require('../../core').SequelizeTimestamp;\n\nmodule.exports = (sequelize, DataTypes) => {\n var Order = sequelize.define('Order', {\n steamid: DataTypes.STRING,\n item_name: DataTypes.STRING,\n price: DataTypes.FLOAT,\n type: DataTypes.STRING,\n website: DataTypes.STRING,\n amount: DataTypes.INTEGER,\n status: DataTypes.INTEGER,\n img: DataTypes.STRING,\n send_attempts: DataTypes.INTEGER,\n message: DataTypes.STRING,\n date: customDataTypes.TIMESTAMP,\n }, {\n timestamps: false\n });\n Order.associate = function(models) {\n // associations can be defined here\n Order.belongsTo(models.User, {\n foreignKey: 'steamid',\n as: 'user'\n })\n };\n return Order;\n};\n```\n\nIn my API i want to get user and his orders.\nSo in the controller i am doing:\n\n```\nuser.findOne({\n where: { steamid: req.params.steamId },\n include: [{\n model: order,\n as: 'orders',\n limit: 50\n }],\n })\n```\n\nSo I expect to have user order array in the response but for some reason I get empty orders array.\n\nSequelize is doing these two queries:\n\n```\nSELECT `User`.`id`, `User`.`steamid`, `User`.`name`, `User`.`img`, `User`.`tradelink`, `User`.`ban_chat`, `User`.`block_sms`, `User`.`balance`, `User`.`ref`, `User`.`refcode`, `User`.`ip_address` FROM `Users` AS `User` WHERE `User`.`steamid` = '1234' LIMIT 1;\n```\n\nThis is successfully finding the user but the second query is incorrect:\n\n```\nSELECT `id`, `steamid`, `item_name`, `price`, `type`, `website`, `amount`, `status`, `img`, `send_attempts`, `message`, `date` FROM `Orders` AS `Order` WHERE `Order`.`steamid` IN (1) LIMIT 50;\n```\n\nThis part is incorrect \"WHERE `Order`.`steamid` IN (1)\"\nIt is looking for orders which steamid is = 1 which is user id (primary key) but it should be user steamid which is \"1234\"\n\nWhat is wrong with my associations?\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  var User = sequelize.define('User', {\n    steamid: DataTypes.STRING,\n    name: DataTypes.STRING,\n    img: DataTypes.STRING,\n    tradelink: DataTypes.STRING,\n    ban_chat: DataTypes.INTEGER,\n    block_sms: DataTypes.INTEGER,\n    balance: DataTypes.INTEGER,\n    ref: DataTypes.STRING,\n    refcode: DataTypes.STRING,\n    ip_address: DataTypes.STRING\n  }, {\n    timestamps: false\n  });\n  User.associate = function(models) {\n    // associations can be defined here\n    User.hasMany(models.Order,{\n      foreignKey: 'steamid',\n      as: 'orders'\n    });\n\n  };\n  return User;\n};\n```\n\n```text\nconst customDataTypes = require('../../core').SequelizeTimestamp;\n\nmodule.exports = (sequelize, DataTypes) => {\n  var Order = sequelize.define('Order', {\n    steamid: DataTypes.STRING,\n    item_name: DataTypes.STRING,\n    price: DataTypes.FLOAT,\n    type: DataTypes.STRING,\n    website: DataTypes.STRING,\n    amount: DataTypes.INTEGER,\n    status: DataTypes.INTEGER,\n    img: DataTypes.STRING,\n    send_attempts: DataTypes.INTEGER,\n    message: DataTypes.STRING,\n    date: customDataTypes.TIMESTAMP,\n  }, {\n    timestamps: false\n  });\n  Order.associate = function(models) {\n    // associations can be defined here\n    Order.belongsTo(models.User, {\n      foreignKey: 'steamid',\n      as: 'user'\n    })\n  };\n  return Order;\n};\n```\n\n```text\nuser.findOne({\n      where: { steamid: req.params.steamId },\n      include: [{\n        model: order,\n        as: 'orders',\n        limit: 50\n      }],\n    })\n```\n\n```text\nSELECT `User`.`id`, `User`.`steamid`, `User`.`name`, `User`.`img`, `User`.`tradelink`, `User`.`ban_chat`, `User`.`block_sms`, `User`.`balance`, `User`.`ref`, `User`.`refcode`, `User`.`ip_address` FROM `Users` AS `User` WHERE `User`.`steamid` = '1234' LIMIT 1;\n```\n\n```text\nSELECT `id`, `steamid`, `item_name`, `price`, `type`, `website`, `amount`, `status`, `img`, `send_attempts`, `message`, `date` FROM `Orders` AS `Order` WHERE `Order`.`steamid` IN (1) LIMIT 50;\n```\n\n```text\nOrder\n```\n\n```text\nsteamid\n```\n\n```text\nOrder.belongsTo(models.User, {\n      foreignKey: 'steamid',\n      targetKey: 'steamid',\n      as: 'user'\n    })\n```\n\n```text\nOrder.belongsTo(models.User, {\n      foreignKey: 'steamid',\n      sourceKey: 'steamid',\n      as: 'user'\n    })\n```\n\n========================================\n\nComments:\n- Related: stackoverflow.com/questions/49818406/&hellip;\n- You are right, now the query is correct but for some reason when I console.log(user.orders) it gives me Order object with empty dataValues: {} but the query is returning 50 rows","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":212,"estimatedTokens":1326}}829{"id":"stack-56203479","source":"stackoverflow","questionId":56203479,"title":"How to generate fake records in a relation N-M in Sequelize","tags":["javascript","sequelize.js"],"text":"Title: How to generate fake records in a relation N-M in Sequelize\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two tables: `User` and `Scope`; with the cardinality of N (`User`) -> M (`Scope`). When I insert fake records inside the `User` and the `Scope` tables, everything goes well, but if I insert fake records (ids from the `User` and `Scope` tables) inside the `UserScope` relation table, which represents the relation between `User` and `Scope`, I receive the errors:\n\n1:\n\n```\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n```\n\n2: \n\n```\nUnhandled rejection SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails (`graph`.`userScope`, CONSTRAINT 'userScope_ibfk_1' FOREIGN KEY (`scopeId`) REFERENCES `scope` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)\n```\n\nI had tried to debug via MySQL console (`SHOW ENGINE INNODB STATUS\\G`):\n\n```\nCONSTRAINT 'userScope_ibfk_1' FOREIGN KEY ('scopeId') REFERENCES 'scope' ('id') ON DELETE CASCADE ON UPDATE CASCADE\nTrying to add in child table, in index userScope_userId_scopeId_unique tuple:\nDATA TUPLE: 3 fields;\n 0: len 4; hex 80000008; asc ;;\n 1: len 4; hex 8000000a; asc ;;\n 2: len 4; hex 80000001; asc ;;\n\nBut in parent table 'graph'. 'scope', in index PRIMARY,\nthe closest match we can find is record:\nPHYSICAL RECORD: n_fields 1; compact format; info bits 0\n 0: len 8; hex 696e66696d756d00; asc infimum ;;\n```\n\nAnd I had found this question that makes me think that the way I'm inserting data in the relation table is not right, i.g, duplicate relations are being added in the relation table.\n\nI'm inserting the relations this way:\n\n```\nimport db from \"./models\";\n\nimport faker from \"faker\";\n\nimport times from \"lodash.times\";\n\nimport random from \"lodash.random\";\n\nconst amount = 10;\n\ndb.user.bulkCreate(\n times(amount, () => ({\n email: faker.internet.email(),\n password: faker.internet.password(),\n name: `${faker.name.firstName} ${faker.name.lastName}`,\n birth: Date.now()\n }))\n)\n\ndb.scope.bulkCreate(\n times(amount, () => ({\n title: faker.hacker.verb()\n }))\n)\n\ndb.userScope.bulkCreate(\n times(amount, () => ({\n scopeId: random(1, amount),\n userId: random(1, amount)\n }))\n);\n```\n\nThe tables:\n\nhttps://i.sstatic.net/gEZ1H.png\n\nhttps://i.sstatic.net/3PxY7.png\n\nI expect to insert fake relations in the `UserScope` table, without any errors and in a random way.\n\nObs: I had set the `amount` to `1` / set manually the ids and I still receiving this error. I had also already read threads like this one, this one but...\n\n========================================\n\nCode:\n```sh\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n```\n\n```sh\nUnhandled rejection SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails (`graph`.`userScope`, CONSTRAINT 'userScope_ibfk_1' FOREIGN KEY (`scopeId`) REFERENCES `scope` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)\n```\n\n```sh\nCONSTRAINT 'userScope_ibfk_1' FOREIGN KEY ('scopeId') REFERENCES 'scope' ('id') ON DELETE CASCADE ON UPDATE CASCADE\nTrying to add in child table, in index userScope_userId_scopeId_unique tuple:\nDATA TUPLE: 3 fields;\n 0: len 4; hex 80000008; asc     ;;\n 1: len 4; hex 8000000a; asc     ;;\n 2: len 4; hex 80000001; asc     ;;\n\nBut in parent table 'graph'. 'scope', in index PRIMARY,\nthe closest match we can find is record:\nPHYSICAL RECORD: n_fields 1; compact format; info bits 0\n 0: len 8; hex 696e66696d756d00; asc infimum ;;\n```\n\n```text\nimport db from \"./models\";\n\nimport faker from \"faker\";\n\nimport times from \"lodash.times\";\n\nimport random from \"lodash.random\";\n\nconst amount = 10;\n\ndb.user.bulkCreate(\n  times(amount, () => ({\n    email: faker.internet.email(),\n    password: faker.internet.password(),\n    name: `${faker.name.firstName} ${faker.name.lastName}`,\n    birth: Date.now()\n  }))\n)\n\ndb.scope.bulkCreate(\n  times(amount, () => ({\n    title: faker.hacker.verb()\n  }))\n)\n\ndb.userScope.bulkCreate(\n  times(amount, () => ({\n    scopeId: random(1, amount),\n    userId: random(1, amount)\n  }))\n);\n```\n\n```text\nUser\n```\n\n```text\nScope\n```\n\n```text\nUser\n```\n\n```text\nScope\n```\n\n```text\nUser\n```\n\n```text\nScope\n```\n\n```text\nUser\n```\n\n```text\nScope\n```\n\n```text\nUserScope\n```\n\n```text\nUser\n```\n\n```text\nScope\n```\n\n```text\nSHOW ENGINE INNODB STATUS\\G\n```\n\n```text\nUserScope\n```\n\n```text\namount\n```\n\n```text\n1\n```\n\n```text\nconst randomNumbers = (length, start=1) => {\n  let array = [...Array(length).keys()].map(value => start + value);\n\n  array.sort(() => Math.random() - 0.5);\n\n  return array;\n};\n\nexport { randomUniqueNumbers };\n```\n\n```text\n// ...\n\nimport { randomUniqueNumbers } from \"./util\";\n\nlet scopeIds = randomUniqueNumbers(length);\n\nlet userIds = randomUniqueNumbers(length);\n\ndb.userScope\n  .bulkCreate(\n    times(length, () => ({\n      scopeId: scopeIds.pop(),\n      userId: userIds.pop()\n    }))\n  )\n  .then(userScope => {})\n  .catch(error => console.log(error));\n```\n\n```text\nINSERT INTO userScope(createdAt, updatedAt, scopeId, userId) VALUES(STR_TO_DATE('18,05,2019','%d,%m,%Y'), STR_TO_DATE('18,05,2019','%d,%m,%Y'), 1, 1);\n```\n\n```text\nunique\n```\n\n```text\nunique\n```\n\n```text\nrandom\n```\n\n```text\nunique\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":253,"estimatedTokens":1300}}830{"id":"stack-56000198","source":"stackoverflow","questionId":56000198,"title":"Cannot increment with sequelize: 'Column \"0\" of relation \"users\" does not exists'","tags":["node.js","postgresql","express","sequelize.js","increment"],"text":"Title: Cannot increment with sequelize: 'Column \"0\" of relation \"users\" does not exists'\nTags: node.js, postgresql, express, sequelize.js, increment\nSource: Stack Overflow\n\nQuestion:\nI use Sequelize 4.42.0 and PostgreSQL 11.2 and struggle a lot to make `increment` works, I do as described in the documentation.\n\nI've searched everywhere but can't find a solution.\nI've also tried with:\n\n```\nawait Users.update({ testIncrement: database.literal('testIncrement + 1') }, {\n where: { id: user.id }\n})\n```\n\n### Code\n\n### Controller\n\n```\nexport const test = async ({ body, user }, res) => {\n try {\n await Users.increment('testIncrement', { where: { id: user.id }})\n } catch(error) {\n console.log(error)\n }\n}\n```\n\n### Model\n\n```\nconst Users = database.define('users',\n {\n id: {\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4\n },\n testIncrement: {\n defaultValue: 0,\n type: Sequelize.INTEGER,\n },\n }\n)\n\nexport default Users\n```\n\n### Expected\n\ntestIncrement to be incremented by 1\n\n### Results\n\n```\nerror: column \"0\" of relation \"users\" does not exist\n at Connection.parseE (/Users/.../node_modules/pg/lib/connection.js:555:11)\n at Connection.parseMessage (/Users/.../node_modules/pg/lib/connection.js:380:19)\n at Socket. (/Users/.../node_modules/pg/lib/connection.js:120:22)\n at Socket.emit (events.js:189:13)\n at Socket.EventEmitter.emit (domain.js:441:20)\n at addChunk (_stream_readable.js:284:12)\n at readableAddChunk (_stream_readable.js:265:11)\n at Socket.Readable.push (_stream_readable.js:220:10)\n at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\n name: 'error',\n length: 121,\n severity: 'ERROR',\n code: '42703',\n detail: undefined,\n hint: undefined,\n position: '35',\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'analyze.c',\n line: '2346',\n routine: 'transformUpdateTargetList',\n sql:\n 'UPDATE \"users\" SET \"testIncrement\"=\"testIncrement\"+ 1,\"0\"=\\'id\\',\"1\"=\\'testIncrement\\',\"2\"=\\'createdAt\\',\"3\"=\\'updatedAt\\' WHERE \"id\" = \\'adbe346a-b117-4f21-aa74-8a46d1ededae\\' RETURNING *' }\n```\n\n========================================\n\nTop Answer:\nPlease try with this snipet, it should work. \n\n```\nUsers.find({where: { id: user.id }})\n .then((user) => {\n if(user == null) console.log(\"Invalid user\")\n return User.update({\n testIncrement: user.testIncrement + 1\n })\n })\n .then((updated) => {\n if(updated == false) console.log(\"Cannot be updated\")\n return updated;\n })\n```\n\n========================================\n\nCode:\n```text\nawait Users.update({ testIncrement: database.literal('testIncrement + 1') }, {\n      where: { id: user.id }\n})\n```\n\n```text\nexport const test = async ({ body, user }, res) => {\n  try {\n    await Users.increment('testIncrement', { where: { id: user.id }})\n  } catch(error) {\n    console.log(error)\n  }\n}\n```\n\n```text\nconst Users = database.define('users',\n  {\n    id: {\n      primaryKey: true,\n      type: Sequelize.UUID,\n      defaultValue: Sequelize.UUIDV4\n    },\n    testIncrement: {\n      defaultValue: 0,\n      type: Sequelize.INTEGER,\n    },\n  }\n)\n\nexport default Users\n```\n\n```text\nerror: column \"0\" of relation \"users\" does not exist\n       at Connection.parseE (/Users/.../node_modules/pg/lib/connection.js:555:11)\n       at Connection.parseMessage (/Users/.../node_modules/pg/lib/connection.js:380:19)\n       at Socket.<anonymous> (/Users/.../node_modules/pg/lib/connection.js:120:22)\n       at Socket.emit (events.js:189:13)\n       at Socket.EventEmitter.emit (domain.js:441:20)\n       at addChunk (_stream_readable.js:284:12)\n       at readableAddChunk (_stream_readable.js:265:11)\n       at Socket.Readable.push (_stream_readable.js:220:10)\n       at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\n     name: 'error',\n     length: 121,\n     severity: 'ERROR',\n     code: '42703',\n     detail: undefined,\n     hint: undefined,\n     position: '35',\n     internalPosition: undefined,\n     internalQuery: undefined,\n     where: undefined,\n     schema: undefined,\n     table: undefined,\n     column: undefined,\n     dataType: undefined,\n     constraint: undefined,\n     file: 'analyze.c',\n     line: '2346',\n     routine: 'transformUpdateTargetList',\n     sql:\n      'UPDATE \"users\" SET \"testIncrement\"=\"testIncrement\"+ 1,\"0\"=\\'id\\',\"1\"=\\'testIncrement\\',\"2\"=\\'createdAt\\',\"3\"=\\'updatedAt\\' WHERE \"id\" = \\'adbe346a-b117-4f21-aa74-8a46d1ededae\\' RETURNING *' }\n```\n\n```text\nincrement\n```\n\n```text\ndefaultScope: {\n  attributes: { exclude: ['password', 'email'] }\n}\n```\n\n```text\nUsers.find({where: { id: user.id }})\n    .then((user) => {\n      if(user == null) console.log(\"Invalid user\")\n       return User.update({\n            testIncrement: user.testIncrement + 1\n          })\n    })\n    .then((updated) => {\n        if(updated == false) console.log(\"Cannot be updated\")\n        return updated;\n    })\n```\n\n========================================\n\nComments:\n- Thank you Riajul :) But while it would works it feels hacky, I'd like to use increment to keep the code consistent with the documentation\n- @RiajulIslam strongly disagree, because your select and update statements are not in the context of the same transaction. There's a high risk to end up with a race condition.","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":207,"estimatedTokens":1329}}831{"id":"stack-55550194","source":"stackoverflow","questionId":55550194,"title":"sequelize model versioning and optimistic","tags":["database","postgresql","sequelize.js"],"text":"Title: sequelize model versioning and optimistic\nTags: database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am wondering if there was an easy way to add versioning to model for easy optimistic concurrency. I was curious if anyone here has integrated that into their project with sequelize and got it to work seamless, without having to manually add the version to the where of every update ect.\nI started with something like this \n\n```\nexport const User = sequelize.define('user', {\n id: {type: Sequelize.STRING, primaryKey: true},\n name: {type: Sequelize.STRING, allowNull: false}\n}, {\n underscored: true,\n tableName: 'r_users',\n version: true // but the version doesn't change when updating the record or migration\n\n========================================\n\nCode:\n```text\nexport const User = sequelize.define('user', {\n  id: {type: Sequelize.STRING, primaryKey: true},\n  name: {type: Sequelize.STRING, allowNull: false}\n}, {\n  underscored: true,\n  tableName: 'r_users',\n  version: true // <- here\n});\n```\n\n```text\n\"migrationStorageTableName\": \"sequelize_meta\",\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":34,"estimatedTokens":271}}832{"id":"stack-45595365","source":"stackoverflow","questionId":45595365,"title":"How to validate a string field in sequelize.js?","tags":["node.js","validation","sequelize.js"],"text":"Title: How to validate a string field in sequelize.js?\nTags: node.js, validation, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I validate a database field to accept just a string?\n\nIn my database, I have two fields:\n\n- `description`: String\n\n- `completed`: Boolean\n\nI want the description field accept just a string value. What I mean is:\n\n- 'description':'text' => database accept this request\n\n- 'descrition': true or false => database refuse this request\n\n- 'descrition': 123 => database refuse this request\n\nCurrently, the `description` field can accept a boolean value , so there is an issue in my configuration.\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('todo', {\n description: {\n type: DataTypes.STRING,\n allowNull:false,\n validate: {\n len: [1, 250],\n isBoolean:false,\n isAlpha:true\n }\n },\n completed: {\n type: DataTypes.BOOLEAN,\n allowNull: false,\n defaultValue: false,\n validate:{\n isBoolean:true\n }\n }\n });\n};\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    return sequelize.define('todo', {\n        description: {\n            type: DataTypes.STRING,\n            allowNull:false,\n            validate: {\n                len: [1, 250],\n                isBoolean:false,\n                isAlpha:true\n            }\n        },\n        completed: {\n            type: DataTypes.BOOLEAN,\n            allowNull: false,\n            defaultValue: false,\n            validate:{\n                isBoolean:true\n            }\n        }\n    });\n};\n```\n\n```text\ndescription\n```\n\n```text\ncompleted\n```\n\n```text\ndescription\n```\n\n```text\nreturn sequelize.define('todo', {\n    description: {\n        type: DataTypes.STRING,\n        allowNull:false,\n        validate: {\n            is: ^((?!true|false|TRUE|FALSE).){1,255}$\n        }\n    },\n    ...\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- I'm not sure this is what the OP wants. They say *The description field can accept a boolean variable so there is an issue in my configuration* which makes me think they don't want to be able to enter true but they can. Could be wrong though but just wanted to point it out.\n- Thank you for your answer , i want just the description field accept just a string value not boolean so i tried just the first part of your answer : is: [a-z|A-Z]{1,250} and also tryed this is: /^[a-z]+$/i, but doesn't work , i don't want description accept a boolean value\n- @NathanOliver, yes, you're right, I've updated the answer.\n- @Zola please check the new answer.\n- Why do we still need to manually enforce validation, isn't the type declaration enough to make sequelize/underlying database to make sure the input is actually a string?\n- @Yos OP wants to validate that value is a string, and it's in a special format. How to validate that with type declaration?","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":115,"estimatedTokens":724}}833{"id":"stack-40638814","source":"stackoverflow","questionId":40638814,"title":"Sequelize insert in multiple tables with associations (cascading)","tags":["sequelize.js"],"text":"Title: Sequelize insert in multiple tables with associations (cascading)\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a model with cascading association such as:\nSurveys > Questions > Options\n\nSurvey has many Questions\nQuestion has many Options\n\nWhen I create a survey I want to create questions with options. \nex object:\n\n```\nsurvey = {\n title: title,\n description: description,\n Questions:[\n {\n question_type: 'Radio',\n question: 'q1',\n Options:[\n {\n option: 'o1'\n },\n {\n option: 'o2'\n }\n ]\n }\n ]\n }\n```\n\nWhen I create using the option below I get error.\n\n```\nUnhandled rejection TypeError: Cannot read property 'getTableName' of undefined\n```\n\nMy create looks like this\n\n```\nmodels.Survey.create(survey,{\n include: [models.Question,{include: [models.Option]}]\n }).then(function() {\n reply({success:1});\n });\n```\n\nTable scema\n\nQuestion:\n\n```\nQuestionId\nSurveyId\n```\n\nI also have another question. If I remove the \"Option\" association it inserts Questions but it is entering the \"NULL\" as SurveyId after \"Survey\" creation.\n\n========================================\n\nCode:\n```text\nsurvey = {\n        title: title,\n        description: description,\n        Questions:[\n          {\n            question_type: 'Radio',\n            question: 'q1',\n            Options:[\n              {\n                option: 'o1'\n              },\n              {\n                option: 'o2'\n              }\n            ]\n          }\n        ]\n      }\n```\n\n```text\nUnhandled rejection TypeError: Cannot read property 'getTableName' of undefined\n```\n\n```text\nmodels.Survey.create(survey,{\n          include:  [models.Question,{include: [models.Option]}]\n        }).then(function() {\n      reply({success:1});\n    });\n```\n\n```text\nQuestionId\nSurveyId\n```\n\n```text\nmodels.Survey.create(survey, {\n    include: [{\n        model: models.Question, \n        include: [models.Option]\n    }]\n}).then(function() {\n    reply({success:1});\n});\n```\n\n========================================\n\nComments:\n- are you sure Survey is defined?\n- i get same issue right now. Did you have a solution?\n- Thank you Tilov. The second include seems to do the trick. However, when the question is inserted for the Survey the Id seems to be null. For ex: INSERT INTO `Surveys` (`id`,`title`,`description`) VALUES (NULL,'title',''); INSERT INTO `Questions` (`id`,`question_type`,`question`,`SurveyId`) VALUES (DEFAULT,'Radio','q1',NULL); INSERT INTO `Options` (`id`,`option`,`QuestionId`) VALUES (DEFAULT,'o1',7); INSERT INTO `Options` (`id`,`option`,`QuestionId`) VALUES (DEFAULT,'o2',7);","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":120,"estimatedTokens":639}}834{"id":"stack-41286833","source":"stackoverflow","questionId":41286833,"title":"Sequelize: using build to update a record","tags":["node.js","sequelize.js"],"text":"Title: Sequelize: using build to update a record\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet's say I have the following simple model:\n\n```\nvar Foo = sequelize.define('Foo', {\n bar: Sequelize.STRING,\n});\n```\n\nAnd the table `Foos` in the database has a record:\n\n```\nid bar\n--- ---\n1 abc\n```\n\nIn order to update this record I could do the following:\n\n```\nFoo.findById(1).then(function(foo) {\n foo.bar = 'xyz';\n foo.save();\n});\n```\n\nNow I have found another way to update the record without having to find it form the database:\n\n```\nvar foo = Foo.build({ id: 1, bar: 'xyz' });\nfoo.isNewRecord = false; // makes save use UPDATE instead of INSERT INTO\nfoo.save();\n```\n\nThis is perfect for my use case, but I'm wondering if I'm breaking anything in sequelize.\n\n========================================\n\nCode:\n```text\nvar Foo = sequelize.define('Foo', {\n    bar: Sequelize.STRING,\n});\n```\n\n```text\nid   bar\n---  ---\n1    abc\n```\n\n```text\nFoo.findById(1).then(function(foo) {\n    foo.bar = 'xyz';\n    foo.save();\n});\n```\n\n```text\nvar foo = Foo.build({ id: 1, bar: 'xyz' });\nfoo.isNewRecord = false;  // makes save use UPDATE instead of INSERT INTO\nfoo.save();\n```\n\n```text\nFoos\n```\n\n```text\nlet instance = await db.Model.build({}, {isNewRecord: false});\nconst result = await instance.update({\n    id: instanceId,\n    column : newValue\n});\n```\n\n```text\nbuild\n```\n\n```text\noptions\n```\n\n```text\noptions\n```\n\n```text\nisNewRecord\n```\n\n```text\nupdate()\n```\n\n========================================\n\nComments:\n- So manually changing the `isNewRecord` value is supported by sequelize?\n- 'isNewRecord' is a property of the 'build()' parameter. You're not changing anything. Yes this is supported by sequelize","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":105,"estimatedTokens":429}}835{"id":"stack-37125879","source":"stackoverflow","questionId":37125879,"title":"How to prevent Sequelize adding 'Id' to column name?","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: How to prevent Sequelize adding 'Id' to column name?\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am finding when I do a query with Sequelize 'Id' is being added to the end of my column name, but I am not sure how to instruct Sequelize not to do so?\n\nI have created an entity data Model for Sequelize, as follows:\n\n```\nfunction initializeDataModel(sequelize) {\n var dataModel = { }; \n\n dataModel.Playlist = this.sequelize.define('playlist', {\n name: Sequelize.STRING,\n }); \n\n dataModel.PlaylistEntry = this.sequelize.define('playlist_entry', {\n playlist: {\n name: 'playlist',\n type: Sequelize.INTEGER,\n references: {\n // This is a reference to another model\n model: dataModel.Playlist,\n\n // This is the column name of the referenced model\n key: 'id'\n\n // This declares when to check the foreign key constraint. PostgreSQL only.\n //deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE \n } \n },\n track: Sequelize.INTEGER\n }); \n\n dataModel.PlaylistEntry.belongsTo(\n dataModel.Playlist,\n { as: 'Playlist', foreignKey: { name: 'playlist' }});\n\n dataModel.Playlist.hasMany(dataModel.PlaylistEntry);\n\n return dataModel;\n}\n```\n\nThe fields in the 'playlist_entry' table (in MariaDB) are as follows:\n\n- id: INT(11)\n\n- playlist: INT(11)\n\n- track: INT(11)\n\nThe query I am performing is as follows:\n\n```\neagerIncludes.push(this.dataModel.PlaylistEntry);\n\n this.dataModel.Playlist.find({\n where: { id: playlistId },\n limit: limit,\n offset: offset,\n include: eagerIncludes \n }).then(function (results) {\n callback(results, options, undefined);\n }).catch(function (error) {\n callback(undefined, options, error);\n });\n```\n\nThis results in:\n\n```\nER_BAD_FIELD_ERROR: Unknown column 'playlist_entries.playlistId' in 'field list'\n```\n\nAny suggestions would be appreciated. Changing the column names in the database is not an option.\n\nNote, this is an issue when trying to use the 'eager includes'.\n\n========================================\n\nCode:\n```text\nfunction initializeDataModel(sequelize) {\n    var dataModel = { };    \n\n    dataModel.Playlist = this.sequelize.define('playlist', {\n        name: Sequelize.STRING,\n    }); \n\n    dataModel.PlaylistEntry = this.sequelize.define('playlist_entry', {\n        playlist: {\n            name: 'playlist',\n            type: Sequelize.INTEGER,\n            references: {\n                // This is a reference to another model\n                model: dataModel.Playlist,\n\n                // This is the column name of the referenced model\n                key: 'id'\n\n                // This declares when to check the foreign key constraint. PostgreSQL only.\n                //deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE \n            }               \n        },\n        track: Sequelize.INTEGER\n    });                \n\n    dataModel.PlaylistEntry.belongsTo(\n         dataModel.Playlist,\n         { as: 'Playlist', foreignKey: { name: 'playlist' }});\n\n    dataModel.Playlist.hasMany(dataModel.PlaylistEntry);\n\n    return dataModel;\n}\n```\n\n```text\neagerIncludes.push(this.dataModel.PlaylistEntry);\n\n    this.dataModel.Playlist.find({\n       where: { id: playlistId },\n       limit: limit,\n       offset: offset,\n       include: eagerIncludes                 \n    }).then(function (results) {\n        callback(results, options, undefined);\n    }).catch(function (error) {\n        callback(undefined, options, error);\n    });\n```\n\n```text\nER_BAD_FIELD_ERROR: Unknown column 'playlist_entries.playlistId' in 'field list'\n```\n\n```text\nentities.Playlist.hasMany(entities.PlaylistEntry, { foreignKey: 'playlist' });\n```\n\n========================================\n\nComments:\n- It's worth mentioning that Sequelize adds `Id` to differentiate between the relationship property which is a record and the relationship key. I'm not sure you can have these with the same name without introducing serious problems.\n- if I am able to get the field name changed to 'playlist_id', in the 'playlist_entry' table, what changes should I be making to get this to work?\n- Generally it's best to adhere to the conventions Sequelize sets out unless you can't alter the schema. The defaults can be adjusted with options if necessary, but one thing you can't do is have the property and the column it's stored in with the same name.\n- I am working with an existing database and there are conventions, such as field and table names are all lower case and are words are separated by underscores. I am not sure I understand what you mean by \"one thing you can't do is have the property and the column it's stored in with the same name\". How does that represent itself in Sequelize? Any examples?\n- What I mean is you can't have a column called `x` and a property called `x` as those two will collide. This is why it's usually `xId` or `x_id` depending on your preference to distinguish between they key and any related record that's been instantiated.\n- I'll pass on this point to the DBA. In the mean time, I have a solution which works now - thanks.","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":151,"estimatedTokens":1249}}836{"id":"stack-30325193","source":"stackoverflow","questionId":30325193,"title":"Sequelize hasMany association issue","tags":["mysql","sequelize.js"],"text":"Title: Sequelize hasMany association issue\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn my application a user can have several `module` which is stored in the `user_has_module` table. This means that for each `user_has_module` row, I want to include `module` where the `module_id` matches.\n\n**module**\n\n```\nModule = sequelize.define('module', {\n academy_id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n module_id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n module_module_type_id: DataTypes.INTEGER,\n sort_number: DataTypes.INTEGER,\n score_to_pass: DataTypes.INTEGER\n }, {\n freezeTableName: true\n })\n```\n\n**user_has_module**\n\n```\nUser_has_module = sequelize.define('user_has_module', {\n user_id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n module_id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n academy_team_id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n academy_id: {\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n sort_number: DataTypes.INTEGER,\n is_complete: DataTypes.INTEGER,\n score_to_pass: DataTypes.INTEGER,\n is_open: DataTypes.INTEGER,\n deadline: DataTypes.DATE\n}, {\n freezeTableName: true\n})\n```\n\n**My relation**\n\n```\nUser_has_module.belongsTo(Module, {foreignKey: 'module_id'});\n```\n\nNow what I want to do is join them on `module.module_id = user_has_module.module_id`.\n\nMy problem is that `module` has, as you can see, two `primary key`, and when sequelize joins these two tables, it chooses `academy_id` as its `primary key`.\n\nMy question is, is there a way to tell `Sequelize` that in this relation it has to choose the `primary key` `module_id` from `module`?\n\n========================================\n\nCode:\n```text\nModule = sequelize.define('module', {\n    academy_id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true\n    },\n    module_id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true\n    },\n    module_module_type_id: DataTypes.INTEGER,\n    sort_number: DataTypes.INTEGER,\n    score_to_pass: DataTypes.INTEGER\n    }, {\n        freezeTableName: true\n    })\n```\n\n```text\nUser_has_module = sequelize.define('user_has_module', {\n     user_id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true\n     },\n     module_id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true\n     },\n     academy_team_id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true\n     },\n     academy_id: {\n        type: DataTypes.INTEGER,\n        primaryKey: true\n     },\n     sort_number: DataTypes.INTEGER,\n     is_complete: DataTypes.INTEGER,\n     score_to_pass: DataTypes.INTEGER,\n     is_open: DataTypes.INTEGER,\n     deadline: DataTypes.DATE\n}, {\n   freezeTableName: true\n})\n```\n\n```text\nUser_has_module.belongsTo(Module, {foreignKey: 'module_id'});\n```\n\n```text\nmodule\n```\n\n```text\nuser_has_module\n```\n\n```text\nuser_has_module\n```\n\n```text\nmodule\n```\n\n```text\nmodule_id\n```\n\n```text\nmodule.module_id = user_has_module.module_id\n```\n\n```text\nmodule\n```\n\n```text\nprimary key\n```\n\n```text\nacademy_id\n```\n\n```text\nprimary key\n```\n\n```text\nSequelize\n```\n\n```text\nprimary key\n```\n\n```text\nmodule_id\n```\n\n```text\nmodule\n```\n\n```text\nvar User = sequelize.define(\"User\", {\n        name: DataTypes.STRING\n    }, {\n        classMethods: {\n            associate: function(models) {\n                User.hasMany(models.Module);\n            }\n        }\n    });\n```\n\n```text\nvar Module = sequelize.define(\"Module\", {\n        name: DataTypes.STRING\n    }, {\n        classMethods: {\n            associate: function(models) {\n                Module.belongsToMany(models.User);\n            }\n        }\n    });\n```\n\n```text\nmodels.User.findAll({ include: [models.Module]}).then(function(users){\n        console.log(users);\n    });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.405Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":207,"estimatedTokens":929}}837{"id":"stack-35225193","source":"stackoverflow","questionId":35225193,"title":"What must I return in a GraphQL Mutation with Sequelize?","tags":["sequelize.js","graphql","graphql-js"],"text":"Title: What must I return in a GraphQL Mutation with Sequelize?\nTags: sequelize.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement a GraphQL server that uses Sequelize in the back-end (to work with MSSQL behind the scenes).\nAnd I have a query that works perfectly (retrieving data from a single SQL table) as expected.\n\nBut then I set up a mutation for the same schema, and when I run the mutation in GraphiQL I find that, while it does execute the stuff inside the mutation's resolve function (which is to create an instance of my Sequelize schema), it does not return my object back to me.\n\nhttps://i.sstatic.net/sY1q0.png\n\nNow, I figure it's because my Sequelize `.create` function returns a promise and resolve can't handle that? \n\nHere's what I've got so far:\n\n```\nresolve(_,args){\n Forecast.create({\n bunit: args.bunit,\n season: args.season,\n position: args.position,\n currency: args.currency,\n settle_date: new Date(args.settle_date),\n reference: args.reference\n }).then(forecast => {\n return forecast;\n }).catch(err => {\n console.error(err);\n return err;\n });\n}\n```\n\nI can't find any clear explanation or tutorial that shows me how to construct what the resolve function needs to return when I'm doing something asynchronously. Or I just don't understand it, which is also quite likely.\n\n========================================\n\nTop Answer:\nRemoving the `then` and `catch` implementation works but shouldn't be done, you've encountered a promises `then`-chain.\nEach `then` (or catch) `return` section changes the returned value of the resolver.\n\nHence, adding a `return` on the `Forecast` AND returns within the `then` and the `catch` is the right approach \n\n```\nresolve(_,args){\n return Forecast.create({\n bunit: args.bunit,\n season: args.season,\n position: args.position,\n currency: args.currency,\n settle_date: new Date(args.settle_date),\n reference: args.reference\n });\n .then(forecast => {\n console.error(err);\n return forecast;\n }).catch(err => {\n console.error(err);\n return err;\n });\n\n return newForecast;\n }\n }\n```\n\n========================================\n\nCode:\n```js\nresolve(_,args){\n  Forecast.create({\n    bunit: args.bunit,\n    season: args.season,\n    position: args.position,\n    currency: args.currency,\n    settle_date: new Date(args.settle_date),\n    reference: args.reference\n  }).then(forecast => {\n    return forecast;\n  }).catch(err => {\n    console.error(err);\n    return err;\n  });\n}\n```\n\n```text\n.create\n```\n\n```js\nresolve(_,args){\n      return Forecast.create({\n        bunit: args.bunit,\n        season: args.season,\n        position: args.position,\n        currency: args.currency,\n        settle_date: new Date(args.settle_date),\n        reference: args.reference\n      });\n      // .then(forecast => {\n      //   console.error(err);\n      //   //return forecast;\n      // }).catch(err => {\n      //   console.error(err);\n      //   //return err;\n      // });\n\n      //return newForecast;\n    }\n  }\n```\n\n```text\n.create\n```\n\n```text\nresolve(_,args){\n      return Forecast.create({\n        bunit: args.bunit,\n        season: args.season,\n        position: args.position,\n        currency: args.currency,\n        settle_date: new Date(args.settle_date),\n        reference: args.reference\n      });\n       .then(forecast => {\n         console.error(err);\n         return forecast;\n       }).catch(err => {\n         console.error(err);\n         return err;\n       });\n\n      return newForecast;\n    }\n  }\n```\n\n```text\nthen\n```\n\n```text\ncatch\n```\n\n```text\nthen\n```\n\n```text\nthen\n```\n\n```text\nreturn\n```\n\n```text\nreturn\n```\n\n```text\nForecast\n```\n\n```text\nthen\n```\n\n```text\ncatch\n```\n\n========================================\n\nComments:\n- you should `return` like this: `return Forecast.create(...`\n- I did that at first, but it wouldn't work. However, I just removed the `.then` and `.catch` calls as well, effectively leaving the handling of the returning promise to the resolve function, and that seems to work!\n- I do wonder though, what that means for error handling etc. Will my mutation automatically return the rejection of the promise?\n- this way you are able to see the errors from sequelize?\n- @stackdave Yes, graphql will add an \"errors\" property to its response (same as \"data\"), if the promise from your resolver (in this case Sequelize's .create function) is rejected for whatever reason.\n- This is definitely not going to work: a) because you forgot to remove a semi-colon before the .then() call, and b) because you're returning \"newForecast\" at the end which does not exist. None of this is necessary, just return the Promise that Forecast.create() returns, as above.","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":187,"estimatedTokens":1163}}838{"id":"stack-44546032","source":"stackoverflow","questionId":44546032,"title":"Sequelize foreign key error on Heroku but not local testing","tags":["javascript","mysql","heroku","foreign-keys","sequelize.js"],"text":"Title: Sequelize foreign key error on Heroku but not local testing\nTags: javascript, mysql, heroku, foreign-keys, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new developer and am trying to teach myself Sequelize and mysql with some little test projects. What I have right now is a little RPG team strength analyzer. I have a SQL table of Units, which has schema (id, name, elementOne, elementTwo) - integer, string, string, string. \n\nFor now, the elementOne and ElementTwo tables are both the same 18 string values because I couldn't figure out how to set up the Sequelize query with foreign keys refs to the same table (e.g. just 'elements').\n\nAdding to the Unit table works fine on a local server, but breaks on Heroku ONLY when trying to add a **third** unit with the following error:\n\n```\nError was: { SequelizeForeignKeyConstraintError: Cannot add or update a child \nrow: a foreign key constraint fails (`heroku_f4daeab1e260595`.`units`, \nCONSTRAINT `units_ibfk_1` FOREIGN KEY (`id`) REFERENCES `elementtwos` (`id`) \nON DELETE CASCADE ON UPDATE CASCADE)\n```\n\nHere are all the tables and the relationship declarations.\n\n```\nconst Unit = sequelize.define('unit', {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: false\n },\n image: {\n type: Sequelize.STRING,\n allowNull: true,\n unique: false\n },\n elementOne: {\n type: Sequelize.INTEGER,\n allowNull: true,\n references: {\n model: Element,\n key: 'id'\n }\n },\n elementTwo: {\n type: Sequelize.INTEGER,\n allowNull: true,\n defaultValue: 10001,\n references: {\n model: ElementTwo,\n key: 'id'\n }\n }\n});\n\nconst Element = sequelize.define('element', {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: false\n }\n});\nconst ElementTwo = sequelize.define('elementtwo', {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false,\n unique: false\n }\n});\n```\n\nAfter these are all loaded, I set up the following: \n\n```\nUnit.belongsTo(Element, {foreignKey: 'elementOne'});\nUnit.belongsTo(ElementTwo, {foreignKey: 'elementTwo'});\nElementTwo.hasMany(Unit, {foreignKey: 'id'});\nElement.hasMany(Unit, {foreignKey: 'id'});\n```\n\nAnd this is the query that Sequelize is doing (in a Unit.create({...}):\n\n```\nINSERT INTO `units` \n(`id`,`name`,`image`,`elementOne`,`elementTwo`,`createdAt`,`updatedAt`) VALUES \n (DEFAULT,'raichu','http://longimgurl.png',13,10001,'2017-06-14 \n12:57:54','2017-06-14 12:57:54');\n```\n\nIf anyone can offer any advice it would be greatly appreciated.\n\n========================================\n\nCode:\n```text\nError was:  { SequelizeForeignKeyConstraintError: Cannot add or update a child  \nrow: a foreign key constraint fails (`heroku_f4daeab1e260595`.`units`, \nCONSTRAINT `units_ibfk_1` FOREIGN KEY (`id`) REFERENCES `elementtwos` (`id`) \nON DELETE CASCADE ON UPDATE CASCADE)\n```\n\n```text\nconst Unit = sequelize.define('unit', {\n  id: {\n    type: Sequelize.INTEGER,\n    allowNull: false,\n    unique: true,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    unique: false\n  },\n  image: {\n    type: Sequelize.STRING,\n    allowNull: true,\n    unique: false\n  },\n  elementOne: {\n    type: Sequelize.INTEGER,\n    allowNull: true,\n    references: {\n      model: Element,\n      key: 'id'\n    }\n  },\n  elementTwo: {\n    type: Sequelize.INTEGER,\n    allowNull: true,\n    defaultValue: 10001,\n    references: {\n      model: ElementTwo,\n      key: 'id'\n    }\n  }\n});\n\nconst Element = sequelize.define('element', {\n  id: {\n    type: Sequelize.INTEGER,\n    allowNull: false,\n    unique: true,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    unique: false\n  }\n});\nconst ElementTwo = sequelize.define('elementtwo', {\n  id: {\n    type: Sequelize.INTEGER,\n    allowNull: false,\n    unique: true,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: {\n    type: Sequelize.STRING,\n    allowNull: false,\n    unique: false\n  }\n});\n```\n\n```text\nUnit.belongsTo(Element, {foreignKey: 'elementOne'});\nUnit.belongsTo(ElementTwo, {foreignKey: 'elementTwo'});\nElementTwo.hasMany(Unit, {foreignKey: 'id'});\nElement.hasMany(Unit, {foreignKey: 'id'});\n```\n\n```text\nINSERT INTO `units` \n(`id`,`name`,`image`,`elementOne`,`elementTwo`,`createdAt`,`updatedAt`) VALUES \n (DEFAULT,'raichu','http://longimgurl.png',13,10001,'2017-06-14 \n12:57:54','2017-06-14 12:57:54');\n```\n\n```text\nelement\n```\n\n```text\nelementTwo\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":207,"estimatedTokens":1182}}839{"id":"stack-33015142","source":"stackoverflow","questionId":33015142,"title":"Sequelize.js query to get total count through relationship","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize.js query to get total count through relationship\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize to get a total count through a relationship. I need it by a `customerId` that is in a parent table joined through a pivot table. The plain query looks something like this:\n\n```\nSELECT count(p.*) FROM parcels as p\nLEFT JOIN orders_parcels as op ON op.\"parcelId\" = p.id\nLEFT JOIN orders as o ON op.\"orderId\" = o.id\nWHERE o.\"customerId\"=1\n```\n\nThis works fine. But not sure how to get the sequelize query.\n\n```\nParcel.findAndCountAll();\n```\n\n**EDIT: OrderParcel**\n\n```\nvar OrderParcel = service.sequelize.define('OrderParcel', {\n\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n }\n}, {\n tableName: 'orders_parcels',\n freezeTableName: true,\n paranoid: true\n});\n\nmodule.exports = OrderParcel;\n\nvar Order = require('./Order');\n\nOrderParcel.belongsTo(Order, {\n as: 'Order',\n foreignKey: 'orderId'\n});\n\nvar Parcel = require('../parcel/Parcel');\n\nOrderParcel.belongsTo(Parcel, {\n as: 'Parcel',\n foreignKey: 'parcelId'\n});\n```\n\n========================================\n\nTop Answer:\nAssuming that you've defined the associations, you can use Model.findAndCountAll. It'd look something like this:\n\n```\nParcel.findAndCountAll({\n include: [{\n model: OrderParcel,\n required: true,\n include: [{\n model: Order,\n where: {\n customerId: idNum\n }\n }]\n }]\n}).then(function(result) { \n\n});\n```\n\n========================================\n\nCode:\n```text\nSELECT count(p.*) FROM parcels as p\nLEFT JOIN orders_parcels as op ON op.\"parcelId\" = p.id\nLEFT JOIN orders as o ON op.\"orderId\" = o.id\nWHERE o.\"customerId\"=1\n```\n\n```text\nParcel.findAndCountAll();\n```\n\n```text\nvar OrderParcel = service.sequelize.define('OrderParcel', {\n\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    }\n}, {\n    tableName: 'orders_parcels',\n    freezeTableName: true,\n    paranoid: true\n});\n\nmodule.exports = OrderParcel;\n\nvar Order = require('./Order');\n\nOrderParcel.belongsTo(Order, {\n    as: 'Order',\n    foreignKey: 'orderId'\n});\n\nvar Parcel = require('../parcel/Parcel');\n\nOrderParcel.belongsTo(Parcel, {\n    as: 'Parcel',\n    foreignKey: 'parcelId'\n});\n```\n\n```text\ncustomerId\n```\n\n```text\nvar query = \"SELECT count(p.*) FROM parcels as p\" +\n\" LEFT JOIN orders_parcels as op ON op.\"parcelId\" = p.id\" +\n\" LEFT JOIN orders as o ON op.\"orderId\" = o.id\" +\n\" WHERE o.customerId=1;\";\n\nsequelize.query(query, { type: sequelize.QueryTypes.SELECT}).success(function(count){\n    console.log(count); // It's show the result of query          \n    res.end();\n}).catch(function(error){            \n    res.send('server-error', {error: error});\n});\n```\n\n```text\nsequelize.query\n```\n\n```text\nsequelize.query\n```\n\n```text\nParcel.findAndCountAll({\n  include: [{\n    model: OrderParcel,\n    required: true,\n    include: [{\n      model: Order,\n      where: {\n        customerId: idNum\n      }\n    }]\n  }]\n}).then(function(result) { \n\n});\n```\n\n```text\nParcel.findAndCountAll({\ninclude: [{\n  model: Order,\n  where: {\n    customerId: idNum\n  },\n  duplicating: false // Add this line for retrieving all objects\n}]\n}).then(function(result) { \n   console.log('Rows: ' + result.rows + ' Count: ' + result.count)\n});\n```\n\n========================================\n\nComments:\n- Yes, I'm using the raw query now, but was hoping to avoid that.\n- Okay, because the joints I do not see another way.\n- @Rob see my answer for avoiding raw queries\n- I'm getting an `Error: OrderParcel is not associated to Parcel`, I've added the `OrderParcel` code to the question.\n- Make sure to add in the .hasMany associations as well for Parcel and Order. You might even be able to use belongsToMany in this table structure. (docs.sequelizejs.com/en/latest/docs/associations/&hellip;)","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":185,"estimatedTokens":957}}840{"id":"stack-25340531","source":"stackoverflow","questionId":25340531,"title":"Getting id of just saved object In Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: Getting id of just saved object In Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo I have this code:\n\n```\n//defining partner\nvar Partner = sequelize.define('Partner', {\n order: Sequelize.INTEGER,\n image: Sequelize.STRING,\n}, {\n tableName: 'partners',\n});\n//creating partner instance\nvar partner=Partner.build();\npartner.save().success(function(newpartner){\n console.log(newpartner.id);\n});\n```\n\nWhen this code gets executed, 2 instances of partner are inserted to the database. The second one is pushed when I access `id` property of `partner`.\n\nHere is the log from the console:\n\n```\nExecuting (default): INSERT INTO `partners` (`updatedAt`,`createdAt`) VALUES ('2014-08-16 13:13:26','2014-08-16 13:13:26');\nExecuting (default): INSERT INTO `partners` (`id`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'2014-08-16 13:13:26','2014-08-16 13:13:26');\n```\n\nI need to get id of the partner and send it to client after persisting it to the database. How do I do it properly?\nFor now I just access `id` property without invoking `save()`, since it saves object anyway. However this is not documented. Is there a proper way to do it?\n\n========================================\n\nCode:\n```text\n//defining partner\nvar Partner = sequelize.define('Partner', {\n    order: Sequelize.INTEGER,\n    image: Sequelize.STRING,\n}, {\n    tableName: 'partners',\n});\n//creating partner instance\nvar partner=Partner.build();\npartner.save().success(function(newpartner){\n     console.log(newpartner.id);\n});\n```\n\n```text\nExecuting (default): INSERT INTO `partners` (`updatedAt`,`createdAt`) VALUES ('2014-08-16 13:13:26','2014-08-16 13:13:26');\nExecuting (default): INSERT INTO `partners` (`id`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'2014-08-16 13:13:26','2014-08-16 13:13:26');\n```\n\n```text\nid\n```\n\n```text\npartner\n```\n\n```text\nid\n```\n\n```text\nsave()\n```\n\n```text\nPartner.setManager(manager);\n```\n\n```text\nManager\n```\n\n```text\nsuccess\n```\n\n```text\nsetManager()\n```\n\n========================================\n\nComments:\n- I'm not sure how to work around it, but you should file a bug report or check to see if it's already been reported. What version are you using?\n- @furydevoid Yes, I was wondering if it's a bug. I'm using 1.7.9, the one that came with npm install.","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":94,"estimatedTokens":569}}841{"id":"stack-23331897","source":"stackoverflow","questionId":23331897,"title":"Error connecting to a postgres db with nodejs sequelize pg.js \"the dialect postgres is not supported\"","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Error connecting to a postgres db with nodejs sequelize pg.js \"the dialect postgres is not supported\"\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to establish a simple connection from a NodeJs app to my Postgres local database.\nHere is the content of my node code index2.js\n\n```\nvar fs = require('fs');\nvar path = require('path');\nvar PGPASS_FILE = path.join(__dirname, \"./.pgpass\");\n\nvar pgtokens = fs.readFileSync(PGPASS_FILE).toString().trimRight().split(\":\");\nvar host = pgtokens[2];\nvar port = pgtokens[3];\nvar dbname = pgtokens[4];\nvar user = pgtokens[0];\nvar password = pgtokens[1];\n\nvar conString = \"postgres://\"+user+\":\"+password+\"@\"+host+\":\"+port+\"/\"+dbname;\n\nvar pg = require('pg.js');\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize(dbname, user, password,{\n dialectModulePath:\"pg.js\",\n dialect: \"postgres\",\n port: 5432\n });\n\nsequelize\n .authenticate()\n .complete(function (err) {\n if (!err) {\n console.log('Unable to connect to the database', err);\n } else {\n console.log('Connection has been establised succesfully!');\n }\n })\n```\n\nI am using the module `pg.js` not `pg` to connect to Postgres and I have tested that it works.\n\nMy problem is with Sequelize. The error I get is the following:\n\n```\nc:\\psql-node\\node-modules\\sequelize\\lib\\transaction-manager.js:10\nthrow new Error(\"The dialect + sequelize.getDialect()+\" is not support\n ^\nError: The dialect postgres is not suppported.\n at new module.exports (c:\\psql-node\\node_modules\\sequelize\\lib\\transaction-manager.js:10:11)\n at new module.exports.Sequelize (c:\\psql-node\\node_modules\\sequelize\\lib\\sequelize.js:128:31)\n at Object. (c:\\psql-node\\index2.js:16:17)\netc...\n```\n\nTo be honest, I'm not sure if how I tell Sequelize to use `'pg.js'` is correct, that's the line `dialectModulePath:\"pg.js\"`\nAny ideas?\n\nEdit:\nThanks to @peter-lyons I found out a bit more about the issue:\nThe error I get is almost the same but before it indicates:\n\n```\n[Error: Cannot find module 'pg/lib/connection-parameters'] code: 'MODULE_NOT_FOUND'\n```\n\nwhich is normal as the path to it should be `pg.js/lib/connection-parameters`\nAny idea how I modify `node_modules\\sequelize\\lib\\sequelize.js` so it gets the right file?\n\n========================================\n\nCode:\n```text\nvar fs = require('fs');\nvar path = require('path');\nvar PGPASS_FILE = path.join(__dirname, \"./.pgpass\");\n\nvar pgtokens = fs.readFileSync(PGPASS_FILE).toString().trimRight().split(\":\");\nvar host = pgtokens[2];\nvar port = pgtokens[3];\nvar dbname = pgtokens[4];\nvar user = pgtokens[0];\nvar password = pgtokens[1];\n\nvar conString = \"postgres://\"+user+\":\"+password+\"@\"+host+\":\"+port+\"/\"+dbname;\n\nvar pg = require('pg.js');\nvar Sequelize =  require('sequelize');\nvar sequelize = new Sequelize(dbname, user, password,{\n      dialectModulePath:\"pg.js\",\n      dialect: \"postgres\",\n      port: 5432\n    });\n\nsequelize\n  .authenticate()\n  .complete(function (err) {\n    if (!err) {\n      console.log('Unable to connect to the database', err);\n    } else {\n      console.log('Connection has been establised succesfully!');\n    }\n  })\n```\n\n```text\nc:\\psql-node\\node-modules\\sequelize\\lib\\transaction-manager.js:10\nthrow new Error(\"The dialect + sequelize.getDialect()+\"  is not support\n       ^\nError: The dialect postgres is not suppported.\n    at new module.exports (c:\\psql-node\\node_modules\\sequelize\\lib\\transaction-manager.js:10:11)\n    at new module.exports.Sequelize (c:\\psql-node\\node_modules\\sequelize\\lib\\sequelize.js:128:31)\n    at Object.<anonymous> (c:\\psql-node\\index2.js:16:17)\netc...\n```\n\n```text\n[Error: Cannot find module 'pg/lib/connection-parameters'] code: 'MODULE_NOT_FOUND'\n```\n\n```text\npg.js\n```\n\n```text\npg\n```\n\n```text\n'pg.js'\n```\n\n```text\ndialectModulePath:\"pg.js\"\n```\n\n```text\npg.js/lib/connection-parameters\n```\n\n```text\nnode_modules\\sequelize\\lib\\sequelize.js\n```\n\n```text\nlib/transaction-manager.js\n```\n\n```text\nconsole.error(err)\n```\n\n```text\ncatch\n```\n\n```text\nthrow\n```\n\n========================================\n\nComments:\n- OK, so now to be sane, be sure you are using the absolute most recent version of sequelize. The code in master looks like it should work OK. github.com/sequelize/sequelize/blob/&hellip;\n- I downloaded it yesterday, with npm install --save sequelize and it added in my package.json the '^1.7.3' version. However I checked your link and my connector-managers.js file and this particular line is missing, so will try to uninstall and reinstall to see if this makes a difference, otherwise will modify it by hand and report an issue on Sequelize's github. Thx @PeterLyons\n- Doesn't work, I get exactly the same error. And how would Sequelize know that it needs to use pg.js instead of the pg module if I don't indicate this option?\n- Correct me if I'm wrong but what I indicate as option is mentionned here: github.com/sequelize/sequelize/wiki/&hellip; I'm not inventing it, maybe I don't know how to use it, that's for sure!\n- Ah, so sequelize seems to be swallowing the error that might explain WTF is really the problem. Answer updated again.\n- Edited as requested. Thx for your help.","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":170,"estimatedTokens":1282}}842{"id":"stack-55412760","source":"stackoverflow","questionId":55412760,"title":"Why is findAll() not returning all objects in model?","tags":["node.js","mocha.js","sequelize.js"],"text":"Title: Why is findAll() not returning all objects in model?\nTags: node.js, mocha.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIm working on mocking DB because im unit testing API. For mocking i use sequelize-mock library and for models i use sequelize. When im calling GET request the function getAll() returns only first element in that array.\n\nMy mock model:\n\n```\nconst assetmeter = (sequelize) => {\n const AssetMeter = sequelize.define('assetmeter', {\n id: 1,\n assetId: 1,\n sequence: null,\n meterName: 'BAD',\n measureUnit: 'km',\n meterType: 'CHARACTERISTIC', \n description: 'test description', \n active: true,\n },{\n id: 2,\n assetId: 2,\n sequence: null,\n meterName: 'TEST',\n measureUnit: 'TEST',\n meterType: 'TEST', \n description: 'TEST', \n active: true,\n });\n\n return AssetMeter;\n}\n\nmodule.exports = assetmeter;\n```\n\nGet all function:\n\n```\nimport { AssetMeter } from '../../models';\nimport paginate from '../../utils/paginate';\n\nexport default async (req, res) => {\n let assetMeters = [];\n try {\n assetMeters = await AssetMeter.findAndCountAll({\n limit: req.pagination.limit, \n offset: req.pagination.offset\n });\n console.log(assetMeters);\n } catch (err) {\n console.log(err);\n return res.status(500).send({ error: 'Internal server error' });\n }\n const links = paginate(req.protocol, req.hostname, req.baseUrl, req.pagination, assetMeters.count);\n if (links) {\n res.set('Link', links);\n }\n return res.set('X-Total-Count', assetMeters.count).send(assetMeters.rows);\n};\n```\n\nThe output im expecting is that it would return two objects in array.\nCurrent result:\n\n```\n[ { id: 1,\n assetId: 1,\n sequence: null,\n meterName: 'BAD',\n measureUnit: 'km',\n meterType: 'CHARACTERISTIC',\n description: 'test description',\n active: true,\n createdAt: '2019-03-29T07:33:02.812Z',\n updatedAt: '2019-03-29T07:33:02.812Z' } ]\n```\n\n========================================\n\nCode:\n```text\nconst assetmeter = (sequelize) => {\n  const AssetMeter = sequelize.define('assetmeter', {\n    id: 1,\n    assetId: 1,\n    sequence: null,\n    meterName: 'BAD',\n    measureUnit: 'km',\n    meterType: 'CHARACTERISTIC', \n    description: 'test description', \n    active: true,\n  },{\n    id: 2,\n    assetId: 2,\n    sequence: null,\n    meterName: 'TEST',\n    measureUnit: 'TEST',\n    meterType: 'TEST', \n    description: 'TEST', \n    active: true,\n  });\n\n  return AssetMeter;\n}\n\nmodule.exports = assetmeter;\n```\n\n```text\nimport { AssetMeter } from '../../models';\nimport paginate from '../../utils/paginate';\n\nexport default async (req, res) => {\n  let assetMeters = [];\n  try {\n    assetMeters = await AssetMeter.findAndCountAll({\n      limit: req.pagination.limit, \n      offset: req.pagination.offset\n    });\n    console.log(assetMeters);\n  } catch (err) {\n    console.log(err);\n    return res.status(500).send({ error: 'Internal server error' });\n  }\n  const links = paginate(req.protocol, req.hostname, req.baseUrl, req.pagination, assetMeters.count);\n  if (links) {\n    res.set('Link', links);\n  }\n  return res.set('X-Total-Count', assetMeters.count).send(assetMeters.rows);\n};\n```\n\n```text\n[ { id: 1,\n    assetId: 1,\n    sequence: null,\n    meterName: 'BAD',\n    measureUnit: 'km',\n    meterType: 'CHARACTERISTIC',\n    description: 'test description',\n    active: true,\n    createdAt: '2019-03-29T07:33:02.812Z',\n    updatedAt: '2019-03-29T07:33:02.812Z' } ]\n```\n\n```text\ndefine(name, [obj={}], [opts]) -> Model\n```\n\n```text\nconst DEFAULT_VALUE: { /*...*/ };\n\nconst assetmeter = (sequelize) => {\n\n  const AssetMeter = sequelize.define('assetmeter', DEFAULT_VALUE);\n\n  AssetMeter.$queueResult([UserMock.build(), UserMock.build(), /* ... */]);\n\n  return AssetMeter;\n}\n\nmodule.exports = assetmeter;\n```\n\n```text\ndefine\n```\n\n```text\nAssetMeter\n```\n\n```text\nopts\n```\n\n```text\nAssetMeter\n```\n\n```text\nAssetMeter\n```\n\n```text\nfindAll\n```\n\n```text\n$queueResults\n```\n\n========================================\n\nComments:\n- What is the value of `req.pagination.limit` and `req.pagination.offset`?\n- @bird Value for pagination is 100, offset is 0\n- please sql command generated from findAndCountAll. add option \"log: console.log\" just like limit offset options.\n- @RohitDalal i didn't get nothing, sequelize doesn't have this feature i think\n- Log will be made in your terminal of sql query","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":202,"estimatedTokens":1064}}843{"id":"stack-25485391","source":"stackoverflow","questionId":25485391,"title":"Losing Data every time app is restarted","tags":["sequelize.js"],"text":"Title: Losing Data every time app is restarted\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nEvery time my application is restarted Sequelize drops all my tables in the database and defines them again (including the data), which is troublesome.\nIs there any way that only the schema changes can be applied to the database and to do nothing if there is no change?\n\n========================================\n\nTop Answer:\nTry this:\n\n```\nconst db = new Sequelize('db_name', 'username', 'pwd', {\n dialect: 'sqlite', \n storage: 'database.sqlite' // If you don't give storage location then by default it will store data in memory and each time when you restart your server, your data will be lost.\n\n========================================\n\nCode:\n```text\nSet logging option to true:   \n\n     sequelize.sync({logging:true}).then(function () {\n            console.log(\"CONNECTION ESTABLISHED SUCCESSFULLY\");\n        }).catch(function () {\n            console.log(\"CONNECTION REFUSED\");\n        })\n\n\nor else you can set the 'force' property to 'false' so that it will not create the table if it is already exists.\n\nsequelize.sync({ force: false}).then(function () {\n    console.log(\"CONNECTION ESTABLISHED SUCCESSFULLY\");\n}).catch(function () {\n    console.log(\"CONNECTION REFUSED\");\n})\n```\n\n```text\ndb\n  .sequelize\n  .sync({ force: false })\n  .complete(function(err) {\n    if (err) {\n      throw err[0];\n    } else {\n      http.createServer(app).listen(app.get('port'), function(){\n        console.log('Express server listening on port ' + app.get('port'));\n      });\n    }\n  });\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var User = sequelize.define('User', {\n    username: DataTypes.STRING,\n   });\n\n  return User;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var User = sequelize.define('User', {\n    username: DataTypes.STRING,\n    firstname: DataTypes.STRING\n  });\n\n  return User;\n};\n```\n\n```text\nconst db = new Sequelize('db_name', 'username', 'pwd', {\n    dialect: 'sqlite',    \n    storage: 'database.sqlite' // <----- this is important to mention, if you want to store your data on file.\n});\n```\n\n========================================\n\nComments:\n- I'm voting to close this question as off-topic because it makes no sense","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":87,"estimatedTokens":570}}844{"id":"stack-67911370","source":"stackoverflow","questionId":67911370,"title":"Javascript heap out of memory while running a js script to fetch data from an api every minute- javascript/node.js","tags":["javascript","node.js","sqlite","sequelize.js","v8"],"text":"Title: Javascript heap out of memory while running a js script to fetch data from an api every minute- javascript/node.js\nTags: javascript, node.js, sqlite, sequelize.js, v8\nSource: Stack Overflow\n\nQuestion:\nMy program grabs ~70 pages of 1000 items from an API and bulk-inserts it into a SQLite database using Sequelize. After looping through a few times, the memory usage of node goes up to around 1.2GB and and then eventually crashes the program with this error: `FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory`. I've tried using `delete` for all of the big variables that I use for the response of the API call and stuff with `variable = undefined` and then `global.gc()`, however I still get huge amounts of memory usage and eventually it crashes. Would increasing the memory cap of Node.js help? Or would the memory usage of it just keep increasing until it hits the next cap?\n\nHere's the full output of the error:\n\n```\n\n[6760:0x128008000] 436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n\n[6760:0x128008000] 436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\n\n[6760:0x128008000] 436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\n\n[6760:0x128008000] 436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000] 436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms (average mu = 0.918, current mu = 0.875) allocation failure \n\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\nzsh: segmentation fault npm start\n```\n\nI'm running node v15.12.0 on a MacBook Air M1 with 16GB of ram, however I don't think its the hardware that's the issue here as far as I understand this... Does anyone know why this is happening? Thanks in advance :)\n\nEdit:\n\nTurns out one of the node modules I was using never removed it's responses from the api calls, so I just rewrote that section of my code and now I'm good to go.\n\n========================================\n\nCode:\n```text\n<--- Last few GCs --->\n\n[6760:0x128008000]   436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n\n\n<--- JS stacktrace --->\n\n\n<--- Last few GCs --->\n\n[6760:0x128008000]   436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n\n\n<--- JS stacktrace --->\n\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\n\n<--- Last few GCs --->\n\n[6760:0x128008000]   436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n\n\n<--- JS stacktrace --->\n\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\n\n<--- Last few GCs --->\n\n[6760:0x128008000]   436085 ms: Scavenge 4068.7 (4110.5) -> 4068.7 (4110.5) MB, 2.7 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436345 ms: Scavenge 4073.0 (4113.8) -> 4072.9 (4118.8) MB, 9.2 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n[6760:0x128008000]   436565 ms: Scavenge (reduce) 4079.1 (4122.1) -> 4079.3 (4121.9) MB, 4.6 / 0.0 ms  (average mu = 0.918, current mu = 0.875) allocation failure \n\n\n<--- JS stacktrace --->\n\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\nzsh: segmentation fault  npm start\n```\n\n```text\nFATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory\n```\n\n```text\ndelete\n```\n\n```text\nvariable = undefined\n```\n\n```text\nglobal.gc()\n```\n\n```text\n--max-old-space-size=8000\n```\n\n```text\nglobal.gc()\n```\n\n========================================\n\nComments:\n- Which node module caused the issue? And how did you find out?","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":120,"estimatedTokens":1698}}845{"id":"stack-61369310","source":"stackoverflow","questionId":61369310,"title":"Sequelize transactions inside forEach issue","tags":["node.js","transactions","sequelize.js"],"text":"Title: Sequelize transactions inside forEach issue\nTags: node.js, transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've tried to wrap these 2 queries on a transaction like this\n\n```\nconst transaction = await db.sequelize.transaction()\ntry {\n await Table1.create({\n name: data.name\n }, {transaction});\n\n trainees.foreach(async trainee => {\n await Table2.create({\n name: trainee.name\n }, {transaction});\n })\n\n await transaction.commit();\n api.publish(source, target, false, {message: `Data successfully saved`});\n} catch (error) {\n await transaction.rollback();\n api.error(source, target, {\n message: error.message || `Unable to save data`\n });\n}\n```\n\nThe first query is executed , but following error appear on second query. \n\n```\ncommit has been called on this transaction(2f8905df-94b9-455b-a565-803e327e98e1), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)\n```\n\n========================================\n\nCode:\n```text\nconst transaction = await db.sequelize.transaction()\ntry {\n    await Table1.create({\n        name: data.name\n    }, {transaction});\n\n    trainees.foreach(async trainee => {\n        await Table2.create({\n            name: trainee.name\n        }, {transaction});\n    })\n\n    await transaction.commit();\n    api.publish(source, target, false, {message: `Data successfully saved`});\n} catch (error) {\n    await transaction.rollback();\n    api.error(source, target, {\n        message: error.message || `Unable to save data`\n    });\n}\n```\n\n```text\ncommit has been called on this transaction(2f8905df-94b9-455b-a565-803e327e98e1), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)\n```\n\n```text\ntry {\n  await db.sequelize.transaction(async transaction => {\n    await Table1.create({\n        name: data.name\n    }, {transaction});\n\n    // you should await each iteration\n    // forEach function of an Array object can't do it\n    for (const trainee of trainees) {\n      await Table2.create({\n          name: trainee.name\n      }, {transaction});\n    }\n    await Table3.create({\n        name: data.name\n    }, {transaction});\n\n    api.publish(source, target, false, {message: `Data successfully saved`});\n  })\n} catch (error) {\n    api.error(source, target, {\n        message: error.message || `Unable to save data`\n    });\n}\n```\n\n========================================\n\nComments:\n- Hi @Anatoly thanks for the answer. I just found the actual problem of my code and have edited the question. Perhaps you can update your answer too based on my updated question.\n- What is trainees? Array or collection-like object?\n- It's array of object","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":99,"estimatedTokens":663}}846{"id":"stack-36455513","source":"stackoverflow","questionId":36455513,"title":"Query two combined fields at once in Sequelize","tags":["sql","node.js","sequelize.js"],"text":"Title: Query two combined fields at once in Sequelize\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a search box for people's names in my application. Candidate's names are stored as firstName and then lastName. When I search the application, the application input submits a call to an ajax function, where I have this piece of code. \n\n```\nfilters.where = {\n $or: ['firstName', 'lastName', 'email'].map((item) =>\n ({[item]: {[queryClause]: `%${query}%`}}))\n };\n\n const scope = req.query.list;\n const candidates = await CandidateModel.scope(scope).findAll(filters);\n```\n\nHence if I type in the search box \"John\", it will find the candidate, and if I type in the word \"Smith\" it will find the candidate. \n\nThe problem is, if I type in the full name \"John Smith\" it won't come up, because the query is checking to see if \"John Smith\" equals \"John\", i.e. the first name, or if \"John Smith\" equals \"Smith\", the last name. It doesn't equal either of these. \n\nIs there a way to filter via combined fields in sequalize, so it tests if the query matches the firstName AND lastName fields combined?\n\n========================================\n\nTop Answer:\nuse something like the following to search by full name in this form \"firstName lastName\"\n\n```\nSequelize.where(Sequelize.fn(\"concat\", Sequelize.col(\"firstName\"), ' ', Sequelize.col(\"lastName\")), {\n $ilike: '%john smith%'\n })\n```\n\nby doing so you fix the issue of firstname or last name might have spaces.\n\n========================================\n\nCode:\n```text\nfilters.where = {\n    $or: ['firstName', 'lastName', 'email'].map((item) =>\n      ({[item]: {[queryClause]: `%${query}%`}}))\n  };\n\n  const scope = req.query.list;\n  const candidates = await CandidateModel.scope(scope).findAll(filters);\n```\n\n```text\nvar queryClause ='John Smith';\nfilters.where = {\n    $or: _.flatten(_.map(['firstName', 'lastName', 'email'], function(){\n        return _.map(queryClause.split(' '), function(q){\n            return {[item]: { $like : '%'+q+'%'}}\n        })\n    }))\n }\n```\n\n```text\n{\n    \"where\": {\n        \"$or\": [{\n                \"firstName\": {\n                    \"$like\": \"%John%\"\n                }\n            }, {\n                \"firstName\": {\n                    \"$like\": \"%Smith%\"\n                }\n            }, {\n                \"lastName\": {\n                    \"$like\": \"%John%\"\n                }\n            }, {\n                \"lastName: {\n                \"$like\": \"%Smith%\"\n            }\n        },\n        {\n            \"email\": {\n                \"$like\": \"%John%\"\n            }\n        },\n        {\n            \"email\": {\n                \"$like\": \"%Smith%\"\n            }\n        }]\n}\n}\n```\n\n```text\nsequelize.query('SELECT * FROM candidates where (firstName+lastName) like query OR email like query', { model: Candidate})\n  .then(function(projects){\n    // Each record will now be a instance of Candidate\n})\n```\n\n```text\nSequelize.where(Sequelize.fn(\"concat\", Sequelize.col(\"firstName\"), ' ', Sequelize.col(\"lastName\")), {\n                        $ilike: '%john smith%'\n                    })\n```\n\n========================================\n\nComments:\n- That would not work if first/last name has multiple words in it. For example firstName='Charles' lastName='de Gaulle'.\n- how world i use multiple where conditions with your approach ?\n- Sequelize.where is a chainable function. so try Sequelize.where(,,).where(,,)\n- @MinaLuke the chainable where does not work on my end\n- This also works perfectly. `where(fn(\"concat\", col(\"firstName\"), \" \", col(\"lastName\")), { [Op.iLike]: `%${search}%`, })`","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":115,"estimatedTokens":896}}847{"id":"stack-49459596","source":"stackoverflow","questionId":49459596,"title":"How do plurals work in Sequelize?","tags":["javascript","sequelize.js"],"text":"Title: How do plurals work in Sequelize?\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhile using Sequelize and reading the Sequelize docs, I observed that sometimes model names are used in singular and sometimes in plural. Some methods automatically added to models by associations have the singular form and some have the plural form.\n\n**1.** How does Sequelize compute the plurals? Does it simply append an \"s\" to the string?\n\n**2.** What if I want to use a noun with an irregular plural, such as \"Person\"?\n\n**3.** When defining an instance, should I use the singular or the plural form?\n\n**4.** When defining an alias, should I use the singular or the plural form?\n\n**5.** When defining a Many-to-many relationship, should I use the singular or the plural form in the `through` option?\n\n========================================\n\nCode:\n```text\nthrough\n```\n\n```text\nconst Foo = sequelize.define(\"foo\", {\n    // attributes\n});\n```\n\n```text\nconst Foo = sequelize.define(\"foo\", {\n    // attributes\n}, {\n    name: {\n        singular: \"mycustomsingularstring\",\n        plural: \"mycustompluralstring\"\n    }\n});\n```\n\n```text\nFoo.belongsTo(Bar, { as: \"person\" });\n```\n\n```text\nFoo.belongsToMany(Bar, { through: Foo_Bar, as: \"people\" });\n```\n\n```text\nFoo.belongsToMany(Bar, {\n    through: Foo_Bar,\n    as: {\n        singular: \"mycustomsingularstring\",\n        plural: \"mycustompluralstring\"\n    }\n});\n```\n\n```text\n// If you have this somewhere\nconst Foo_Bar = sequelize.define(\"foo_bar\", {\n    // attributes\n});\n\n// Then the best practice is to pass the model itself\nFoo.belongsToMany(Bar, { through: Foo_Bar });\n```\n\n```text\nFoo.belongsToMany(Bar, { through: \"foo_bars\" });\n```\n\n```text\n\"Person\" -> \"People\"\n```\n\n```text\n\"Octopus\" -> \"Octopi\"\n```\n\n```text\n\"Tooth\" -> \"Teeth\"\n```\n\n```text\n{ singular: \"your-singular-here\", plural: \"your-plural-here\" }\n```\n\n```text\nhasOne\n```\n\n```text\nbelongsTo\n```\n\n```text\nhasMany\n```\n\n```text\nbelongsToMany\n```\n\n```text\nthrough\n```\n\n========================================\n\nComments:\n- to be frank they should honestly have not added this, why do they want to make decisions on behalf of the user what the tablename would be called, this has complicated maintenance of their lib\n- @PirateApp Hello, I've become a maintainer now, in the future I might start some changes to move towards changing this default behavior!\n- Im really getting irritated with this singular and plural thing and its confusing as to where which has to be used. Its making the entire usage cumbersome and waste of time\n- @ShyamSundarR Hi, sorry to hear that you're having trouble, thank you for letting me know, perhaps we can add an option to disable this altogether. However, ideally we would want plurals to be applied on places where it does make sense, of course we don't want peopke's time to be wasted, can you please open an issue showing a minimal example in which this bothered you? Thanks!\n- @PedroA, Im a very new person trying to get around this package very recently maybe about a week back. I basically was trying to look into github's existing packages for some sample code. I generally know the general db principles and have worked with mongoose and mongo. I mean Im basically confused at places where we define models, the migrations createtable method. Multiple places are there. I also never could really understand when the models js files will be used, , will it be internally used to restrain data which are migrated to those models? really not interested to go through full docs\n- @PedroA, there are a multiple methods I find to define a model. When I auto generate it using CLI I get something that uses classes. In another way I can do it using sequelize.define method. Which exactly is the right way to define a model. Lot of confusing stuff.\n- Hi @ShyamSundarR, take a look at our express-example, it might help. Indeed I need to improve the documentation on all this. About using classes versus using `sequelize.define`, both work. You can choose what you like the most.\n- @PedroA, ya I had a look on that. Things seems to be pretty convincing. But what exactly is the need to maintain 2 separate folders, models and migrations, when both almost contain the same data model.\n- @PedroA, also your github repo doesnt have anything like migrations, seeders and all. I was expecting some properly working sample code.","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":121,"estimatedTokens":1092}}848{"id":"stack-74262031","source":"stackoverflow","questionId":74262031,"title":"Managing Transactions in Sequelize on NestJS","tags":["node.js","typescript","sequelize.js","nestjs"],"text":"Title: Managing Transactions in Sequelize on NestJS\nTags: node.js, typescript, sequelize.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nIve integrated sequelize ORM in typescript. My database is connected successfully and even queries are working. Now i need to use transactions in my application but there's no clear documentation on how to make it work on nestjs.\n\nIve tried to integrate transactions through sequelize connection but it seems not to be working.\n\nin my app.module ive created the sequelize configuration for root\n\n```\n@Module({\n\nimports: [\n SequelizeModule.forRoot({\n dialect: 'mysql',\n host: 'localhost',\n port: 3306,\n username: Config.db_userName,\n // password: Config.db_password,\n database: \"myDbName\",\n autoLoadModels: true,\n models: []\n }),\n myModule],\n controllers: [AppController],\n providers: [AppService],\n```\n\nand in my service.ts file i have the following constructor trying to use this connection of sequelize\n\n```\n@InjectConnection()\nprivate sequelize: Sequelize,\n```\n\nafter that im trying to use this.sequelize.transaction its not giving me any error in code.. but after compiling. im receiving this error\n\n```\nthis.sequelize.transaction() is not a function\n```\n\n========================================\n\nTop Answer:\nI had an issue with:\n\n```\nprivate sequelize: Sequelize\n```\n\nAnd then I realized, I used wrong Sequelize import (from \"sequelize\"). This import worked for me.\n\n```\nimport { Sequelize } from \"sequelize-typescript\"\n```\n\nMaybe it will help someone :)\n\n========================================\n\nCode:\n```text\n@Module({\n\n\nimports: [\n    SequelizeModule.forRoot({\n      dialect: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: Config.db_userName,\n     // password: Config.db_password,\n      database: \"myDbName\",\n      autoLoadModels: true,\n      models: []\n    }),\n  myModule],\n  controllers: [AppController],\n  providers: [AppService],\n```\n\n```text\n@InjectConnection()\nprivate sequelize: Sequelize,\n```\n\n```text\nthis.sequelize.transaction() is not a function\n```\n\n```text\nprivate sequelize: Sequelize\n```\n\n```text\ninjectConnection()\n```\n\n```text\nprivate sequelize: Sequelize\n```\n\n```text\nimport { Sequelize } from \"sequelize-typescript\"\n```\n\n```text\ninitSequelizeCLS();\n```\n\n```text\n@Module({\n  imports: [\n    SequelizeModule.forRoot({\n      ...\n    }),\n    SequelizeTransactionalModule.register(), // << this\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n@Injectable()\nexport class AppService {\n  constructor(\n    @InjectModel(Something)\n    private readonly something: typeof Something,\n    private readonly anotherService: AnotherService,\n  ) {}\n\n  @Transactional()\n  async appMethod(): Promise<void> {\n    await this.something.create({ message: 'hello' });\n    await this.something.create({ message: 'world' });\n    await this.anotherService.method(); // will use the same transaction by default, customizable with propagation option\n  }\n}\n```\n\n========================================\n\nComments:\n- Did you check what is stored in `this.sequelize`?\n- Its Empty object","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":149,"estimatedTokens":774}}849{"id":"stack-38085582","source":"stackoverflow","questionId":38085582,"title":"Express 4 - chaining res.json with promise.then does not work","tags":["node.js","express","promise","sequelize.js","bluebird"],"text":"Title: Express 4 - chaining res.json with promise.then does not work\nTags: node.js, express, promise, sequelize.js, bluebird\nSource: Stack Overflow\n\nQuestion:\nI'm working on an express 4 app that uses `mysql` and `sequelize` packages. Sequelize ORM uses promises to fetch data from database. I'm trying to fetch data in router and send json response. When I try to chain `then` callback of promise with `res.json` I get an error in console saying `Unhandled rejection TypeError: Cannot read property 'get' of undefined`\n\n```\n// This works\nemployeeRouter.get(\"/:id\", function(req, res){\n Employee.findById(req.params.id).then(function(data){\n res.json(data);\n });\n});\n\n// Replacing above code with following doesn't work\nemployeeRouter.get(\"/:id\", function(req, res){\n Employee.findById(req.params.id).then(res.json);\n});\n```\n\n**Error Stack:**\n\n```\nUnhandled rejection TypeError: Cannot read property 'get' of undefined\n at json (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\express\\lib\\response.js:241:21)\n at tryCatcher (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\util.js:16:23)\n at Promise._settlePromiseFromHandler (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:504:31)\n at Promise._settlePromise (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:561:18)\n at Promise._settlePromise0 (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:606:10)\n at Promise._settlePromises (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:685:18)\n at Async._drainQueue (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\async.js:138:16)\n at Async._drainQueues (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\async.js:148:10)\n at Immediate.Async.drainQueues [as _onImmediate] (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\async.js:17:14)\n at processImmediate [as _immediateCallback] (timers.js:383:17)\n```\n\n**models/employee.js**\n\n```\nvar Sequelize = require('sequelize'),\n sequelize = require('../db-connect/sequelize');\n\n(function(){\n\n // Use Strict Linting\n 'use strict';\n\n // Define Sequalize\n var Employee = sequelize.define('employee', {\n empNo: { field: 'emp_no', type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },\n birthDate: { field: 'birth_date', type: Sequelize.DATE },\n firstName: { field: 'first_name', type: Sequelize.STRING },\n lastName: { field: 'last_name', type: Sequelize.STRING },\n gender: { field: 'gender', type: Sequelize.ENUM('M', 'F') },\n hireDate: { field: 'hire_date', type: Sequelize.DATE },\n });\n\n // Export\n module.exports = Employee;\n\n}());\n```\n\n**db-connect/sequelize.js**\n\n```\nvar Sequelize = require('sequelize');\n\n(function(){\n\n // Use Strict Linting\n 'use strict';\n\n // Sequalize Connection\n var sequelize = null;\n\n // Create Sequalize Connection\n if(!sequelize){\n sequelize = new Sequelize('employees', 'root', '', {\n host: 'localhost',\n dialect: 'mysql',\n define: {\n timestamps: false\n }\n });\n }\n\n module.exports = sequelize;\n\n}());\n```\n\n**routes/employees.js**\n\n```\nvar express = require('express'),\n Employee = require('../models/employee');\n\n(function(app){\n\n // Use Strict Linting\n 'use strict';\n\n // Create Router\n var employeeRouter = express.Router();\n\n // Home Page\n employeeRouter.get(\"/\", function(req, res){\n res.json({employees: ['all']});\n });\n\n // Get Specific Employee\n employeeRouter.get(\"/:id\", function(req, res, next){\n Employee.findById(req.params.id).then(function(data){\n res.json(data);\n });\n });\n\n // ----------------------------------\n // Export\n // ----------------------------------\n\n module.exports = employeeRouter;\n\n}());\n```\n\n========================================\n\nCode:\n```text\n// This works\nemployeeRouter.get(\"/:id\", function(req, res){\n   Employee.findById(req.params.id).then(function(data){\n      res.json(data);\n   });\n});\n\n// Replacing above code with following doesn't work\nemployeeRouter.get(\"/:id\", function(req, res){\n   Employee.findById(req.params.id).then(res.json);\n});\n```\n\n```text\nUnhandled rejection TypeError: Cannot read property 'get' of undefined\n    at json (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\express\\lib\\response.js:241:21)\n    at tryCatcher (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\util.js:16:23)\n    at Promise._settlePromiseFromHandler (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:504:31)\n    at Promise._settlePromise (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:561:18)\n    at Promise._settlePromise0 (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:606:10)\n    at Promise._settlePromises (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\promise.js:685:18)\n    at Async._drainQueue (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\async.js:138:16)\n    at Async._drainQueues (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\async.js:148:10)\n    at Immediate.Async.drainQueues [as _onImmediate] (D:\\Workstation\\DataPro\\CountryStats\\node_modules\\bluebird\\js\\release\\async.js:17:14)\n    at processImmediate [as _immediateCallback] (timers.js:383:17)\n```\n\n```text\nvar Sequelize = require('sequelize'),\n    sequelize = require('../db-connect/sequelize');\n\n(function(){\n\n  // Use Strict Linting\n  'use strict';\n\n  // Define Sequalize\n  var Employee = sequelize.define('employee', {\n    empNo: { field: 'emp_no', type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },\n    birthDate: { field: 'birth_date', type: Sequelize.DATE },\n    firstName: { field: 'first_name', type: Sequelize.STRING },\n    lastName: { field: 'last_name', type: Sequelize.STRING },\n    gender: { field: 'gender', type: Sequelize.ENUM('M', 'F') },\n    hireDate: { field: 'hire_date', type: Sequelize.DATE },\n  });\n\n  // Export\n  module.exports = Employee;\n\n}());\n```\n\n```text\nvar Sequelize = require('sequelize');\n\n(function(){\n\n  // Use Strict Linting\n  'use strict';\n\n  // Sequalize Connection\n  var sequelize = null;\n\n  // Create Sequalize Connection\n  if(!sequelize){\n    sequelize = new Sequelize('employees', 'root', '', {\n      host: 'localhost',\n      dialect: 'mysql',\n      define: {\n        timestamps: false\n      }\n    });\n  }\n\n  module.exports = sequelize;\n\n}());\n```\n\n```text\nvar express = require('express'),\n    Employee = require('../models/employee');\n\n(function(app){\n\n  // Use Strict Linting\n  'use strict';\n\n  // Create Router\n  var employeeRouter = express.Router();\n\n  // Home Page\n  employeeRouter.get(\"/\", function(req, res){\n    res.json({employees: ['all']});\n  });\n\n  // Get Specific Employee\n  employeeRouter.get(\"/:id\", function(req, res, next){\n    Employee.findById(req.params.id).then(function(data){\n      res.json(data);\n    });\n  });\n\n  // ----------------------------------\n  // Export\n  // ----------------------------------\n\n  module.exports = employeeRouter;\n\n}());\n```\n\n```text\nmysql\n```\n\n```text\nsequelize\n```\n\n```text\nthen\n```\n\n```text\nres.json\n```\n\n```text\nUnhandled rejection TypeError: Cannot read property 'get' of undefined\n```\n\n```text\nemployeeRouter.get(\"/:id\", function(req, res){\n   Employee.findById(req.params.id).then(res.json.bind(res));\n});\n```\n\n```text\nemployeeRouter.get(\"/:id\", function(req, res){\n   Employee.findById(req.params.id).then(function(data) {\n       return res.json(data);\n   });\n});\n```\n\n```text\nvar x = res1.json;\nvar y = res2.json;\n\nconsole.log(x === y);    // true, no association with either res1 or res2 any more\n```\n\n```text\nvar z = res.json;\nz();\n```\n\n```text\nres.json\n```\n\n```text\nres\n```\n\n```text\njson()\n```\n\n```text\n.bind()\n```\n\n```text\nres\n```\n\n```text\n.bind()\n```\n\n```text\n.bind()\n```\n\n```text\nres\n```\n\n```text\nres1\n```\n\n```text\nres2\n```\n\n```text\nres1.json\n```\n\n```text\n.json\n```\n\n```text\nres1\n```\n\n```text\nres.json\n```\n\n```text\nres\n```\n\n```text\nres.json\n```\n\n```text\nz()\n```\n\n```text\nthis\n```\n\n```text\njson\n```\n\n```text\nundefined\n```\n\n```text\nres\n```\n\n```text\n.bind()\n```\n\n```text\nres.json(...)\n```\n\n```text\nthis\n```\n\n========================================\n\nComments:\n- Just to make sure I understand. res is undefined because passing res.json without () get's stored by doesn't get called right away and since the call site determines this binding we get undefined ?\n- what's a stub function?\n- @d9ngle - A stub function is just a little short function that wraps another function and makes a slight adjustment to how the wrapped function is called. You can see a polyfill for `.bind()` here on MDN to see an example of how it works.","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":38,"totalLines":392,"estimatedTokens":2158}}850{"id":"stack-44218974","source":"stackoverflow","questionId":44218974,"title":"SequelizeJS Error: TypeError: User.findAll is not a function","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: SequelizeJS Error: TypeError: User.findAll is not a function\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelizejs with expressjs app.\n\nhere is the code of my user model.\n\n**user.js**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define('User', {\n first_name: DataTypes.STRING,\n last_name: DataTypes.STRING,\n bio: DataTypes.STRING,\n email: DataTypes.STRING,\n profile_picture: DataTypes.STRING\n }, {\n classMethods: {\n associate: function(models) {\n // associations can be defined here\n }\n }\n }, {\n tableName: 'users'\n });\n return User;\n};\n```\n\nHere is my user controller\n\n**userComponent.js**\n\n```\nconst express = require( 'express' )\nconst router = express.Router()\nconst User = require( '../../models/user' )\n\nrouter.get( '/user', ( req, res, next ) => {\n User.findAll()\n .then( userResponse => {\n res.status( 200 ).json( userResponse )\n } )\n .catch( error => {\n res.status( 400 ).send( error )\n } )\n} )\n\nmodule.exports = router\n```\n\nBut when i am trying to get the data it throws this errors:\n\n TypeError: User.findAll is not a function\n at router.get (D:\\StateBoard-Project\\v2\\components\\user\\userComponent.js:6:8)\n at Layer.handle [as handle_request] (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at next (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\route.js:137:13)\n at Route.dispatch (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\route.js:112:3)\n at Layer.handle [as handle_request] (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\index.js:281:22\n at Function.process_params (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\index.js:335:12)\n at next (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\index.js:275:10)\n at Function.handle (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\index.js:174:3)\n at router (D:\\StateBoard-Project\\v2\\node_modules\\express\\lib\\router\\index.js:47:12)\n\nhttps://i.sstatic.net/1tmzR.png\n\nHere is the model/index.js file which has been auto generated by Sequelize. \n\n```\nconst fs = require( 'fs' )\nconst path = require( 'path' )\nconst Sequelize = require( 'sequelize' )\nconst basename = path.basename( module.filename )\nconst env = process.env.NODE_ENV || 'development'\nconst config = require( __dirname + '/..\\database.json' )[env]\nconst db = {}\n\nlet sequelize\nif (config.use_env_variable) {\n sequelize = new Sequelize( process.env[ config.use_env_variable ] )\n} else {\n sequelize = new Sequelize( config.database, config.username, config.password, config )\n}\n\nfs\n .readdirSync( __dirname )\n .filter( function( file ) {\n return ( file.indexOf( '.' ) !== 0 ) && ( file !== basename ) && ( file.slice( -3 ) === '.js' )\n } )\n .forEach( function( file ) {\n var model = sequelize[ 'import' ]( path.join( __dirname, file ) )\n db[ model.name ] = model\n });\n\nObject.keys( db ).forEach( function( modelName ) {\n if ( db[ modelName ].associate ) {\n db[ modelName ].associate( db )\n }\n});\n\ndb.sequelize = sequelize\ndb.Sequelize = Sequelize\n\nmodule.exports = db\n```\n\nWhat is missing here?\n\n========================================\n\nTop Answer:\nYour *user.js* file is exporting a function but you never instantiated it.\n\n```\nmodule.exports = function(sequelize, DataTypes) { // When you require it\n\n```\nconst User = require('../../models/user')\n```\n\nNow `User` is a reference to that function. Where does it get `sequelize` and `DataTypes` from?\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define('User', {\n    first_name: DataTypes.STRING,\n    last_name: DataTypes.STRING,\n    bio: DataTypes.STRING,\n    email: DataTypes.STRING,\n    profile_picture: DataTypes.STRING\n  }, {\n    classMethods: {\n      associate: function(models) {\n        // associations can be defined here\n      }\n    }\n  }, {\n    tableName: 'users'\n  });\n  return User;\n};\n```\n\n```text\nconst express = require( 'express' )\nconst router  = express.Router()\nconst User    = require( '../../models/user' )\n\nrouter.get( '/user', ( req, res, next ) => {\n  User.findAll()\n    .then( userResponse => {\n      res.status( 200 ).json( userResponse )\n    } )\n    .catch( error => {\n      res.status( 400 ).send( error )\n    } )\n} )\n\nmodule.exports = router\n```\n\n```text\nconst fs        = require( 'fs' )\nconst path      = require( 'path' )\nconst Sequelize = require( 'sequelize' )\nconst basename  = path.basename( module.filename )\nconst env       = process.env.NODE_ENV || 'development'\nconst config    = require( __dirname + '/..\\database.json' )[env]\nconst db        = {}\n\nlet sequelize\nif (config.use_env_variable) {\n  sequelize = new Sequelize( process.env[ config.use_env_variable ] )\n} else {\n  sequelize = new Sequelize( config.database, config.username, config.password, config )\n}\n\nfs\n  .readdirSync( __dirname )\n  .filter( function( file ) {\n    return ( file.indexOf( '.' ) !== 0 ) && ( file !== basename ) && ( file.slice( -3 ) === '.js' )\n  } )\n  .forEach( function( file ) {\n    var model = sequelize[ 'import' ]( path.join( __dirname, file ) )\n    db[ model.name ] = model\n  });\n\nObject.keys( db ).forEach( function( modelName ) {\n  if ( db[ modelName ].associate ) {\n    db[ modelName ].associate( db )\n  }\n});\n\ndb.sequelize = sequelize\ndb.Sequelize = Sequelize\n\nmodule.exports = db\n```\n\n```text\nconst models = require( '../../models/index');\n\nrouter.get( '/user', ( req, res, next ) => {\n  models.User.findAll()\n    .then( userResponse => {\n      res.status( 200 ).json( userResponse )\n    })\n    .catch( error => {\n      res.status( 400 ).send( error )\n    })\n} )\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) { // <-- function\n```\n\n```text\nconst User = require('../../models/user')\n```\n\n```text\nUser\n```\n\n```text\nsequelize\n```\n\n```text\nDataTypes\n```\n\n```text\neg. const user = require('../model/user');\n```\n\n========================================\n\nComments:\n- Hi, Sequelize auto generated a index file in model, model/index.js, i have added the code above. I think this models are instantiated there.\n- Yes, but how does `sequelize` gets injected into your `User` model? More like `require('..&#47;..&#47;models&#47;user')(sequelize, db)`. Then you'll need to import sequelize and db too before you can use it\n- anyhow, in your example, you are importing `User` from the 'user.js' file, which will give you the function I mentioned, not the instantiated model. I'll have in the docs\n- i think you have to instantiate the model using `sequelize = new Sequelize(...); sequelize.import('..&#47;..&#47;models&#47;user.js');` which will pass in `sequelize` and `DataTypes`\n- I don't have models/index.js file what should I do. In `module.exports = function(sequelize, DataTypes) {` I think `sequelize` is the object of library itself but what does the `DataTypes` object represents?\n- I don't have models/index.js file what should I do. In `module.exports = function(sequelize, DataTypes) {` I think `sequelize` is the object of library itself but what does the `DataTypes` object represents?","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":253,"estimatedTokens":1788}}851{"id":"stack-51771380","source":"stackoverflow","questionId":51771380,"title":"Sequelize with sqlite3 doesn't create a database","tags":["node.js","sqlite","sequelize.js","sequelize-cli"],"text":"Title: Sequelize with sqlite3 doesn't create a database\nTags: node.js, sqlite, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nCould you please help me to solve the problem?\nI use sqlite3 with sequelize npm package. After running migrations I don't see errors in console but I also don't see any database file. Also I can run migrations again and again, it doesn't look like correct behavior.\nHere is my **/config/config.js** file:\n\n```\nconst path = require('path');\n\nmodule.exports = {\n test: {\n username: 'root',\n password: 'root',\n database: path.join(__dirname, '..', 'database_test.sqlite'),\n host: 'localhost',\n dialect: 'sqlite',\n logging: console.log,\n operatorsAliases: false\n }\n};\n```\n\nHere is **migrations/XXXXXXXXXXXXXX-create-appeal.js** file:\n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => queryInterface.createTable('appeals', {\n appealId: {\n allowNull: false,\n primaryKey: true,\n type: Sequelize.UUID\n },\n name: {\n allowNull: false,\n type: Sequelize.STRING\n },\n description: {\n type: Sequelize.STRING(511)\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n }),\n down: queryInterface => queryInterface.dropTable('appeals')\n};\n```\n\nHere is **models/index.js** file\n\n```\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(path.join(__dirname, '..', 'config', 'config.js'))[env];\nconst db = {};\n\nlet sequelize = new Sequelize(config.database, config.username, config.password, config);\n\nfs\n .readdirSync(__dirname)\n .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))\n .forEach(file => {\n const model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nHere is **models/appeal.js** file:\n\n```\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n const Appeal = sequelize.define('appeals', {\n appealId: {\n allowNull: false,\n defaultValue: DataTypes.UUIDV4,\n primaryKey: true,\n type: DataTypes.UUID,\n validate: {\n isUUID: 4\n },\n get() {\n return this.getDataValue('appealId').toLowerCase();\n }\n },\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n description: {\n type: DataTypes.STRING(511)\n }\n }, {\n tableName: 'appeals'\n });\n Appeal.associate = models => {\n // associations can be defined here\n };\n return Appeal;\n};\n```\n\nAnother strange thing: if I put console log or error throwing in **models/index.js**, I'll see nothing, so that nodejs doesn't execute file.\n\nThanks.\n\n========================================\n\nTop Answer:\nTry it:\n\n**./config.js**\n\n```\nconst path = require('path');\n\nmodule.exports = {\n development: {\n username: 'root',\n password: 'root',\n database: path.join(__dirname, '..', 'database_test.sqlite'),\n host: 'localhost',\n dialect: 'sqlite',\n logging: true,\n operatorsAliases: false\n }\n};\n```\n\n**.sequelizerc**\n\n```\nconst path = require('path');\n\nmodule.exports = {\n 'models-path': path.resolve('./models'),\n 'seeders-path': path.resolve('./seeders'),\n 'migrations-path': path.resolve('./migrations'),\n 'config': path.resolve('./config', 'config.js')\n};\n```\n\n========================================\n\nCode:\n```text\nconst path = require('path');\n\nmodule.exports = {\n    test: {\n        username: 'root',\n        password: 'root',\n        database: path.join(__dirname, '..', 'database_test.sqlite'),\n        host: 'localhost',\n        dialect: 'sqlite',\n        logging: console.log,\n        operatorsAliases: false\n    }\n};\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n    up: (queryInterface, Sequelize) => queryInterface.createTable('appeals', {\n        appealId: {\n            allowNull: false,\n            primaryKey: true,\n            type: Sequelize.UUID\n        },\n        name: {\n            allowNull: false,\n            type: Sequelize.STRING\n        },\n        description: {\n            type: Sequelize.STRING(511)\n        },\n        createdAt: {\n            allowNull: false,\n            type: Sequelize.DATE\n        },\n        updatedAt: {\n            allowNull: false,\n            type: Sequelize.DATE\n        }\n    }),\n    down: queryInterface => queryInterface.dropTable('appeals')\n};\n```\n\n```text\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(path.join(__dirname, '..', 'config', 'config.js'))[env];\nconst db = {};\n\nlet sequelize = new Sequelize(config.database, config.username, config.password, config);\n\nfs\n    .readdirSync(__dirname)\n    .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))\n    .forEach(file => {\n        const model = sequelize.import(path.join(__dirname, file));\n        db[model.name] = model;\n    });\n\nObject.keys(db).forEach(modelName => {\n    if (db[modelName].associate) {\n        db[modelName].associate(db);\n    }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n'use strict';\n\nmodule.exports = (sequelize, DataTypes) => {\n    const Appeal = sequelize.define('appeals', {\n        appealId: {\n            allowNull: false,\n            defaultValue: DataTypes.UUIDV4,\n            primaryKey: true,\n            type: DataTypes.UUID,\n            validate: {\n                isUUID: 4\n            },\n            get() {\n                return this.getDataValue('appealId').toLowerCase();\n            }\n        },\n        name: {\n            type: DataTypes.STRING,\n            allowNull: false\n        },\n        description: {\n            type: DataTypes.STRING(511)\n        }\n    }, {\n        tableName: 'appeals'\n    });\n    Appeal.associate = models => {\n        // associations can be defined here\n    };\n    return Appeal;\n};\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n    test: {\n        username: 'root',\n        password: 'root',\n        storage: path.join(__dirname, '..', 'database_test.sqlite'),\n        host: 'localhost',\n        dialect: 'sqlite',\n        logging: console.log\n    }\n};\n```\n\n```text\nstorage\n```\n\n```text\ndatabase\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n    development: {\n        username: 'root',\n        password: 'root',\n        database: path.join(__dirname, '..', 'database_test.sqlite'),\n        host: 'localhost',\n        dialect: 'sqlite',\n        logging: true,\n        operatorsAliases: false\n    }\n};\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n    'models-path': path.resolve('./models'),\n    'seeders-path': path.resolve('./seeders'),\n    'migrations-path': path.resolve('./migrations'),\n     'config': path.resolve('./config', 'config.js')\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":329,"estimatedTokens":1759}}852{"id":"stack-56344840","source":"stackoverflow","questionId":56344840,"title":"Sequelize + Express TypeError: User.find is not a function","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize + Express TypeError: User.find is not a function\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am following an online tutorial on using PostgreSQL, Express and Passport and when I try to sign in, I get the following error stack trace:\n\n```\nat /path/to/server/routes/api.js:30:8\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat next (/path/to/server/node_modules/express/lib/router/route.js:137:13)\nat Route.dispatch (/path/to/server/node_modules/express/lib/router/route.js:112:3)\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat /path/to/server/node_modules/express/lib/router/index.js:281:22\nat Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)\nat next (/path/to/server/node_modules/express/lib/router/index.js:275:10)\nat Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)\nat router (/path/to/server/node_modules/express/lib/router/index.js:47:12)\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)\nat /path/to/server/node_modules/express/lib/router/index.js:284:7\nat Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)\nat next (/path/to/server/node_modules/express/lib/router/index.js:275:10)\nat /path/to/server/node_modules/express/lib/router/index.js:635:15\nat next (/path/to/server/node_modules/express/lib/router/index.js:260:14)\nat Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)\nat router (/path/to/server/node_modules/express/lib/router/index.js:47:12)\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)\nat /path/to/server/node_modules/express/lib/router/index.js:284:7\n```\n\n### /path/to/server/models/index.js\n\n```\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(__dirname + '/../config/config.json')[env];\nconst db = {};\n\nlet sequelize;\nif (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n .readdirSync(__dirname)\n .filter(file => {\n return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n })\n .forEach(file => {\n const model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(modelName => {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n### /path/to/server/models/user.js\n\n```\n'use strict';\n\nvar bcrypt = require('bcryptjs');\n\nmodule.exports = (sequelize, DataTypes) => {\n const User = sequelize.define('User', {\n username: DataTypes.STRING,\n password: DataTypes.STRING\n }, {});\n User.beforeSave((user, options) => {\n if (user.changed('password')) {\n user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);\n }\n });\n User.prototype.comparePassword = function (passw, cb) {\n bcrypt.compare(passw, this.password, function (err, isMatch) {\n if (err) {\n return cb(err);\n }\n cb(null, isMatch);\n });\n };\n User.associate = function(models) {\n // associations can be defined here\n };\n return User;\n};\n```\n\n### /path/to/server/api.js\n\n```\nconst express = require('express');\nconst jwt = require('jsonwebtoken');\nconst passport = require('passport');\nconst router = express.Router();\nrequire('../config/passport')(passport);\nconst User = require('../models').User;\n\nrouter.post('/signin', function(req, res) {\n User\n .find({\n where: {\n username: req.body.username\n }\n })\n .then((user) => {\n if (!user) {\n return res.status(401).send({\n message: 'Authentication failed. User not found.',\n });\n }\n user.comparePassword(req.body.password, (err, isMatch) => {\n if(isMatch && !err) {\n var token = jwt.sign(JSON.parse(JSON.stringify(user)), 'nodeauthsecret', {expiresIn: 86400 * 30});\n jwt.verify(token, 'nodeauthsecret', function(err, data){\n console.log(err, data);\n })\n res.json({success: true, token: 'JWT ' + token});\n } else {\n res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});\n }\n })\n })\n .catch((error) => res.status(400).send(error));\n});\n```\n\nWhy is User.find() not being recognised as a method? and how do I fix this issue?\n\n========================================\n\nTop Answer:\nAs it was already stated, it's due to it being deprecated now.\n\nThe official guide to upgrade sequelize to v5, in the model section, removed the aliases subsection.\n\n========================================\n\nCode:\n```text\nat /path/to/server/routes/api.js:30:8\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat next (/path/to/server/node_modules/express/lib/router/route.js:137:13)\nat Route.dispatch (/path/to/server/node_modules/express/lib/router/route.js:112:3)\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat /path/to/server/node_modules/express/lib/router/index.js:281:22\nat Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)\nat next (/path/to/server/node_modules/express/lib/router/index.js:275:10)\nat Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)\nat router (/path/to/server/node_modules/express/lib/router/index.js:47:12)\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)\nat /path/to/server/node_modules/express/lib/router/index.js:284:7\nat Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)\nat next (/path/to/server/node_modules/express/lib/router/index.js:275:10)\nat /path/to/server/node_modules/express/lib/router/index.js:635:15\nat next (/path/to/server/node_modules/express/lib/router/index.js:260:14)\nat Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)\nat router (/path/to/server/node_modules/express/lib/router/index.js:47:12)\nat Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)\nat trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)\nat /path/to/server/node_modules/express/lib/router/index.js:284:7\n```\n\n```text\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst Sequelize = require('sequelize');\nconst basename = path.basename(__filename);\nconst env = process.env.NODE_ENV || 'development';\nconst config = require(__dirname + '/../config/config.json')[env];\nconst db = {};\n\nlet sequelize;\nif (config.use_env_variable) {\n  sequelize = new Sequelize(process.env[config.use_env_variable], config);\n} else {\n  sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n  .readdirSync(__dirname)\n  .filter(file => {\n    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');\n  })\n  .forEach(file => {\n    const model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(modelName => {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\n'use strict';\n\nvar bcrypt = require('bcryptjs');\n\nmodule.exports = (sequelize, DataTypes) => {\n  const User = sequelize.define('User', {\n    username: DataTypes.STRING,\n    password: DataTypes.STRING\n  }, {});\n  User.beforeSave((user, options) => {\n    if (user.changed('password')) {\n      user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);\n    }\n  });\n  User.prototype.comparePassword = function (passw, cb) {\n    bcrypt.compare(passw, this.password, function (err, isMatch) {\n        if (err) {\n            return cb(err);\n        }\n        cb(null, isMatch);\n    });\n  };\n  User.associate = function(models) {\n    // associations can be defined here\n  };\n  return User;\n};\n```\n\n```text\nconst express = require('express');\nconst jwt = require('jsonwebtoken');\nconst passport = require('passport');\nconst router = express.Router();\nrequire('../config/passport')(passport);\nconst User = require('../models').User;\n\nrouter.post('/signin', function(req, res) {\n  User\n      .find({\n        where: {\n          username: req.body.username\n        }\n      })\n      .then((user) => {\n        if (!user) {\n          return res.status(401).send({\n            message: 'Authentication failed. User not found.',\n          });\n        }\n        user.comparePassword(req.body.password, (err, isMatch) => {\n          if(isMatch && !err) {\n            var token = jwt.sign(JSON.parse(JSON.stringify(user)), 'nodeauthsecret', {expiresIn: 86400 * 30});\n            jwt.verify(token, 'nodeauthsecret', function(err, data){\n              console.log(err, data);\n            })\n            res.json({success: true, token: 'JWT ' + token});\n          } else {\n            res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});\n          }\n        })\n      })\n      .catch((error) => res.status(400).send(error));\n});\n```\n\n```text\nfind\n```\n\n```text\nfind\n```\n\n```text\nfindAll\n```\n\n```text\nfindOne\n```\n\n========================================\n\nComments:\n- In the ./models folder there should be an index.js file. If it's there add it to your question. If it's not then create it and copy&paste code shown here github.com/sequelize/express-example/blob/master/models/&hellip;\n- Could you try a `console.log` on the object returned when you require the models folder? This way we can see whats is the returned object. Like this: `console.log(require('..&#47;models'))`\n- @viniciusjssouza I added the line `console.log(require('..&#47;models'))` but that printed out several hundreds of lines of code. I now tried this instead `console.log(require('..&#47;models').User)` this printed out `User`. I then tried this: `console.log(typeof require('..&#47;models').User)` this printed out `function`. I don't know if that helps.\n- @HomunculusReticulli I was looking for a `find` method on the sequelize doc and couldn't find the `find` method, just a `findAll` and `findOne`. Perhaps it was deprecated on newer versions docs.sequelizejs.com/manual/querying.html\n- Well spotted. This was the problem. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":313,"estimatedTokens":2707}}853{"id":"stack-33161145","source":"stackoverflow","questionId":33161145,"title":"ExpressJS - Sequelize - Column Missing Error","tags":["mysql","express","sequelize.js"],"text":"Title: ExpressJS - Sequelize - Column Missing Error\nTags: mysql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to properly query all images that fit my sequelize query in addition to the description that is connected to the specific query, but I receive an error for a `createdAt` column, which is not located in my table. How can I specify the columns I want to use within my query?\n\nHere is the query (The pattern and color are correctly pulled into the query):\n\n```\nrouter.get('/:pattern/:color/result', function(req, res){\n\n console.log(req.params.color);\n console.log(req.params.pattern);\n\n Images.findAll({ \n where: {\n pattern: req.params.pattern,\n color: req.params.color\n }\n });\n //console.log(image);\n //console.log(doc.descriptions_id);\n res.render('pages/result.hbs', {\n pattern : req.params.pattern,\n color : req.params.color,\n image : image\n });\n\n});\n```\n\nHere is my table:\n\n```\nCREATE TABLE `images` (\n `id` int(5) NOT NULL AUTO_INCREMENT,\n `pattern` varchar(225) DEFAULT NULL,\n `color` varchar(225) DEFAULT NULL,\n `imageUrl` varchar(225) DEFAULT NULL,\n `imageSource` varchar(225) DEFAULT NULL,\n `description_id` int(11) DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `description_id` (`description_id`),\n CONSTRAINT `images_ibfk_1` FOREIGN KEY (`description_id`) REFERENCES `description` (`description_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;\n```\n\nHere is the error:\n\n```\nExecuting (default): SELECT `id`, `pattern`, `color`, `imageUrl`, `imageSource`, `description_id`, `createdAt`, `updatedAt` FROM `images` AS `images` WHERE `images`.`pattern` = 'solid' AND `images`.`color` = 'navy-blue';\n Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'createdAt' in 'field list'\n at Query.formatError (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/dialects/mysql/query.js:160:14)\n```\n\n========================================\n\nTop Answer:\nBy default, sequelize assumes that you have timestamps in your table. This can be disabled either globally\n\n```\nnew Sequelize(..., { define: { timestamps: false }});\n```\n\nOr per model:\n\n```\nsequelize.define(name, attributes, { timestamps: false });\n```\n\nOr if you only have some timesstamps (fx updated, but not created)\n\n```\nsequelize.define(name, attributes, { createdAt: false });\n```\n\nIn case your column is called something else:\n\n```\nsequelize.define(name, attributes, { createdAt: 'make_at' });\n```\n\nhttp://docs.sequelizejs.com/en/latest/api/sequelize/\n\nIn this way, you don't have to specify all attributes each time - sequelize knows which attributes it can actually select.\n\nIf you really wanted to specify which attributes should be selected by \ndefault you could use a scope\n\n```\nsequelize.define(name, attributes, { defaultScope { attributes: [...] }});\n```\n\nAnd that will be applied to each find call\n\n========================================\n\nCode:\n```text\nrouter.get('/:pattern/:color/result', function(req, res){\n\n    console.log(req.params.color);\n    console.log(req.params.pattern);\n\n    Images.findAll({ \n        where: {\n            pattern: req.params.pattern,\n            color: req.params.color\n        }\n        });\n        //console.log(image);\n        //console.log(doc.descriptions_id);\n        res.render('pages/result.hbs', {\n            pattern : req.params.pattern,\n            color : req.params.color,\n            image : image\n        });\n\n});\n```\n\n```text\nCREATE TABLE `images` (\n  `id` int(5) NOT NULL AUTO_INCREMENT,\n  `pattern` varchar(225) DEFAULT NULL,\n  `color` varchar(225) DEFAULT NULL,\n  `imageUrl` varchar(225) DEFAULT NULL,\n  `imageSource` varchar(225) DEFAULT NULL,\n  `description_id` int(11) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `description_id` (`description_id`),\n  CONSTRAINT `images_ibfk_1` FOREIGN KEY (`description_id`) REFERENCES `description` (`description_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;\n```\n\n```text\nExecuting (default): SELECT `id`, `pattern`, `color`, `imageUrl`, `imageSource`, `description_id`, `createdAt`, `updatedAt` FROM `images` AS `images` WHERE `images`.`pattern` = 'solid' AND `images`.`color` = 'navy-blue';\n    Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'createdAt' in 'field list'\n        at Query.formatError (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/dialects/mysql/query.js:160:14)\n```\n\n```text\ncreatedAt\n```\n\n```text\nImages.findAll({\n    where : {\n        pattern: req.params.pattern,\n        color: req.params.color\n    },\n    attributes : ['id', 'pattern', 'color', 'imageUrl', 'imageSource']\n})\n```\n\n```text\nid\n```\n\n```text\npattern\n```\n\n```text\ncolor\n```\n\n```text\nimageUrl\n```\n\n```text\nimageSource\n```\n\n```text\nnew Sequelize(..., { define: { timestamps: false }});\n```\n\n```text\nsequelize.define(name, attributes, { timestamps: false });\n```\n\n```text\nsequelize.define(name, attributes, { createdAt: false });\n```\n\n```text\nsequelize.define(name, attributes, { createdAt: 'make_at' });\n```\n\n```text\nsequelize.define(name, attributes, { defaultScope { attributes: [...] }});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":195,"estimatedTokens":1274}}854{"id":"stack-28844617","source":"stackoverflow","questionId":28844617,"title":"sequelize with postgres database not working after migration from mysql","tags":["mysql","postgresql","sequelize.js","postgresql-9.3"],"text":"Title: sequelize with postgres database not working after migration from mysql\nTags: mysql, postgresql, sequelize.js, postgresql-9.3\nSource: Stack Overflow\n\nQuestion:\nI change MySQL databese into postgreSQL in sequelize. But After migration I have issue with upper and lowercase first letter in Table or Model...\nBefore my MySQL version was working properly but after migration I got error message: \n`500 SequelizeDatabaseError: relation \"Users\" does not exist`\n\n**My User model:**\n\n```\nmodule.exports = function(sequelize, Sequelize) {\n var User = sequelize.define(\"User\", {\n // profile\n userlevel: Sequelize.STRING,\n restaurant: Sequelize.STRING,\n access: Sequelize.STRING,\n optionsid: Sequelize.STRING,\n email: Sequelize.STRING,\n name: Sequelize.STRING,\n gender: Sequelize.STRING,\n location: Sequelize.STRING,\n website: Sequelize.STRING,\n picture: Sequelize.STRING,\n // Oauth\n password: {\n type: Sequelize.STRING,\n set: function(v) {\n var salt = bcrypt.genSaltSync(5);\n var password = bcrypt.hashSync(v, salt);\n return this.setDataValue('password', password);\n }\n },\n .....\n```\n\n**Migration file:**\n\n```\n\"use strict\";\nmodule.exports = {\n up: function(migration, DataTypes, done) {\n migration.createTable(\"users\", {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: DataTypes.INTEGER\n },\n userlevel: {\n type: DataTypes.STRING,\n defaultValue: '5'\n },\n restaurant: {\n type: DataTypes.STRING,\n defaultValue: ''\n },\n access: {\n type: DataTypes.STRING,\n defaultValue: '1'\n },\n optionsid: {\n type: DataTypes.STRING,\n defaultValue: ''\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false\n },\n name: {\n type: DataTypes.STRING,\n defaultValue: ''\n },\n gender: {\n type: DataTypes.STRING,\n defaultValue: ''\n },\n location: {\n type: DataTypes.STRING,\n defaultValue: ''\n },\n website: {\n type: DataTypes.STRING,\n defaultValue: ''\n },\n picture: {\n type: DataTypes.STRING,\n defaultValue: ''\n },\n password: {\n type: DataTypes.STRING\n },\n facebook: {\n type: DataTypes.STRING\n },\n twitter: {\n type: DataTypes.STRING\n },\n google: {\n type: DataTypes.STRING\n },\n tokens: {\n type: DataTypes.STRING\n },\n resetPasswordToken: {\n type: DataTypes.STRING\n },\n resetPasswordExpires: {\n type: DataTypes.DATE\n },\n createdAt: {\n allowNull: false,\n type: DataTypes.DATE\n },\n updatedAt: {\n allowNull: false,\n type: DataTypes.DATE\n }\n }).done(done);\n },\n down: function(migration, DataTypes, done) {\n migration.dropTable(\"users\").done(done);\n }\n};\n```\n\nIf I change first letter of table in postgreSQL to uppercase everything is working properly...\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, Sequelize) {\n  var User = sequelize.define(\"User\", {\n    // profile\n    userlevel: Sequelize.STRING,\n    restaurant: Sequelize.STRING,\n    access: Sequelize.STRING,\n    optionsid: Sequelize.STRING,\n    email: Sequelize.STRING,\n    name: Sequelize.STRING,\n    gender: Sequelize.STRING,\n    location: Sequelize.STRING,\n    website: Sequelize.STRING,\n    picture: Sequelize.STRING,\n    // Oauth\n    password: {\n      type: Sequelize.STRING,\n      set: function(v) {\n        var salt = bcrypt.genSaltSync(5);\n        var password = bcrypt.hashSync(v, salt);\n        return this.setDataValue('password', password);\n      }\n    },\n    .....\n```\n\n```text\n\"use strict\";\nmodule.exports = {\n  up: function(migration, DataTypes, done) {\n    migration.createTable(\"users\", {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: DataTypes.INTEGER\n      },\n      userlevel: {\n        type: DataTypes.STRING,\n        defaultValue: '5'\n      },\n      restaurant: {\n        type: DataTypes.STRING,\n        defaultValue: ''\n      },\n      access: {\n        type: DataTypes.STRING,\n        defaultValue: '1'\n      },\n      optionsid: {\n        type: DataTypes.STRING,\n        defaultValue: ''\n      },\n      email: {\n        type: DataTypes.STRING,\n        allowNull: false\n      },\n      name: {\n        type: DataTypes.STRING,\n        defaultValue: ''\n      },\n      gender: {\n        type: DataTypes.STRING,\n        defaultValue: ''\n      },\n      location: {\n        type: DataTypes.STRING,\n        defaultValue: ''\n      },\n      website: {\n        type: DataTypes.STRING,\n        defaultValue: ''\n      },\n      picture: {\n        type: DataTypes.STRING,\n        defaultValue: ''\n      },\n      password: {\n        type: DataTypes.STRING\n      },\n      facebook: {\n        type: DataTypes.STRING\n      },\n      twitter: {\n        type: DataTypes.STRING\n      },\n      google: {\n        type: DataTypes.STRING\n      },\n      tokens: {\n        type: DataTypes.STRING\n      },\n      resetPasswordToken: {\n        type: DataTypes.STRING\n      },\n      resetPasswordExpires: {\n        type: DataTypes.DATE\n      },\n      createdAt: {\n        allowNull: false,\n        type: DataTypes.DATE\n      },\n      updatedAt: {\n        allowNull: false,\n        type: DataTypes.DATE\n      }\n    }).done(done);\n  },\n  down: function(migration, DataTypes, done) {\n    migration.dropTable(\"users\").done(done);\n  }\n};\n```\n\n```text\n500 SequelizeDatabaseError: relation \"Users\" does not exist\n```\n\n```text\nusers\n```\n\n```text\nUsers\n```\n\n```text\nUSERS\n```\n\n```text\nusers\n```\n\n```text\n\"users\"\n```\n\n```text\n\"Users\"\n```\n\n```text\n\"USERS\"\n```\n\n```text\n\"users\"\n```\n\n```text\n\"Users\"\n```\n\n```text\n\"users\"\n```\n\n```text\n\"Users\"\n```\n\n========================================\n\nComments:\n- Thanks for answer! So my tables then will have first letter uppercase ? Is this good idea ?\n- @Makromat The usual advice with PostgreSQL is to use lower case identifiers with underscores between words. However, the naming convention that you'd use depends on what your ORM expects. If Sequalize doesn't have a convention then I'd recommend lower case and underscores so that you won't get stuck quoting your identifiers all the time but anything consistent should be good enough.\n- PostgreSQL doesn't care whether you use delimited identifiers. They're mildly inconvenient, because when you write *SQL*, you have to use double quotes all the time. But you're using an ORM, so you're unlikely to write much SQL. Most (all?) ORMs let you overide their conventions. For Sequelize, see Working with legacy tables.\n- Damn it this one is another bad part of sequelize (along with the migration and sync decoupling) ! So you migrate your table with \"users\", and you have no choice to call it \"Users\" in your code ? Having 3 points of verification ( model, migration file, automagic sync stuff) all this is bery misleading, and do not provide a robust pattern. Oh yeah; quote it if \"...(no reason provided by any convention)..\", that'll work\n- @MikeSherrill'CatRecall' link is broken\n- @JamesKlein: Do we really want to work with frameworks that keep breaking links? It's 2018. We know how hypertext and web servers and URIs work now. Updated link. Also, see Cool URIs don't change","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":303,"estimatedTokens":1726}}855{"id":"stack-49480021","source":"stackoverflow","questionId":49480021,"title":"Sequelize model loading in NodeJS","tags":["node.js","sequelize.js"],"text":"Title: Sequelize model loading in NodeJS\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am currently studying using NodeJS, Express, PostgreSQL and Sequelize on Scotch.io then I came across this:\n\n```\n'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar Sequelize = require('sequelize');\nvar basename = path.basename(module.filename);\nvar env = process.env.NODE_ENV || 'development';\nvar config = require(__dirname + '/../config/config.json')[env];\nvar db = {};\n\nif (config.use_env_variable) {\n var sequelize = new Sequelize(process.env[config.use_env_variable]);\n} else {\n var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf('.') !== 0) && (file !== basename) & (file.slice(-3) === '.js');\n })\n .forEach(function(file) {\n var model = sequelize['import'](path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function(modelName) {\n if (db[modelName].associate) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\nI am seeking an explanation of this code in plain terms. What exactly is happening here?\n\nI do understand the part where we default to `development` if Node environment is not set but I need clarification of the file reading part i.e where `fs` begins.\n\n========================================\n\nTop Answer:\nIn plain terms, this is importing all the `.js` files from the same directory as this file. This is done through `sequelize['import']` method.\n\nMoreover it is assumed that all these files contain sequelize models, as the return value from the import is mapped on dictionary named `db`. \n\n```\ndb[model.name] = model\n```\n\nOnce all the files are imported and models are mapped to `db`, a loop is run to call `associate` on each model, only if that model contains associate method. Usually associate method is used to define all the associations between the models i.e. `hasMany`, `hasOne`, `belongsTo` etc.\n\n========================================\n\nCode:\n```text\n'use strict';\n\nvar fs        = require('fs');\nvar path      = require('path');\nvar Sequelize = require('sequelize');\nvar basename  = path.basename(module.filename);\nvar env       = process.env.NODE_ENV || 'development';\nvar config    = require(__dirname + '/../config/config.json')[env];\nvar db        = {};\n\nif (config.use_env_variable) {\n  var sequelize = new Sequelize(process.env[config.use_env_variable]);\n} else {\n  var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf('.') !== 0) && (file !== basename) & (file.slice(-3) === '.js');\n  })\n  .forEach(function(file) {\n    var model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(function(modelName) {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\ndevelopment\n```\n\n```text\nfs\n```\n\n```text\nif (config.use_env_variable) {\n  var sequelize = new Sequelize(process.env[config.use_env_variable]);\n} else {\n  var sequelize = new Sequelize(config.database, config.username, config.password, config);\n}\n```\n\n```text\nmodule.exports = {\n  development: {\n    dialect: 'postgres',\n    username: '<username name>',\n    password: 'test',\n    database: '<db name>',\n    host: 'localhost'\n  },\n  production: {\n    dialect: 'postgres',\n    dialectOptions: {\n      ssl: true\n    },\n    protocol: 'postgres',\n    use_env_variable: 'DATABASE_URL'\n  }\n}\n```\n\n```text\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf('.') !== 0) && (file !== basename) & (file.slice(-3) === '.js');\n  })\n  .forEach(function(file) {\n    var model = sequelize['import'](path.join(__dirname, file));\n    db[model.name] = model;\n  });\n```\n\n```text\nObject.keys(db).forEach(function(modelName) {\n  if (db[modelName].associate) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  var Model1 = sequelize.define('Model1',\n    { ... })\n\n  // Class Method\n  Model1.associate = function (models) {\n    Model1.belongsTo(models.Model2)\n  }\n  return Model1\n}\n```\n\n```text\nrequire('./models')\n  .sequelize.sync({ force: true }) // access to your sequelize db\n```\n\n```text\nsequelize-cli\n```\n\n```text\nsequelize init\n```\n\n```text\nindex.js\n```\n\n```text\nmodels/\n```\n\n```text\nDATABASE_URL\n```\n\n```text\nconfig.js\n```\n\n```text\nfs.readdirSync\n```\n\n```text\n__dirname\n```\n\n```text\nmodels/\n```\n\n```text\ndb[model.name] = model;\n```\n\n```text\nassociate\n```\n\n```text\nsequelize\n```\n\n```text\nSequelize\n```\n\n```text\nrequire('./models').Model1 // access to your models\n```\n\n```text\ndb[model.name] = model\n```\n\n```text\n.js\n```\n\n```text\nsequelize['import']\n```\n\n```text\ndb\n```\n\n```text\ndb\n```\n\n```text\nassociate\n```\n\n```text\nhasMany\n```\n\n```text\nhasOne\n```\n\n```text\nbelongsTo\n```\n\n========================================\n\nComments:\n- Wow! Thank you so much for the explanation. Much clearer now. Just one more thing, what is this line for: var basename = path.basename(module.filename);?\n- I believe it just strips the filename from its path. Check out stackoverflow.com/questions/19811541/&hellip; for a discussion on it if you'd like. Ie I believe the return is `index.js` (assuming the file is called index.js).\n- Thank you so much man! Your response was really helpful.\n- That's great, happy to help!\n- is your `config.json` is in `.gitignore` ?\n- @keshavAggarwal No - it's safe to checkin `.config.json`. If you don't want the development credentials exposed, then use environment variables. A common package used is `dotenv`. **You *should* ignore `.env` files.**\n- Great! Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":286,"estimatedTokens":1489}}856{"id":"stack-36195338","source":"stackoverflow","questionId":36195338,"title":"Iterate sequelize query result set (Hapijs)","tags":["javascript","sequelize.js","hapi.js"],"text":"Title: Iterate sequelize query result set (Hapijs)\nTags: javascript, sequelize.js, hapi.js\nSource: Stack Overflow\n\nQuestion:\nI have a code that returns a result. Normaly when I receive that result, I send it to the client and along the way it is converted to pure JSON object.\n\nBut now I need to do some operations on that result set, and then do another lookup in the database.\n\nWhat I dont understand is the structure of the result set. How Do I properly iterate on it. I could extract the values manualy using a for loop, but I have a feeling that is not the way to do it.\n\nThis is the code that returns results:\n\n```\nmodels.Results.findAll({\n where: {ProjectId: projectId}\n })\n .then(function (resultset) { \n //How do I properly iterate over the resultset\n for(p in resultset){\n\n var a = p;\n var something;\n\n }\n\n reply(resultset).code(200);\n }, function (rejectedPromiseError) {\n reply(rejectedPromiseError).code(401);\n });\n```\n\nImage shows the result in debug mode. It has 4 objects in array:https://i.sstatic.net/6Vxxl.jpg\n\n========================================\n\nTop Answer:\nYou want to avoid forEach operations because NodeJS runs on a single thread. This is wonderful because it forces us to code differently. So imagine this, when the forEach runs its hogs the CPU because it's a greedy synchronous operation. We need to resources and always think about running in parallel.\n\nhttp://bluebirdjs.com/docs/api/promise.each.html\n\n\"Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (value, index, length) where value is the resolved value of a respective promise in the input array. Iteration happens serially. If the iterator function returns a promise or a thenable, ***then the result of the promise is awaited before continuing with next iteration***. If any promise in the input array is rejected, then the returned promise is rejected as well.\"\n\nThis code, in essence, waits for the previous record to be retrieved before moving on to the next. So the faster the CPU, the faster the output.\n\n```\nnotification.sendAll = (message, cb) => {\n db.models.users.findAll().then(users => {\n db.Promise.each(users, user => {\n console.log('user id: ' + user.id)\n notification.sendMessage(message, ret => {\n })\n return\n })\n })\n}\n```\n\n========================================\n\nCode:\n```text\nmodels.Results.findAll({\n            where: {ProjectId: projectId}\n        })\n        .then(function (resultset) {              \n            //How do I properly iterate over the resultset\n            for(p in resultset){\n\n                var a = p;\n                var something;\n\n            }\n\n\n            reply(resultset).code(200);\n        }, function (rejectedPromiseError) {\n            reply(rejectedPromiseError).code(401);\n        });\n```\n\n```text\nresultset.forEach((resultSetItem) => {\n    console.log(resultSetItem.get({\n        plain: true\n    }));\n});\n```\n\n```text\nmodel.findAll\n```\n\n```text\nresultset\n```\n\n```text\nInstance\n```\n\n```text\nresultset\n```\n\n```text\nget\n```\n\n```text\nplain: true\n```\n\n```text\nnotification.sendAll = (message, cb) => {\n    db.models.users.findAll().then(users => {\n        db.Promise.each(users, user => {\n            console.log('user id: ' + user.id)\n            notification.sendMessage(message, ret => {\n            })\n            return\n        })\n    })\n}\n```\n\n```js\nawait Request.findAll({\n         where: {\n             S_Id: 13, \n             Customer_Id:req.body.Customer_Id,\n         }\n     }).then(function (results) {\n         res.send(results[0][\"CardNumber\"])\n         quitFunction.status =true;\n```\n\n```text\n[\n    {\n        \"id\": 1,\n        \"S_Id\": 13,\n        \"Customer_Id\": 4,\n        \"CardNumber\": 345345,\n        \"createdAt\": \"2019-04-02T19:16:35.000Z\",\n        \"updatedAt\": \"2019-04-02T19:24:41.000Z\"\n    },\n    {\n        \"id\": 2,\n        \"S_Id\": 13,\n        \"Customer_Id\": 4,\n        \"CardNumber\": 345345,\n        \"createdAt\": \"2019-04-02T19:24:48.000Z\",\n        \"updatedAt\": \"2019-04-02T19:35:26.000Z\"\n    },\n    {\n        \"id\": 3,\n        \"ServicAction_Id\": 13,\n        \"Customer_Id\": 4,\n        \"CardNumber\": 345345,\n        \"createdAt\": \"2019-04-02T19:39:40.000Z\",\n        \"updatedAt\": \"2019-04-04T20:03:52.000Z\"\n    },\n    {\n        \"id\": 4,\n        \"ServicAction_Id\": 13,\n        \"Customer_Id\": 4,\n        \"CardNumber\": 345345,\n        \"createdAt\": \"2019-04-04T20:08:11.000Z\",\n        \"updatedAt\": \"2019-04-04T20:08:11.000Z\"\n    },\n    {\n        \"id\": 5,\n        \"ServicAction_Id\": 13,\n        \"Customer_Id\": 4,\n        \"CardNumber\": 345345,\n        \"createdAt\": \"2019-04-05T18:53:34.000Z\",\n        \"updatedAt\": \"2019-04-05T18:53:34.000Z\"\n    },\n    {\n        \"id\": 6,\n        \"S_Id\": 13,\n        \"Customer_Id\": 4,\n        \"CardNumber\": 345345,\n        \"createdAt\": \"2019-04-05T18:54:32.000Z\",\n        \"updatedAt\": \"2019-04-05T18:54:32.000Z\"\n    },\n    {\n        \"id\": 7,\n        \"S_Id\": 13,\n        \"Customer_Id\": 4,\n        \"CardNumber\": 345345,\n        \"createdAt\": \"2019-04-05T18:54:57.000Z\",\n        \"updatedAt\": \"2019-04-05T18:54:57.000Z\"\n    } ]\n```\n\n========================================\n\nComments:\n- Instead of a `for in` loop, try `resultset.forEach(function(result){&#47;&#47; result should be the object that has the properties you're looking for (dataValues, hasPrimaryKeys, etc.)});`.\n- `db.Promise` is not native in Sequelize, which is what the OP is asking about.","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":202,"estimatedTokens":1363}}857{"id":"stack-37396592","source":"stackoverflow","questionId":37396592,"title":"Sequelize not creating join table many-to-many","tags":["many-to-many","sequelize.js"],"text":"Title: Sequelize not creating join table many-to-many\nTags: many-to-many, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen I start my server, soon after establishing a database connection I do this:\n\n```\nvar tool = require(\"./tool\"); //created with Sequelize.define()\nvar requirement = require(\"./requirement\"); //created with Sequelize.define()\n\ntool.belongsToMany(requirement, {through: \"toolRequirements\"});\nrequirement.belongsToMany(tool, {through: \"toolRequirements\"});\n\ntool.sync();\nrequirement.sync();\n```\n\nI expect to see the join table being created, but it's not there. What am I missing?\n\n```\nExecuting (default): CREATE TABLE IF NOT EXISTS `requirements` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): CREATE TABLE IF NOT EXISTS `tools` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255) NOT NULL, `idCode` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`requirements`)\nExecuting (default): PRAGMA INDEX_LIST(`tools`)\n```\n\nIt says in the documentation that the table is created for me. I shouldn't have to manually create one myself.\n\nI am using:\n\n- Sequelize v3.23\n\n- SQLite 3\n\n========================================\n\nCode:\n```text\nvar tool = require(\"./tool\"); //created with Sequelize.define()\nvar requirement = require(\"./requirement\"); //created with Sequelize.define()\n\ntool.belongsToMany(requirement, {through: \"toolRequirements\"});\nrequirement.belongsToMany(tool, {through: \"toolRequirements\"});\n\ntool.sync();\nrequirement.sync();\n```\n\n```text\nExecuting (default): CREATE TABLE IF NOT EXISTS `requirements` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): CREATE TABLE IF NOT EXISTS `tools` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255) NOT NULL, `idCode` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);\nExecuting (default): PRAGMA INDEX_LIST(`requirements`)\nExecuting (default): PRAGMA INDEX_LIST(`tools`)\n```\n\n```text\nvar tool = require(\"./tool\"); //created with Sequelize.define()\nvar requirement = require(\"./requirement\"); //created with Sequelize.define()\n\ntool.belongsToMany(requirement, {through: \"toolRequirements\"});\nrequirement.belongsToMany(tool, {through: \"toolRequirements\"});\n\nsequelize.sync();\n\n//DO NOT tool.sync();\n//DO NOT requirement.sync();\n```\n\n```text\n.sync()\n```\n\n```text\nsequelize.sync()\n```\n\n========================================\n\nComments:\n- I think you should be using `sequelize.sync()` instead to sync all table states rather than synchronizing per table. Have you tried this one?\n- @JasonWihardja I have not- no. I'll try and let you know\n- Have you solved this? I'm experiencing the same situation.\n- I have same issue\n- I'm having the same issue.\n- @miqueloi please see the answer I've posted. It is what I ended up doing.\n- @CoredusK please see the answer I've posted. It is what I ended up doing\n- @aec I've also solved it by using the posted answer. Although it feels like a bit of magic. I don't know how the sequelize db instance \"knows\" all the tables that exist.\n- Thanks a lot! Really helped me move on :)\n- 'welcome (4 years later, haha)","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":90,"estimatedTokens":836}}858{"id":"stack-53076888","source":"stackoverflow","questionId":53076888,"title":"How do i disable Sequelize syncing?","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: How do i disable Sequelize syncing?\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect mysql to my nodejs project. While creating connection to nodejs it automatically creates tables based on models i have defined. I don't want to auto create tables. How do i disable it?\n\n**My DB Configuration**\n\n```\nvar sequelize = new Sequelize(config.db.database, config.db.username, \nconfig.db.password, {\n host : config.db.host,\n port : config.db.port,\n dialect : config.db.connection\n});\n```\n\n**My Connection to DB**\n\n```\n/* Database Connection */\ndb.sequelize.sync().then(function() {\n console.log('Nice! Database looks fine')\n}).catch(function(err) {\n console.log(err, \"Something went wrong with the Database Update!\")\n});\n```\n\n========================================\n\nTop Answer:\nUnless I'm missing something... Just don't call `db.sequelize.sync()`?\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize(config.db.database, config.db.username, \nconfig.db.password, {\n    host : config.db.host,\n    port : config.db.port,\n    dialect : config.db.connection\n});\n```\n\n```text\n/* Database Connection */\ndb.sequelize.sync().then(function() {\n  console.log('Nice! Database looks fine')\n}).catch(function(err) {\n  console.log(err, \"Something went wrong with the Database Update!\")\n});\n```\n\n```text\ndb.sequelize\n.authenticate()\n.then(() => {\n    console.log('Connection has been established successfully.');\n})\n.catch(err => {\n    console.error('Unable to connect to the database:', err);\n});\n```\n\n```text\ndb.sequelize.sync({\n    force : false , // To create table if exists , so make it false\n    alter : true // To update the table if exists , so make it true\n})\n```\n\n```text\nsync()\n```\n\n```text\nsync\n```\n\n```text\nsync\n```\n\n```text\ndb.sequelize.sync()\n```\n\n========================================\n\nComments:\n- awesome i was actually searching for replacement of `sync()` and `authenticate()` works perfectly\n- db.sequelize.sync({force: false}) still creates table is exists. I don't know why","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":94,"estimatedTokens":519}}859{"id":"stack-57826352","source":"stackoverflow","questionId":57826352,"title":"sequelize.sync(): error in SQL syntax near NUMBER","tags":["javascript","mysql","node.js","typescript","sequelize.js"],"text":"Title: sequelize.sync(): error in SQL syntax near NUMBER\nTags: javascript, mysql, node.js, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI made 4 Sequelize Models with use of `sequelize.define();`. Models are pretty much the same thing but with different table names. since I don't wanted to make them manually on MySQL cli, I decided to use sequelize.sync() in my main index.js file to let Sequelize to create the table but when I ran the application It faced an `Unhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax;` error and didn't make the tables.\n\nI have tried both `sequelize.sync();` and `sequelize.sync({ force: true });`\nand also tried syncing Models one by one but same error apeared!\n\n### one of My Models\n\n```\nexport const Product = sequelize.define(\n \"product\",\n {\n doInMyPlace: { type: Sequelize.BOOLEAN, allowNull: false },\n address: { type: Sequelize.STRING, allowNull: false },\n mapAddress: { type: Sequelize.STRING, allowNull: false },\n date: { type: Sequelize.STRING, allowNull: false },\n time: { type: Sequelize.STRING, allowNull: false },\n voucher: { type: Sequelize.STRING, allowNull: true },\n companyName: { type: Sequelize.STRING, allowNull: false },\n phoneNumber: { type: Sequelize.STRING, allowNull: false },\n itemCount: { type: Sequelize.NUMBER, allowNull: false }\n },\n {\n freezeTableName: true\n }\n);\n```\n\n### Shown Error\n\n```\nUnhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, P' at line 1\n```\n\nSince the error aims at SQL syntax I was wondering if it has something to do with my code or is just an issue with sequelize itself.\n\n### Rest of The Error\n\n```\nat Query.formatError (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:244:16)\n at Query.handler [as onResult] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:51:23)\n at Query.execute (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\commands\\command.js:30:14)\n at Connection.handlePacket (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\connection.js:408:32)\n at PacketParser.Connection.packetParser.p [as onPacket] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\connection.js:70:12)\n at PacketParser.executeStart (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\packet_parser.js:75:16)\n at Socket.Connection.stream.on.data (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\connection.js:77:25)\n at Socket.emit (events.js:198:13)\n at addChunk (_stream_readable.js:288:12)\n at readableAddChunk (_stream_readable.js:269:11)\n at Socket.Readable.push (_stream_readable.js:224:10)\n at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\nFrom previous event:\n at Query.run (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:39:12)\n at runHooks.then.then (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:643:29)\nFrom previous event:\n at Promise.try.then.connection (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:643:12)\nFrom previous event:\n at Promise.resolve.retry (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:639:10)\n at C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\retry-as-promised\\index.js:70:21\n at new Promise ()\n at retryAsPromised (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\retry-as-promised\\index.js:60:10)\n at Promise.try (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:629:30)\nFrom previous event:\n at Sequelize.query (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:578:23)\n at promise.then (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\query-interface.js:236:46)\nFrom previous event:\n at QueryInterface.createTable (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\query-interface.js:236:20)\n at Promise.try.then.then (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\model.js:1292:39)\n at runCallback (timers.js:705:18)\n at tryOnImmediate (timers.js:676:5)\n at processImmediate (timers.js:658:5)\nFrom previous event:\n at Function.sync (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\model.js:1292:8)\n at Object. (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\models\\products\\product.ts:21:9)\n at Module._compile (internal/modules/cjs/loader.js:776:30)\n at Module._compile (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\source-map-support\\source-map-support.js:521:25)\n at Module.m._compile (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:56:25)\n at Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at require.extensions.(anonymous function) (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:58:14)\n at Object.nodeDevHook [as .ts] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\ts-node-dev\\lib\\hook.js:61:7)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at Module.require (internal/modules/cjs/loader.js:690:17)\n at require (internal/modules/cjs/helpers.js:25:18)\n at Object. (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\models\\products\\index.ts:4:1)\n at Module._compile (internal/modules/cjs/loader.js:776:30)\n at Module._compile (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\source-map-support\\source-map-support.js:521:25)\n at Module.m._compile (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:56:25)\n at Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at require.extensions.(anonymous function) (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:58:14)\n at Object.nodeDevHook [as .ts] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\ts-node-dev\\lib\\hook.js:61:7)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at Module.require (internal/modules/cjs/loader.js:690:17)\n at require (internal/modules/cjs/helpers.js:25:18)\n```\n\n### Executing Query\n\n```\nExecuting (default): CREATE TABLE IF NOT EXISTS `user` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) NOT NULL, `phone` VARCHAR(255) NOT NULL, `gender` VARCHAR(255) NOT NULL DEFAULT 'm', `birthday` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME\nNOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;\nExecuting (default): SHOW INDEX FROM `user`\nExecuting (default): CREATE TABLE IF NOT EXISTS `food` (`id` INTEGER NOT NULL auto_increment , `doInMyPlace` TINYINT(1) NOT NULL, `address` VARCHAR(255) NOT NULL, `mapAddress` VARCHAR(255) NOT NULL, `date` VARCHAR(255) NOT NULL, `time` VARCHAR(255) NOT NULL, `voucher` VARCHAR(255), `companyName` VARCHAR(255) NOT NULL,\n`phoneNumber` VARCHAR(255) NOT NULL, `itemCount` NUMBER NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;\n```\n\n========================================\n\nTop Answer:\nDatatypes supported in sequelize:\n\nhttps://sequelize.readthedocs.io/en/1.7.0/docs/models/\n\nSo use INTEGER instead of NUMBER.\n\n========================================\n\nCode:\n```text\nexport const Product = sequelize.define(\n  \"product\",\n  {\n    doInMyPlace: { type: Sequelize.BOOLEAN, allowNull: false },\n    address: { type: Sequelize.STRING, allowNull: false },\n    mapAddress: { type: Sequelize.STRING, allowNull: false },\n    date: { type: Sequelize.STRING, allowNull: false },\n    time: { type: Sequelize.STRING, allowNull: false },\n    voucher: { type: Sequelize.STRING, allowNull: true },\n    companyName: { type: Sequelize.STRING, allowNull: false },\n    phoneNumber: { type: Sequelize.STRING, allowNull: false },\n    itemCount: { type: Sequelize.NUMBER, allowNull: false }\n  },\n  {\n    freezeTableName: true\n  }\n);\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, P' at line 1\n```\n\n```text\nat Query.formatError (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:244:16)\n    at Query.handler [as onResult] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:51:23)\n    at Query.execute (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\commands\\command.js:30:14)\n    at Connection.handlePacket (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\connection.js:408:32)\n    at PacketParser.Connection.packetParser.p [as onPacket] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\connection.js:70:12)\n    at PacketParser.executeStart (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\packet_parser.js:75:16)\n    at Socket.Connection.stream.on.data (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\mysql2\\lib\\connection.js:77:25)\n    at Socket.emit (events.js:198:13)\n    at addChunk (_stream_readable.js:288:12)\n    at readableAddChunk (_stream_readable.js:269:11)\n    at Socket.Readable.push (_stream_readable.js:224:10)\n    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)\nFrom previous event:\n    at Query.run (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\dialects\\mysql\\query.js:39:12)\n    at runHooks.then.then (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:643:29)\nFrom previous event:\n    at Promise.try.then.connection (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:643:12)\nFrom previous event:\n    at Promise.resolve.retry (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:639:10)\n    at C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\retry-as-promised\\index.js:70:21\n    at new Promise (<anonymous>)\n    at retryAsPromised (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\retry-as-promised\\index.js:60:10)\n    at Promise.try (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:629:30)\nFrom previous event:\n    at Sequelize.query (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\sequelize.js:578:23)\n    at promise.then (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\query-interface.js:236:46)\nFrom previous event:\n    at QueryInterface.createTable (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\query-interface.js:236:20)\n    at Promise.try.then.then (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\model.js:1292:39)\n    at runCallback (timers.js:705:18)\n    at tryOnImmediate (timers.js:676:5)\n    at processImmediate (timers.js:658:5)\nFrom previous event:\n    at Function.sync (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\sequelize\\lib\\model.js:1292:8)\n    at Object.<anonymous> (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\models\\products\\product.ts:21:9)\n    at Module._compile (internal/modules/cjs/loader.js:776:30)\n    at Module._compile (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\source-map-support\\source-map-support.js:521:25)\n    at Module.m._compile (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:56:25)\n    at Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n    at require.extensions.(anonymous function) (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:58:14)\n    at Object.nodeDevHook [as .ts] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\ts-node-dev\\lib\\hook.js:61:7)\n    at Module.load (internal/modules/cjs/loader.js:653:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n    at Module.require (internal/modules/cjs/loader.js:690:17)\n    at require (internal/modules/cjs/helpers.js:25:18)\n    at Object.<anonymous> (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\models\\products\\index.ts:4:1)\n    at Module._compile (internal/modules/cjs/loader.js:776:30)\n    at Module._compile (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\source-map-support\\source-map-support.js:521:25)\n    at Module.m._compile (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:56:25)\n    at Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n    at require.extensions.(anonymous function) (C:\\Users\\Amirali\\AppData\\Local\\Temp\\ts-node-dev-hook-7490429646471359.js:58:14)\n    at Object.nodeDevHook [as .ts] (C:\\Users\\Amirali\\Desktop\\feature-2-authorization\\node_modules\\ts-node-dev\\lib\\hook.js:61:7)\n    at Module.load (internal/modules/cjs/loader.js:653:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n    at Module.require (internal/modules/cjs/loader.js:690:17)\n    at require (internal/modules/cjs/helpers.js:25:18)\n```\n\n```text\nExecuting (default): CREATE TABLE IF NOT EXISTS `user` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) NOT NULL, `phone` VARCHAR(255) NOT NULL, `gender` VARCHAR(255) NOT NULL DEFAULT 'm', `birthday` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME\nNOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;\nExecuting (default): SHOW INDEX FROM `user`\nExecuting (default): CREATE TABLE IF NOT EXISTS `food` (`id` INTEGER NOT NULL auto_increment , `doInMyPlace` TINYINT(1) NOT NULL, `address` VARCHAR(255) NOT NULL, `mapAddress` VARCHAR(255) NOT NULL, `date` VARCHAR(255) NOT NULL, `time` VARCHAR(255) NOT NULL, `voucher` VARCHAR(255), `companyName` VARCHAR(255) NOT NULL,\n`phoneNumber` VARCHAR(255) NOT NULL, `itemCount` NUMBER NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;\n```\n\n```text\nsequelize.define();\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax;\n```\n\n```text\nsequelize.sync();\n```\n\n```text\nsequelize.sync({ force: true });\n```\n\n```text\nitemCount: { type: Sequelize.INTEGER, allowNull: false }\n```\n\n```text\nSequelize.INTEGER.UNSIGNED              // INTEGER UNSIGNED\nSequelize.INTEGER(11).UNSIGNED          // INTEGER(11) UNSIGNED\nSequelize.INTEGER(11).ZEROFILL          // INTEGER(11) ZEROFILL\nSequelize.INTEGER(11).ZEROFILL.UNSIGNED // INTEGER(11) UNSIGNED ZEROFILL\nSequelize.INTEGER(11).UNSIGNED.ZEROFILL // INTEGER(11) UNSIGNED ZEROFILL\n```\n\n```text\nINTEGER\n```\n\n```text\nNUMBER\n```\n\n```text\nNUMBER\n```\n\n```text\nINTEGER\n```\n\n```text\n'itemCount' NUMBER NOT NULL\n```\n\n```text\nNUMBER\n```\n\n========================================\n\nComments:\n- can you debug and show the complete sql query generated by sequelize?\n- I Have added them at the end of my question. @majidarif\n- I have added an answer.\n- Your shown error block pinpoints the problem area - right before \"NUMBER\", so you know it doesn't like it. majidarif is right, changing it to integer should fix it","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":277,"estimatedTokens":4018}}860{"id":"stack-65799885","source":"stackoverflow","questionId":65799885,"title":"Sequelize: Force update for a JSON array","tags":["node.js","sequelize.js"],"text":"Title: Sequelize: Force update for a JSON array\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSequelize won't update a JSON field under some circumstances.\n\nFor example, I have:\n\n```\n[[1]] (an array inside array)\n```\n\nAnd I'm trying to push something:\n\n```\ninstance.arr[0].push(1); // [[1,1]]\ninstance.save();\n// or:\ninstance.update({arr: instance.arr});\n```\n\nNow inside the instance I have changed the array and nothing changed inside the database. Not even a query is sent. :(\n\nFrom the Sequelize website:\n\nhttps://sequelize.org/master/manual/model-instances.html\nThe save method is optimized internally to only update fields that really\nchanged. This means that if you don't change anything and call save,\nSequelize will know that the save is superfluous and do nothing, i.e.,\nno query will be generated (it will still return a Promise, but it\nwill resolve immediately).\n\nThat's good, but it seems like it doesn't work for JSON. Can I do a force update?\n\nAs of today, I have to do a deep copy of the array to save it.\n\nI'm using MariaDB. I don't know if that matters.\n\n========================================\n\nCode:\n```text\n[[1]] (an array inside array)\n```\n\n```text\ninstance.arr[0].push(1); // [[1,1]]\ninstance.save();\n// or:\ninstance.update({arr: instance.arr});\n```\n\n```text\ninstance.changed( 'arr', true);\ninstance.save\n```\n\n========================================\n\nComments:\n- If you just make a shallow copy so that the array reference itself changes, i.e. `instance.arr = [...instance.arr]` before pushing, does it work?","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":62,"estimatedTokens":387}}861{"id":"stack-34916895","source":"stackoverflow","questionId":34916895,"title":"use bulkDestroy in Sequelize","tags":["sql-delete","sequelize.js"],"text":"Title: use bulkDestroy in Sequelize\nTags: sql-delete, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'd like to know how to delete all values in an array, my array contains the ids like: `[1,2,3,4]`, I've tried:\n\n```\nmodels.products\n.destroy({where: {req.body.ids}})\n.then(function(data){ res.json(data) })\n```\n\nBut I got `data` undefined, and nothing is deleted...\n\n========================================\n\nTop Answer:\nJust to add to +Adam's response:\n\nfor arrays you'll need to add an $in: clause.\n\n```\nModels.products\n .destroy({where: {$in: req.body.ids}})\n ...\n```\n\n========================================\n\nCode:\n```text\nmodels.products\n.destroy({where: {req.body.ids}})\n.then(function(data){ res.json(data) })\n```\n\n```text\n[1,2,3,4]\n```\n\n```text\ndata\n```\n\n```text\nModel.destroy({ where: { id: [1,2,3,4] }})\n```\n\n```text\nid\n```\n\n```text\nModels.products\n .destroy({where: {$in: req.body.ids}})\n ...\n```\n\n========================================\n\nComments:\n- I think that should be `{where: {id: {$in: req.body.ids}}}`, per docs.sequelizejs.com/en/latest/docs/querying/#operators","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":63,"estimatedTokens":272}}862{"id":"stack-36209921","source":"stackoverflow","questionId":36209921,"title":"Sequelize default connection pool size","tags":["sequelize.js"],"text":"Title: Sequelize default connection pool size\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSimple question seeking a simple answer.\n\nWhat is the default connection pool size for a sequelize managed pg database?\n\nThe docs don't say anything about this, however they do mention options for setting min/max idle times.\n\n========================================\n\nTop Answer:\nGo to connection-manager.js file and you'll find this\n\n```\nconst defaultPoolingConfig = {\n max: 5,\n min: 0,\n idle: 10000,\n acquire: 10000,\n evict: 10000,\n handleDisconnects: true\n};\n```\n\n========================================\n\nCode:\n```json\n{\n    max: 5,\n    min: 0,\n    idle: 10000,\n    acquire: 60000,\n    evict: 1000\n}\n```\n\n```text\nconst defaultPoolingConfig = {\n  max: 5,\n  min: 0,\n  idle: 10000,\n  acquire: 10000,\n  evict: 10000,\n  handleDisconnects: true\n};\n```\n\n========================================\n\nComments:\n- Did I answer your question? If I did, please accept my answer so people know this question is answered.\n- sequelize.org/master/manual/getting-started.html pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } });","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":56,"estimatedTokens":279}}863{"id":"stack-66265618","source":"stackoverflow","questionId":66265618,"title":"Nesting .then() and catch in Javascript promise","tags":["node.js","express","sequelize.js"],"text":"Title: Nesting .then() and catch in Javascript promise\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm not experienced with Javascript promises and recently I started using promises instead of callbacks in my Javascript projects.\n\nWhen I tried to run several promise functions one after another I landed in a nested chaos of then(). The code works exactly as expected, but my question is that if this is the way to resolve several promise functions one after another then what is the advantage of using promises instead of callbacks.\n\nIf I'm not doing it the right way, then it is a request from you guys to show me the proper way of resolving nested promises.\nBelow is my code that I don't like it they way it looks:\n\n```\nexports.editExpense = (req, res, next) => {\n Account.findAll().then(accounts => {\n Budget.findAll().then(budgets => {\n Expense.findAll().then(expenses => {\n Expense.findByPk(id).then(expense => {\n res.render('expenses/index', {\n urlQuery: urlQuery,\n expenses: expenses,\n expense: expense,\n accounts: accounts,\n budgets: budgets\n });\n })\n })\n })\n }).catch(error => console.log(error));\n};\n```\n\n========================================\n\nTop Answer:\nIf you prefer to use the `then catch` structure, in order to take fully advantage of it I recommend you not to nest them. Of course you can, but then you should put a `.catch()` after each of them. That's why the `async` introduction made an easier code to read and handle errors, as it simplifies it with the `try catch` structure.\n\nIf you pipe multiple `.then()`, you can return a value as a promise from each of them that can be used inside the next one once the promise resolves. The only thing is that you loose these values unless you save them either in `req` with new properties or in variables declared outside the pipe of `.then()`.\n\nThat's why, in this snippet, I declared all the variables at the beginning in order to save all the values and use them in the final `res`\n\n\r\n\r\n\n```\nexports.editExpense = (req, res, next) => {\n \n let accounts;\n let budgets;\n let expenses;\n\n Account.findAll()\n .then(fetchedAccounts => {\n accounts = fetchedAccounts;\n return Budget.findAll()\n })\n .then(fetchedBudgets => {\n budgets = fetchedBudgets;\n return Expense.findAll()\n })\n .then(fetchedExpenses => {\n expenses = fetchedExpenses\n return Expense.findByPk(id)\n })\n .then(expense => {\n return res.render('expenses/index', {\n urlQuery: urlQuery,\n expenses: expenses,\n expense: expense,\n accounts: accounts,\n budgets: budgets\n });\n })\n .catch(error => console.log(error));\n};\n```\n\n========================================\n\nCode:\n```text\nexports.editExpense = (req, res, next) => {\n    Account.findAll().then(accounts => {\n        Budget.findAll().then(budgets => {\n            Expense.findAll().then(expenses => {\n                Expense.findByPk(id).then(expense => {\n                    res.render('expenses/index', {\n                        urlQuery: urlQuery,\n                        expenses: expenses,\n                        expense: expense,\n                        accounts: accounts,\n                        budgets: budgets\n                    });\n                })\n            })\n        })\n    }).catch(error => console.log(error));\n};\n```\n\n```text\nexports.editExpense = async(req, res, next) => {\n    try {\n      let accounts = await Account.findAll();\n      let budgets = await Budget.findAll();\n      let expenses = await Expense.findAll()\n      let expense = await Expense.findByPk(id);\n      if (expense) {\n        res.render('expenses/index', {\n          urlQuery: urlQuery,\n          expenses: expenses,\n          expense: expense,\n          accounts: accounts,\n          budgets: budgets\n        });\n      } else {\n        console.log('else') //<<- Render/Handle else condition otherwise server will hang.\n      }\n    } catch (error) {\n      console.error(error)\n    }\n```\n\n```text\nasync/await\n```\n\n```text\nasync\n```\n\n```js\nexports.editExpense = (req, res, next) => {\n    \n    let accounts;\n    let budgets;\n    let expenses;\n\n    Account.findAll()\n        .then(fetchedAccounts => {\n            accounts = fetchedAccounts;\n            return Budget.findAll()\n        })\n        .then(fetchedBudgets => {\n            budgets = fetchedBudgets;\n            return Expense.findAll()\n        })\n        .then(fetchedExpenses => {\n            expenses = fetchedExpenses\n            return Expense.findByPk(id)\n        })\n        .then(expense => {\n            return res.render('expenses/index', {\n                urlQuery: urlQuery,\n                expenses: expenses,\n                expense: expense,\n                accounts: accounts,\n                budgets: budgets\n            });\n        })\n        .catch(error => console.log(error));\n};\n```\n\n```text\nthen catch\n```\n\n```text\n.catch()\n```\n\n```text\nasync\n```\n\n```text\ntry catch\n```\n\n```text\n.then()\n```\n\n```text\nreq\n```\n\n```text\n.then()\n```\n\n```text\nres\n```\n\n========================================\n\nComments:\n- A quick rule of thumb, all Promises should return. And they always return Promises even if you don't.\n- Thank you for answer, but where and how to take advantage of then() and catch()?\n- Well using `then&#47;catch` is similar to using `async&#47;await` as both resolve promise, I personally try not to use `then&#47;catch` because of the issue you are having i.e. nesting.\n- After a good searching and learning, your answer was the best.\n- Thank you! This is what I needed to know and learn.","metadata":{"transformedAt":"2026-08-18T18:33:34.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":204,"estimatedTokens":1368}}864{"id":"stack-68804086","source":"stackoverflow","questionId":68804086,"title":"Sequelize Setter has no effect on update","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize Setter has no effect on update\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to use the getters and setters defined in the models to encrypt and decrypt some data in my database. But during implementation I noticed, that the setters get triggered on update as well as creation but only have an real effect on creation. So creating an entry calls the setter and the value of (see the code) \"secret\" stands encrypted in the database. But if i want to update this entry, the setter gets called but nothing gets updated.\n\nIf I update also values which have no setter function defined for them only this values get updated.\n\nThis is my setter:\n\n```\nsecret: {\n type: DataTypes.STRING,\n defaultValue: null,\n async get() {\n try {\n return await crypt.decryptGetter(this, 'secret');\n } catch (err) { \n throw new Error(\"Error while decrypting secret: \" + err);\n }\n },\n async set(value) {\n try {\n return await crypt.encryptSetter(this, 'secret', value);\n } catch (err) {\n throw new Error(\"Error while encrypting secret: \" + err);\n }\n }\n}\n```\n\nI use this setters and getters more often, that's why I outsourced them.\nI pass the current instance of the model as well as the key and the value if necessary:\n\n```\nasync decryptGetter(sequelizeModel, key) {\n try {\n return await module.exports.decrypt(sequelizeModel.getDataValue(key),config.internal.secret)\n } catch (err) {\n throw new Error(\"GETTER: \" + err, __filename);\n }\n},\n \nasync encryptSetter(sequelizeModel, key, value) {\n try {\n let encValue = await module.exports.encrypt(value, config.internal.secret);\n return sequelizeModel.setDataValue(key, encValue);\n } catch (err) {\n throw new Error(\"SETTER: \" + err, __filename);\n }\n}\n```\n\nCan anybody help me out here? Did I miss something along the way? Thank you in advance!\n\n========================================\n\nTop Answer:\nAs r9119 mentioned in his answer, hooks are the right solution for this!\nI just thought I post a little summary how I did it in the end for others having this problem in the future!\n\nI added beforeCreate and beforeUpdate hooks to my model, as well as a getter function to getterMethods:\n\n```\nconst MyModel = sequelize.define(\n 'MyModel', {\n MyModelID: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true\n },\n name: {\n ...\n },\n secret: {\n ...\n }\n }, {\n timestamps: true,\n paranoid: true,\n freezeTableName: true,\n getterMethods: {\n async decrypt() {\n try {\n return await sequelizeUtils.cryptHookSpecific(this, config.internalSecret, modelCryptConfig.specificProps, projectDecrypt)\n } catch(err) {\n throw new Error(err);\n }\n }\n },\n hooks: {\n beforeCreate: async (myModel, options) => {\n try {\n await sequelizeUtils.cryptHookSpecific(myModel, config.internalSecret, modelCryptConfig.specificProps, projectDecrypt)\n } catch(err) {\n throw new Error(err);\n }\n },\n beforeUpdate: async (myModel, options) => {\n try {\n await sequelizeUtils.cryptHookSpecific(myModel, config.internalSecret, modelCryptConfig.specificProps, projectDecrypt)\n } catch(err) {\n throw new Error(err);\n }\n },\n }\n }\n);\n```\n\nPer model I define a modelCryptConfig which defines which fields should be decrypted. There I can also define a special key for each field used for de-/encryption:\n\n```\nlet modelCryptConfig = {\n specificProps: [{field: \"apiKey\", key:\"mySpecialKeyForThisField\"},{field: \"secret\"},{field: \"someInfo\"},{field: \"someOtherInfo\"},{field: \"somethingElse\"},]\n}\n```\n\nThe sequelizeUtils.cryptHookSpecific function takes in the model, a key to encrypt/decrypt, the fields which should be encrypted / decrypted and at last a project specific function which actually does the encryption/decryption.\n\n```\nasync cryptHookSpecific(sequelizeModel, globalKey, specificProps, cryptFunction) {\n try {\n // loop over all specific properties to encrypt them\n for (let propIdx in specificProps) {\n if (!sequelizeModel.__proto__.rawAttributes[specificProps[propIdx].field].primaryKey && // is not a primary key\n !sequelizeModel.__proto__.rawAttributes[specificProps[propIdx].field].foreignKey && // is not a foreign key\n sequelizeModel.dataValues[specificProps[propIdx].field]) { // is not null\n // check if there is a specific key provided\n if (specificProps[propIdx].hasOwnProperty(\"key\")) {\n // if so encrypt the property with the provided specific key\n sequelizeModel.dataValues[specificProps[propIdx].field] = await cryptFunction(sequelizeModel.dataValues[specificProps[propIdx].field], specificProps[propIdx].key)\n } else {\n // if not encrypt it with the globalKey\n sequelizeModel.dataValues[specificProps[propIdx].field] = await cryptFunction(sequelizeModel.dataValues[specificProps[propIdx].field], globalKey)\n }\n }\n }\n \n return sequelizeModel;\n } catch(err) {\n throw new Error(err);\n }\n},\n```\n\nBesides the cryptHookSpecific function I wrote a cryptHookComplete function as well which encrypts/decrypts all field by default and you can defined fields to exclude in the modelCryptConfig.\n\nMaybe this helps someone out! Thanks again to r9119!\n\n========================================\n\nCode:\n```js\nsecret: {\n  type: DataTypes.STRING,\n  defaultValue: null,\n  async get() {\n    try {\n      return await crypt.decryptGetter(this, 'secret');\n    } catch (err) { \n      throw new Error(\"Error while decrypting secret: \" + err);\n    }\n  },\n  async set(value) {\n    try {\n      return await crypt.encryptSetter(this, 'secret', value);\n    } catch (err) {\n      throw new Error(\"Error while encrypting secret: \" + err);\n    }\n  }\n}\n```\n\n```js\nasync decryptGetter(sequelizeModel, key) {\n  try {\n    return await module.exports.decrypt(sequelizeModel.getDataValue(key),config.internal.secret)\n  } catch (err) {\n    throw new Error(\"GETTER: \" + err, __filename);\n  }\n},\n    \nasync encryptSetter(sequelizeModel, key, value) {\n  try {\n    let encValue = await module.exports.encrypt(value, config.internal.secret);\n    return sequelizeModel.setDataValue(key, encValue);\n  } catch (err) {\n    throw new Error(\"SETTER: \" + err, __filename);\n  }\n}\n```\n\n```text\nfunction hashPassword (user) {\n    const SALT_FACTOR = 12\n\n    if (!user.changed('password')) {\n        return;\n    } else {\n        user.setDataValue('password', bcrypt.hashSync(user.password, SALT_FACTOR))\n    }\n}\n\nmodule.exports = User = (sequelize, DataTypes) => {\n    const User = sequelize.define('User', {\n        id: {\n            type: DataTypes.UUID,\n            defaultValue: DataTypes.UUIDV4,\n            primaryKey: true\n        },\n        password: {\n            type: DataTypes.STRING\n        },\n        {\n        hooks: {\n            beforeCreate: hashPassword,\n            beforeUpdate: hashPassword\n        }\n    })\n\n    return User\n}\n```\n\n```text\nconst MyModel = sequelize.define(\n  'MyModel', {\n    MyModelID: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      allowNull: false,\n      autoIncrement: true\n    },\n    name: {\n      ...\n    },\n    secret: {\n      ...\n    }\n  }, {\n    timestamps: true,\n    paranoid: true,\n    freezeTableName: true,\n    getterMethods: {\n      async decrypt() {\n        try {\n          return await sequelizeUtils.cryptHookSpecific(this, config.internalSecret, modelCryptConfig.specificProps, projectDecrypt)\n        } catch(err) {\n          throw new Error(err);\n        }\n      }\n    },\n    hooks: {\n      beforeCreate: async (myModel, options) => {\n        try {\n          await sequelizeUtils.cryptHookSpecific(myModel, config.internalSecret, modelCryptConfig.specificProps, projectDecrypt)\n        } catch(err) {\n          throw new Error(err);\n        }\n      },\n      beforeUpdate: async (myModel, options) => {\n        try {\n          await sequelizeUtils.cryptHookSpecific(myModel, config.internalSecret, modelCryptConfig.specificProps, projectDecrypt)\n        } catch(err) {\n          throw new Error(err);\n        }\n      },\n    }\n  }\n);\n```\n\n```text\nlet modelCryptConfig = {\n    specificProps: [{field: \"apiKey\", key:\"mySpecialKeyForThisField\"},{field: \"secret\"},{field: \"someInfo\"},{field: \"someOtherInfo\"},{field: \"somethingElse\"},]\n}\n```\n\n```text\nasync cryptHookSpecific(sequelizeModel, globalKey, specificProps, cryptFunction) {\n  try {\n    // loop over all specific properties to encrypt them\n    for (let propIdx in specificProps) {\n      if (!sequelizeModel.__proto__.rawAttributes[specificProps[propIdx].field].primaryKey && // is not a primary key\n        !sequelizeModel.__proto__.rawAttributes[specificProps[propIdx].field].foreignKey && // is not a foreign key\n        sequelizeModel.dataValues[specificProps[propIdx].field]) { // is not null\n        // check if there is a specific key provided\n        if (specificProps[propIdx].hasOwnProperty(\"key\")) {\n          // if so encrypt the property with the provided specific key\n          sequelizeModel.dataValues[specificProps[propIdx].field] = await cryptFunction(sequelizeModel.dataValues[specificProps[propIdx].field], specificProps[propIdx].key)\n        } else {\n          // if not encrypt it with the globalKey\n          sequelizeModel.dataValues[specificProps[propIdx].field] = await cryptFunction(sequelizeModel.dataValues[specificProps[propIdx].field], globalKey)\n        }\n      }\n    }\n  \n    return sequelizeModel;\n  } catch(err) {\n    throw new Error(err);\n  }\n},\n```\n\n========================================\n\nComments:\n- I already read that there maybe be some problems with async functions but I couldnt find anything about this in the doc's. Also as I mentioned on create it works\n- yes, that's the way to do it! I now use hooks and already wrote a function to outsource the logic to use it for multiple models without having to wirte the crypt function over and over again. I'll post this here! Thanks for your help!!\n- Np, glad I could help :)","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":313,"estimatedTokens":2430}}865{"id":"stack-47044077","source":"stackoverflow","questionId":47044077,"title":"Sequelize - How do I seed database with Geometry value?","tags":["node.js","postgresql","sequelize.js","postgis","sequelize-cli"],"text":"Title: Sequelize - How do I seed database with Geometry value?\nTags: node.js, postgresql, sequelize.js, postgis, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI use Sequelize to connect to my PostgreSQL database and during development, I use seed files to populate database with example data. I recently installed PostGIS for my database and wanted to use the GEOMETRY('POINT') type to describe the latitude/longitude position.\n\nHowever, I have no idea how to put some GEOMETRY data using seeders. I tried following the examples in Sequelize docs:\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) =>\n queryInterface.bulkInsert('Vets', [{\n title: 'Centrum Zdrowia Małych Zwierząt',\n city: 'Poznań',\n googleMapsID: 'ChIJQ8EgpGpDBEcR1d0wYZTGPbI',\n position: {\n type: 'Point',\n coordinates: [52.458415, 16.904740]\n },\n rodents: true\n }], {}),\n down: (queryInterface, Sequelize) =>\n queryInterface.bulkDelete('Vets', null, {})\n};\n```\n\nbut when I run the `sequelize db:seed:all` command, following error occurs:\n\n`ERROR: Invalid value [object Object]`\n\nI guess I just need to specify the position in some other way, but the Sequelize docs don't mention any for seeds. Can anyone help me with this problem?\n\nThe migration file for the Vets database is as follows:\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => queryInterface.createTable('Vets', {\n ...\n rodents: {\n type: Sequelize.BOOLEAN\n },\n position: {\n type: Sequelize.GEOMETRY\n },\n websiteUrl: {\n type: Sequelize.STRING\n },\n ...\n }, {\n indexes: [\n {\n unique: true,\n fields: ['title', 'city']\n }\n ]\n }),\n down: (queryInterface, Sequelize) =>\n queryInterface.dropTable('Vets')\n};\n```\n\nAnd the model definition:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Vet = sequelize.define('Vet', {\n ...\n rodents: {\n type: DataTypes.BOOLEAN,\n defaultValue: false\n },\n position: DataTypes.GEOMETRY('POINT'),\n websiteUrl: DataTypes.STRING,\n ...\n }, {\n indexes: [\n {\n unique: true,\n fields: ['title', 'city']\n }\n ]\n });\n\n Vet.associate = (models) => {\n Vet.belongsTo(models.User, { as: 'suggestedBy' });\n Vet.belongsTo(models.User, { as: 'acceptedBy' });\n };\n\n return Vet;\n};\n```\n\n========================================\n\nTop Answer:\nI would like to add to your answer, that if you want to add a `type: 'Polygon'` and as a geoJson you can do the following:\n\n```\nup: (queryInterface, Sequelize) => {\n\n const polygon = { type: 'Polygon', coordinates: [\n [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],\n [100.0, 1.0], [100.0, 0.0] ]\n ]};\n\n const cityCreated = {\n ....\n boundaries: Sequelize.fn('ST_GeomFromGeoJSON', JSON.stringify(polygon)),\n ....\n }\n\n return queryInterface.bulkInsert('cities', [cityCreated], {});\n },\n```\n\nin this case, the column `boundaries` is the one defined as `GEOMETRY`\n\nthis is good for adding boundaries, and geoJson is a more common dataType than text for this purpose.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n    up: (queryInterface, Sequelize) =>\n        queryInterface.bulkInsert('Vets', [{\n            title: 'Centrum Zdrowia Małych Zwierząt',\n            city: 'Poznań',\n            googleMapsID: 'ChIJQ8EgpGpDBEcR1d0wYZTGPbI',\n            position: {\n                type: 'Point',\n                coordinates: [52.458415, 16.904740]\n            },\n            rodents: true\n        }], {}),\n    down: (queryInterface, Sequelize) =>\n        queryInterface.bulkDelete('Vets', null, {})\n};\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => queryInterface.createTable('Vets', {\n    ...\n    rodents: {\n      type: Sequelize.BOOLEAN\n    },\n    position: {\n      type: Sequelize.GEOMETRY\n    },\n    websiteUrl: {\n      type: Sequelize.STRING\n    },\n    ...\n  }, {\n    indexes: [\n      {\n        unique: true,\n        fields: ['title', 'city']\n      }\n    ]\n  }),\n  down: (queryInterface, Sequelize) =>\n    queryInterface.dropTable('Vets')\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Vet = sequelize.define('Vet', {\n    ...\n    rodents: {\n      type: DataTypes.BOOLEAN,\n      defaultValue: false\n    },\n    position: DataTypes.GEOMETRY('POINT'),\n    websiteUrl: DataTypes.STRING,\n    ...\n  }, {\n    indexes: [\n      {\n        unique: true,\n        fields: ['title', 'city']\n      }\n    ]\n  });\n\n  Vet.associate = (models) => {\n    Vet.belongsTo(models.User, { as: 'suggestedBy' });\n    Vet.belongsTo(models.User, { as: 'acceptedBy' });\n  };\n\n  return Vet;\n};\n```\n\n```text\nsequelize db:seed:all\n```\n\n```text\nERROR: Invalid value [object Object]\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) =>\n    queryInterface.bulkInsert('Vets', [\n      {\n        ...\n        position: Sequelize.fn('ST_GeomFromText', 'POINT(52.458415 16.904740)'),\n        ...\n      }\n    ], {}),\n  down: (queryInterface, Sequelize) =>\n    queryInterface.bulkDelete('Vets', null, {})\n};\n```\n\n```text\nSequelize.fn()\n```\n\n```js\nup: (queryInterface, Sequelize) => {\n\n\n    const polygon = { type: 'Polygon', coordinates: [\n      [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],\n        [100.0, 1.0], [100.0, 0.0] ]\n      ]};\n\n    const cityCreated = {\n   ....\n      boundaries: Sequelize.fn('ST_GeomFromGeoJSON', JSON.stringify(polygon)),\n   ....\n    }\n\n    return queryInterface.bulkInsert('cities', [cityCreated], {});\n  },\n```\n\n```text\ntype: 'Polygon'\n```\n\n```text\nboundaries\n```\n\n```text\nGEOMETRY\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":254,"estimatedTokens":1339}}866{"id":"stack-52916870","source":"stackoverflow","questionId":52916870,"title":"Sequelize db:migrate doesn't update model","tags":["javascript","orm","sequelize.js","sequelize-cli"],"text":"Title: Sequelize db:migrate doesn't update model\nTags: javascript, orm, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI made a table using sequelize-cli, however I forgot to add a column: title.\n\nSo I generated new migration:\n\n```\n$ sequelize migration:create --name update-notes\n```\n\nAnd put these codes inside of migration file:\n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n\n return queryInterface.addColumn(\n 'Notes',\n 'title',\n Sequelize.STRING\n );\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.removeColumn(\n 'Notes',\n 'title'\n );\n }\n};\n```\n\nAfter run migration and check the table schema from DB, it works:\n\n```\n$ sequelize db:migrate\n```\n\nHowever model doesn't have my new added column yet:\n\n```\n'use strict';\n// models/notes.js\nmodule.exports = (sequelize, DataTypes) => {\n const Notes = sequelize.define('Notes', {\n content: DataTypes.TEXT // NO 'TITLE' COLUMN\n }, {});\n Notes.associate = function(models) {\n // associations can be defined here\n };\n return Notes;\n};\n```\n\nWhat am I missing? How should I apply my updates to model file?\n\nAlso what if previous data in table is not compatible with new table schema? Is it just fail the migration and developer fix the issue manually?\n\n========================================\n\nCode:\n```text\n$ sequelize migration:create --name update-notes\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n\n    return queryInterface.addColumn(\n      'Notes',\n      'title',\n      Sequelize.STRING\n    );\n  },\n\n  down: (queryInterface, Sequelize) => {\n   return queryInterface.removeColumn(\n     'Notes',\n     'title'\n   );\n  }\n};\n```\n\n```text\n$ sequelize db:migrate\n```\n\n```text\n'use strict';\n// models/notes.js\nmodule.exports = (sequelize, DataTypes) => {\n  const Notes = sequelize.define('Notes', {\n    content: DataTypes.TEXT    // NO 'TITLE' COLUMN\n  }, {});\n  Notes.associate = function(models) {\n    // associations can be defined here\n  };\n  return Notes;\n};\n```\n\n========================================\n\nComments:\n- With Sequelize migrations, you will need to manually update *both* your model and migration files. Running a new migration will not automatically update your model file.\n- @mcranston18 Oh, that's bad news 😢😢 However thanks, dude!\n- @mcranston18 Hey, would you post to answer to I can accept it?","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":592}}867{"id":"stack-49579117","source":"stackoverflow","questionId":49579117,"title":"NodeJS Sequelize returning data from query","tags":["node.js","express","promise","sequelize.js"],"text":"Title: NodeJS Sequelize returning data from query\nTags: node.js, express, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nTotally new to Javascript and Node. I am trying to get started with Sequelize as an ORM and did a simple query \n\n```\nvar employeeList = Employee.findAll().then(function(result){\n console.log(result.length);\n console.log(result[0].employeeName);\n //how do I return this to a variable with which I can do further processing\n return result;\n });\n\n//do something with employeeList\nemployeeList[0].employeeName //cannot read property of undefined\n```\n\nWhile the console logs print out the right name the employeeList itself does not contain any data. I tried printing the employeeList and it shows the promise \n\n```\nPromise {\n _bitField: 0,\n _fulfillmentHandler0: undefined,\n _rejectionHandler0: undefined,\n _promise0: undefined,\n _receiver0: undefined }\n```\n\nI did skim through the promise concept but could not get an east example as to how to return the results from the promise to a variable outside the function. I thought returning the result would do t he trick. Am I missing something here? I can understand that I could work on the results within the promise function. If the scenario is to make two database calls and then process the results of both calls to return a merged result how could that be done without getting results to variables.\n\n========================================\n\nTop Answer:\nAnother way of doing is use **`async await`** :\n\n```\nasync function getEmployees(){\n var employeeList = await Employee.findAll().then(function(result){\n console.log(result.length);\n console.log(result[0].employeeName);\n return result;\n });\n\n employeeList[0].employeeName;\n}\n```\n\n========================================\n\nCode:\n```text\nvar employeeList = Employee.findAll().then(function(result){\n    console.log(result.length);\n    console.log(result[0].employeeName);\n    //how do I return this to a variable with which I can do further processing\n    return result;\n });\n\n//do something with employeeList\nemployeeList[0].employeeName //cannot read property of undefined\n```\n\n```text\nPromise {\n  _bitField: 0,\n  _fulfillmentHandler0: undefined,\n  _rejectionHandler0: undefined,\n  _promise0: undefined,\n  _receiver0: undefined }\n```\n\n```js\n//Each request in it's own function to respect the single responsability principle \nfunction getAllEmployees() {\n  return Employee\n    .findAll()\n    .then(function(employees){\n      //do some parsing/editing\n      //this then is not required if you don't want to change anything\n      return employees;\n     });\n}\n\nfunction doAnotherJob() {\n  return YourModel\n    .findAll()\n    .then(function(response) => {\n      //do some parsing/editing\n      //this then is not required if you don't want to change anything\n      return response;\n    });\n}\n\nfunction do2IndependentCalls() {\n  return Promise.all([\n    getAllEmployees(),\n    doAnotherJob()\n  ]).then(([employees, secondRequest]) => {\n    //do the functionality you need\n  })\n}\n```\n\n```text\nEmployee\n  .findAll()\n  .then(function(el){\n    console.log(el.length);\n    console.log(el[0].employeeName);\n    return el;\n   })\n  .then(function(employeeList){\n    //do something with employeeList\n    employeeList[0].employeeName\n   });\n```\n\n```text\nthen\n```\n\n```text\nthen\n```\n\n```text\nthen\n```\n\n```text\nasync function getEmployees(){\n    var employeeList = await Employee.findAll().then(function(result){\n        console.log(result.length);\n        console.log(result[0].employeeName);\n        return result;\n    });\n\n    employeeList[0].employeeName;\n}\n```\n\n```text\nasync await\n```\n\n========================================\n\nComments:\n- What if I need to process the results of say two independent queries? Will I need to daisy chain the queries within the thens i.e 2nd query happens within the second then?\n- There is no need to process 2 truly independent queries in the same Promise chain, as long as it is OK for the 2 queries to be processed asynchronously with respect to each other.","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":152,"estimatedTokens":1004}}868{"id":"stack-42492249","source":"stackoverflow","questionId":42492249,"title":"Sequelize How to save without changing updatedAt?","tags":["node.js","sequelize.js"],"text":"Title: Sequelize How to save without changing updatedAt?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it anyhow possible to NOT update the updatedAt value on sequelize model.save()?\n\nI'm incrementing counters of an object and do not update the model at its root, thus I'd like the updatedAt value to stay as it is. Is this anyhow possible with sequelize?\n\n========================================\n\nCode:\n```text\ninstance.save ({ silent: true })\n```\n\n```text\nupdatedAt\n```\n\n```text\nsave\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":23,"estimatedTokens":128}}869{"id":"stack-45036547","source":"stackoverflow","questionId":45036547,"title":"Sequelize: How to multiply column into an aggregate function","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize: How to multiply column into an aggregate function\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo basically what I want is:\n\n```\nselect (table2.col1 * sum(table1.col1)) as myAggregate\nfrom table1 \njoin table2 ON table2.id = table1.id\n```\n\nI've gotten this far but don't know how to add the multiplication:\n\n```\nTable1Model.findAll({\n\n attributes: [[Sequelize.fn('SUM', 'col1'), 'myAggregate']]\n include: [Table2Model]\n})\n```\n\n========================================\n\nTop Answer:\nI don't know if this is covered by Sequelize docs, but you could use Sequelize.where to accomplish this. You might need to change table names, but it would be roughly like this:\n\n```\nTable1Model.findAll({\n attributes: [\n [\n Sequelize.where(\n Sequelize.col('table2.col1'),\n '*',\n Sequelize.fn('SUM', Sequelize.col('col1')),\n ),\n 'myAggregate',\n ]\n ],\n include: [Table2Model]\n})\n```\n\n========================================\n\nCode:\n```text\nselect (table2.col1 * sum(table1.col1)) as myAggregate\nfrom table1 \njoin table2 ON table2.id = table1.id\n```\n\n```text\nTable1Model.findAll({\n\n    attributes: [[Sequelize.fn('SUM', 'col1'), 'myAggregate']]\n    include: [Table2Model]\n})\n```\n\n```text\nattributes: [\n        [Sequelize.literal('(`Meetup.MeetupBusinessPercentages`.percentageCut * SUM(MeetupCharges.amount) / 100 )'), 'totalAmount']\n    ],\n```\n\n```text\nTable1Model.findAll({\n  attributes: [\n    [\n      Sequelize.where(\n        Sequelize.col('table2.col1'),\n        '*',\n        Sequelize.fn('SUM', Sequelize.col('col1')),\n      ),\n      'myAggregate',\n    ]\n  ],\n  include: [Table2Model]\n})\n```\n\n========================================\n\nComments:\n- Do you got any solution of this ?\n- Yup. Added relevant code from my app in the answer\n- Yes this is the only possible way for now\n- Any other solution ?\n- that's awesome!","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":91,"estimatedTokens":461}}870{"id":"stack-33093177","source":"stackoverflow","questionId":33093177,"title":"Sequelize connection error","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize connection error\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to transfer my application to a new machine. It works on the old machine perfectly, and I have been trying to copy the settings as closely as possible, but there is something missing. This is the error I'm getting:\n\n```\nUnhandled rejection SequelizeConnectionError: Handshake inactivity timeout\n at Handshake._callback (/Applications/MAMP/htdocs/dashboard-server/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:63:20)\n at Handshake.Sequence.end (/Applications/MAMP/htdocs/dashboard-server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n at /Applications/MAMP/htdocs/dashboard-server/node_modules/mysql/lib/protocol/Protocol.js:393:18\n at Array.forEach (native)\n at /Applications/MAMP/htdocs/dashboard-server/node_modules/mysql/lib/protocol/Protocol.js:392:13\n at doNTCallback0 (node.js:417:9)\n at process._tickCallback (node.js:346:13)\n```\n\nThoughts?\n\n========================================\n\nCode:\n```text\nUnhandled rejection SequelizeConnectionError: Handshake inactivity timeout\n    at Handshake._callback (/Applications/MAMP/htdocs/dashboard-server/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:63:20)\n    at Handshake.Sequence.end (/Applications/MAMP/htdocs/dashboard-server/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)\n    at /Applications/MAMP/htdocs/dashboard-server/node_modules/mysql/lib/protocol/Protocol.js:393:18\n    at Array.forEach (native)\n    at /Applications/MAMP/htdocs/dashboard-server/node_modules/mysql/lib/protocol/Protocol.js:392:13\n    at doNTCallback0 (node.js:417:9)\n    at process._tickCallback (node.js:346:13)\n```\n\n```text\nnode-mysql\n```\n\n========================================\n\nComments:\n- It seems to be a problem with the node-mysql package, did you try re-downloading the packages?\n- Why don't you try to increment the value of `acquireTimeout` of the connection?\n- Im still trying to find a definitive cause, but as a side-note node `4.2.0` was released under 12 hours ago, very possible that may be the culprit.\n- @JonathanS. - Thanks for that suggestion - I tried updating the associated packages, to no avail :( As for the `acquireTimeout`, I thought about doing that, but the only reason I haven't is because I'm not using pooling, and it's working as is on the other machine. @Aren - that's a good point, maybe I'll try rolling back to a previous version of NodeJS to see if it resolves the issue - I'll post my results soon.\n- This was it! Thank you so much for your help - saved me a lot of headache! I downgraded to 4.1.1 and my application booted right up!\n- See This Pull Request It looks like they're rushing out 4.2.1 today or tomorrow because there's 2 regressions that are breaking things everywhere.\n- @Jonathan You can now safely update to the latest node version **4.2.1** if you wish.\n- Thank you - I'll check it out tomorrow!","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":49,"estimatedTokens":743}}871{"id":"stack-40961709","source":"stackoverflow","questionId":40961709,"title":"called with something that's not an instance of Sequelize.Model at Model.belongsTo","tags":["javascript","node.js","sequelize.js"],"text":"Title: called with something that's not an instance of Sequelize.Model at Model.belongsTo\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to refer a foreign key between 2 models.\n\nbut I'm getting this error:\n\n```\nthrow new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\\'s not an instance of Sequelize.Model');\ncalled with something that's not an instance of Sequelize.Model\n at Model.belongsTo\n```\n\nHow can I fix this?\n\nThis is my code so far.\n\nThis is my models/mercadolibre.js\n\n```\n\"use strict\";\nvar User = require('../models/index').User;\n\nmodule.exports = function(sequelize, DataTypes) {\n var MercadoLibre = sequelize.define(\"MercadoLibre\", {\n id: { \n type: DataTypes.INTEGER, \n autoIncrement: true, \n primaryKey: true\n },\n access_token: DataTypes.STRING,\n refresh_token: DataTypes.STRING,\n environment_hash: DataTypes.STRING \n }, {\n tableName: 'mercadolibres',\n underscored: true,\n timestamps: true\n }\n\n );\n\n MercadoLibre.belongsTo(User);\n\n return MercadoLibre;\n};\n```\n\nThis is my models/user.js\n\n```\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define(\"User\", {\n id: { \n type: DataTypes.INTEGER, \n autoIncrement: true, \n primaryKey: true\n },\n name: DataTypes.STRING,\n slack_id: DataTypes.STRING,\n environment_hash: {\n type: DataTypes.STRING,\n defaultValue: DataTypes.UUIDV4\n }\n }, {\n tableName: 'users',\n underscored: false,\n timestamps: false\n }\n\n );\n\n return User;\n};\n```\n\nThis is my models/index.js\n\n```\n\"use strict\";\n\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar Sequelize = require('sequelize')\n , sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {\n dialect: \"mysql\", // or 'sqlite', 'postgres', 'mariadb'\n port: 3306, // or 5432 (for postgres)\n});\n\nvar db = {};\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n })\n .forEach(function(file) {\n var model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function(modelName) {\n if (\"associate\" in db[modelName]) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n========================================\n\nCode:\n```text\nthrow new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\\'s not an instance of Sequelize.Model');\ncalled with something that's not an instance of Sequelize.Model\n    at Model.belongsTo\n```\n\n```text\n\"use strict\";\nvar User  = require('../models/index').User;\n\nmodule.exports = function(sequelize, DataTypes) {\n  var MercadoLibre = sequelize.define(\"MercadoLibre\", {\n    id:  { \n          type: DataTypes.INTEGER, \n          autoIncrement: true, \n          primaryKey: true\n        },\n    access_token: DataTypes.STRING,\n    refresh_token: DataTypes.STRING,\n    environment_hash: DataTypes.STRING \n  }, {\n    tableName: 'mercadolibres',\n    underscored: true,\n    timestamps: true\n  }\n\n  );\n\n  MercadoLibre.belongsTo(User);\n\n  return MercadoLibre;\n};\n```\n\n```text\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define(\"User\", {\n    id:  { \n          type: DataTypes.INTEGER, \n          autoIncrement: true, \n          primaryKey: true\n        },\n    name: DataTypes.STRING,\n    slack_id: DataTypes.STRING,\n    environment_hash: {\n          type: DataTypes.STRING,\n          defaultValue: DataTypes.UUIDV4\n        }\n  }, {\n    tableName: 'users',\n    underscored: false,\n    timestamps: false\n  }\n\n  );\n\n  return User;\n};\n```\n\n```text\n\"use strict\";\n\nvar fs        = require(\"fs\");\nvar path      = require(\"path\");\nvar Sequelize = require('sequelize')\n  , sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {\n      dialect: \"mysql\", // or 'sqlite', 'postgres', 'mariadb'\n      port:    3306, // or 5432 (for postgres)\n});\n\n\nvar db = {};\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n  })\n  .forEach(function(file) {\n    var model = sequelize.import(path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(function(modelName) {\n  if (\"associate\" in db[modelName]) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\nvar MercadoLibre = sequelize.define(\"MercadoLibre\", {\n   id:  { \n      type: DataTypes.INTEGER, \n      autoIncrement: true, \n      primaryKey: true\n    },\n    access_token: DataTypes.STRING,\n    refresh_token: DataTypes.STRING,\n    environment_hash: DataTypes.STRING \n}, {\n    tableName: 'mercadolibres',\n    underscored: true,\n    timestamps: true,\n    classMethods: {\n        associate : function(models) {\n            MercadoLibre.belongsTo(models.User)\n        },\n      },\n  });\n\n\n\nreturn MercadoLibre;\n```\n\n========================================\n\nComments:\n- but you dont have user_id in this model !!","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":246,"estimatedTokens":1286}}872{"id":"stack-29247408","source":"stackoverflow","questionId":29247408,"title":"Updating a many to many join table using sequelize for nodejs","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Updating a many to many join table using sequelize for nodejs\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a Products table and a Categories table. A single Product can have many Categories and a single Category can have many Products, therefore I have a ProductsCategories table to handle the many-to-many join.\n\nIn the example below, I'm trying to associate one of my products (that has an ID of 1) with 3 different categories (that have IDs of 1, 2, & 3). I know something is off in my code snippet below because I'm getting an ugly SQL error message indicating that I'm trying to insert an object into the ProductsCategories join table. I have no idea how to fix the snippet below or if I'm even on the right track here. The Sequelize documentation is pretty sparse for this kind of thing.\n\n```\nmodels.Product.find({ where: {id: 1} }).on('success', function(product) {\n models.Category.findAll({where: {id: [1,2,3]}}).on('success', function(category){\n product.setCategories([category]);\n }); \n});\n```\n\nI'd really appreciate some help here, thanks. Also, I'm using Postgres, not sure if that matters.\n\n========================================\n\nTop Answer:\nI think you are close. I had a similar issue with some of my code. Try iterating over your found categories and then add them. I think this might do the trick. \n\n```\nmodels.Category.findAll({where: {id: [1,2,3]}}).on('success', function(category){\n for(var i=0; i<category.length; i++){\n product.setCategories([category[i]]);\n }\n });\n```\n\n========================================\n\nCode:\n```text\nmodels.Product.find({ where: {id: 1} }).on('success', function(product) {\n  models.Category.findAll({where: {id: [1,2,3]}}).on('success', function(category){\n    product.setCategories([category]);\n  });      \n});\n```\n\n```text\nmodels.Category.findAll\n```\n\n```text\nsetCategories([category]);\n```\n\n```text\nsetCategories(category);\n```\n\n```text\nmodels.Category.findAll({where: {id: [1,2,3]}}).on('success', function(category){\n            for(var i=0; i<category.length; i++){\n                product.setCategories([category[i]]);\n            }\n      });\n```\n\n========================================\n\nComments:\n- One reason I am not a fan of database frameworks... this code does not seem like it would scale. 3 SQL statements for what could be done in 1, and passing every column of each table back and forth from the DB server to app server just to satisfy the ORM.\n- Thank you so much Jan! I can't even tell you how much time I wasted trying to get to the bottom of this. I really appreciate your help.\n- Hey Rick, thank you for the response. I think what you did will definitely work but the solution above is a little cleaner. +1 either way\n- I don't think this works because each call to setCategories replaces the entire list of categories, or in other words, only the last category would win and be added.\n- This should be using `product.addCategories()` as that will properly append","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":71,"estimatedTokens":747}}873{"id":"stack-16371739","source":"stackoverflow","questionId":16371739,"title":"Why I cannot add field to a JS object?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Why I cannot add field to a JS object?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm programming Node with Sequelize ORM for MySQL. I need to add a new field to the object that Sequelize returns on a query, but it doesn't seems to work.\n\n```\nCategory.find({\n where: { id: req.params.id }, \n include: [Item]\n}).success(function(category) {\n var items = category.items;\n var ci = category.items.map(function(item) { return item.id; });\n delete category.items; // this works\n category.item_ids = ci; // this doesn't\n // category['item_ids'] = ci; // this doesn't work as well\n\n res.send({\n category: category,\n items: items\n });\n});\n```\n\n`Object.isExtensible` returns true on `category` object, but I can't figure out how to actually extend it\n\n========================================\n\nTop Answer:\nYou can add a computed property:\n\nhttp://www.sequelizejs.com/documentation#models-expansion\n\n========================================\n\nCode:\n```text\nCategory.find({\n  where: { id: req.params.id }, \n  include: [Item]\n}).success(function(category) {\n  var items = category.items;\n  var ci = category.items.map(function(item) { return item.id; });\n  delete category.items; // this works\n  category.item_ids = ci; // this doesn't\n  // category['item_ids'] = ci; // this doesn't work as well\n\n  res.send({\n    category: category,\n    items: items\n  });\n});\n```\n\n```text\nObject.isExtensible\n```\n\n```text\ncategory\n```\n\n```text\n.success(function(category) {\n  category = category.toJSON(); // convert to a simple JS object\n  ...\n  category.item_ids = ci;\n  ...\n  res.render(...);\n});\n```\n\n========================================\n\nComments:\n- I need to pass the object as JSON response, don't think that accessors would help in this case.\n- Thank you, fixed my problem. Although `typeof(category)` was returning `object` and I know is a JSON, still I couldn't add a field to it.\n- @Airwavezx `toJSON()` actually returns an object, but a plain JS one and not a Sequelize class instance. If you can't solve your problem, you should consider creating a new question.\n- No no! your answer resolved my problem. I was using Mongoose object though.\n- @Airwavezx oh yeah, with Mongoose objects there's a similar issue, in that you can't add fields to them (unless you can `.toJSON` or `.toObject` on them).","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":81,"estimatedTokens":582}}874{"id":"stack-44248753","source":"stackoverflow","questionId":44248753,"title":"Ssequelizejs, MySQL and passportjs user.findOne not a function","tags":["mysql","node.js","passport.js","sequelize.js"],"text":"Title: Ssequelizejs, MySQL and passportjs user.findOne not a function\nTags: mysql, node.js, passport.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently migrating from mongodb to MySQL in my Node js application. I use sequelize as ORM, but I'm having some trouble migrating some passportjs code.\n\nI have the following modal.\n\nuser.js:\n\n```\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define(\"users\", {\n username: DataTypes.STRING,\n localemail: DataTypes.STRING,\n localpassword: DataTypes.STRING,\n facebookid: DataTypes.STRING,\n facebooktoken: DataTypes.STRING,\n facebookemail: DataTypes.STRING,\n facebookname: DataTypes.STRING,\n twitterid: DataTypes.STRING,\n twittertoken: DataTypes.STRING,\n twitterdisplayname: DataTypes.STRING,\n twitterusername: DataTypes.STRING,\n googleid: DataTypes.STRING,\n googletoken: DataTypes.STRING,\n googleemail: DataTypes.STRING,\n googlename: DataTypes.STRING\n });\n\n return User;\n};\n```\n\nAnd the following function in my passportjs file:\n\n...\n\n```\n// load all the things we need\nvar LocalStrategy = require('passport-local').Strategy;\nvar FacebookStrategy = require('passport-facebook').Strategy;\nvar TwitterStrategy = require('passport-twitter').Strategy;\nvar GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;\n\n// load up the user model\nvar User = require('../models/user');\n```\n\n...\n\n```\npassport.use('local-login', new LocalStrategy({\n usernameField : 'email',\n passwordField : 'password',\n passReqToCallback : true \n },\n function(req, email, password, done) {\n if (email)\n email = email.toLowerCase(); \n // asynchronous\n process.nextTick(function() {\n User.findOne({\n where: {\n localemail: email\n }\n }).then(function(user) {\n // if there are any errors, return the error\n if (err)\n return done(err);\n\n // if no user is found, return the message\n if (!user)\n return done(null, false, req.flash('loginMessage', 'No user found.'));\n\n if (!validPassword(password))\n return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));\n\n // all is well, return user\n else\n return done(null, user);\n });\n });\n\n}));\n```\n\n...\n\nThe applications exits with the following error:\n\n```\npassport.js:100\n User.findOne({\n ^\n\nTypeError: User.findOne is not a function\n```\n\nI have looked at this code on github for inspiration:\n\nhttps://github.com/sequelize/express-example\n\nAny ideas to what i'm overlooking?\n\nUPDATE:\n\nSo in my passport.js file I have done this: \n\n```\nvar models = require('../models'); \nconsole.log(\"models.User:\" +models.User);\n```\n\nwhich output this: \n\n```\nnpm start app.js \n> myapp0.0.0 start /home/mathias/nodejs/myapp \n> DEBUG=express-sequelize \nnode ./bin/www \"app.js\" \nmodels.User:undefined \nexpress-sequelize \nExpress server listening on port 3000 +0ms express-sequelize \nListening on port 3000 +7ms –\n```\n\nThis gives an [object:object] in the console:\n\n```\nvar models = require('../models');\nconsole.log(\"models:\" +models);\n```\n\nAn this also gives an undefined:\n\n```\nvar models = require('../models').User;\nconsole.log(\"models:\" +models);\n```\n\nUpdate with config.json file:\n\n```\n{\n \"development\": {\n \"username\": \"root\",\n \"password\": \"password\",\n \"database\": \"myapp\",\n \"host\": \"0.0.0.0\",\n \"dialect\": \"mysql\"\n },\n \"test\": {\n \"username\": \"root\",\n \"password\": \"password\",\n \"database\": \"myapp\",\n \"host\": \"0.0.0.0\",\n \"dialect\": \"mysql\"\n },\n \"production\": {\n \"username\": \"root\",\n \"password\": \"password\",\n \"database\": \"myapp\",\n \"host\": \"0.0.0.0\",\n \"dialect\": \"mysql\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nThe problem is how you require the module. Replace:\n\n```\nvar User = require('../models/user');\n```\n\nWith this:\n\n```\nvar User = require('../models').User;\n```\n\nThis is like this because of the way the models are dynamically exported. You can have a look at your files, models/index.js. There you will find how each model is exported in a single object. So you basically always require the models/index.js and there specify which key you want to access, in this case \"User\"\n\n========================================\n\nCode:\n```text\n\"use strict\";\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define(\"users\", {\n    username: DataTypes.STRING,\n    localemail: DataTypes.STRING,\n    localpassword: DataTypes.STRING,\n    facebookid: DataTypes.STRING,\n    facebooktoken: DataTypes.STRING,\n    facebookemail: DataTypes.STRING,\n    facebookname: DataTypes.STRING,\n    twitterid: DataTypes.STRING,\n    twittertoken: DataTypes.STRING,\n    twitterdisplayname: DataTypes.STRING,\n    twitterusername: DataTypes.STRING,\n    googleid: DataTypes.STRING,\n    googletoken: DataTypes.STRING,\n    googleemail: DataTypes.STRING,\n    googlename: DataTypes.STRING\n  });\n\n  return User;\n};\n```\n\n```text\n// load all the things we need\nvar LocalStrategy    = require('passport-local').Strategy;\nvar FacebookStrategy = require('passport-facebook').Strategy;\nvar TwitterStrategy  = require('passport-twitter').Strategy;\nvar GoogleStrategy   = require('passport-google-oauth').OAuth2Strategy;\n\n// load up the user model\nvar User       = require('../models/user');\n```\n\n```text\npassport.use('local-login', new LocalStrategy({\n        usernameField : 'email',\n        passwordField : 'password',\n        passReqToCallback : true \n    },\n    function(req, email, password, done) {\n        if (email)\n            email = email.toLowerCase(); \n    // asynchronous\n    process.nextTick(function() {\n        User.findOne({\n            where: {\n                localemail: email\n            }\n        }).then(function(user) {\n            // if there are any errors, return the error\n            if (err)\n                return done(err);\n\n            // if no user is found, return the message\n            if (!user)\n                return done(null, false, req.flash('loginMessage', 'No user found.'));\n\n            if (!validPassword(password))\n                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));\n\n            // all is well, return user\n            else\n                return done(null, user);\n        });\n    });\n\n}));\n```\n\n```text\npassport.js:100\n                    User.findOne({\n                         ^\n\nTypeError: User.findOne is not a function\n```\n\n```text\nvar models = require('../models'); \nconsole.log(\"models.User:\" +models.User);\n```\n\n```text\nnpm start app.js \n> myapp0.0.0 start /home/mathias/nodejs/myapp \n> DEBUG=express-sequelize \nnode ./bin/www \"app.js\" \nmodels.User:undefined \nexpress-sequelize \nExpress server listening on port 3000 +0ms express-sequelize \nListening on port 3000 +7ms –\n```\n\n```text\nvar models  = require('../models');\nconsole.log(\"models:\" +models);\n```\n\n```text\nvar models  = require('../models').User;\nconsole.log(\"models:\" +models);\n```\n\n```text\n{\n  \"development\": {\n    \"username\": \"root\",\n    \"password\": \"password\",\n    \"database\": \"myapp\",\n    \"host\": \"0.0.0.0\",\n    \"dialect\": \"mysql\"\n  },\n  \"test\": {\n    \"username\": \"root\",\n    \"password\": \"password\",\n    \"database\": \"myapp\",\n    \"host\": \"0.0.0.0\",\n    \"dialect\": \"mysql\"\n  },\n  \"production\": {\n    \"username\": \"root\",\n    \"password\": \"password\",\n    \"database\": \"myapp\",\n    \"host\": \"0.0.0.0\",\n    \"dialect\": \"mysql\"\n  }\n}\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  ...\n  return User;\n}\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst DataTypes = sequelize.DataTypes;\n\nlet sequelize = new Sequelize(...);\n\nconst User = require('../models/user')(sequelize, DataTypes);\n```\n\n```text\n// models/user.js\nconst sequelize = require('sequelize');\nconst DataTypes = sequelize.DataTypes;\n\nmodule.exports = sequelize.define(\"users\", { ... });\n```\n\n```text\nconst User = require('../models/user');\n```\n\n```text\nuser.js\n```\n\n```text\nsequelize\n```\n\n```text\nDataTypes\n```\n\n```js\nvar User = require('../models/user');\n```\n\n```js\nvar User = require('../models').User;\n```\n\n```js\nvar { User } = require('../models');\n```\n\n========================================\n\nComments:\n- `user.js` exports a function that returns a model, so after importing that function you need to call it (with the correct arguments) and the return value will be the `User` model.\n- Hi robertklep I tried that with the var models = require('../models').User; with no luck. Any uess to what I might be overlooking?\n- It dosen't seem to work (I'm getting the same error), you are saying that ...\"So you basically always require the models/index.js\"... Does this mean that I need to require require('../models/index.js');? If so, what should I call the variable (I guess some other code should be able to reference it)?\n- if you don't specify a key, you can call it \"models\". If you specify a Key the way I replied, you call it User or whatever. Show me a pastebin with the contents of your models/index.js\n- I also tried this: // load up the user model var models = require('../models'); and then \"models.User.findOne({\"\n- There's probably a problem with the file path. Are you sure that ../models is the right path? Also, debug the var models (or User) and see what it outputs\n- When I change the file path to something that I now isen't right, ex. /models I get an error on start saying that the module cannot be found, so I quess that the path is right? a console.log from the user.js dosen't seem to output something usefull.\n- I mean output the console log of models.User or User, depending how you are requiring\n- I've updated the question with an example of what I guess you meant?\n- Cannot find module '../models' When I use models = require('../models'); instead of User= require('../models/User');\n- @wafutech take a look at this example repo github.com/sequelize/express-example/blob/master/models/&hellip;\n- So to make minimal impact on my code, I started with the first example where iam passing sequelize and DataTypes around. When this works, I will implement the more simple model you describe, it makes a lot more sense. So the user.js still looks like the one in my original question above. Implementing the changes that you describe to my passport.js file gives the following error in the console: /home/tony/code/myapp/models/user.js:4 var User = sequelize.define(\"users\", { ^ TypeError: sequelize.define is not a function\n- @Tony oh I think that I misunderstood the code, and `sequelize` is not the module reference but the database instance (so the result of `new Sequelize(...)`). In that case, you may still need to pass it around. I'll update my answer.\n- Thanks alot that helped! Now the code compiles. Unfortunately I receive an error when trying to use the sign in route: Unhandled rejection SequelizeAccessDeniedError: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'localhost' (using password: NO) I guess it might, be because of my config.json file, which I have added to the original question.\n- @Tony according to MySQL, you're not passing the correct credentials.\n- But iam wondering if it sees the password/configuration, because of the \"using password: NO\". I would have expected a yes and a username at least?\n- @Tony unless you're not passing the credentials correctly (see this: sequelize.readthedocs.io/en/latest/api/sequelize/&hellip;)\n- Okay, this must be the reason. I will try to figure out the right way to connect. Anyway thats not part of the original question, and and you have been more than helpfull towards resolving my problem with setting up Sequelize. Thanks!\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":399,"estimatedTokens":2858}}875{"id":"stack-71730361","source":"stackoverflow","questionId":71730361,"title":"How to programatically run sequelize seeders?","tags":["javascript","node.js","sequelize.js"],"text":"Title: How to programatically run sequelize seeders?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to NodeJS and Sequelize and am trying to execute the sequelize seeders on project startup.\n\nHere is an example of one of my seed functions.\n\n`filePath: src/database/seeders/20220402125658-default-filters.js`\n\n```\n'use strict';\n\nmodule.exports = {\n async up(queryInterface, Sequelize) {\n await queryInterface.bulkInsert('Filters', [\n {\n id: 'b16c15ce-9841-4ea5-95fb-0d21f8cd85f0', // TODO: use uuid4()\n name: 'Amount Filter',\n maxAmount: 200.0,\n minAmount: 0.2,\n createdAt: new Date(),\n updatedAt: new Date(),\n },\n ]);\n },\n\n async down(queryInterface, Sequelize) {\n await queryInterface.bulkDelete('Filters', null, bulkDeleteOptions);\n },\n};\n```\n\nIn my index.js file I am executing sequelize.sync() which synchronizes my database model.\nThis is working great, but I want to also execute the seed code above when the sync is complete.\n\n`filePath: src/database/index.js`\n\n```\ndb.sequelize.sync().then(() => {\n// execute seeders here ...\n});\n```\n\nDo you have any idea how can I do that ?\nThe seeding is working correctly when I use it through npx command: `npx sequelize-cli db:seed:all`, but I want to do it automatically on project start.\n\n========================================\n\nTop Answer:\nHere is an example that puts data in database. Postgres:15.6, Sequelize 6, Umzug.\n\nSequelize and Umzug setup:\n\n```\n// db.ts\nimport {Sequelize} from 'sequelize';\n\nimport {DB} from '../types/db';\nimport pg from 'pg';\nimport ClickhouseStatisticsModel from './models/ClickhouseStatistics.model';\nimport VisitedUsersModel from './models/VisitedUsers.model';\nimport ExampleModel from './models/Example.model';\nimport SharedStatesModel from './models/SharedStates.model';\nimport ClickhouseCacheModel from './models/ClickhouseCache.model';\nimport SharedLogsModel from './models/SharedLogs.model';\nimport {Umzug, SequelizeStorage} from 'umzug';\n\nconst sequelize: Sequelize = new Sequelize(\n process.env.DB_NAME as string,\n process.env.DB_USERNAME as string,\n process.env.DB_PASSWORD as string,\n {\n host: process.env.DB_HOSTNAME,\n port: Number(process.env.DB_PORT),\n dialect: 'postgres',\n dialectModule: pg,\n ssl: true,\n dialectOptions: process.env.DB_SSL === 'false' ? {} : {ssl: {require: true}},\n // logging: (msg: string) => console.log(msg),\n logging: false,\n define: {\n freezeTableName: true,\n },\n },\n);\n\nconst db: DB = {\n sequelize,\n models: {\n clickhouseStatistics: ClickhouseStatisticsModel(sequelize),\n clickhouseCache: ClickhouseCacheModel(sequelize),\n visitedUser: VisitedUsersModel(sequelize),\n example: ExampleModel(sequelize),\n sharedStates: SharedStatesModel(sequelize),\n sharedLogs: SharedLogsModel(sequelize),\n },\n};\n\nconst umzug: Umzug = new Umzug({\n migrations: {glob: ['migrations/*.{js,ts}', {cwd: __dirname}]},\n context: sequelize.getQueryInterface(),\n storage: new SequelizeStorage({sequelize}),\n logger: console,\n});\n\nexport {db, umzug};\n```\n\nMigration file:\n\n```\n// 20_add_data.ts\nimport {Migration, MigrationParams} from '../../../types/db.migrations';\nimport {SharedLogRecord} from '../../../types/db';\nimport fs from 'fs';\n\ntype SharedLogRecordFromSqlite = SharedLogRecord & {\n updatedAt: string;\n deletedAt: string;\n};\n\nexport const up: Migration = async ({context: queryInterface}: MigrationParams) => {\n // 20_shared_logs.json\n const data: SharedLogRecordFromSqlite[] = JSON.parse(\n fs.readFileSync(__dirname + '/20_shared_logs.json', 'utf8'),\n );\n\n let maxId: number = 0;\n data.forEach((record: SharedLogRecordFromSqlite) => {\n delete record.updatedAt;\n delete record.deletedAt;\n\n if (record.id > maxId) maxId = record.id;\n });\n maxId++;\n\n await queryInterface.bulkInsert('SharedLogs', data);\n\n // https://stackoverflow.com/a/78306713/10099510\n await queryInterface.sequelize.query(`ALTER SEQUENCE \"SharedLogs_id_seq\" RESTART WITH ${maxId};`);\n};\n\nexport const down: Migration = async () => {};\n\nmodule.exports = {up, down};\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = {\n  async up(queryInterface, Sequelize) {\n    await queryInterface.bulkInsert('Filters', [\n      {\n        id: 'b16c15ce-9841-4ea5-95fb-0d21f8cd85f0', // TODO: use uuid4()\n        name: 'Amount Filter',\n        maxAmount: 200.0,\n        minAmount: 0.2,\n        createdAt: new Date(),\n        updatedAt: new Date(),\n      },\n    ]);\n  },\n\n  async down(queryInterface, Sequelize) {\n    await queryInterface.bulkDelete('Filters', null, bulkDeleteOptions);\n  },\n};\n```\n\n```text\ndb.sequelize.sync().then(() => {\n// execute seeders here ...\n});\n```\n\n```text\nfilePath: src/database/seeders/20220402125658-default-filters.js\n```\n\n```text\nfilePath: src/database/index.js\n```\n\n```text\nnpx sequelize-cli db:seed:all\n```\n\n```js\n/* <PROJECT_ROOT>/migrations.js */\nvar Umzug = require(\"umzug\");\nvar models = require(\"./models\");\n\nvar migrationsConfig = {\n  storage: \"sequelize\",\n  storageOptions: {\n    sequelize: models.sequelize\n    // modelName: 'SequelizeMeta' // No need to specify, because this is default behaviour\n  },\n  migrations: {\n    params: [\n      models.sequelize.getQueryInterface(),\n      models.sequelize.constructor\n    ],\n    path: \"./migrations\", // path to folder containing migrations\n    pattern: /\\.js$/\n  }\n};\n\nvar seedsConfig = {\n  storage: \"sequelize\",\n  storageOptions: {\n    sequelize: models.sequelize,\n    modelName: 'SequelizeData' // Or whatever you want to name the seeder storage table\n  },\n  migrations: {\n    params: [\n      models.sequelize.getQueryInterface(),\n      models.sequelize.constructor\n    ],\n    path: \"./seeds\", // path to folder containing seeds\n    pattern: /\\.js$/\n  }\n};\n\nvar migrator = new Umzug(migrationsConfig);\nvar seeder = new Umzug(seedsConfig);\n\nmodule.exports = () => migrator.up().then(() => seeder.up());\n\n/* <PROJECT_ROOT>/index.js */\nvar migrations = require(\"./migrations\");\n\n// Run migrations & seeds\nmigrations().then(function() {\n  console.log(\"Migrations completed\");\n});\n```\n\n```text\npackage.json\n```\n\n```text\nstart\n```\n\n```text\n./run-migrations.sh && node .\n```\n\n```text\nsequelize-cli db:migrate && sequelize-cli db:seed:all && node .\n```\n\n```text\nnpm run start\n```\n\n```js\n// db.ts\nimport {Sequelize} from 'sequelize';\n\nimport {DB} from '../types/db';\nimport pg from 'pg';\nimport ClickhouseStatisticsModel from './models/ClickhouseStatistics.model';\nimport VisitedUsersModel from './models/VisitedUsers.model';\nimport ExampleModel from './models/Example.model';\nimport SharedStatesModel from './models/SharedStates.model';\nimport ClickhouseCacheModel from './models/ClickhouseCache.model';\nimport SharedLogsModel from './models/SharedLogs.model';\nimport {Umzug, SequelizeStorage} from 'umzug';\n\nconst sequelize: Sequelize = new Sequelize(\n  process.env.DB_NAME as string,\n  process.env.DB_USERNAME as string,\n  process.env.DB_PASSWORD as string,\n  {\n    host: process.env.DB_HOSTNAME,\n    port: Number(process.env.DB_PORT),\n    dialect: 'postgres',\n    dialectModule: pg,\n    ssl: true,\n    dialectOptions: process.env.DB_SSL === 'false' ? {} : {ssl: {require: true}},\n    // logging: (msg: string) => console.log(msg),\n    logging: false,\n    define: {\n      freezeTableName: true,\n    },\n  },\n);\n\nconst db: DB = {\n  sequelize,\n  models: {\n    clickhouseStatistics: ClickhouseStatisticsModel(sequelize),\n    clickhouseCache: ClickhouseCacheModel(sequelize),\n    visitedUser: VisitedUsersModel(sequelize),\n    example: ExampleModel(sequelize),\n    sharedStates: SharedStatesModel(sequelize),\n    sharedLogs: SharedLogsModel(sequelize),\n  },\n};\n\nconst umzug: Umzug = new Umzug({\n  migrations: {glob: ['migrations/*.{js,ts}', {cwd: __dirname}]},\n  context: sequelize.getQueryInterface(),\n  storage: new SequelizeStorage({sequelize}),\n  logger: console,\n});\n\nexport {db, umzug};\n```\n\n```js\n// 20_add_data.ts\nimport {Migration, MigrationParams} from '../../../types/db.migrations';\nimport {SharedLogRecord} from '../../../types/db';\nimport fs from 'fs';\n\ntype SharedLogRecordFromSqlite = SharedLogRecord & {\n  updatedAt: string;\n  deletedAt: string;\n};\n\nexport const up: Migration = async ({context: queryInterface}: MigrationParams) => {\n  // 20_shared_logs.json\n  const data: SharedLogRecordFromSqlite[] = JSON.parse(\n      fs.readFileSync(__dirname + '/20_shared_logs.json', 'utf8'),\n  );\n\n  let maxId: number = 0;\n  data.forEach((record: SharedLogRecordFromSqlite) => {\n    delete record.updatedAt;\n    delete record.deletedAt;\n\n    if (record.id > maxId) maxId = record.id;\n  });\n  maxId++;\n\n  await queryInterface.bulkInsert('SharedLogs', data);\n\n  // https://stackoverflow.com/a/78306713/10099510\n  await queryInterface.sequelize.query(`ALTER SEQUENCE \"SharedLogs_id_seq\" RESTART WITH ${maxId};`);\n};\n\nexport const down: Migration = async () => {};\n\nmodule.exports = {up, down};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":355,"estimatedTokens":2205}}876{"id":"stack-68926254","source":"stackoverflow","questionId":68926254,"title":"Sequelize : Using 'where' in 'include' in findByPk","tags":["javascript","sequelize.js"],"text":"Title: Sequelize : Using 'where' in 'include' in findByPk\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn Sequelize I´m using findByPk but I also need to pass another condition\n\n```\nreturn dependencies.db.models.user.findByPk(userId, {\n include: [\n {\n model: dependencies.db.models.userGroup,\n required: false,\n where: {\n Time: null,\n },\n```\n\nI know that 'options.where' is not supported for findByPk , however it is being used inside of a include.\nI couldn't find verification in the sequelize documentation that what I am doing is correct.\n\n========================================\n\nCode:\n```text\nreturn dependencies.db.models.user.findByPk(userId, {\n        include: [\n            {\n                model: dependencies.db.models.userGroup,\n                required: false,\n                where: {\n                    Time: null,\n                },\n```\n\n```text\nreturn dependencies.db.models.user.findByPk(userId, {\n        include: [\n            {\n                model: dependencies.db.models.userGroup,\n                required: false,\n                where: {\n                    Time: { [op.eq]:null }\n                },\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":45,"estimatedTokens":288}}877{"id":"stack-45248189","source":"stackoverflow","questionId":45248189,"title":"Not store updatedAt with sequelize model","tags":["mysql","sequelize.js"],"text":"Title: Not store updatedAt with sequelize model\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen I store models in my MySQL DB, they are immutable. As a result I can see the need for the createdAt column in my tables, but I don't need the redundant updatedAt column. Can I configure sequelize not to store updatedAt time and then can I drop the column from my table?\n\n========================================\n\nTop Answer:\nLooking at the documentation regarding your situation\n\n If you want sequelize to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each column individually:\n\n```\nconst Foo = sequelize.define('foo', { /* bla */ }, {\n // don't forget to enable timestamps!\n timestamps: true,\n\n // I don't want createdAt\n createdAt: false,\n\n // I want updatedAt to actually be called updateTimestamp\n updatedAt: 'updateTimestamp',\n\n // And deletedAt to be called destroyTime (remember to enable paranoid for this to work)\n deletedAt: 'destroyTime',\n paranoid: true\n})\n```\n\nSo in the above example, just set `timestamps` to be `true` but then `createdAt` to be false\n\n========================================\n\nCode:\n```text\nupdatedAt: false\n```\n\n```text\nconst Foo = sequelize.define('foo',  { /* bla */ }, {\n  // don't forget to enable timestamps!\n  timestamps: true,\n\n  // I don't want createdAt\n  createdAt: false,\n\n  // I want updatedAt to actually be called updateTimestamp\n  updatedAt: 'updateTimestamp',\n\n  // And deletedAt to be called destroyTime (remember to enable paranoid for this to work)\n  deletedAt: 'destroyTime',\n  paranoid: true\n})\n```\n\n```text\ntimestamps\n```\n\n```text\ntrue\n```\n\n```text\ncreatedAt\n```\n\n========================================\n\nComments:\n- Isn't this just simply removing the column and removing cases where you are setting the data for that column?\n- Nope, it seems that when I set `timestamps: true` to the model, sequelize automatically creates and tries to use these columns.\n- oh sorry didn't realize you found the answer. glad things worked out :)\n- Can we just disable updating updateAt for a specific query? (such as some jobs which update some summary fields on all instances)","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":76,"estimatedTokens":551}}878{"id":"stack-51783864","source":"stackoverflow","questionId":51783864,"title":"encrypt password column using Sequelize and mysql","tags":["mysql","sequelize.js"],"text":"Title: encrypt password column using Sequelize and mysql\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize at first time and have a question about encrypt user password.\n\nI want use the function AES_ENCRYPT to encrypt a string text.\nMy question is, how can I call that function on sequelize??\n\n========================================\n\nTop Answer:\nYou nedd bcrypt and hooks : beforeCreate and beforeUpdate.\n\n```\nconst User = sequelize.define('User', {\n...\n password: {\n type: DataTypes.STRING,\n allowNull: false,\n }\n...\n});\n\nfunction generateHash(user) {\n if (user === null) {\n throw new Error('No found employee');\n }\n else if (!user.changed('password')) return user.password;\n else {\n let salt = bcrypt.genSaltSync();\n return user.password = bcrypt.hashSync(user.password, salt);\n }\n}\n\nUser.beforeCreate(generateHash);\n\nUser.beforeUpdate(generateHash);\n```\n\n========================================\n\nCode:\n```text\nconst bcrypt = require('bcrypt');\n\nvar User = db.sequelize.define( 'user' , {\n    ...\n    password : {\n        type : db.Sequelize.STRING\n    },\n    ...\n},\n{\n    hooks : {\n        beforeCreate : (user , options) => {\n            {\n                user.password = user.password && user.password != \"\" ? bcrypt.hashSync(user.password, 10) : \"\";\n            }\n        }\n    }\n});\n```\n\n```text\nbcrypt\n```\n\n```text\nbeforeCreate\n```\n\n```text\nconst User = sequelize.define('User', {\n...\n    password: {\n        type: DataTypes.STRING,\n        allowNull: false,\n    }\n...\n});\n\nfunction generateHash(user) {\n    if (user === null) {\n        throw new Error('No found employee');\n    }\n    else if (!user.changed('password')) return user.password;\n    else {\n        let salt = bcrypt.genSaltSync();\n        return user.password = bcrypt.hashSync(user.password, salt);\n    }\n}\n\nUser.beforeCreate(generateHash);\n\nUser.beforeUpdate(generateHash);\n```\n\n========================================\n\nComments:\n- There is not another way without external packages?\n- @Raugaral , this packages is most popular for encryption, so dont worry about it , you wont regret on this.\n- Writing your own encryption is a bad idea, encryption is incredibly sophisticated and it's easy to make costly mistakes. bcrypt is a popular library so it's secure and works well!\n- You can't decrypt if you have encrypted with bcrypt. @KieranQuinn\n- Correct, this is the reason I couldn't use any form of NodeJs encryption\n- @KieranQuinn , you can use crypto js and use other encryption method so that you can decrypt it back , like AES. npmjs.com/package/crypto-js","metadata":{"transformedAt":"2026-08-18T18:33:34.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":108,"estimatedTokens":643}}879{"id":"stack-54055302","source":"stackoverflow","questionId":54055302,"title":"SequelizeJS: Wrong order of Column Values when using Numbers as String","tags":["postgresql","sequelize.js"],"text":"Title: SequelizeJS: Wrong order of Column Values when using Numbers as String\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to SequelizeJS and using it for PostgreSQL with NodeJS application.\n\nI have a table:\n\n```\nsequelize.define('log', {\n id: {\n type: type.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n statusCode: type.INTEGER,\n status: type.STRING,\n message: type.TEXT,\n lastRecordId: type.STRING,\n lastRecordTime: type.DATE\n});\n```\n\nThe problem is that, when I run a query for fetching the values from `lastRecordId` column in `DESC` order, I get wrong order of the values:\n\nhttps://i.sstatic.net/OnIr1.png\n\nI did not want to use `INTEGER` nor `BIGINT` on that column, because it contains a code not a real number.\n\nThe query I am using is:\n\n```\nLoggerModel\n .findAll({\n order: [ [ 'lastRecordId', 'DESC' ]],\n })\n .then( allLogs => {\n //...\n })\n```\n\n========================================\n\nTop Answer:\nYou can cast it on the fly without changing the column to type. Then you can order on with that. \n\n```\nLoggerModel\n .findAll({\n order: [\n sequelize.cast('lastRecordId', 'BIGINT'),\n [ 'lastRecordId', 'DESC' ]\n ],\n })\n .then( allLogs => {\n //...\n })\n```\n\ninspired by this\n\n========================================\n\nCode:\n```text\nsequelize.define('log', {\n    id: {\n        type: type.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    statusCode: type.INTEGER,\n    status: type.STRING,\n    message: type.TEXT,\n    lastRecordId: type.STRING,\n    lastRecordTime: type.DATE\n});\n```\n\n```text\nLoggerModel\n            .findAll({\n                order: [ [ 'lastRecordId', 'DESC' ]],\n            })\n            .then( allLogs => {\n                //...\n            })\n```\n\n```text\nlastRecordId\n```\n\n```text\nDESC\n```\n\n```text\nINTEGER\n```\n\n```text\nBIGINT\n```\n\n```text\nLoggModel\n        .findAll({\n            order: [\n                [ sequelize.cast(sequelize.col('lastRecordId'), 'BIGINT') , 'DESC' ]\n            ]\n        })\n        .then((logs) => { /// })\n```\n\n```text\nLoggerModel\n        .findAll({\n            order: [\n                     sequelize.cast('lastRecordId', 'BIGINT'),\n                     [ 'lastRecordId', 'DESC' ]\n              ],\n        })\n        .then( allLogs => {\n            //...\n        })\n```\n\n========================================\n\nComments:\n- It's generating `invalid input syntax for integer: \"log.lastRecordId\"`. Any idea about...???\n- My table name is Log and I am using `log` as table name in model definition.\n- Ok, try just with 'lastRecordId', I hv updated my answer.\n- Sorry for late reply. I have tried with `lastRecordId` but failed to get the results. Also, I have used `log.lastRecordId` without any luck. Same database error is occurring.\n- This also worked perfectly for me.","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":137,"estimatedTokens":696}}880{"id":"stack-53235353","source":"stackoverflow","questionId":53235353,"title":"SQL query to find a row with a specific number of associations","tags":["sql","postgresql","sequelize.js","relational-division"],"text":"Title: SQL query to find a row with a specific number of associations\nTags: sql, postgresql, sequelize.js, relational-division\nSource: Stack Overflow\n\nQuestion:\nUsing Postgres I have a schema that has `conversations` and `conversationUsers`. Each `conversation` has many `conversationUsers`. I want to be able to find the conversation that has the exactly specified number of `conversationUsers`. In other words, provided an array of `userIds` (say, `[1, 4, 6]`) I want to be able to find the conversation that contains only those users, and no more. \n\nSo far I've tried this:\n\n```\nSELECT c.\"conversationId\"\nFROM \"conversationUsers\" c\nWHERE c.\"userId\" IN (1, 4)\nGROUP BY c.\"conversationId\"\nHAVING COUNT(c.\"userId\") = 2;\n```\n\nUnfortunately, this also seems to return conversations which include these 2 users among others. (For example, it returns a result if the conversation also includes `\"userId\"` 5).\n\n========================================\n\nTop Answer:\nyou can modify your query like this and it should work:\n\n```\nSELECT c.\"conversationId\"\nFROM \"conversationUsers\" c\nWHERE c.\"conversationId\" IN (\n SELECT DISTINCT c1.\"conversationId\"\n FROM \"conversationUsers\" c1\n WHERE c1.\"userId\" IN (1, 4)\n )\nGROUP BY c.\"conversationId\"\nHAVING COUNT(DISTINCT c.\"userId\") = 2;\n```\n\n========================================\n\nCode:\n```text\nSELECT c.\"conversationId\"\nFROM \"conversationUsers\" c\nWHERE c.\"userId\" IN (1, 4)\nGROUP BY c.\"conversationId\"\nHAVING COUNT(c.\"userId\") = 2;\n```\n\n```text\nconversations\n```\n\n```text\nconversationUsers\n```\n\n```text\nconversation\n```\n\n```text\nconversationUsers\n```\n\n```text\nconversationUsers\n```\n\n```text\nuserIds\n```\n\n```text\n[1, 4, 6]\n```\n\n```text\n\"userId\"\n```\n\n```sql\nSELECT \"conversationId\"\nFROM   \"conversationUsers\" c\nWHERE  \"userId\" = ANY ('{1,4,6}'::int[])\nGROUP  BY 1\nHAVING count(*) = array_length('{1,4,6}'::int[], 1)\nAND    NOT EXISTS (\n   SELECT FROM \"conversationUsers\"\n   WHERE  \"conversationId\" = c.\"conversationId\"\n   AND    \"userId\" <> ALL('{1,4,6}'::int[])\n   );\n```\n\n```sql\nWITH RECURSIVE rcte AS (\n   SELECT \"conversationId\", 1 AS idx\n   FROM   \"conversationUsers\"\n   WHERE  \"userId\" = ('{1,4,6}'::int[])[1]\n\n   UNION ALL\n   SELECT c.\"conversationId\", r.idx + 1\n   FROM   rcte                r\n   JOIN   \"conversationUsers\" c USING (\"conversationId\")\n   WHERE  c.\"userId\" = ('{1,4,6}'::int[])[idx + 1]\n   )\nSELECT \"conversationId\"\nFROM   rcte r\nWHERE  idx = array_length(('{1,4,6}'::int[]), 1)\nAND    NOT EXISTS (\n   SELECT FROM \"conversationUsers\"\n   WHERE  \"conversationId\" = r.\"conversationId\"\n   AND    \"userId\" <> ALL('{1,4,6}'::int[])\n   );\n```\n\n```sql\nPREPARE conversations(int[]) AS\nWITH RECURSIVE rcte AS (\n   SELECT \"conversationId\", 1 AS idx\n   FROM   \"conversationUsers\"\n   WHERE  \"userId\" = $1[1]\n\n   UNION ALL\n   SELECT c.\"conversationId\", r.idx + 1\n   FROM   rcte                r\n   JOIN   \"conversationUsers\" c USING (\"conversationId\")\n   WHERE  c.\"userId\" = $1[idx + 1]\n   )\nSELECT \"conversationId\"\nFROM   rcte r\nWHERE  idx = array_length($1, 1)\nAND    NOT EXISTS (\n   SELECT FROM \"conversationUsers\"\n   WHERE  \"conversationId\" = r.\"conversationId\"\n   AND    \"userId\" <> ALL($1);\n```\n\n```text\nEXECUTE conversations('{1,4,6}');\n```\n\n```sql\nCREATE MATERIALIZED VIEW mv_conversation_users AS\nSELECT \"conversationId\", array_agg(\"userId\") AS users  -- sorted array\nFROM (\n   SELECT \"conversationId\", \"userId\"\n   FROM   \"conversationUsers\"\n   ORDER  BY 1, 2\n   ) sub\nGROUP  BY 1\nORDER  BY 1;\n\nCREATE INDEX ON mv_conversation_users (users) INCLUDE (\"conversationId\");\n```\n\n```text\nSELECT \"conversationId\"\nFROM   mv_conversation_users c\nWHERE  users = '{1,4,6}'::int[];  -- sorted array!\n```\n\n```text\n\"conversationUsers\"\n```\n\n```text\n(\"userId\", \"conversationId\")\n```\n\n```text\nNOT NULL\n```\n\n```text\n(\"conversationId\", \"userId\")\n```\n\n```text\nNOT EXISTS\n```\n\n```text\n\"conversationUsers\"\n```\n\n```text\nMATERIALIZED VIEW\n```\n\n```text\n(users, \"conversationId\")\n```\n\n```text\nconversation_id\n```\n\n```text\n\"conversationId\"\n```\n\n```text\nSELECT c.\"conversationId\"\nFROM \"conversationUsers\" c\nWHERE c.\"conversationId\" IN (\n    SELECT DISTINCT c1.\"conversationId\"\n    FROM \"conversationUsers\" c1\n    WHERE c1.\"userId\" IN (1, 4)\n    )\nGROUP BY c.\"conversationId\"\nHAVING COUNT(DISTINCT c.\"userId\") = 2;\n```\n\n```text\nselect\n      cu.ConversationId\n   from\n      conversationUsers cu\n   group by\n      cu.ConversationID\n   having \n      sum( case when cu.userId IN (1, 4) then 1 else 0 end ) = count( distinct cu.UserID )\n```\n\n```text\nselect\n      cu.ConversationId\n   from\n      ( select cu2.ConversationID\n           from conversationUsers cu2\n           where cu2.userID = 4 ) preQual\n      JOIN conversationUsers cu\n         preQual.ConversationId = cu.ConversationId\n   group by\n      cu.ConversationID\n   having \n      sum( case when cu.userId IN (1, 4) then 1 else 0 end ) = count( distinct cu.UserID )\n```\n\n========================================\n\nComments:\n- It would be helpful to provide your version of Postgres, minimum table definition and some sample rows to test with.\n- Hi. This is a faq. Please always google many clear, concise & specific versions/phrasings of your question/problem/goal with & without your particular strings/names & read many answers. Add relevant keywords you discover to your searches. If you don't find an answer then post, using 1 variant search as title & keywords for tags. See the downvote arrow mouseover text. When you do have a non-duplicate code question to post please read & act on minimal reproducible example.\n- @HummingBird24: My apologies, I butchered the assumption about the PK in my previous edit, so it wasn't obvious any more, why it works like that. Consider the edit fixing that. Given the PK, the filter in the `HAVING` clause eliminates conversations with only a subset of the given users, e.g. `'{1,6}'` when looking for `'{1,4,6}'`. `having count() = n` acts like `having count() >= n` (not like `having count() > n`!) because after `WHERE \"userId\" = ANY ('{1,4,6}'::int[])` there can never be more than `array_length('{1,4,6}'::int[], 1)` matches.\n- Ahh okay I understand now. Thanks for the clarification! And yes `>=` not `>` that was a typo on my part.","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":245,"estimatedTokens":1539}}881{"id":"stack-38303924","source":"stackoverflow","questionId":38303924,"title":"Promise chaining in Sequelize migrations - relation does not exist","tags":["sequelize.js","sequelize-cli","umzug"],"text":"Title: Promise chaining in Sequelize migrations - relation does not exist\nTags: sequelize.js, sequelize-cli, umzug\nSource: Stack Overflow\n\nQuestion:\nThis simple test code:\n\n```\nreturn queryInterface.createTable('tadam', {id: Sequelize.INTEGER, humus: Sequelize.STRING(255)})\n .then(queryInterface.sequelize.query('ALTER TABLE tadam ADD PRIMARY KEY (id)'));\n```\n\nreturns the following error:\n\n```\nUnhandled rejection SequelizeDatabaseError: relation \"tadam\" does not exist\n```\n\nNow, I understand that by the time the second promise (about altering the table) is executed, the table hasn't been created yet.\n\nIt could not be because all queries within the migration are executed together at once, because I have, f.e. this test migration:\n\n```\nreturn queryInterface.sequelize.query('ALTER TABLE tadam DROP CONSTRAINT tadam_pkey')\n .then(queryInterface.removeIndex('tadam', 'tadam_pkey'));\n```\n\nand it works fine.\n\nSo, can anyone give explanation why the first one does not work and how can I implement it, so that the creation of the table + adding the PK can be executed from a single migration?\n\n========================================\n\nCode:\n```text\nreturn queryInterface.createTable('tadam', {id: Sequelize.INTEGER, humus: Sequelize.STRING(255)})\n      .then(queryInterface.sequelize.query('ALTER TABLE tadam ADD PRIMARY KEY (id)'));\n```\n\n```text\nUnhandled rejection SequelizeDatabaseError: relation \"tadam\" does not exist\n```\n\n```text\nreturn queryInterface.sequelize.query('ALTER TABLE tadam DROP CONSTRAINT tadam_pkey')\n  .then(queryInterface.removeIndex('tadam', 'tadam_pkey'));\n```\n\n```text\nreturn queryInterface.createTable('tadam', {id: Sequelize.INTEGER, humus: Sequelize.STRING(255)})\n  .then(function(results) {\n    // results will be the result of the first query\n    return queryInterface.sequelize.query('ALTER TABLE tadam ADD PRIMARY KEY (id)');\n  });\n```\n\n```text\nqueryInterface.sequelize.query('ALTER TABLE tadam ADD PRIMARY KEY (id)')\n```\n\n```text\nthen()\n```\n\n========================================\n\nComments:\n- One small suggestion (to be more compatible with common eslint rules) is to use `() => queryInterface...` instead of the function","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":68,"estimatedTokens":541}}882{"id":"stack-42782260","source":"stackoverflow","questionId":42782260,"title":"PassportJs Authentication Infinite Loop and Execute(default) query","tags":["node.js","authentication","express","passport.js","sequelize.js"],"text":"Title: PassportJs Authentication Infinite Loop and Execute(default) query\nTags: node.js, authentication, express, passport.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to build the authentication system using PassportJs and Sequelize. I made the registration system by myself, using Sequelize. I want to use PassportJS only for Login.\n\nIt does not redirect me to the failureRedirect route, neither to the SuccessRedirect one, but when submitting the form it enters into an endless loop and in my console, the following message appears: \n\n```\nExecuting (default): SELECT `id`, `username`, `lastName`, `password`, `email`, `phone`, `createdAt`, `updatedAt` FROM `user` AS `user` LIMIT 1;\n```\n\nMy project is structured in: users_model.js , index.js and users.js (the controller).\n\nThe code I have in my index.js looks like this: \n\n```\n//===============Modules=============================\nvar express = require('express');\nvar bodyParser = require('body-parser'); \nvar session = require('express-session');\nvar authentication= require('sequelize-authentication');\nvar passport = require('passport');\nvar LocalStrategy = require('passport-local').Strategy;\nvar passportlocal= require('passport-local');\nvar passportsession= require('passport-session');\n\nvar User = require('./models/users_model.js');\n\npassport.use(new LocalStrategy(\n function(username, password, done) {\n User.findOne({ username: username }, function(err, user) {\n if (err) { return done(err); }\n if (!user) {\n return done(null, false, { message: 'Incorrect username.' });\n }\n if (!user.validPassword(password)) {\n return done(null, false, { message: 'Incorrect password.' });\n }\n return done(null, user);\n });\n }\n));\n\npassport.serializeUser(function(user, done) {\n done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done) {\n User.findById(id, function(err, user) {\n done(err, user);\n console.log(id);\n });\n});\n\nvar users= require('./controllers/users.js'); \nvar app = express();\n\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'ejs');\n\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json());\n\napp.use('/users', users);\napp.use('/events', events);\n\n//-------------------------------------------Setup Session------------\napp.use(session({\n secret: \"ceva\",\n resave:true,\n saveUninitialized:true,\n cookie:{},\n duration: 45 * 60 * 1000,\n activeDuration: 15 * 60 * 1000,\n}));\n\n// Passport init\napp.use(passport.initialize());\napp.use(passport.session());\n\n//------------------------------------------------Routes----------\napp.get('/', function (req, res) {\n res.send('Welcome!');\n});\n\n //-------------------------------------Server-------------------\n\napp.listen(3000, function () {\n console.log('Example app listening on port 3000!');\n});\n```\n\nIn my controller, I made the registration system by myself, using Sequelize. In users.js, I have:\n\n```\nvar express = require('express');\nvar passport = require('passport');\nvar LocalStrategy = require('passport-local').Strategy;\nvar passportlocal= require('passport-local');\nvar passportsession= require('passport-session');\nvar router = express.Router();\n\nvar User = require('../models/users_model.js');\n\n//____________________Initialize Sequelize____________________\n\nconst Sequelize = require(\"sequelize\");\nconst sequelize = new Sequelize('millesime_admin', 'root', '', {\n host: 'localhost',\n dialect: 'mysql',\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n }\n}); \n\n//________________________________________\n\nrouter.get('/',function(req,res){\nres.send('USERS');\n});\n\nrouter.get('/register', function(req, res) {\n res.render('registration', {title: \"Register\" });\n});\n\nrouter.post('/register', function(req, res) {\n var email = req.body.email;\n var password = req.body.password;\n var username= req.body.username;\n var lastname= req.body.lastname;\n var phone= req.body.phone;\n\n User.findAll().then(user => {\n usersNumber = user.length;\n x=usersNumber+1;\n var y =usersNumber.toString();\n var uid='ORD'+ y;\n\n User.sync().then(function (){\n return User.create({\n id:uid,\n email: email,\n password:password,\n username: username,\n lastName: lastname,\n phone: phone,\n });\n }).then(c => {\n console.log(\"User Created\", c.toJSON());\n res.redirect('/users');\n }).catch(e => console.error(e)); \n }); \n});\n\nrouter.get('/login',function(req,res){\n res.render('authentication');\n});\n\n//router.post('/login', function(req, res, next) {\n// console.log(req.url); // '/login'\n// console.log(req.body);\n// I got these:{ username: 'username', password: 'parola' } \n// passport.authenticate('local', function(err, user, info) {\n// console.log(\"authenticate\");\n// console.log('error:',err);\n// console.log('user:',user);\n// console.log('info:',info);\n// })(req, res, next);\n//});\n\nrouter.post('/login', passport.authenticate('local', { \n successRedirect: '/events', \n failureRedirect: '/users/register' \n }));\n\nrouter.get('/logout', function(req, res){\n req.logout(); \n res.redirect('/users/login');\n}); \n\n//__________________________________________\nmodule.exports = router;\n```\n\n========================================\n\nCode:\n```text\nExecuting (default): SELECT `id`, `username`, `lastName`, `password`,  `email`, `phone`, `createdAt`, `updatedAt` FROM `user` AS `user` LIMIT 1;\n```\n\n```text\n//===============Modules=============================\nvar express = require('express');\nvar bodyParser = require('body-parser');   \nvar session = require('express-session');\nvar authentication= require('sequelize-authentication');\nvar passport = require('passport');\nvar LocalStrategy = require('passport-local').Strategy;\nvar passportlocal= require('passport-local');\nvar passportsession= require('passport-session');\n\nvar User = require('./models/users_model.js');\n\n\npassport.use(new LocalStrategy(\n  function(username, password, done) {\n    User.findOne({ username: username }, function(err, user) {\n      if (err) { return done(err); }\n      if (!user) {\n        return done(null, false, { message: 'Incorrect username.' });\n      }\n      if (!user.validPassword(password)) {\n        return done(null, false, { message: 'Incorrect password.' });\n      }\n      return done(null, user);\n    });\n  }\n));\n\n\npassport.serializeUser(function(user, done) {\n  done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done) {\n  User.findById(id, function(err, user) {\n    done(err, user);\n    console.log(id);\n  });\n});\n\n\nvar users= require('./controllers/users.js');    \nvar app = express();\n\n\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'ejs');\n\n\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json());\n\napp.use('/users', users);\napp.use('/events', events);\n\n//-------------------------------------------Setup Session------------\napp.use(session({\n    secret: \"ceva\",\n    resave:true,\n    saveUninitialized:true,\n    cookie:{},\n    duration: 45 * 60 * 1000,\n    activeDuration: 15 * 60 * 1000,\n}));\n\n\n// Passport init\napp.use(passport.initialize());\napp.use(passport.session());\n\n//------------------------------------------------Routes----------\napp.get('/', function (req, res) {\n     res.send('Welcome!');\n});\n\n   //-------------------------------------Server-------------------\n\napp.listen(3000, function () {\n  console.log('Example app listening on port 3000!');\n});\n```\n\n```text\nvar express = require('express');\nvar passport = require('passport');\nvar LocalStrategy = require('passport-local').Strategy;\nvar passportlocal= require('passport-local');\nvar passportsession= require('passport-session');\nvar router = express.Router();\n\nvar User = require('../models/users_model.js');\n\n//____________________Initialize Sequelize____________________\n\nconst Sequelize = require(\"sequelize\");\nconst sequelize = new Sequelize('millesime_admin', 'root', '', {\n  host: 'localhost',\n  dialect: 'mysql',\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  }\n}); \n\n//________________________________________\n\n\nrouter.get('/',function(req,res){\nres.send('USERS');\n});\n\nrouter.get('/register', function(req, res) {\n     res.render('registration', {title: \"Register\" });\n});\n\nrouter.post('/register', function(req, res) {\n    var email = req.body.email;\n    var password = req.body.password;\n    var username= req.body.username;\n    var lastname= req.body.lastname;\n    var phone= req.body.phone;\n\n   User.findAll().then(user => {\n    usersNumber = user.length;\n    x=usersNumber+1;\n    var y =usersNumber.toString();\n    var uid='ORD'+ y;\n\n    User.sync().then(function (){\n      return User.create({\n      id:uid,\n      email: email,\n      password:password,\n      username: username,\n      lastName: lastname,\n      phone: phone,\n         });\n    }).then(c => {\n        console.log(\"User Created\", c.toJSON());\n         res.redirect('/users');\n    }).catch(e => console.error(e));    \n });    \n});\n\nrouter.get('/login',function(req,res){\n    res.render('authentication');\n});\n\n//router.post('/login', function(req, res, next) {\n//    console.log(req.url);  // '/login'\n//    console.log(req.body);\n// I got these:{ username: 'username', password: 'parola' } \n//    passport.authenticate('local', function(err, user, info) {\n//        console.log(\"authenticate\");\n//        console.log('error:',err);\n//        console.log('user:',user);\n//        console.log('info:',info);\n//    })(req, res, next);\n//});\n\n\nrouter.post('/login', passport.authenticate('local', { \n    successRedirect: '/events',                    \n    failureRedirect: '/users/register' \n    }));\n\nrouter.get('/logout', function(req, res){\n    req.logout();    \n    res.redirect('/users/login');\n});    \n\n//__________________________________________\nmodule.exports = router;\n```\n\n```text\npassport.use(new LocalStrategy(\n  function(username, password, done) {\n    ...\n  }\n));\n```\n\n```text\nUser.findOne({ username: username }).then(user => {\n  if (!user) {\n    return done(null, false, { message: 'Incorrect username.' });\n  }\n  if (!user.validPassword(password)) {\n    return done(null, false, { message: 'Incorrect password.' });\n  }\n  done(null, user);\n}).catch(err => done(err));\n```\n\n```text\npassport.serializeUser(function(user, done) {\n  done(null, user.userid);\n});\n\npassport.deserializeUser(function(id, done) {\n  User.findOne({ userid: id }).then(user => {\n    done(null, user);\n    console.log(id);\n  }).catch(err => done(err));\n});\n```\n\n```text\npassport\n```\n\n```text\nexpress\n```\n\n```text\ndone\n```\n\n```text\ndone()\n```\n\n```text\ndone\n```\n\n```text\nid\n```\n\n```text\nuserid\n```\n\n========================================\n\nComments:\n- Yes, now it works! Thank you for you your help, your answer and explanations. I get it now! Thanks! :)","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":437,"estimatedTokens":2652}}883{"id":"stack-59272750","source":"stackoverflow","questionId":59272750,"title":"SSH tunnel to Sequelize PostgreSQL database","tags":["database","sequelize.js","ssh-tunnel"],"text":"Title: SSH tunnel to Sequelize PostgreSQL database\nTags: database, sequelize.js, ssh-tunnel\nSource: Stack Overflow\n\nQuestion:\nI am trying to access one of our remote databases (AWS RDS) that is hidden behind a bastion EC2 instance. I can access the database easily through my SQL client, but cannot access it through the CLI tool I am building (using `Sequelize` and `tunnel-ssh`). I was following this GitHub Gist but it uses the same values everywhere and is quite confusing unfortunately.\n\nI will admit to having a poor understanding of SSH tunnelling in general, which may be apparent in the examples below. Is there something wrong with my configuration?\n\n**Database Config**\n\n```\nHost: wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com\nPort: 5432\nUser: [DB_USER]\nPassword: [DB_PASSWORD]\nDatabase: [DB_NAME]\n```\n\n**Bastion Config**\n\n```\nServer: 35.183.XX.XXX\nPort: 22\nPassword:\nSSH Key: ~/.ssh/id_rsa.aws\n```\n\n```\nconst config = {\n // I don't need to specify any local values, do I?\n // localHost: \"127.0.0.1\",\n // localPort: 5432,\n\n // This should be bastion config, correct?\n username: \"ec2-user\",\n host: 35.183.XX.XXX,\n port: 22,\n privateKey: require(\"fsf\").readFileSync(\"/path/to/ssh/key\"),\n\n // This should be destination (database) config, correct?\n dstHost: wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com,\n dstPort: 5432\n};\n\n// NOTE: If I don't have an \"await\" here, nothing seems to run inside the function itself (no consoles, etc)\nconst server = await tunnel(config, async (error, server) => {\n if (error) return console.error(error);\n\n const db = new Sequelize(DB_NAME, DB_USER, DB_PASSWORD, {\n dialect: \"postgres\",\n // NOTE: If this is already the destination in the SSH tunnel, should I use it again vs localhost?\n host: \"wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com\",\n port: 5432\n });\n\n db.authenticate().then(async () => {\n const orgs = await db.organization.findAll();\n\n console.log(\"Successful query\", orgs);\n }).catch(err => {\n console.error(\"DB auth error\": err);\n });\n});\n```\n\nIs there something wrong with my configuration above? Is my understanding of tunnels flawed by the values I've used in the tunnel config?\n\nAlso, why doesn't the tunnel callback appear to be called **unless** I `await` the function (which doesn't seem to be a `Promise` at all)?\n\nP.S. There's also this Sequelize GitHub issue that mentions connecting with Sequelize via an SSH tunnel, but gives no examples.\n\n========================================\n\nTop Answer:\nWhile this specifically mentions tunnel-ssh I think it is important to add an additional way of doing this.\n\n**What you will need**\n\n.pem key used to start your ec2 instance. `// this is your private key and is generated in step 1b`\n\nIP address of your Bastion host(ec2)\n\nIP address of your database running in RDS.\n\nssh on your Linux, or Mac machine. `You can use WSL2 on Windows`\n\n**Assumptions**\n\nI am assuming for sake of simplicity that you are doing most of these tasks in AWS Console.\n\nI am assuming you are using postgres which is why I defaulted to port 5432. If mysql use 3306.\n\nI am assuming you know how to start an ec2 instance and have the security groups set up to allow inbound traffic on port 22 from approved IP Addresses i.e your machine.\n\n**Steps**\n\nGenerate a id_ed25519 key pair.\n\na. Navigate to EC2 Dashboard and on the left gutter under Network & Security click on Key Pairs.\n\nb. Click on Create key pair at the top of your screen. You will need to provide a name and select the PEM format. `// This will create a public key and will download a corresponding private key to your downloads folder.`\n\nc. Launch your ec2 instance. In the Key Pair section, select the key pair you just created.\n\nIn your local terminal make sure that your private key has the correct permissions.\n\na. `chmod 400 path/to/YourKeyPair.pem`\n\nCreate an SSH tunnel between your localhost and the ec2 instance.\n\na. `ssh -i path/to/YourKeyPair.pem -L 5432::5432 ec2-user@`\n\nCheck if the tunnel was successful\n\na. `lsof -i :5432` `// Run me in separate terminal`\n\nRun your Node.js app\n\n```\nconst db = new Sequelize(DB_NAME, DB_USER, DB_PASSWORD, {\n dialect: \"postgres\",\n host: \"localhost\",\n port: 5432\n });\n```\n\n========================================\n\nCode:\n```text\nHost:     wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com\nPort:     5432\nUser:     [DB_USER]\nPassword: [DB_PASSWORD]\nDatabase: [DB_NAME]\n```\n\n```text\nServer:   35.183.XX.XXX\nPort:     22\nPassword:\nSSH Key:  ~/.ssh/id_rsa.aws\n```\n\n```js\nconst config = {\n  // I don't need to specify any local values, do I?\n  // localHost: \"127.0.0.1\",\n  // localPort: 5432,\n\n  // This should be bastion config, correct?\n  username: \"ec2-user\",\n  host: 35.183.XX.XXX,\n  port: 22,\n  privateKey: require(\"fsf\").readFileSync(\"/path/to/ssh/key\"),\n\n  // This should be destination (database) config, correct?\n  dstHost: wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com,\n  dstPort: 5432\n};\n\n// NOTE: If I don't have an \"await\" here, nothing seems to run inside the function itself (no consoles, etc)\nconst server = await tunnel(config, async (error, server) => {\n  if (error) return console.error(error);\n\n  const db = new Sequelize(DB_NAME, DB_USER, DB_PASSWORD, {\n    dialect: \"postgres\",\n    // NOTE: If this is already the destination in the SSH tunnel, should I use it again vs localhost?\n    host: \"wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com\",\n    port: 5432\n  });\n\n  db.authenticate().then(async () => {\n    const orgs = await db.organization.findAll();\n\n    console.log(\"Successful query\", orgs);\n  }).catch(err => {\n    console.error(\"DB auth error\": err);\n  });\n});\n```\n\n```text\nSequelize\n```\n\n```text\ntunnel-ssh\n```\n\n```text\nawait\n```\n\n```text\nPromise\n```\n\n```text\nHost:     wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com\nPort:     5432\nUser:     [DB_USER]\nPassword: [DB_PASSWORD]\nDatabase: [DB_NAME]\n```\n\n```text\nServer:   35.183.XX.XXX\nPort:     22\nPassword:\nSSH Key:  ~/.ssh/id_rsa.aws\n```\n\n```js\nconst config = {\n  // I have confirmed that the local values are unnecessary (defaults work)\n\n  // Configuration for SSH bastion\n  username: \"ec2-user\",\n  host: 35.183.XX.XXX,\n  port: 22,\n  privateKey: require(\"fs\").readFileSync(\"/path/to/ssh/key\"),\n\n  // Configuration for destination (database)\n  dstHost: wdXXXXXXXXXXXX.XXXXXXXXX.XX-XXXXX-X.rds.amazonaws.com,\n  dstPort: 5432\n};\n\n// NOTE: Moved to its own function, refactor likely fixed a few issues along the way\nconst getDB = () => new Promise((resolve, reject) => {\n  const tnl = await tunnel(config, async error => {\n    if (error) return reject(error);\n\n    const db = new Sequelize(DB_NAME, DB_USER, DB_PASSWORD, {\n      dialect: \"postgres\",\n      // NOTE: This is super important as the tunnel has essentially moved code execution to the database server already...\n      host: \"localhost\",\n      port: 5432\n    });\n\n    return resolve(db);\n  });\n});\n```\n\n```text\nlocalhost\n```\n\n```js\nconst db = new Sequelize(DB_NAME, DB_USER, DB_PASSWORD, {\n      dialect: \"postgres\",\n      host: \"localhost\",\n      port: 5432\n    });\n```\n\n```text\n// this is your private key and is generated in step 1b\n```\n\n```text\nYou can use WSL2 on Windows\n```\n\n```text\n// This will create a public key and will download a corresponding private key to your downloads folder.\n```\n\n```text\nchmod 400 path/to/YourKeyPair.pem\n```\n\n```text\nssh -i path/to/YourKeyPair.pem -L 5432:<RDSEndpoint>:5432 ec2-user@<EC2Endpoint>\n```\n\n```text\nlsof -i :5432\n```\n\n```text\n// Run me in separate terminal\n```\n\n========================================\n\nComments:\n- I am using this exact steps but I still cannot access the Database. it gives me this error - uncaught exception: Error: All configured authentication methods failed. Can someone help me understand the error\n- Me too, I can not connect DB although I did exactly the same as you :(\n- I figured that you need to add `keepAlive: true` option to your tunnel initialisation code, otherwise it will flop after the very first connection attempt\n- I think @PavloSirous has the right of it. I kept getting `connect ECONNREFUSED 127.0.0.1:5432` until I set `keepAlive: true` on my tunnel config.","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":293,"estimatedTokens":2032}}884{"id":"stack-40820813","source":"stackoverflow","questionId":40820813,"title":"Error: Missing where attribute in the options parameter passed to findOrCreate.","tags":["javascript","node.js","sequelize.js"],"text":"Title: Error: Missing where attribute in the options parameter passed to findOrCreate.\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use sequelize findOrCreate function, but I'm getting this error:\n\n```\nError: Missing where attribute in the options parameter passed to findOrCreate.\n```\n\nThis is my code:\n\n```\nvar values = { slack_id: profile.id, name: profile.user };\nvar selector = { where: { slack_id: profile.id } };\nUser.findOrCreate(values, selector)\n .then(function() {\n return done(err, user);\n });\n```\n\n========================================\n\nCode:\n```text\nError: Missing where attribute in the options parameter passed to findOrCreate.\n```\n\n```text\nvar values = { slack_id: profile.id, name: profile.user };\nvar selector = { where: { slack_id: profile.id } };\nUser.findOrCreate(values, selector)\n            .then(function() {\n                return done(err, user);\n            });\n```\n\n```text\nMissing where attribute in the options parameter passed to \n findOrCreate. Please note that the API has changed, and is now options \n only (an object with where, defaults keys, transaction etc.)\n```\n\n```text\nUser.findOrCreate(selector, values)\n        .then(function() {\n            return done(err, user);\n        });\n```\n\n========================================\n\nComments:\n- `User.findOrCreate({ where: { email: profile.emails[0].value } }, { email: profile.emails[0].value, username: profile.displayName, token: token }) .then(user => { console.log(user) return user; }).catch(error => console.log(error))`","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":55,"estimatedTokens":390}}885{"id":"stack-65671048","source":"stackoverflow","questionId":65671048,"title":"How to fix Sequelize update issue?","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: How to fix Sequelize update issue?\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI use MySQL ORM. But update method not working.\n\n```\nUser.update({\n ResetPasswordToken : resetPasswordToken\n},{\n where: {\n UserName: 'testuser'\n }\n})\n```\n\nSequelize Log:\n\nExecuting (default): UPDATE `Users` SET `ResetPasswordToken`=?,`updatedAt`=? WHERE `UserName` = ?\n\n========================================\n\nTop Answer:\nYou can update several fields at once with the set method:\n\n```\nconst jane = await User.create({ name: \"Jane\" });\n\njane.set({\n name: \"Ada\",\n favoriteColor: \"blue\"\n});\n// As above, the database still has \"Jane\" and \"green\"\nawait jane.save();\n// The database now has \"Ada\" and \"blue\" for name and favorite color\n```\n\n========================================\n\nCode:\n```text\nUser.update({\n  ResetPasswordToken : resetPasswordToken\n},{\n  where: {\n      UserName: 'testuser'\n  }\n})\n```\n\n```text\nUsers\n```\n\n```text\nResetPasswordToken\n```\n\n```text\nupdatedAt\n```\n\n```text\nUserName\n```\n\n```text\nconst jane = await User.create({ name: \"Jane\" });\n    console.log(jane.name); // \"Jane\"\n    jane.name = \"Ada\";\n    // the name is still \"Jane\" in the database\n    await jane.save();\n    // Now the name was updated to \"Ada\" in the database!\n```\n\n```text\nconst foo = async (resetPasswordToken) => {\n       //Finding current instance of the user\n       const currentUser = await User.findOne({\n          where:{\n            UserName: 'testuser'\n          }\n       });\n       //modifying the related field\n       currentUser.ResetPasswordToken = resetPasswordToken;\n       //saving the changes\n       currentUser.save({fields: ['ResetPasswordToken']});\n    }\n```\n\n```text\nconst jane = await User.create({ name: \"Jane\" });\n\njane.set({\n  name: \"Ada\",\n  favoriteColor: \"blue\"\n});\n// As above, the database still has \"Jane\" and \"green\"\nawait jane.save();\n// The database now has \"Ada\" and \"blue\" for name and favorite color\n```\n\n========================================\n\nComments:\n- I dont want create new user. I want to change old data. For example: change password\n- Yes, I modified the answer according to your question. First, you can find the current user instance and then save the related field. Just give it a try, I believe it should work.\n- What if I want to update multiple rows, not just one row, based on some condition. Why isn't the above update code not working ?","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":109,"estimatedTokens":604}}886{"id":"stack-62286812","source":"stackoverflow","questionId":62286812,"title":"How to properly convert uuid to BINARY(16)?","tags":["mysql","node.js","sequelize.js","uuid"],"text":"Title: How to properly convert uuid to BINARY(16)?\nTags: mysql, node.js, sequelize.js, uuid\nSource: Stack Overflow\n\nQuestion:\nI have an id field of type `BINARY(16)` in a mysql table. \n\nI generate the following id: `66e2105c-bff5-4206-a9cc-e212f5622368`\n\nWith this code:\n\n```\nconst v = uuidV4Bytes(16);\n```\n\nThe insert via sequalize is: \n\n```\nINSERT INTO SPORTS(Id,Name,HouseId,Date,Active)\n VALUES ('66e2105c-bff5-4206-a9cc-e212f5622368','SPORTNAME',1, '2020-05-04', 0)\n```\n\nProblem:\n\n```\nError Code: 1406. Data too long for column 'Id' at row\n```\n\nIm trying to convert a uuid to a binary(16) but apperently Im getting a value that is to big. \nHow do I solve this?\n\n========================================\n\nTop Answer:\nThanks to @hanshenrik I started searching for a way to use UNHEX in nodeexpress. \n\nI found the following: \n\n```\nconst byteValue = Buffer.from(uuidV4Bytes(16).replace('-', ''), 'hex')\n```\n\nThis did the trick. However I can not say that this is the most optimal way but it solved my problem.\n\n========================================\n\nCode:\n```text\nconst v = uuidV4Bytes(16);\n```\n\n```text\nINSERT INTO SPORTS(Id,Name,HouseId,Date,Active)\n        VALUES ('66e2105c-bff5-4206-a9cc-e212f5622368','SPORTNAME',1, '2020-05-04', 0)\n```\n\n```text\nError Code: 1406. Data too long for column 'Id' at row\n```\n\n```text\nBINARY(16)\n```\n\n```text\n66e2105c-bff5-4206-a9cc-e212f5622368\n```\n\n```text\nINSERT INTO SPORTS(Id,Name,HouseId,WDate,Active)\n    VALUES (UNHEX(REPLACE('66e2105c-bff5-4206-a9cc-e212f5622368','-','')),'SPORTNAME',1, '2020-05-04', 0)\n```\n\n```text\n8-4-4-4-12\n```\n\n```text\nconst byteValue = Buffer.from(uuidV4Bytes(16).replace('-', ''), 'hex')\n```\n\n========================================\n\nComments:\n- Looks like you got your column names and DATA a bit muddled up. `Name` : 1? and HouseId : SPORTNAME??\n- just a copy paste issue, updated. Main problem remains\n- `66e2105c-bff5-4206-a9cc-e212f5622368` thats MORE than 16 bytes. Its more like 36 bytes.\n- I gatherd that but the thing is that Im new at this and as far as I understood these methods should generate a 16 bytes but im missing something.\n- @RiggsFolly yeah but the dashes position never changes and don't have to be stored, so then you're left with 32 characters, and those 32 characters are in base16 hex, if you convert those 32 characters from base16 (hex) to base256 (bytes), then you're left with 16 base256 characters (or 16 bytes) ^^\n- @hanshenrik OK, so now how would you search the table based on a uuid?\n- @RiggsFolly one way to do it would be: `SELECT * FROM `tbl` WHERE `id` = UNHEX(REPLACE('66e2105c-bff5-4206-a9cc-e212f5622368','-','')&zwnj;&#8203;);`\n- Jump started my brain to search for the right thing. My answer below is the way I did it but accepting this since it pointed me in the right direction. Thanks!\n- What if I need to perform query like `SELECT id, fname FROM table_name WHERE id=UNHEX(REPLACE('4568-7899-2543-8yu5', \"-\", \"\"))`, it returns me result like: `id:<buffer 45 68 78 99 25 43 8y u5, fname:john`. Is there any way to convert this buffer value back to the original format & show in response data from database (using Aurora-AWS with nodejs)?\n- @bubble-cord maybe `SELECT CONCAT( HEX(SUBSTRING(id, 1, 4)),'-', HEX(SUBSTRING(id, 5, 2)),'-', HEX(SUBSTRING(id, 7, 2)),'-', HEX(SUBSTRING(id, 9, 2)),'-', HEX(SUBSTRING(id, 11, 6)) ) AS `id`, `fname` FROM table_name WHERE id = '4568-7899-2543-8yu5'`","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":94,"estimatedTokens":853}}887{"id":"stack-57719038","source":"stackoverflow","questionId":57719038,"title":"sequelize find and update a record without a model","tags":["mysql","sql","node.js","sequelize.js","mysql2"],"text":"Title: sequelize find and update a record without a model\nTags: mysql, sql, node.js, sequelize.js, mysql2\nSource: Stack Overflow\n\nQuestion:\nI would like to update a database record using sequelize.js and mysql2\nI do not have access to the models folder or either they have not been made so is there a way to update can't find solution all solutions are that i checked are with model name dot update\n\n```\nvar Book = db.define(‘books’, {\n title: {\n type: Sequelize.STRING\n },\n pages: {\n type: Sequelize.INTEGER\n }\n})\n\nBook.update(\n {title: req.body.title},\n {returning: true, where: {id: req.params.bookId} }\n )\n .then(function([ rowsUpdate, [updatedBook] ]) {\n res.json(updatedBook)\n })\n .catch(e => console.log(e));\n```\n\nI would like your expert solution on that please\n\n========================================\n\nCode:\n```text\nvar Book = db.define(‘books’, {\n title: {\n   type: Sequelize.STRING\n },\n pages: {\n   type: Sequelize.INTEGER\n }\n})\n\n\nBook.update(\n   {title: req.body.title},\n   {returning: true, where: {id: req.params.bookId} }\n )\n .then(function([ rowsUpdate, [updatedBook] ]) {\n   res.json(updatedBook)\n })\n .catch(e => console.log(e));\n```\n\n```text\n// Using query model(User)\nawait User.update({ y: 42 }, {\n  where: {\n    x: 12\n  }\n});\n\n// Using raw query\nconst [results, metadata] = await sequelize.query(\"UPDATE users SET y = 42 WHERE x = 12\");\n// Results will be an empty array and metadata will contain the number of affected rows.\n```\n\n```text\nsequelize.query(\"UPDATE users SET y = 42 WHERE x = 12\").spread(function(results, metadata) {\n  // Results will be an empty array and metadata will contain the number of affected rows.\n})\n```\n\n```text\nquery model(preferred)\n```\n\n```text\nraw queries\n```\n\n========================================\n\nComments:\n- @JitendraYadav accepted","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":85,"estimatedTokens":449}}888{"id":"stack-28700150","source":"stackoverflow","questionId":28700150,"title":"Create row including association with hasOne in Sequelize","tags":["mysql","node.js","orm","sequelize.js"],"text":"Title: Create row including association with hasOne in Sequelize\nTags: mysql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm testing different ORM's for Node.js and got stuck at this error: \n\n```\nPossibly unhandled TypeError: undefined is not a function\n@ person.setUser(user);\n```\n\nTried `person.setUsers`, `user.setPerson` and `user.setPeople`. Also tried console.log to find the function with no luck.\n\nWhat am I doing wrong?\n\n```\nvar config = require('./config.json');\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize(config.connection, {\n define: {\n freezeTableName: true,\n underscoredAll: true,\n underscored: true\n }\n});\n\nvar Person = sequelize.define('person', {\n first_name: Sequelize.STRING,\n last_name: Sequelize.STRING\n});\n\nvar User = sequelize.define('user', {});\n\nPerson.hasOne(User);\n\nsequelize.sync().then(run);\n\nfunction run() {\n var person = Person.create({ first_name: 'Markus', last_name: 'Hedlund' });\n var user = User.create();\n\n person.setUser(user);\n}\n```\n\n========================================\n\nTop Answer:\nAlthough dege answer is correct I would write it with a nice promise chain:\n\n```\nPerson.create({ first_name: 'Markus', last_name: 'Hedlund' })\n.bind({})\n.then(function(person){\n this.person = person;\n return User.create()\n})\n.then(function(user){\n return this.person.setUser(user);\n});\n```\n\n========================================\n\nCode:\n```text\nPossibly unhandled TypeError: undefined is not a function\n@ person.setUser(user);\n```\n\n```text\nvar config = require('./config.json');\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize(config.connection, {\n    define: {\n        freezeTableName: true,\n        underscoredAll: true,\n        underscored: true\n    }\n});\n\nvar Person = sequelize.define('person', {\n    first_name: Sequelize.STRING,\n    last_name: Sequelize.STRING\n});\n\nvar User = sequelize.define('user', {});\n\nPerson.hasOne(User);\n\nsequelize.sync().then(run);\n\nfunction run() {\n    var person = Person.create({ first_name: 'Markus', last_name: 'Hedlund' });\n    var user = User.create();\n\n    person.setUser(user);\n}\n```\n\n```text\nperson.setUsers\n```\n\n```text\nuser.setPerson\n```\n\n```text\nuser.setPeople\n```\n\n```text\nPerson.create({ first_name: 'Markus', last_name: 'Hedlund' }).then((person) => {\n      User.create().then((user) => {\n           person.setUser(user);\n      });\n});\n```\n\n```text\nPerson.create({ first_name: 'Markus', last_name: 'Hedlund' })\n.bind({})\n.then(function(person){\n    this.person = person;\n    return User.create()\n})\n.then(function(user){\n    return this.person.setUser(user);\n});\n```\n\n========================================\n\nComments:\n- Of course, that solved it, thanks! :) Wish this was clearer in the docs\n- isnt there a way to do with `Person.create({ first_name: 'Markus', last_name: 'Hedlund', {user: { &#47;* data *&#47; }} }` ?","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":138,"estimatedTokens":716}}889{"id":"stack-66153760","source":"stackoverflow","questionId":66153760,"title":"Sequelize error: column reference \"id\" is ambiguous. Can't find answer in documentation","tags":["javascript","node.js","postgresql","express","sequelize.js"],"text":"Title: Sequelize error: column reference \"id\" is ambiguous. Can't find answer in documentation\nTags: javascript, node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI use Sequelize to link the database to my application. But I recently encountered the above bug. It says everywhere that it is a database error. Since both tables have the same primary key. In SQL this is solved with aliases. But in documentation to Sequelize I haven't found solution to this problem. What should I do ?\n\n```\nconst { DataTypes } = require(\"sequelize\");\nconst db = require(\"../config/database\");\n\nconst Office = db.define(\n \"Office\",\n {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n address: DataTypes.STRING(45),\n },\n {\n // Other model options go here\n tableName: \"office\",\n timestamps: false,\n }\n);\n\nconst Employees = db.define(\n \"Employees\",\n {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n name: DataTypes.STRING(45),\n job: DataTypes.STRING(45),\n reg_date: DataTypes.DATEONLY,\n salary: DataTypes.DECIMAL(10, 2),\n weekend: DataTypes.INTEGER,\n office_id: { type: DataTypes.INTEGER, allowNull: false },\n },\n {\n // Other model options go here\n tableName: \"employees\",\n timestamps: false,\n }\n);\n\nEmployees.belongsTo(Office, { foreignKey: \"office_id\" }); // Foreign key\n\nconst Developer = db.define(\n \"Developer\",\n {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n role: DataTypes.STRING(45),\n level: DataTypes.STRING(45),\n project_count: DataTypes.INTEGER,\n },\n {\n // Other model options go here\n tableName: \"developer\",\n timestamps: false,\n }\n);\n\n// Developer.belongsTo(Employees);\nEmployees.hasOne(Developer, { foreignKey: \"id\", targetKey: \"id\" }); // Foreign key\n\nconst Clients = db.define(\n \"Clients\",\n {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n name: DataTypes.STRING(45),\n total_sum: DataTypes.DECIMAL(20, 2),\n },\n {\n // Other model options go here\n tableName: \"clients\",\n timestamps: false,\n }\n);\n\nconst Projects = db.define(\n \"Projects\",\n {\n id: {\n type: DataTypes.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n price: DataTypes.DECIMAL(15, 2),\n started: DataTypes.DATEONLY,\n ended: DataTypes.DATEONLY,\n teamlead_id: { type: DataTypes.INTEGER, allowNull: false },\n designer_id: { type: DataTypes.INTEGER, allowNull: false },\n programmer_id: { type: DataTypes.INTEGER, allowNull: false },\n dbarch_id: { type: DataTypes.INTEGER, allowNull: false },\n client_id: { type: DataTypes.INTEGER, allowNull: false },\n },\n {\n // Other model options go here\n tableName: \"projects\",\n timestamps: false,\n }\n);\n\nDeveloper.hasOne(Projects, { foreignKey: \"teamlead_id\" }); // Foreign key\nDeveloper.hasOne(Projects, { foreignKey: \"designer_id\" }); // Foreign key\nDeveloper.hasOne(Projects, { foreignKey: \"programmer_id\" }); // Foreign key\nDeveloper.hasOne(Projects, { foreignKey: \"dbarch_id\" }); // Foreign key\nClients.hasOne(Projects, { foreignKey: \"client_id\" }); // Foreign key\n\nmodule.exports = { Clients, Developer, Employees, Office, Projects };\n```\n\nAnd express request:\n\n```\napp.get(\"/office_dev_workers_spec_count\", (req, res) => {\n Employees.findAll({\n include: {\n model: Developer,\n where: {\n \"$Developer.role$\": req.query.dev,\n \"$Developer.level$\": req.query.lvl,\n \"$Employees.office_id$\": req.query.office,\n },\n attributes: [\n [sequelize.fn(\"COUNT\", sequelize.col(\"id\")), \"n_devEmployees\"],\n ],\n },\n }).then((result) => {\n res.send(result);\n });\n});\n```\n\n========================================\n\nTop Answer:\nin my case **[SOLVED]** ....\nso we can ignore the ambigous column in some condition here is example\n\ni have **user table** ( *here is a users* )\n\n```\nid\nfull_name\n```\n\ni have **driver table** ( *here is a person* )\n\n```\nid\nuser_id\nfull_name\n```\n\nwhen we load the driver table like these\n\n```\n...\nawait driver.findAndCountAll({\n include: [\n {\n model: user, // here is problem its would like to ambiguous column\n paranoid: false,\n },\n ],\n where: arrayOfSearch // here is problem that trigger ambigious column // if you didnt implement to search its work.\n ...\n...\n```\n\nthen why we got ambigous ?\nhere is why ( by the war **advanceSearchCondition** is **arrayOfSearch** ya !!! )\n\n```\n// /api/driver?keyword=full_name%3DA%26phone%3D2\nif(keyword){\n let keywordSplit = keyword.split('&');\n keywordSplit.map(el => {\n const data = el.split(\"=\");\n if (data[0] == 'created_at') {\n advanceSearchCondition.push({\n created_at: {\n [Op.substring]: `${data[1]}`\n }\n });\n } else if (data[0] == 'updated_at') {\n advanceSearchCondition.push({\n updated_at: {\n [Op.substring]: `${data[1]}`\n }\n });\n } else if (data[0] == 'full_name') { // if you didnt code like these you will get ambigous column for full_name\n advanceSearchCondition.push({\n full_name: {\n [Op.like]: Sequelize.literal(`\\'%${data[1]}%\\'`)\n }\n });\n } else if (data[0] == 'phone') {\n advanceSearchCondition.push({\n phone: {\n [Op.like]: Sequelize.literal(`\\'%${data[1]}%\\'`)\n }\n });\n } else { // because you make code like these \n winLogger.error(data[0]);\n winLogger.error(data[1]);\n advanceSearchCondition.push({\n [`$${data[0]}$`]: {\n [Op.substring]: `${data[1]}`\n }\n });\n }\n })\n }\n```\n\nexplanation...\nin else condition i search by **$driver.full_name$** so i dont need to pass in include / associate where properties... we can put the search in outside of **include** but it would ambigous when other associate have same column and you implement search with **$table.column$** to put outside the include.\n\n========================================\n\nCode:\n```text\nconst { DataTypes } = require(\"sequelize\");\nconst db = require(\"../config/database\");\n\nconst Office = db.define(\n    \"Office\",\n    {\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true,\n        },\n        address: DataTypes.STRING(45),\n    },\n    {\n        // Other model options go here\n        tableName: \"office\",\n        timestamps: false,\n    }\n);\n\nconst Employees = db.define(\n    \"Employees\",\n    {\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true,\n        },\n        name: DataTypes.STRING(45),\n        job: DataTypes.STRING(45),\n        reg_date: DataTypes.DATEONLY,\n        salary: DataTypes.DECIMAL(10, 2),\n        weekend: DataTypes.INTEGER,\n        office_id: { type: DataTypes.INTEGER, allowNull: false },\n    },\n    {\n        // Other model options go here\n        tableName: \"employees\",\n        timestamps: false,\n    }\n);\n\nEmployees.belongsTo(Office, { foreignKey: \"office_id\" }); // Foreign key\n\nconst Developer = db.define(\n    \"Developer\",\n    {\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true,\n        },\n        role: DataTypes.STRING(45),\n        level: DataTypes.STRING(45),\n        project_count: DataTypes.INTEGER,\n    },\n    {\n        // Other model options go here\n        tableName: \"developer\",\n        timestamps: false,\n    }\n);\n\n// Developer.belongsTo(Employees);\nEmployees.hasOne(Developer, { foreignKey: \"id\", targetKey: \"id\" }); // Foreign key\n\nconst Clients = db.define(\n    \"Clients\",\n    {\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true,\n        },\n        name: DataTypes.STRING(45),\n        total_sum: DataTypes.DECIMAL(20, 2),\n    },\n    {\n        // Other model options go here\n        tableName: \"clients\",\n        timestamps: false,\n    }\n);\n\nconst Projects = db.define(\n    \"Projects\",\n    {\n        id: {\n            type: DataTypes.INTEGER,\n            allowNull: false,\n            primaryKey: true,\n            autoIncrement: true,\n        },\n        price: DataTypes.DECIMAL(15, 2),\n        started: DataTypes.DATEONLY,\n        ended: DataTypes.DATEONLY,\n        teamlead_id: { type: DataTypes.INTEGER, allowNull: false },\n        designer_id: { type: DataTypes.INTEGER, allowNull: false },\n        programmer_id: { type: DataTypes.INTEGER, allowNull: false },\n        dbarch_id: { type: DataTypes.INTEGER, allowNull: false },\n        client_id: { type: DataTypes.INTEGER, allowNull: false },\n    },\n    {\n        // Other model options go here\n        tableName: \"projects\",\n        timestamps: false,\n    }\n);\n\nDeveloper.hasOne(Projects, { foreignKey: \"teamlead_id\" }); // Foreign key\nDeveloper.hasOne(Projects, { foreignKey: \"designer_id\" }); // Foreign key\nDeveloper.hasOne(Projects, { foreignKey: \"programmer_id\" }); // Foreign key\nDeveloper.hasOne(Projects, { foreignKey: \"dbarch_id\" }); // Foreign key\nClients.hasOne(Projects, { foreignKey: \"client_id\" }); // Foreign key\n\nmodule.exports = { Clients, Developer, Employees, Office, Projects };\n```\n\n```text\napp.get(\"/office_dev_workers_spec_count\", (req, res) => {\n    Employees.findAll({\n        include: {\n            model: Developer,\n            where: {\n                \"$Developer.role$\": req.query.dev,\n                \"$Developer.level$\": req.query.lvl,\n                \"$Employees.office_id$\": req.query.office,\n            },\n            attributes: [\n                [sequelize.fn(\"COUNT\", sequelize.col(\"id\")), \"n_devEmployees\"],\n            ],\n        },\n    }).then((result) => {\n        res.send(result);\n    });\n});\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nsequelize.col(\"id\")\n```\n\n```text\nsequelize.col(\"Employees.id\")\n```\n\n```text\nid\nfull_name\n```\n\n```text\nid\nuser_id\nfull_name\n```\n\n```text\n...\nawait driver.findAndCountAll({\n      include: [\n        {\n          model: user, // here is problem its would like to ambiguous column\n          paranoid: false,\n        },\n      ],\n      where: arrayOfSearch // here is problem that trigger ambigious column // if you didnt implement to search its work.\n ...\n...\n```\n\n```text\n// /api/driver?keyword=full_name%3DA%26phone%3D2\nif(keyword){\n      let keywordSplit = keyword.split('&');\n      keywordSplit.map(el => {\n        const data = el.split(\"=\");\n        if (data[0] == 'created_at') {\n          advanceSearchCondition.push({\n            created_at: {\n              [Op.substring]: `${data[1]}`\n            }\n          });\n        } else if (data[0] == 'updated_at') {\n          advanceSearchCondition.push({\n            updated_at: {\n              [Op.substring]: `${data[1]}`\n            }\n          });\n        } else if (data[0] == 'full_name') { // if you didnt code like these you will get ambigous column for full_name\n          advanceSearchCondition.push({\n            full_name: {\n              [Op.like]: Sequelize.literal(`\\'%${data[1]}%\\'`)\n            }\n          });\n        } else if (data[0] == 'phone') {\n          advanceSearchCondition.push({\n            phone: {\n              [Op.like]: Sequelize.literal(`\\'%${data[1]}%\\'`)\n            }\n          });\n        } else { // because you make code like these \n          winLogger.error(data[0]);\n          winLogger.error(data[1]);\n          advanceSearchCondition.push({\n            [`$${data[0]}$`]: {\n              [Op.substring]: `${data[1]}`\n            }\n          });\n        }\n      })\n    }\n```\n\n========================================\n\nComments:\n- Unfortunatelly this resulted in: 'UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column \"Employees.id\" must appear in the GROUP BY clause or be used in an aggregate function'\n- Right. Could you specify your SQL query? That one in the code is different from sequelize code.\n- I specified the correct query. Right as I send request I get this output. pastebin.com/SbiA1Wnb\n- There is no `COUNT` in your query inside the comment. But you have `COUNT` inside your sequelize query. Why did you add it?\n- Don't look at the commented query. These are leftovers from the first iteration of my app. I forgot to add `COUNT` first time, so I added it in second iteration, where I use only Sequelize built in model functionality.\n- Ok, so could you write your query here?\n- `SELECT COUNT(*) FROM employees JOIN developer ON employees.id = developer.id WHERE developer.role = '${req.query.dev}' AND developer.level = '${req.query.lvl}' AND employees.office_id = ${req.query.office}`\n- For this request better use `count` instead of `findAll`\n- I can't find any async function in your code. To be sure could you add catch after then with console.log error?\n- This is express error.Try `console.log(result)`\n- Well, that returned the right result. But why express doesn't work on that exact query...\n- I think the reason in different type of return. Try toString result\n- I read about this problem. Model.count returns number, and it must be string in order to send response. But as all of my previous queries responded with json, I just did res.json.\n- in my case i have user table and dirver table that ambiguous only for full_name column where the both table have same on naming column , so we need to change it into user_full_name and driver_full_name insted of only full_name column ???/\n- @YogiArifWidodo it's an option. But better you can use aliases.\n- no ... i have solved by separate multiple search ... [Op.substring] for full_name in driver then [Op.like] for full_name column in user table. i have an array need to search but all of search use substring then i make different just for ambiguous column. that solved me\n- not working . their is no affect of paranoid: false,\n- in my case , its work for avoid the warning error from sequelize with the tricks and some case when implement dynamic key on search `where` condition from request API.\n- the different is about 'full_name' in where query with Op.like and Op.substring .","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":490,"estimatedTokens":3445}}890{"id":"stack-32673138","source":"stackoverflow","questionId":32673138,"title":"Get many results in Sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: Get many results in Sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow to get many results in Sequelize in array? Example: I need get all values field `name` in table `test` and return this in console. I write:\n\n```\ntest.findAll().them(function(result) {\n result.forEach(function(item) {\n console.log(item.name);\n });\n});\n```\n\nHow to get all values field `name` in array, without `forEach()`?\n\n(Sorry for bad english)\n\n========================================\n\nTop Answer:\n```\ntest.findAll({attributes: ['name']}).them(function(result) {\n console.log(result);\n});\n```\n\n========================================\n\nCode:\n```text\ntest.findAll().them(function(result) {\n    result.forEach(function(item) {\n        console.log(item.name);\n    });\n});\n```\n\n```text\nname\n```\n\n```text\ntest\n```\n\n```text\nname\n```\n\n```text\nforEach()\n```\n\n```text\ntest.findAll().then(function(result) {\n    var names = result.map(function(item) {\n        return item.name;\n    });\n    console.log(names);\n});\n```\n\n```text\ntest.findAll( {attributes: ['name']} ).then(function(result) {\n    var names = result.map(function(item) {\n        return item.name;\n    });\n    console.log(names);\n});\n```\n\n```text\nmap\n```\n\n```text\nattributes\n```\n\n```text\nfindAll\n```\n\n```text\ntest.findAll({attributes: ['name']}).them(function(result) {\n    console.log(result);\n});\n```\n\n========================================\n\nComments:\n- Do you need to seach all results and projection column `name` or filter by `name`?\n- No, it is all results. I need only values field `name`.","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":96,"estimatedTokens":393}}891{"id":"stack-53495730","source":"stackoverflow","questionId":53495730,"title":"Sequelize: Adding a day to the date doesn't work","tags":["node.js","sequelize.js","graphql","sequelize-cli"],"text":"Title: Sequelize: Adding a day to the date doesn't work\nTags: node.js, sequelize.js, graphql, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI have a column `updatedAt` in my table `User` which is of `Date` type, it stores date along with time. I want to query using only date and not datetime. I am using sequelize `Sequelize.Op.gt` and `Sequelize.Op.lt` operators to get `Users` updated on that exact date regardless of time by adding `24 * 60 * 60 * 1000`. But the date is not incrementing one day. When I try to subtract, it is working flawlessly. I could add one day only after using getTime() method.\n\nI'm confused as to why it works when subtracting without using `getTime()` but doesn't work when adding. Could anyone explain?\n\n**TL;DR**\n\nThis **works:**\n\n```\n[Sequelize.Op.gt]: new Date(new Date(updatedAt) - 24 * 60 * 60 * 1000)\n//updateAt: 2018-11-27\n//output: 2018-11-26\n```\n\nThis **doesn't** work:\n\n```\n[Sequelize.Op.gt]: new Date(new Date(updatedAt) + 24 * 60 * 60 * 1000)\n//updateAt: 2018-11-27\n//output: 2018-11-27\n```\n\nAnd this **works:**\n\n```\n[Sequelize.Op.lt]: new Date(new Date(updatedAt).getTime() + 24 * 60 * 60 * 1000)\n//updateAt: 2018-11-27\n//output: 2018-11-28\n```\n\n========================================\n\nTop Answer:\n```\nsequelize.fn(\"DATEADD\", sequelize.literal(\"DAY\"), 4, sequelize.col('Your Date')) // 4 number of days adding\n```\n\nIf want to find the difference including this added date from current date\n\n```\nsequelize.fn('DATEDIFF', sequelize.literal(\"DAY\"), sequelize.fn(\"DATEADD\", sequelize.literal(\"DAY\"), 4, sequelize.col('Your Date')), sequelize.fn(\"GETDATE\")\n```\n\n========================================\n\nCode:\n```text\n[Sequelize.Op.gt]: new Date(new Date(updatedAt) - 24 * 60 * 60 * 1000)\n//updateAt: 2018-11-27\n//output: 2018-11-26\n```\n\n```text\n[Sequelize.Op.gt]: new Date(new Date(updatedAt) + 24 * 60 * 60 * 1000)\n//updateAt: 2018-11-27\n//output: 2018-11-27\n```\n\n```text\n[Sequelize.Op.lt]: new Date(new Date(updatedAt).getTime() + 24 * 60 * 60 * 1000)\n//updateAt: 2018-11-27\n//output: 2018-11-28\n```\n\n```text\nupdatedAt\n```\n\n```text\nUser\n```\n\n```text\nDate\n```\n\n```text\nSequelize.Op.gt\n```\n\n```text\nSequelize.Op.lt\n```\n\n```text\nUsers\n```\n\n```text\n24 * 60 * 60 * 1000\n```\n\n```text\ngetTime()\n```\n\n```text\nnew Date(new Date(updatedAt) + 24 * 60 * 60 * 1000)\n```\n\n```text\nnew Date(new Date(updatedAt) + 86400000)\n```\n\n```text\nnew Date('Tue Nov 27 2018 17:34:48 GMT+0800 (Some Region)86400000')\n```\n\n```text\nnew Date('Tue Nov 27 2018 17:34:48 GMT+0800 (Some Region)')\n```\n\n```text\nsequelize.fn(\"DATEADD\", sequelize.literal(\"DAY\"), 4, sequelize.col('Your Date')) // 4 number of days adding\n```\n\n```text\nsequelize.fn('DATEDIFF', sequelize.literal(\"DAY\"), sequelize.fn(\"DATEADD\", sequelize.literal(\"DAY\"), 4, sequelize.col('Your Date')), sequelize.fn(\"GETDATE\")\n```\n\n```text\nconst mydate = new Date(\"2024-01-01\") \nconst computedDate = +new Date(mydate) + 24*60*60*1000;\nconsole.log(mydate, new Date(computedDate));\n```\n\n========================================\n\nComments:\n- Thanks! I totally missed the string and int concatenation.\n- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DATEADD(DAY, 1, `schedule_in`), `created_at` DATETIME NOT NULL, `updated_at` DAT' at line 1","metadata":{"transformedAt":"2026-08-18T18:33:34.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":136,"estimatedTokens":825}}892{"id":"stack-39630540","source":"stackoverflow","questionId":39630540,"title":"Sequelize: Calling .get({plain: true })) returns .get is not a function","tags":["javascript","express","sequelize.js"],"text":"Title: Sequelize: Calling .get({plain: true })) returns .get is not a function\nTags: javascript, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm not sure why this would happen as Im returning only the values of an instance in other locations just fine. See anything wrong with my code?\n\n```\napp.get('/profile', checkAuth, function(req, res) {\n var useObj = req.user;\n var guilds = req.user.guilds;\n User.findAll({\n where: { userid: useObj.id },\n include: [{\n model: Guild\n }]\n }).then(function(group) {\n console.log(group.get({\n plain: true\n }))\n }) \n});\n```\n\n========================================\n\nCode:\n```text\napp.get('/profile', checkAuth, function(req, res) {\n    var useObj = req.user;\n    var guilds = req.user.guilds;\n    User.findAll({\n        where: { userid: useObj.id },\n        include: [{\n            model: Guild\n        }]\n    }).then(function(group) {\n        console.log(group.get({\n            plain: true\n        }))\n    })  \n});\n```\n\n```text\nget\n```\n\n```text\nfindAll()\n```\n\n```text\nfindOne()\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":55,"estimatedTokens":258}}893{"id":"stack-48914065","source":"stackoverflow","questionId":48914065,"title":"Sequelize - How to apply Distinct to nested include?","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize - How to apply Distinct to nested include?\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Nodejs, Express, Postgresql, and Sequelize\n\nI have 4 Models\n\nAccount (has many books)\n\nBook (has many parts)\n\n- Part (has many chapters)\n\n- Chapter\n\nI'm returning a book and including both 'Part' and 'Chapter' with some specific ordering - This works fine. \n\nThe model 'Chapter' has a column 'topic' and I only want to include rows from the 'Chapter' model that have distinct 'topics'. \n\nHow do I apply distinct to this 'Chapter' model with this nested include structure?\n\nCode snippet:\n\n```\nreturn Book\n\n.findOne({\n where: {accountid: req.body.accountid,\n id: req.body.bookid}, \n include: [{\n model: Part,\n as: 'parts'\n include: [\n {\n model: Chapter,\n required: false,\n as: 'chapters',\n where: {\n createdAt: {\n $gte: moment().subtract(24,'hours').format()\n }\n }\n }],\n }],\n order: [\n [\n { model: Part, as: 'parts' },\n 'createdAt',\n 'DESC'\n ],\n [\n { model: Part, as: 'parts' },\n { model: Chapter, as: 'chapters' },\n 'createdAt',\n 'DESC'\n ]\n ]\n\n})\n.then(book => res.status(200).send(book))\n.catch(error => res.status(400).send(error.toString()));\n}\n```\n\n========================================\n\nTop Answer:\nI know this is a really late answer but in fact you can have distinct on include table columns. The only drawback is that you have to analyze the query that Sequelize generates and include the attributes from each model.\n\nYour query would end up as something like this:\n\n```\nBook.findOne({\n // Literal DISTINCT ON as 1 so it is not included in the resulting json\n // '*' so all table attributes are included in the json response\n attributes: [Sequelize.literal('DISTINCT ON(\"chapters\".\"topics\") 1'), '*']\n where: {accountid: req.body.accountid,\n id: req.body.bookid}, \n include: [{\n model: Part,\n as: 'parts'\n include: [\n {\n model: Chapter,\n required: false,\n as: 'chapters',\n where: {\n createdAt: {\n $gte: moment().subtract(24,'hours').format()\n }\n }\n }],\n }],\n order: [\n // This order criteria is required because we are using distinct on\n [\n { model: Chapter, as: 'chapters' },\n 'topics',\n 'ASC'\n ],\n [\n { model: Part, as: 'parts' },\n 'createdAt',\n 'DESC'\n ],\n [\n { model: Part, as: 'parts' },\n { model: Chapter, as: 'chapters' },\n 'createdAt',\n 'DESC'\n ]\n ]\n\n})\n```\n\nThis same strategy can be used to make a 'distinct on' more than one column, but youĺl have to remember including the columns as the first search criteria.\n\nSearching 'DISTINCT ON' on the Sequelize's Github leads to several interesting posts on this.\n\nHope it helps. Best regards from Chile.\n\n========================================\n\nCode:\n```text\nreturn Book\n\n.findOne({\n    where: {accountid: req.body.accountid,\n        id: req.body.bookid}, \n    include: [{\n        model: Part,\n        as: 'parts'\n        include: [\n            {\n                model: Chapter,\n                required: false,\n                as: 'chapters',\n                where: {\n                    createdAt: {\n                        $gte: moment().subtract(24,'hours').format()\n                    }\n                }\n            }],\n    }],\n    order: [\n        [\n            { model: Part, as: 'parts' },\n            'createdAt',\n            'DESC'\n        ],\n        [\n            { model: Part, as: 'parts' },\n            { model: Chapter, as: 'chapters' },\n            'createdAt',\n            'DESC'\n        ]\n    ]\n\n\n})\n.then(book => res.status(200).send(book))\n.catch(error => res.status(400).send(error.toString()));\n}\n```\n\n```text\nBook.findOne({\n    // Literal DISTINCT ON as 1 so it is not included in the resulting json\n    // '*' so all table attributes are included in the json response\n    attributes: [Sequelize.literal('DISTINCT ON(\"chapters\".\"topics\") 1'), '*']\n    where: {accountid: req.body.accountid,\n        id: req.body.bookid}, \n    include: [{\n        model: Part,\n        as: 'parts'\n        include: [\n            {\n                model: Chapter,\n                required: false,\n                as: 'chapters',\n                where: {\n                    createdAt: {\n                        $gte: moment().subtract(24,'hours').format()\n                    }\n                }\n            }],\n    }],\n    order: [\n        // This order criteria is required because we are using distinct on\n        [\n            { model: Chapter, as: 'chapters' },\n            'topics',\n            'ASC'\n        ],\n        [\n            { model: Part, as: 'parts' },\n            'createdAt',\n            'DESC'\n        ],\n        [\n            { model: Part, as: 'parts' },\n            { model: Chapter, as: 'chapters' },\n            'createdAt',\n            'DESC'\n        ]\n    ]\n\n\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":214,"estimatedTokens":1178}}894{"id":"stack-33976558","source":"stackoverflow","questionId":33976558,"title":"Why is synchronous SQL \"bad\"?","tags":["javascript","ruby-on-rails","node.js","activerecord","sequelize.js"],"text":"Title: Why is synchronous SQL \"bad\"?\nTags: javascript, ruby-on-rails, node.js, activerecord, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy students struggle a bit with ActiveRecord for Sinatra and Rails, but they eventually get it.\n\nHowever, they completely burn out on Sequelize for Node.\n\nTo my mind, the biggest difference between Sequelize and AR is that AR is synchronous, whereas Sequelize is not.\n\nConsider:\n\n```\n# ActiveRecord\n@post = Post.find(2)\nrender json: @post\n```\n\n```\n// Sequelize\nPost.findById(2).then(function(post){\n response.json(post);\n});\n```\n\nFor small actions like this, the difference is still visible but it doesn't look so bad. With more complicated queries, it's easy to find yourself in callback hell.\n\nSo my question is: **Why is it OK for ActiveRecord to be synchronous, but bad for a JS ORM to be synchronous?**\n\nI understand the disadvantages of synchronous vs. asynchronous. But the disadvantages of synchronicity don't really seem to be hurting ActiveRecord.\n\nThe difficulty with Sequelize isn't just that you have to write `.then(function(){})` a thousand times; it's also that understanding how callbacks work at all takes a good amount of comfort with Javascript, and since Sequelize is the primary relational ORM for Node, it makes Node much less approachable to beginners. One might say \"beginners shouldn't be using Node,\" but Rails has achieved a tremendous amount of success due to endeavors to make it approachable to novice developers.\n\n========================================\n\nCode:\n```text\n# ActiveRecord\n@post = Post.find(2)\nrender json: @post\n```\n\n```text\n// Sequelize\nPost.findById(2).then(function(post){\n  response.json(post);\n});\n```\n\n```text\n.then(function(){})\n```\n\n========================================\n\nComments:\n- a little oversimplicity but...: synchronous means blocking, asynchronous is not blocking. When AR is waiting for data from DB it is blocking, sinatra cannot handle next request, in node while waiting requests are handle continuously .\n- Thanks for your response! I appreciate that Node scales well, and the advantages of being non-blocking. However, Rails seems to also scale well despite using AR: consider Coinbase.com and AirBnB, which both use Rails despite having considerably complicated database needs. I suppose my question is more, \"Do the advantages of non-blocking SQL queries really outweigh the disadvantages in terms of code complexity?\"\n- I didn't realize that Node was single-threaded. That explains a lot! stackoverflow.com/questions/17959663/&hellip;\n- I have updated the answer to explain scalability repurcussions, and strategies for reducing the code complexity.\n- Scalability of system is impacted by multiple aspects other than complexity of database model. In particular, more IO bound tasks benefit more from an Event loop based model. For use cases like Real time games, chat systems, trading systems, Node.js is a much more viable choice than Rails.","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":62,"estimatedTokens":739}}895{"id":"stack-49947876","source":"stackoverflow","questionId":49947876,"title":"Cannot read property 'findOne' of undefined in Node and Sequelize","tags":["express","sequelize.js"],"text":"Title: Cannot read property 'findOne' of undefined in Node and Sequelize\nTags: express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThis is my admin_pages.js file i have done the migrations and models but i am getting this error.\n\n TypeError: Cannot read property 'findOne' of undefined\n at C:\\users\\gaffer\\desktop\\gaffercart\\routes\\admin_pages.js:80:21\n at Layer.handle [as handle_request] (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at next (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\route.js:137:13)\n at Route.dispatch (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\route.js:112:3)\n at Layer.handle [as handle_request] (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:281:22\n at Function.process_params (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:335:12)\n at next (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:275:10)\n at Function.handle (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:174:3)\n at router (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:47:12)\n at Layer.handle [as handle_request] (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at trim_prefix (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:317:13)\n at C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:284:7\n at Function.process_params (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:335:12)\n at next (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:275:10)\n at C:\\users\\gaffer\\desktop\\gaffercart\\index.js:70:3\n at Layer.handle [as handle_request] (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at trim_prefix (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:317:13)\n at C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:284:7\n at Function.process_params (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:335:12)\n at next (C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\express\\lib\\router\\index.js:275:10)\n at C:\\users\\gaffer\\desktop\\gaffercart\\node_modules\\connect-flash\\lib\\flash.js:21:5\n\n```\nvar express=require('express');\nvar router=express.Router();\nvar expressValidator = require('express-validator');\nvar bodyParser=require('body-parser');\nvar models=require('../models');\n\n// var mysql=require('mysql');\n// var Sequelize=require('sequelize');\n// var DataTypes=Sequelize.DataTypes;\n// var sequelize = exports.sequelize = module.parent.exports.sequelize;\n// let sequelize=new Sequelize();\n\n//Get Page model\nconst Page = require('../models/page');\n\n/*\n* GET PAGES INDEX its correct but commiting it\n*/\n\n router.get('/',function(req,res){\n // Page.find({}).sort({sorting: 1}).exec(function(err,pages){\n res.render('admin/pages',{ \n //pages:pages\n });\n });\n //});\n// router.get('/admin/dashboard',function(req,res){\n// res.render('admin/dashboard');\n// });\n\n/*\n** GET ADD PAGE\n*/\n router.get('/add-page',function(req,res){\n var title=\"\";\n var slug=\"\";\n var content=\"\";\n\n res.render('admin/add_page',{\n title:title,\n slug:slug,\n content:content\n\n });\n\n });\n\n//POST ADD page\n router.post('/add-page',function(req,res){\n // console.log(\"alsdjlajsi\")\n\n req.checkBody('title','Title must have a body.').notEmpty();\n req.checkBody('content','Content must have a body.').notEmpty();\n\n var title = req.body.title;\n var slug = req.body.slug.replace(/\\s+/g, '-').toLowerCase();\n if(slug == \" \") \n {\n slug = title.replace(/\\s+/g, '-').toLowerCase();\n }\n var content = req.body.content;\n var errors = req.validationErrors();\n\n //If there are Errors then define it on the same page\n if(errors){\n res.render('admin/add_page',{\n errors:errors,\n title:title,\n slug:slug,\n content:content\n });\n }\n /*\n * Have use Pages\n */\n else{\n\n models.Page.findOne({slug:slug}, function(err, page){\n\n if(page){\n req.flash('danger','Page slug Already Exist,');\n res.render('admin/add_page',{\n\n title:title,\n slug:slug,\n content:content\n });\n }\n else{\n var page = new Page({\n title:title,\n slug:slug,\n content:content,\n sorting:100\n });\n page.save(function(err){\n if(err) return console.log(err);\n\n req.flash('success','Page Added Successfully!!');\n res.redirect('/admin/pages');\n });\n }\n });\n\n }\n\n});\n//Exports\nmodule.exports=router;\n```\n\nThis is mine Page models\n\n```\n'use strict';\n// var Sequelize=require('sequelize');\n\nmodule.exports = (sequelize, DataTypes) => {\n var page = sequelize.define('page', {\n title: DataTypes.STRING,\n slug: DataTypes.STRING,\n content: DataTypes.STRING,\n sorting:DataTypes.INTEGER\n }, {});\n page.associate = function(models) {\n // associations can be defined here\n };\n return page;\n};\n```\n\n========================================\n\nTop Answer:\n```\nyou need to check following things your_model.js file\n\n 1. check name of model (wallet_transaction or wallet_transactions)\n 2. if model (table ) name create with 's then need to set in model also 's \nlike wallet_transactions so please check one more time \n 3. then in controller you import model then check name here it's proper or not \n 4. then set break point in your query and check what's the error (cannot read properties of undefined (reading 'findone')) or not\n```\n\n========================================\n\nCode:\n```text\nvar express=require('express');\nvar router=express.Router();\nvar expressValidator = require('express-validator');\nvar bodyParser=require('body-parser');\nvar models=require('../models');\n\n// var mysql=require('mysql');\n// var Sequelize=require('sequelize');\n// var DataTypes=Sequelize.DataTypes;\n// var sequelize = exports.sequelize = module.parent.exports.sequelize;\n// let sequelize=new Sequelize();\n\n//Get Page model\nconst Page = require('../models/page');\n\n/*\n* GET PAGES INDEX its correct but commiting it\n*/\n\n router.get('/',function(req,res){\n //  Page.find({}).sort({sorting: 1}).exec(function(err,pages){\n    res.render('admin/pages',{ \n      //pages:pages\n    });\n   });\n //});\n//  router.get('/admin/dashboard',function(req,res){\n//    res.render('admin/dashboard');\n//  });\n\n\n/*\n** GET ADD PAGE\n*/\n router.get('/add-page',function(req,res){\n   var title=\"\";\n   var slug=\"\";\n   var content=\"\";\n\n\n   res.render('admin/add_page',{\n      title:title,\n      slug:slug,\n      content:content\n\n   });\n\n });\n\n//POST ADD page\n router.post('/add-page',function(req,res){\n  //  console.log(\"alsdjlajsi\")\n\n  req.checkBody('title','Title must have a body.').notEmpty();\n  req.checkBody('content','Content must have a body.').notEmpty();\n\n  var title = req.body.title;\n  var slug = req.body.slug.replace(/\\s+/g, '-').toLowerCase();\n  if(slug == \" \")  \n  {\n    slug = title.replace(/\\s+/g, '-').toLowerCase();\n  }\n  var content = req.body.content;\n  var errors = req.validationErrors();\n\n  //If there are Errors then define it on the same page\n  if(errors){\n    res.render('admin/add_page',{\n      errors:errors,\n      title:title,\n      slug:slug,\n      content:content\n    });\n  }\n  /*\n  * Have use Pages\n  */\n      else{\n\n        models.Page.findOne({slug:slug}, function(err, page){\n\n        if(page){\n          req.flash('danger','Page slug Already Exist,');\n          res.render('admin/add_page',{\n\n            title:title,\n            slug:slug,\n            content:content\n          });\n        }\n        else{\n            var page = new Page({\n              title:title,\n              slug:slug,\n              content:content,\n              sorting:100\n            });\n            page.save(function(err){\n              if(err) return console.log(err);\n\n              req.flash('success','Page Added Successfully!!');\n              res.redirect('/admin/pages');\n            });\n        }\n      });\n\n  }\n\n});\n//Exports\nmodule.exports=router;\n```\n\n```text\n'use strict';\n// var Sequelize=require('sequelize');\n\nmodule.exports = (sequelize, DataTypes) => {\n  var page = sequelize.define('page', {\n    title: DataTypes.STRING,\n    slug: DataTypes.STRING,\n    content: DataTypes.STRING,\n    sorting:DataTypes.INTEGER\n  }, {});\n  page.associate = function(models) {\n    // associations can be defined here\n  };\n  return page;\n};\n```\n\n```text\nvar page = sequelize.define('page', {...})\n```\n\n```text\nmodels.Page.findOne(...) // uppercase\n```\n\n```text\nvar page = sequelize.define('Page', {...}) // uppercase\n```\n\n```text\n//Get Page model\nconst Page = require('../models/page');\n```\n\n```text\nconst Page = require('../models').Page // or .page if you keep your definition lowercase\n```\n\n```text\nelse { \n  models.Page.findOne({ \n    where: { slug }  // destructuring\n  })\n  .then((page) => {\n    // work with the page instance\n  })\n  .catch((err) => {\n    // error case\n  })\n\n}\n```\n\n```text\npage.save()\n  .then(() => {\n    req.flash('success','Page Added Successfully!!');\n    res.redirect('/admin/pages');\n  })\n  .catch((err) => {\n    // handle error\n  })\n```\n\n```text\n'page'\n```\n\n```text\nmodels.page\n```\n\n```text\nfindOne\n```\n\n```text\nwhere\n```\n\n```text\nslug\n```\n\n```text\npage.save()\n```\n\n```text\nyou need to check following things your_model.js file\n\n 1. check name of model (wallet_transaction or wallet_transactions)\n 2. if model (table ) name create with 's then need to set in model also 's \nlike wallet_transactions so please check one more time \n 3. then in controller you import model then check name here it's proper or not \n 4. then set break point in your query and check what's the  error (cannot read properties of undefined (reading 'findone')) or not\n```\n\n========================================\n\nComments:\n- I am getting this error now friend you are right above it take my one week to find this (sequelize) Warning: Model attributes (slug) passed into finder method options of model Page, but the options.where object is empty. Did you forget to use options.where? Executing (default): SELECT `id`, `title`, `slug`, `content`, `sorting`, `createdAt`, `updatedAt` FROM `Pages` AS `Page` LIMIT 1; Can you please also help me with this\n- models.Page.findOne({slug: slug}, function (err, page) { if (page) {\n- use `where` and `findOne` does not take a function callback, it returns a `Promise` so you have to use `then` or `async&#47;await`. I updated my answer. See the example there.\n- can you tell me how to that in my case\n- stackoverflow.com/questions/49955072/&hellip;\n- exports.isExist = async (email) => { return await Users.findOne({ where: { email } }); }; This one is my function i have same table name 'Users' still i am getting this error","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":401,"estimatedTokens":2676}}896{"id":"stack-19640308","source":"stackoverflow","questionId":19640308,"title":"Sequelize.js - Asynchronous validators","tags":["node.js","sequelize.js"],"text":"Title: Sequelize.js - Asynchronous validators\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to have an asynchronous validator using Sequelize.js? I want to check for the existence of an association before saving a model. Something like this:\n\n```\nUser = db.define(\"user\", {\n name: Sequelize.STRING\n},\n{\n validate:\n hasDevice: ->\n @getDevices().success (devices) ->\n throw Exception if (devices.length Or is there a way to force that check to run synchronously? (not ideal)\n\n========================================\n\nCode:\n```text\nUser = db.define(\"user\", {\n    name: Sequelize.STRING\n},\n{\n    validate:\n        hasDevice: ->\n            @getDevices().success (devices) ->\n                throw Exception if (devices.length < 1)\n              return\n})\n\n# .... Device is just another model\n\nUser.hasMany(Device)\n```\n\n```text\nvar Model = sequelize.define('Model', {\n  attr: Sequelize.STRING\n}, {\n  validate: {\n    hasAssociation: function(next) {\n      functionThatChecksTheAssociation(function(ok) {\n        if (ok) {\n          next()\n        } else {\n          next('Ooops. Something is wrong!')\n        }\n      })\n    }\n  }\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":54,"estimatedTokens":291}}897{"id":"stack-63827852","source":"stackoverflow","questionId":63827852,"title":"SequelizeUniqueConstraintError: Validation error","tags":["node.js","migration","sequelize.js","unique"],"text":"Title: SequelizeUniqueConstraintError: Validation error\nTags: node.js, migration, sequelize.js, unique\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize and node.js. I have one column that want change it's type to unique, when I want run the migration I have this err , How can I solve it?\n\n```\nERROR: SequelizeUniqueConstraintError: Validation error\n```\n\nthis is my code :\n\n```\nup: (queryInterface, Sequelize) => {\n return Promise.all([\n queryInterface.changeColumn('PersonalInfo', 'ssn', {type: Sequelize.STRING, unique: true\n }),\n queryInterface.changeColumn('PersonalInfoDraft', 'ssn', {type: Sequelize.STRING, unique:true\n })\n ])\n }\n```\n\n========================================\n\nCode:\n```text\nERROR: SequelizeUniqueConstraintError: Validation error\n```\n\n```text\nup: (queryInterface, Sequelize) => {\n    return Promise.all([\n      queryInterface.changeColumn('PersonalInfo', 'ssn', {type: Sequelize.STRING, unique: true\n      }),\n      queryInterface.changeColumn('PersonalInfoDraft', 'ssn', {type: Sequelize.STRING, unique:true\n      })\n    ])\n  }\n```\n\n========================================\n\nComments:\n- yes we have duplicate data , Is there any solution for solve this?\n- Create a query to delete the duplicate rows and keep the one copy of each. Backup your data before the delete in case issues occur\n- Updated response to give example on how to delete duplicate data for your convenience","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":48,"estimatedTokens":352}}898{"id":"stack-64701518","source":"stackoverflow","questionId":64701518,"title":"Query Postgres Nested JSONB column using sequelize","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: Query Postgres Nested JSONB column using sequelize\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nHi I have a table where I use JSONB to store Nested JSON data and need to query this JSONB column\nBelow is the structure of the table\n\n```\n{\n \"id\": \"5810f6b3-fefb-4eb1-befc-7df11a24d997\",\n \"entity\": \"LocationTypes\",\n \"event_name\": \"LocationTypes added\",\n \"data\": {\n \"event\":{\n \"id\": \"b2805163-78f0-4384-bad6-1df8d35b456d\",\n \"name\": \"builidng\",\n \"company_id\": \"1dd83f77-fdf1-496d-9e0b-f502788c3a7b\",\n \"is_address_applicable\": true,\n \"is_location_map_applicable\": true}\n },\n \"notes\": null,\n \"event_time\": \"2020-11-05T10:56:34.909Z\",\n \"company_id\": \"1dd83f77-fdf1-496d-9e0b-f502788c3a7b\",\n \"created_at\": \"2020-11-05T10:56:34.909Z\",\n \"updated_at\": \"2020-11-05T10:56:34.909Z\"\n }\n```\n\nThe code below is giving blank array as response\n\n```\nconst dataJson = await database.activity_logs.findAll({\n where: {\n 'data.event.id': {\n $eq: 'b2805163-78f0-4384-bad6-1df8d35b456d',\n },\n },\n raw: true,\n });\n```\n\nIs there any way I can accomplish querying nested json object using sequelize in a better way .\n\n========================================\n\nCode:\n```text\n{\n          \"id\": \"5810f6b3-fefb-4eb1-befc-7df11a24d997\",\n          \"entity\": \"LocationTypes\",\n          \"event_name\": \"LocationTypes added\",\n          \"data\": {\n            \"event\":{\n            \"id\": \"b2805163-78f0-4384-bad6-1df8d35b456d\",\n            \"name\": \"builidng\",\n            \"company_id\": \"1dd83f77-fdf1-496d-9e0b-f502788c3a7b\",\n            \"is_address_applicable\": true,\n            \"is_location_map_applicable\": true}\n          },\n          \"notes\": null,\n          \"event_time\": \"2020-11-05T10:56:34.909Z\",\n          \"company_id\": \"1dd83f77-fdf1-496d-9e0b-f502788c3a7b\",\n          \"created_at\": \"2020-11-05T10:56:34.909Z\",\n          \"updated_at\": \"2020-11-05T10:56:34.909Z\"\n        }\n```\n\n```text\nconst dataJson = await database.activity_logs.findAll({\n          where: {\n            'data.event.id': {\n              $eq: 'b2805163-78f0-4384-bad6-1df8d35b456d',\n            },\n          },\n          raw: true,\n        });\n```\n\n```text\nsequelize.where(sequelize.literal(\"data->'event'->'id'\"), '=', 'b2805163-78f0-4384-bad6-1df8d35b456d')\n```\n\n```text\n{\n  data: {\n    event: {\n     id: 'b2805163-78f0-4384-bad6-1df8d35b456d'\n    }\n  }\n}\n```\n\n```text\nsequelize.literal\n```\n\n```text\nsequelize.where\n```\n\n========================================\n\nComments:\n- Thanks for the reply @Anatoly , Sorry I have one more level inside data column its data.event.id not data.id . I have edited the question\n- is this how I should use ? const dataJson = await database.activity_logs.findAll( sequelize.where(sequelize.literal(\"data->'new'->'id'\", '=', 'c44234ba-79a7-4d94-a378-7568dd4a8f5c')), );\n- Almost. Don't forget to indicate `sequelize.where` in `where` option: `findAll({ where: sequelize.where(sequelize.literal(\"data->'new'->'id'\", '=', 'c44234ba-79a7-4d94-a378-7568dd4a8f5c')) })`\n- i am getting the query like this when I use the above code SELECT \"id\", \"entity\", \"event_name\", \"data\", \"notes\", \"event_time\", \"entity_id\", \"user_id\", \"client_id\", \"request_id\", \"source_ip\", \"company_id\", \"created_at\", \"updated_at\" FROM \"activity_logs\" AS \"activity_logs\" WHERE data->'new'->'id' IS NULL;\n- My bad. Should be `sequelize.where(sequelize.literal(\"data->'new'->'id'\"), '=', 'c44234ba-79a7-4d94-a378-7568dd4a8f5c')`. I updated the answer\n- thanks brother you helped me a lot .. +1 from my side.. not looking for this question ... but the solution solve my another problem ...I wasted my 3 hour..then I got the solution.","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":110,"estimatedTokens":902}}899{"id":"stack-40398376","source":"stackoverflow","questionId":40398376,"title":"How to add promise.all in Node.js Sequelize findOrCreate in loop?","tags":["javascript","node.js","promise","sequelize.js"],"text":"Title: How to add promise.all in Node.js Sequelize findOrCreate in loop?\nTags: javascript, node.js, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI create two models in sequelize. I got array of results \"Users\" and than loop through to get or create new \"Room\" based on User.id. I want to print all rooms after all is done. I got empty array in console, because its asynchronious. How can I call console.log after creating all Rooms?\n\n```\nvar Users = sequelize.import(__dirname + \"/../models/own/user\");\nvar Rooms = sequelize.import(__dirname + \"/../models/own/room\"); \nvar _this = this;\n\nthis.users = [];\nthis.rooms = [];\n\nUsers.findAll().then(function(users) {\n _this.users = users;\n\n users.forEach(function(user){\n\n Rooms.findOrCreate({where: {user_id: user.get('id')}})\n .spread(function(room, created) {\n _this.rooms.push(\n room.get({\n plain: true\n })\n );\n\n });\n\n });\n\n console.log(_this.rooms)\n\n});\n```\n\n========================================\n\nTop Answer:\nTry putting `console.log` in `.then` function. Chain it after .spread. I *believe* an array of the rooms will be passed as an argument to the first callback:\n\n```\n.then(function(rooms){\n ...\n})\n```\n\nor, \n\nyou may try to refactor your code and put your logic in a `.then` function.\n\n```\nRooms.findOrCreate({where: {user_id: user.get('id')}})\n.then(function(rooms, created) {\n var room;\n\n for(var i in rooms){\n room = rooms[i];\n\n _this.rooms.push(\n room.get({\n plain: true\n })\n );\n }\n});\n```\n\n========================================\n\nCode:\n```text\nvar Users = sequelize.import(__dirname + \"/../models/own/user\");\nvar Rooms = sequelize.import(__dirname + \"/../models/own/room\");    \nvar _this = this;\n\nthis.users = [];\nthis.rooms = [];\n\nUsers.findAll().then(function(users) {\n    _this.users = users;\n\n    users.forEach(function(user){\n\n        Rooms.findOrCreate({where: {user_id: user.get('id')}})\n        .spread(function(room, created) {\n          _this.rooms.push(\n            room.get({\n              plain: true\n            })\n          );\n\n        });\n\n    });\n\n    console.log(_this.rooms)\n\n});\n```\n\n```text\nvar promises = users.map(function(user){\n    return Rooms.findOrCreate({where: {user_id: user.get('id')}});\n});\nPromise.all(promises).then(function(dbRooms){\n    for(var key in dbRooms){\n        _this.rooms.push(dbRooms[key][0].get({plain: true}));\n    }\n    console.log(_this.rooms);\n});\n```\n\n```text\n.then(function(rooms){\n    ...\n})\n```\n\n```text\nRooms.findOrCreate({where: {user_id: user.get('id')}})\n.then(function(rooms, created) {\n    var room;\n\n    for(var i in rooms){\n        room = rooms[i];\n\n        _this.rooms.push(\n            room.get({\n                plain: true\n            })\n        );\n    }\n});\n```\n\n```text\nconsole.log\n```\n\n```text\n.then\n```\n\n```text\n.then\n```\n\n========================================\n\nComments:\n- The chain with then doesn't work. Then is executed every spread execution in a loop. I need sth executed once after all iteration of forEach\n- Prefer `map` to `forEach` in this case.\n- With a lambda it's `const rooms = Promise.all(users.map(user => Rooms.findOrCreate({where: {user_id: user.get('id')}}))); rooms.then(...)`","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":155,"estimatedTokens":788}}900{"id":"stack-64546830","source":"stackoverflow","questionId":64546830,"title":"Sequelize: how to eager load, with associations, raw: true?","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize: how to eager load, with associations, raw: true?\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nEager loading in Node.js is the only way I know how to use Sequelize. I am trying to export all User survey data from a MySQL DB with nested includes. There are over 500k rows of survey answers, and my script crashes from running out of memory due to creating an instance for every row returned.\n\nI want to make the query \"raw\" and just get the simple object data, but then it only returns the first associated record of each include, instead of an array containing them all. Is there any way to get all associated records and also make it raw? Or is Sequelize not supposed to be used this way for large queries? Here's my query:\n\n```\ndb.User.findAll({\n include: [\n { model: db.Referrer }, // has one Referrer\n { model: db.Individual }, // has many Individuals (children)\n {\n model: db.UserSurvey, // has many UserSurveys\n include: {\n model: db.Answer, // UserSurveys have many Answers\n include: {\n model: db.Question // survey question definition\n }\n }\n }\n ],\n raw: true // only returns first Individual, UserSurvey, Answer, etc.\n nest: true // unflattens but does not fix problem\n})\n```\n\nThis query works fine if I limit the returned rows. It only crashes from the size of the data set if I don't limit it. I have tried adding raw to the top level and everywhere inside the various includes, and nothing seems to work. Should I just try to base the query on Answer, so all relationships only require a single record? Or is there a way to make these complex queries raw and also include all related records? Thanks for reading, this has had me stumped for a few days.\n\n========================================\n\nCode:\n```text\ndb.User.findAll({\n  include: [\n    { model: db.Referrer }, // has one Referrer\n    { model: db.Individual }, // has many Individuals (children)\n    {\n      model: db.UserSurvey, // has many UserSurveys\n      include: {\n        model: db.Answer, // UserSurveys have many Answers\n        include: {\n          model: db.Question // survey question definition\n        }\n      }\n    }\n  ],\n  raw: true // only returns first Individual, UserSurvey, Answer, etc.\n  nest: true // unflattens but does not fix problem\n})\n```\n\n```text\nconst users = db.User.findAll({\n  include: [\n    { model: db.Referrer }, // has one Referrer\n    { model: db.Individual }, // has many Individuals (children)\n    {\n      model: db.UserSurvey, // has many UserSurveys\n      include: {\n        model: db.Answer, // UserSurveys have many Answers\n        include: {\n          model: db.Question // survey question definition\n        }\n      }\n    }\n  ]\n})\nconst plainUsers = users.map(x => x.get({ plain: true }))\n```\n\n```text\nraw\n```\n\n```text\nlimit\n```\n\n```text\noffset\n```\n\n```text\nget({ plain: true })\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":88,"estimatedTokens":710}}901{"id":"stack-67884413","source":"stackoverflow","questionId":67884413,"title":"Redis connection to my-redis:6379 failed - getaddrinfo ENOTFOUND when running seeds","tags":["mysql","node.js","docker","redis","sequelize.js"],"text":"Title: Redis connection to my-redis:6379 failed - getaddrinfo ENOTFOUND when running seeds\nTags: mysql, node.js, docker, redis, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Docker for the container service.\n\nI have created a seed file and run it by `npx sequelize-cli db:seed:all`, then error occur:\n\n```\nSequelize CLI [Node: 13.12.0, CLI: 6.2.0, ORM: 6.5.1]\n\nLoaded configuration file \"migrations/config.js\".\nUsing environment \"development\".\nevents.js:292\n throw er; // Unhandled 'error' event\n ^\n\nError: Redis connection to my-redis:6379 failed - getaddrinfo ENOTFOUND my-redis\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)\nEmitted 'error' event on RedisClient instance at:\n at RedisClient.on_error (/Users/CCCC/Desktop/Source Tree/my-server/node_modules/redis/index.js:342:14)\n at Socket. (/Users/CCCC/Desktop/Source Tree/my-server/node_modules/redis/index.js:223:14)\n at Socket.emit (events.js:315:20)\n at Socket.EventEmitter.emit (domain.js:485:12)\n at emitErrorNT (internal/streams/destroy.js:84:8)\n at processTicksAndRejections (internal/process/task_queues.js:84:21) {\n errno: -3008,\n code: 'ENOTFOUND',\n syscall: 'getaddrinfo',\n hostname: 'my-redis'\n}\n```\n\nIt seems to show that my redis is not found/not running in port 6379.\n\nThen I run `docker ps`, it shows `my-redis` run in port 6379.\n\n```\nCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\n...\nf637ee218d03 redis:6 \"docker-entrypoint.s…\" 18 minutes ago Up 18 minutes 0.0.0.0:6379->6379/tcp my-server_my-redis_1\n```\n\ndocker-compose.yml\n\n```\nversion: '2.1'\n\nservices:\n my-db:\n image: mysql:5.7\n ...\n ports:\n - 3306:3306\n my-redis:\n image: redis:6\n ports:\n - 6379:6379\n my-web:\n restart: always\n environment:\n - NODE_ENV=dev\n - PORT=3030\n build: .\n command: >\n sh -c \"npm install && ./wait-for-db-redis.sh my-db my-redis npm run dev\"\n ports:\n - \"3030:3030\"\n volumes:\n - ./:/server\n depends_on:\n - my-db\n - my-redis\n```\n\n.sequelizerc\n\n```\nconst path = require('path');\n\nmodule.exports = {\n 'config': path.resolve('migrations/config.js'),\n 'seeders-path': path.resolve('migrations/seeders'),\n 'models-path': path.resolve('migrations/models.js')\n};\n```\n\nmigrations/model.js\n\n```\nconst Sequelize = require('sequelize');\nconst app = require('../src/app');\nconst sequelize = app.get('sequelizeClient');\nconst models = sequelize.models;\n\nmodule.exports = Object.assign({\n Sequelize,\n sequelize\n}, models);\n```\n\nconfig.js\n\n```\nconst app = require('../src/app');\nconst env = process.env.NODE_ENV || 'development';\nconst dialect = 'mysql';\n\nmodule.exports = {\n [env]: {\n dialect,\n url: app.get(dialect),\n migrationStorageTableName: '_migrations'\n }\n};\n```\n\n========================================\n\nCode:\n```text\nSequelize CLI [Node: 13.12.0, CLI: 6.2.0, ORM: 6.5.1]\n\nLoaded configuration file \"migrations/config.js\".\nUsing environment \"development\".\nevents.js:292\n      throw er; // Unhandled 'error' event\n      ^\n\nError: Redis connection to my-redis:6379 failed - getaddrinfo ENOTFOUND my-redis\n    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)\nEmitted 'error' event on RedisClient instance at:\n    at RedisClient.on_error (/Users/CCCC/Desktop/Source Tree/my-server/node_modules/redis/index.js:342:14)\n    at Socket.<anonymous> (/Users/CCCC/Desktop/Source Tree/my-server/node_modules/redis/index.js:223:14)\n    at Socket.emit (events.js:315:20)\n    at Socket.EventEmitter.emit (domain.js:485:12)\n    at emitErrorNT (internal/streams/destroy.js:84:8)\n    at processTicksAndRejections (internal/process/task_queues.js:84:21) {\n  errno: -3008,\n  code: 'ENOTFOUND',\n  syscall: 'getaddrinfo',\n  hostname: 'my-redis'\n}\n```\n\n```text\nCONTAINER ID        IMAGE                            COMMAND                  CREATED             STATUS              PORTS                               NAMES\n...\nf637ee218d03        redis:6                          \"docker-entrypoint.s…\"   18 minutes ago      Up 18 minutes       0.0.0.0:6379->6379/tcp              my-server_my-redis_1\n```\n\n```text\nversion: '2.1'\n\nservices:\n  my-db:\n    image: mysql:5.7\n    ...\n    ports:\n      - 3306:3306\n  my-redis:\n    image: redis:6\n    ports:\n      - 6379:6379\n  my-web:\n    restart: always\n    environment:\n      - NODE_ENV=dev\n      - PORT=3030\n    build: .\n    command: >\n      sh -c \"npm install && ./wait-for-db-redis.sh my-db my-redis npm run dev\"\n    ports:\n      - \"3030:3030\"\n    volumes:\n      - ./:/server\n    depends_on:\n      - my-db\n      - my-redis\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n  'config': path.resolve('migrations/config.js'),\n  'seeders-path': path.resolve('migrations/seeders'),\n  'models-path': path.resolve('migrations/models.js')\n};\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst app = require('../src/app');\nconst sequelize = app.get('sequelizeClient');\nconst models = sequelize.models;\n\nmodule.exports = Object.assign({\n  Sequelize,\n  sequelize\n}, models);\n```\n\n```text\nconst app = require('../src/app');\nconst env = process.env.NODE_ENV || 'development';\nconst dialect = 'mysql';\n\nmodule.exports = {\n  [env]: {\n    dialect,\n    url: app.get(dialect),\n    migrationStorageTableName: '_migrations'\n  }\n};\n```\n\n```text\nnpx sequelize-cli db:seed:all\n```\n\n```text\ndocker ps\n```\n\n```text\nmy-redis\n```\n\n```text\nmy-redis\n```\n\n```text\nlocalhost:6379\n```\n\n========================================\n\nComments:\n- I am running it on my project folder. How should I fix it?\n- You will need to run the command within the application container. See docs.docker.com/compose/reference/exec\n- I run `docker-compose exec my-web sh` and then run `npx sequelize-cli db:seed:all`. It works!\n- Since the host development environment and the docker deployment environment have different host names available, you need to make sure things like the Redis location are configurable, perhaps with environment variables.","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":245,"estimatedTokens":1459}}902{"id":"stack-61254567","source":"stackoverflow","questionId":61254567,"title":"Resetting a Sequelize database","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Resetting a Sequelize database\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n### The Situation\n\nI am writing integration tests for a Node.JS project that uses Sequelize + Postgres. I would like to ensure that the test database is completely reset before tests are run.\n\n### Additional Information\n\n- I would prefer a solution that is done via CLI + sequelize.\n\n- I do not care about the content of the test database.\n\n- I do not want my test user to need any privileges outside of the test database.\n\nI have a `pretest` script that runs:\n\n```\nNODE_ENV=test yarn migrate\n```\n\n### The Exploration\n\nI believe `db:drop` and `db:create` do not work in postgres.\n\nIn Rails I might use `db:migrate:reset`\n\nI know Sequelize has `db:migrate:undo:all` but I believe that rolls back each migration individually, which feels like a waste of time if my intent is simply to drop all tables.\n\n### The Question\n\nHow do I most effectively accomplish the goal of running migrations on the test database from a clean slate?\n\n========================================\n\nTop Answer:\ntry this solution:\n\nusing jest hook pretest and multiples steps together\n\n```\n\"pretest\": \"NODE_ENV=test sequelize db:migrate:undo:all && NODE_ENV=test sequelize db:drop && NODE_ENV=test sequelize db:create && NODE_ENV=test sequelize db:migrate,\n\"test\": \"NODE_ENV=test jest\"\n```\n\n========================================\n\nCode:\n```sh\nNODE_ENV=test yarn migrate\n```\n\n```text\npretest\n```\n\n```text\ndb:drop\n```\n\n```text\ndb:create\n```\n\n```text\ndb:migrate:reset\n```\n\n```text\ndb:migrate:undo:all\n```\n\n```sh\n☁  node-sequelize-examples [master] npx sequelize-cli db:drop\n\nSequelize CLI [Node: 10.16.2, CLI: 5.5.1, ORM: 5.21.3]\n\nLoaded configuration file \"src/config/config.js\".\nUsing environment \"development\".\nExecuting (default): DROP DATABASE \"node-sequelize-examples\"\nDatabase node-sequelize-examples dropped.\n☁  node-sequelize-examples [master] npx sequelize-cli db:create\n\nSequelize CLI [Node: 10.16.2, CLI: 5.5.1, ORM: 5.21.3]\n\nLoaded configuration file \"src/config/config.js\".\nUsing environment \"development\".\nExecuting (default): CREATE DATABASE \"node-sequelize-examples\"\nDatabase node-sequelize-examples created.\n```\n\n```sh\nmodule.exports = {\n  development: {\n    username: process.env.POSTGRES_USER,\n    password: process.env.POSTGRES_PASSWORD,\n    database: process.env.POSTGRES_DB,\n    host: process.env.POSTGRES_HOST,\n    port: process.env.POSTGRES_PORT,\n    dialect: 'postgres',\n    logging: console.log,\n  },\n  test: {\n    username: process.env.POSTGRES_USER,\n    password: process.env.POSTGRES_PASSWORD,\n    database: process.env.POSTGRES_DB,\n    host: process.env.POSTGRES_HOST,\n    port: process.env.POSTGRES_PORT,\n    dialect: 'postgres',\n  },\n  production: {\n    username: process.env.POSTGRES_USER,\n    password: process.env.POSTGRES_PASSWORD,\n    database: process.env.POSTGRES_DB,\n    host: process.env.POSTGRES_HOST,\n    port: process.env.POSTGRES_PORT,\n    dialect: 'postgres',\n  },\n};\n```\n\n```sh\n# psql -U testuser node-sequelize-examples\npsql (9.6.11)\nType \"help\" for help.\n\nnode-sequelize-examples=# \\d\nNo relations found.\n```\n\n```text\ndb:create\n```\n\n```text\ndb:drop\n```\n\n```text\npostgres:9.6\n```\n\n```text\nsrc/config/config.js\n```\n\n```text\npsql\n```\n\n```text\n\"pretest\": \"NODE_ENV=test sequelize db:migrate:undo:all && NODE_ENV=test sequelize db:drop && NODE_ENV=test sequelize db:create && NODE_ENV=test sequelize db:migrate,\n\"test\": \"NODE_ENV=test jest\"\n```\n\n========================================\n\nComments:\n- Great suggestion; unfortunately it looks like postgresql doesn't support those (`ERROR: Dialect postgresql does not support db:create &#47; db:drop commands`)\n- `db:create` and `db:drop` support has now been added for PostgreSQL.\n- `mariadb` doesn't have one. This solution is not ideal.\n- Please add an explanation for your answer","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":164,"estimatedTokens":965}}903{"id":"stack-52915480","source":"stackoverflow","questionId":52915480,"title":"Sequelize column Table.createdAt does not exist","tags":["node.js","sequelize.js"],"text":"Title: Sequelize column Table.createdAt does not exist\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have these two tables:\n\n```\nconst AdminUser = sequelize.define('AdminUser', {\n adminUserId: {\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV4, \n unique: true, \n allowNull: false,\n primaryKey: true\n },\n adminUsername: {\n type: 'citext',\n unique: true,\n allowNull: false\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false\n },\n role: {\n type: DataTypes.ENUM,\n values: ['super-admin', 'non-super-admin'] \n },\n active: {\n type: DataTypes.BOOLEAN\n }\n })\n\nAdminUser.belongsToMany(MsTeam, {\n through: 'AdminUserTeam',\n foreignKey: {\n name: 'adminUserId',\n allowNull: false\n }\n })\n```\n\nAnd\n\n```\nconst MsTeam = sequelize.define('MsTeam', {\n teamId: {\n type: DataTypes.UUID,\n defaultValue: DataTypes.UUIDV4, \n unique: true, \n allowNull: false,\n primaryKey: true\n },\n msTeamId: {\n type: DataTypes.STRING,\n unique: true,\n allowNull: false\n },\n msTeamName: {\n type: DataTypes.STRING,\n allowNull: false\n },\n active: {\n type: DataTypes.BOOLEAN\n }\n })\n\nMsTeam.belongsToMany(models.AdminUser, {\n through: 'AdminUserTeam',\n foreignKey: {\n name: 'teamId',\n allowNull: false\n }\n })\n```\n\nThey have a n:m relationship through 'AdminUserTeam'.\nTimestamps are enabled.\n\nBut a simple query like,\n\n```\n// Include team data\n const includeMsTeam = {\n model: MsTeam,\n through: {\n attributes: []\n },\n attributes: ['teamId', 'msTeamName']\n }\nconst users = await AdminUser.findAll({\n attributes: ['adminUserId', 'adminUsername'],\n limit: 10,\n offset: 10,\n order: [['createdAt', 'DESC']],\n include: [includeMsTeam]\n })\n```\n\nfails with error,\n\n```\n{\n \"error\": \"column AdminUser.createdAt does not exist\"\n}\n```\n\nStrangely, the query succeeds if I remove the `include` field\n\nA solution to this was to disable timestamps as mentioned in this SO answer. But what if I want to keep timestamps? How do I order by \"createdAt\" using associations?\n\nEdit: Add SQL query\n\n```\nExecuting (default): SELECT \"AdminUser\".*, \"MsTeams\".\"teamId\" AS \"MsTeams.teamId\", \"MsTeams\".\"msTeamName\" AS \"MsTeams.msTeamName\", \"MsTeams->AdminUserTeam\".\"createdAt\" AS \"MsTeams.AdminUserTeam.createdAt\", \"MsTeams->AdminUserTeam\".\"updatedAt\" AS \"MsTeams.AdminUserTeam.updatedAt\", \"MsTeams->AdminUserTeam\".\"adminUserId\" AS \"MsTeams.AdminUserTeam.adminUserId\", \"MsTeams->AdminUserTeam\".\"teamId\" AS \"MsTeams.AdminUserTeam.teamId\" FROM (SELECT \"AdminUser\".\"adminUserId\", \"AdminUser\".\"adminUsername\" FROM \"AdminUsers\" AS \"AdminUser\" WHERE \"AdminUser\".\"role\" = 'non-super-admin' AND ( SELECT \"AdminUserTeam\".\"adminUserId\" FROM \"AdminUserTeam\" AS \"AdminUserTeam\" INNER JOIN \"MsTeams\" AS \"MsTeam\" ON \"AdminUserTeam\".\"teamId\" = \"MsTeam\".\"teamId\" WHERE (\"AdminUser\".\"adminUserId\" = \"AdminUserTeam\".\"adminUserId\") LIMIT 1 ) IS NOT NULL ORDER BY \"AdminUser\".\"createdAt\" DESC LIMIT 20 OFFSET 0) AS \"AdminUser\" LEFT OUTER JOIN ( \"AdminUserTeam\" AS \"MsTeams->AdminUserTeam\" INNER JOIN \"MsTeams\" AS \"MsTeams\" ON \"MsTeams\".\"teamId\" = \"MsTeams->AdminUserTeam\".\"teamId\") ON \"AdminUser\".\"adminUserId\" = \"MsTeams->AdminUserTeam\".\"adminUserId\" ORDER BY \"AdminUser\".\"createdAt\" DESC;\n```\n\nThe error happens at, \n\n```\nORDER BY \"AdminUser\".\"createdAt\" DESC\n```\n\n========================================\n\nTop Answer:\nSequelize will automatically add the attributes `createdAt` and `updatedAt` when you use the `define` method: https://sequelize.org/v3/docs/models-definition/\n\n\"If you do not want timestamps on your models, only want some timestamps, or you are working with an existing database where the columns are named something else, jump straight on to configuration to see how to do that\"\n\n========================================\n\nCode:\n```text\nconst AdminUser = sequelize.define('AdminUser', {\n    adminUserId: {\n      type: DataTypes.UUID,\n      defaultValue: DataTypes.UUIDV4, \n      unique: true, \n      allowNull: false,\n      primaryKey: true\n    },\n    adminUsername: {\n      type: 'citext',\n      unique: true,\n      allowNull: false\n    },\n    password: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    role: {\n      type: DataTypes.ENUM,\n      values: ['super-admin', 'non-super-admin']  \n    },\n    active: {\n      type: DataTypes.BOOLEAN\n    }\n  })\n\nAdminUser.belongsToMany(MsTeam, {\n      through: 'AdminUserTeam',\n      foreignKey: {\n        name: 'adminUserId',\n        allowNull: false\n      }\n    })\n```\n\n```text\nconst MsTeam = sequelize.define('MsTeam', {\n    teamId: {\n      type: DataTypes.UUID,\n      defaultValue: DataTypes.UUIDV4, \n      unique: true, \n      allowNull: false,\n      primaryKey: true\n    },\n    msTeamId: {\n      type: DataTypes.STRING,\n      unique: true,\n      allowNull: false\n    },\n    msTeamName: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    active: {\n      type: DataTypes.BOOLEAN\n    }\n  })\n\nMsTeam.belongsToMany(models.AdminUser, {\n      through: 'AdminUserTeam',\n      foreignKey: {\n        name: 'teamId',\n        allowNull: false\n      }\n    })\n```\n\n```text\n// Include team data\n  const includeMsTeam = {\n    model: MsTeam,\n    through: {\n      attributes: []\n    },\n    attributes: ['teamId', 'msTeamName']\n  }\nconst users = await AdminUser.findAll({\n    attributes: ['adminUserId', 'adminUsername'],\n    limit: 10,\n    offset: 10,\n    order: [['createdAt', 'DESC']],\n    include: [includeMsTeam]\n  })\n```\n\n```text\n{\n    \"error\": \"column AdminUser.createdAt does not exist\"\n}\n```\n\n```text\nExecuting (default): SELECT \"AdminUser\".*, \"MsTeams\".\"teamId\" AS \"MsTeams.teamId\", \"MsTeams\".\"msTeamName\" AS \"MsTeams.msTeamName\", \"MsTeams->AdminUserTeam\".\"createdAt\" AS \"MsTeams.AdminUserTeam.createdAt\", \"MsTeams->AdminUserTeam\".\"updatedAt\" AS \"MsTeams.AdminUserTeam.updatedAt\", \"MsTeams->AdminUserTeam\".\"adminUserId\" AS \"MsTeams.AdminUserTeam.adminUserId\", \"MsTeams->AdminUserTeam\".\"teamId\" AS \"MsTeams.AdminUserTeam.teamId\" FROM (SELECT \"AdminUser\".\"adminUserId\", \"AdminUser\".\"adminUsername\" FROM \"AdminUsers\" AS \"AdminUser\" WHERE \"AdminUser\".\"role\" = 'non-super-admin' AND ( SELECT \"AdminUserTeam\".\"adminUserId\" FROM \"AdminUserTeam\" AS \"AdminUserTeam\" INNER JOIN \"MsTeams\" AS \"MsTeam\" ON \"AdminUserTeam\".\"teamId\" = \"MsTeam\".\"teamId\" WHERE (\"AdminUser\".\"adminUserId\" = \"AdminUserTeam\".\"adminUserId\") LIMIT 1 ) IS NOT NULL ORDER BY \"AdminUser\".\"createdAt\" DESC LIMIT 20 OFFSET 0) AS \"AdminUser\" LEFT OUTER JOIN ( \"AdminUserTeam\" AS \"MsTeams->AdminUserTeam\" INNER JOIN \"MsTeams\" AS \"MsTeams\" ON \"MsTeams\".\"teamId\" = \"MsTeams->AdminUserTeam\".\"teamId\") ON \"AdminUser\".\"adminUserId\" = \"MsTeams->AdminUserTeam\".\"adminUserId\" ORDER BY \"AdminUser\".\"createdAt\" DESC;\n```\n\n```text\nORDER BY \"AdminUser\".\"createdAt\" DESC\n```\n\n```text\ninclude\n```\n\n```text\ncreatedAt\n```\n\n```text\nORDER BY\n```\n\n```text\nsubQuery: false\n```\n\n```text\nfindAll\n```\n\n```text\ncreatedAt\n```\n\n```text\nattributes\n```\n\n```text\nsequelize.define('AdminUser', {\n  // Columns\n}, {\n  timestamps: true,\n});\n```\n\n```text\nvar user = sequelize.define('user', { /* bla */ }, {\n  // don't add the timestamp attributes (updatedAt, createdAt)\n  timestamps: false,\n  // your other configuration here\n});\n```\n\n```text\nsubQuery: false\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\ndefine\n```\n\n========================================\n\nComments:\n- You can add `logging: console.log` to the options object to see what the generated SQL looks like in both situations. That might shed some light on what's happening.\n- Thanks. I've added the SQL query. I'm not sure why \"AdminUser\".\"createdAt\" does not exist. It is present in the DB.\n- That did not work. Actually I never set timestamps to false so they were always enabled. Also, I can see the columns created in the table in the postgres UI tool so they are definitely present.\n- @Edl Oh, I thought you disabled it following SO answer you linked. What happens when you put createdAt column definition manually in AdminUser?\n- No change, I still get the same error. That SO answer actually mentioned that the problem occurs due to, \"But when you join, each column of the joined table will be aliased\".. I'm not sure what this is though\n- `subQuery: false` did it. Thanks.\n- how you add `subquery: false`, which options object are you referring to? I'm having a similar issue\n- The first argument of `findAll` is called \"options\" in the documentation. It has an undocumented property called `subQuery` and you use it like so: `Model.findAll({ subQuery: false, &#47;* other stuff *&#47; })`\n- Why would they remove the timestamps if they want to use the `createdAt` timestamp in the query, and stated in the question that they want to keep the timestamps? It's possible that you have a different use case / issue in your code where this helped, however this is not an answer to the user's question.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":307,"estimatedTokens":2253}}904{"id":"stack-48713019","source":"stackoverflow","questionId":48713019,"title":"FindAll with includes involving a complicated many-to-(many-to-many) relationship (sequelizejs)","tags":["javascript","node.js","many-to-many","sequelize.js","eager-loading"],"text":"Title: FindAll with includes involving a complicated many-to-(many-to-many) relationship (sequelizejs)\nTags: javascript, node.js, many-to-many, sequelize.js, eager-loading\nSource: Stack Overflow\n\nQuestion:\nThis has a sibling question in Software Engineering SE.\n\nConsider `Company`, `Product` and `Person`.\n\nThere is a many-to-many relationship between `Company` and `Product`, through a junction table `Company_Product`, because a given company may produce more than one product (such as \"car\" and \"bicycle\"), but also a given product, such as \"car\", can be produced by multiple companies. In the junction table `Company_Product` there is an extra field \"price\" which is the price in which the given company sells the given product.\n\nThere is another many-to-many relationship between `Company_Product` and `Person`, through a junction table `Company_Product_Person`. Yes, it is a many-to-many relationship involving one entity that is already a junction table. This is because a Person can own multiple products, such as a car from company1 and a bicycle from company2, and in turn the same company_product can be owned by more than one person, since for example both person1 and person2 could have bought a car from company1. In the junction table `Company_Product_Person` there is an extra field \"thoughts\" which contains the thoughts of the person at the moment they purchased the company_product.\n\nI want to make a query with sequelize to get from the database all instances of `Company`, with all related `Products` with the respective `Company_Product` which in turn include all related `Persons` with the respective `Company_Product_Persons`.\n\nGetting the elements of both junction tables is important too, because the fields \"price\" and \"thoughts\" are important.\n\nAnd I was not able to figure out how to do this.\n\nI made the code as short as I could to investigate this. **Looks big, but most of it is model declaration boilerplate:** (to run it, first do `npm install sequelize sqlite3`)\n\n```\nconst Sequelize = require(\"sequelize\");\nconst sequelize = new Sequelize({ dialect: \"sqlite\", storage: \"db.sqlite\" });\n\n// ================= MODELS =================\n\nconst Company = sequelize.define(\"company\", {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n autoIncrement: true,\n primaryKey: true\n },\n name: Sequelize.STRING\n});\n\nconst Product = sequelize.define(\"product\", {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n autoIncrement: true,\n primaryKey: true\n },\n name: Sequelize.STRING\n});\n\nconst Person = sequelize.define(\"person\", {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n autoIncrement: true,\n primaryKey: true\n },\n name: Sequelize.STRING\n});\n\nconst Company_Product = sequelize.define(\"company_product\", {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n autoIncrement: true,\n primaryKey: true\n },\n companyId: {\n type: Sequelize.INTEGER,\n allowNull: false,\n references: {\n model: \"company\",\n key: \"id\"\n },\n onDelete: \"CASCADE\"\n },\n productId: {\n type: Sequelize.INTEGER,\n allowNull: false,\n references: {\n model: \"product\",\n key: \"id\"\n },\n onDelete: \"CASCADE\"\n },\n price: Sequelize.INTEGER\n});\n\nconst Company_Product_Person = sequelize.define(\"company_product_person\", {\n id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n autoIncrement: true,\n primaryKey: true\n },\n companyProductId: {\n type: Sequelize.INTEGER,\n allowNull: false,\n references: {\n model: \"company_product\",\n key: \"id\"\n },\n onDelete: \"CASCADE\"\n },\n personId: {\n type: Sequelize.INTEGER,\n allowNull: false,\n references: {\n model: \"person\",\n key: \"id\"\n },\n onDelete: \"CASCADE\"\n },\n thoughts: Sequelize.STRING\n});\n\n// ================= RELATIONS =================\n\n// Many to Many relationship between Company and Product\nCompany.belongsToMany(Product, { through: \"company_product\", foreignKey: \"companyId\", onDelete: \"CASCADE\" });\nProduct.belongsToMany(Company, { through: \"company_product\", foreignKey: \"productId\", onDelete: \"CASCADE\" });\n\n// Many to Many relationship between Company_Product and Person\nCompany_Product.belongsToMany(Person, { through: \"company_product_person\", foreignKey: \"companyProductId\", onDelete: \"CASCADE\" });\nPerson.belongsToMany(Company_Product, { through: \"company_product_person\", foreignKey: \"personId\", onDelete: \"CASCADE\" });\n\n// ================= TEST =================\n\nvar company, product, person, company_product, company_product_person;\n\nsequelize.sync({ force: true })\n .then(() => {\n // Create one company, one product and one person for tests.\n return Promise.all([\n Company.create({ name: \"Company test\" }).then(created => { company = created }),\n Product.create({ name: \"Product test\" }).then(created => { product = created }),\n Person.create({ name: \"Person test\" }).then(created => { person = created }),\n ]);\n })\n .then(() => {\n // company produces product\n return company.addProduct(product);\n })\n .then(() => {\n // Get the company_product for tests\n return Company_Product.findAll().then(found => { company_product = found[0] });\n })\n .then(() => {\n // person owns company_product\n return company_product.addPerson(person);\n })\n .then(() => {\n // I can get the list of Companys with their Products, but couldn't get the nested Persons...\n return Company.findAll({\n include: [{\n model: Product\n }]\n }).then(companies => {\n console.log(JSON.stringify(companies.map(company => company.toJSON()), null, 4));\n });\n })\n .then(() => {\n // And I can get the list of Company_Products with their Persons...\n return Company_Product.findAll({\n include: [{\n model: Person\n }]\n }).then(companyproducts => {\n console.log(JSON.stringify(companyproducts.map(companyproduct => companyproduct.toJSON()), null, 4));\n });\n })\n .then(() => {\n // I should be able to make both calls above in one, getting those nested things\n // at once, but how??\n return Company.findAll({\n include: [{\n model: Product\n // ???\n }]\n }).then(companies => {\n console.log(JSON.stringify(companies.map(company => company.toJSON()), null, 4));\n });\n });\n```\n\n**My goal is to obtain an array of `Companys` already with all the deep-nested `Persons` and `Company_Product_Persons` at one go:**\n\n```\n// My goal:\n[\n {\n \"id\": 1,\n \"name\": \"Company test\",\n \"createdAt\": \"...\",\n \"updatedAt\": \"...\",\n \"products\": [\n {\n \"id\": 1,\n \"name\": \"Product test\",\n \"createdAt\": \"...\",\n \"updatedAt\": \"...\",\n \"company_product\": {\n \"id\": 1,\n \"companyId\": 1,\n \"productId\": 1,\n \"price\": null,\n \"createdAt\": \"...\",\n \"updatedAt\": \"...\",\n \"persons\": [\n {\n \"id\": 1,\n \"name\": \"Person test\",\n \"createdAt\": \"...\",\n \"updatedAt\": \"...\",\n \"company_product_person\": {\n \"id\": 1,\n \"companyProductId\": 1,\n \"personId\": 1,\n \"thoughts\": null,\n \"createdAt\": \"...\",\n \"updatedAt\": \"...\"\n }\n }\n ]\n }\n }\n ]\n }\n];\n```\n\n**How can I do this?**\n\nNote: I could make both queries separately and write some code to \"join\" the retrieved objects, but that would be computationally expensive and ugly. I am looking for the right way to do this.\n\n========================================\n\nCode:\n```text\nconst Sequelize = require(\"sequelize\");\nconst sequelize = new Sequelize({ dialect: \"sqlite\", storage: \"db.sqlite\" });\n\n// ================= MODELS =================\n\nconst Company = sequelize.define(\"company\", {\n    id: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    name: Sequelize.STRING\n});\n\nconst Product = sequelize.define(\"product\", {\n    id: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    name: Sequelize.STRING\n});\n\nconst Person = sequelize.define(\"person\", {\n    id: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    name: Sequelize.STRING\n});\n\nconst Company_Product = sequelize.define(\"company_product\", {\n    id: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    companyId: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        references: {\n            model: \"company\",\n            key: \"id\"\n        },\n        onDelete: \"CASCADE\"\n    },\n    productId: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        references: {\n            model: \"product\",\n            key: \"id\"\n        },\n        onDelete: \"CASCADE\"\n    },\n    price: Sequelize.INTEGER\n});\n\nconst Company_Product_Person = sequelize.define(\"company_product_person\", {\n    id: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    companyProductId: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        references: {\n            model: \"company_product\",\n            key: \"id\"\n        },\n        onDelete: \"CASCADE\"\n    },\n    personId: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        references: {\n            model: \"person\",\n            key: \"id\"\n        },\n        onDelete: \"CASCADE\"\n    },\n    thoughts: Sequelize.STRING\n});\n\n// ================= RELATIONS =================\n\n// Many to Many relationship between Company and Product\nCompany.belongsToMany(Product, { through: \"company_product\", foreignKey: \"companyId\", onDelete: \"CASCADE\" });\nProduct.belongsToMany(Company, { through: \"company_product\", foreignKey: \"productId\", onDelete: \"CASCADE\" });\n\n// Many to Many relationship between Company_Product and Person\nCompany_Product.belongsToMany(Person, { through: \"company_product_person\", foreignKey: \"companyProductId\", onDelete: \"CASCADE\" });\nPerson.belongsToMany(Company_Product, { through: \"company_product_person\", foreignKey: \"personId\", onDelete: \"CASCADE\" });\n\n// ================= TEST =================\n\nvar company, product, person, company_product, company_product_person;\n\nsequelize.sync({ force: true })\n    .then(() => {\n        // Create one company, one product and one person for tests.\n        return Promise.all([\n            Company.create({ name: \"Company test\" }).then(created => { company = created }),\n            Product.create({ name: \"Product test\" }).then(created => { product = created }),\n            Person.create({ name: \"Person test\" }).then(created => { person = created }),\n        ]);\n    })\n    .then(() => {\n        // company produces product\n        return company.addProduct(product);\n    })\n    .then(() => {\n        // Get the company_product for tests\n        return Company_Product.findAll().then(found => { company_product = found[0] });\n    })\n    .then(() => {\n        // person owns company_product\n        return company_product.addPerson(person);\n    })\n    .then(() => {\n        // I can get the list of Companys with their Products, but couldn't get the nested Persons...\n        return Company.findAll({\n            include: [{\n                model: Product\n            }]\n        }).then(companies => {\n            console.log(JSON.stringify(companies.map(company => company.toJSON()), null, 4));\n        });\n    })\n    .then(() => {\n        // And I can get the list of Company_Products with their Persons...\n        return Company_Product.findAll({\n            include: [{\n                model: Person\n            }]\n        }).then(companyproducts => {\n            console.log(JSON.stringify(companyproducts.map(companyproduct => companyproduct.toJSON()), null, 4));\n        });\n    })\n    .then(() => {\n        // I should be able to make both calls above in one, getting those nested things\n        // at once, but how??\n        return Company.findAll({\n            include: [{\n                model: Product\n                // ???\n            }]\n        }).then(companies => {\n            console.log(JSON.stringify(companies.map(company => company.toJSON()), null, 4));\n        });\n    });\n```\n\n```text\n// My goal:\n[\n    {\n        \"id\": 1,\n        \"name\": \"Company test\",\n        \"createdAt\": \"...\",\n        \"updatedAt\": \"...\",\n        \"products\": [\n            {\n                \"id\": 1,\n                \"name\": \"Product test\",\n                \"createdAt\": \"...\",\n                \"updatedAt\": \"...\",\n                \"company_product\": {\n                    \"id\": 1,\n                    \"companyId\": 1,\n                    \"productId\": 1,\n                    \"price\": null,\n                    \"createdAt\": \"...\",\n                    \"updatedAt\": \"...\",\n                    \"persons\": [\n                        {\n                            \"id\": 1,\n                            \"name\": \"Person test\",\n                            \"createdAt\": \"...\",\n                            \"updatedAt\": \"...\",\n                            \"company_product_person\": {\n                                \"id\": 1,\n                                \"companyProductId\": 1,\n                                \"personId\": 1,\n                                \"thoughts\": null,\n                                \"createdAt\": \"...\",\n                                \"updatedAt\": \"...\"\n                            }\n                        }\n                    ]\n                }\n            }\n        ]\n    }\n];\n```\n\n```text\nCompany\n```\n\n```text\nProduct\n```\n\n```text\nPerson\n```\n\n```text\nCompany\n```\n\n```text\nProduct\n```\n\n```text\nCompany_Product\n```\n\n```text\nCompany_Product\n```\n\n```text\nCompany_Product\n```\n\n```text\nPerson\n```\n\n```text\nCompany_Product_Person\n```\n\n```text\nCompany_Product_Person\n```\n\n```text\nCompany\n```\n\n```text\nProducts\n```\n\n```text\nCompany_Product\n```\n\n```text\nPersons\n```\n\n```text\nCompany_Product_Persons\n```\n\n```text\nnpm install sequelize sqlite3\n```\n\n```text\nCompanys\n```\n\n```text\nPersons\n```\n\n```text\nCompany_Product_Persons\n```\n\n```text\nCompany.hasMany(Company_Product, { foreignKey: \"companyId\" });\nCompany_Product.belongsTo(Company, { foreignKey: \"companyId\" });\n\nProduct.hasMany(Company_Product, { foreignKey: \"productId\" });\nCompany_Product.belongsTo(Product, { foreignKey: \"productId\" });\n\nCompany_Product.hasMany(Company_Product_Person, { foreignKey: \"companyProductId\" });\nCompany_Product_Person.belongsTo(Company_Product, { foreignKey: \"companyProductId\" });\n\nPerson.hasMany(Company_Product_Person, { foreignKey: \"personId\" });\nCompany_Product_Person.belongsTo(Person, { foreignKey: \"personId\" });\n```\n\n```text\nreturn Company_Product.create({\n    companyId: company.id,\n    productId: product.id,\n    price: 99\n}).then(created => { company_product = created });\n```\n\n```text\nreturn Company_Product_Person.create({\n    companyProductId: company_product.id,\n    personId: person.id,\n    thoughts: \"nice\"\n}).then(created => { company_product_person = created });\n```\n\n```text\nCompany.findAll({\n    include: [{\n        model: Company_Product,\n        include: [{\n            model: Product\n        }, {\n            model: Company_Product_Person,\n            include: [{\n                model: Person\n            }]\n        }]\n    }]\n})\n```\n\n```text\nCompany.hasMany(Product, { foreignKey: \"companyId\" });\nProduct.belongsTo(Company, { foreignKey: \"companyId\" });\n\nProductType.hasMany(Product, { foreignKey: \"productTypeId\" });\nProduct.belongsTo(ProductType, { foreignKey: \"productTypeId\" });\n\nProduct.hasMany(Purchase, { foreignKey: \"productId\" });\nPurchase.belongsTo(Product, { foreignKey: \"productId\" });\n\nPerson.hasMany(Purchase, { foreignKey: \"personId\" });\nPurchase.belongsTo(Person, { foreignKey: \"personId\" });\n```\n\n```text\nProduct.create({\n    companyId: company.id\n    productTypeId: productType.id,\n    price: 99\n})\n```\n\n```text\nPurchase.create({\n    productId: product.id,\n    personId: person.id,\n    thoughts: \"nice\"\n})\n```\n\n```text\nCompany.findAll({\n    include: [{\n        model: Product,\n        include: [{\n            model: ProductType\n        }, {\n            model: Purchase,\n            include: [{\n                model: Person\n            }]\n        }]\n    }]\n})\n```\n\n```text\nreturn company.addProduct(product);\n```\n\n```text\nreturn company_product.addPerson(person)\n```\n\n```text\nCompany_Product\n```\n\n```text\nCompany\n```\n\n```text\nCompany\n```\n\n```text\nProduct\n```\n\n```text\nProductType\n```\n\n```text\nCompany_Product\n```\n\n```text\nProduct\n```\n\n```text\nPerson\n```\n\n```text\nPerson\n```\n\n```text\nCompany_Product_Person\n```\n\n```text\nPurchase\n```\n\n```text\nProduct\n```\n\n```text\nCompany\n```\n\n```text\nProductType\n```\n\n```text\nCompany\n```\n\n```text\nProduct\n```\n\n```text\nProductType\n```\n\n```text\nProduct\n```\n\n```text\nPurchase\n```\n\n```text\nProduct\n```\n\n```text\nPerson\n```\n\n```text\nProduct\n```\n\n```text\nPurchase\n```\n\n```text\nProduct\n```\n\n```text\nPerson\n```\n\n```text\ncompany.addProduct(product);\n```\n\n```text\ncompany_product.addPerson(person);\n```\n\n========================================\n\nComments:\n- shouldn't it be \"very very very long answer\"?\n- @guilhermecgs perhaps I should add more details :P","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":59,"totalLines":733,"estimatedTokens":4162}}905{"id":"stack-56043246","source":"stackoverflow","questionId":56043246,"title":"node.js sequelize no primary keys when migrating","tags":["database","sequelize.js","migrate"],"text":"Title: node.js sequelize no primary keys when migrating\nTags: database, sequelize.js, migrate\nSource: Stack Overflow\n\nQuestion:\nThis is my `create_user_table` migration in my node.js project. \n\n```\n'use strict';\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable(\"comments\", {\n content: {\n type: Sequelize.STRING(20),\n allowNull: false\n },\n lastName: {\n type: Sequelize.STRING(20),\n allowNull: false\n }\n })\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable(\"comments\")\n }\n};\n```\n\nAfter running sequelize db:migrate this is the result:\n\n```\nsequelize db:migrate\n\nSequelize CLI [Node: 10.15.2, CLI: 5.4.0, ORM: 5.8.5]\n\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\n== 20190507193540-create_comment_table: migrating =======\n== 20190507193540-create_comment_table: migrated (0.021s)\n\n== 20190507195058-create_user_table: migrating =======\n== 20190507195058-create_user_table: migrated (0.011s)\n```\n\nWhen I run `describe users;` in mysql CLI, the table does not include an ID?\n\n```\n+----------+-------------+------+-----+---------+-------+\n | Field | Type | Null | Key | Default | Extra |\n +----------+-------------+------+-----+---------+-------+\n | username | varchar(20) | NO | | NULL | |\n | lastName | varchar(20) | NO | | NULL | |\n +----------+-------------+------+-----+---------+-------+\n```\n\nAnd to completely make sure, I've also tried.\n\n```\nmysql> show index from users where id = 'PRIMARY';\nERROR 1054 (42S22): Unknown column 'id' in 'where clause'\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable(\"comments\", {\n      content: {\n        type: Sequelize.STRING(20),\n        allowNull: false\n      },\n      lastName: {\n        type: Sequelize.STRING(20),\n        allowNull: false\n      }\n    })\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable(\"comments\")\n  }\n};\n```\n\n```text\nsequelize db:migrate\n\nSequelize CLI [Node: 10.15.2, CLI: 5.4.0, ORM: 5.8.5]\n\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\n== 20190507193540-create_comment_table: migrating =======\n== 20190507193540-create_comment_table: migrated (0.021s)\n\n== 20190507195058-create_user_table: migrating =======\n== 20190507195058-create_user_table: migrated (0.011s)\n```\n\n```text\n+----------+-------------+------+-----+---------+-------+\n    | Field    | Type        | Null | Key | Default | Extra |\n    +----------+-------------+------+-----+---------+-------+\n    | username | varchar(20) | NO   |     | NULL    |       |\n    | lastName | varchar(20) | NO   |     | NULL    |       |\n    +----------+-------------+------+-----+---------+-------+\n```\n\n```text\nmysql> show index from users where id = 'PRIMARY';\nERROR 1054 (42S22): Unknown column 'id' in 'where clause'\n```\n\n```text\ncreate_user_table\n```\n\n```text\ndescribe users;\n```\n\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable(\"comments\", {\n      id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true,\n      },\n      content: {\n        type: Sequelize.STRING(20),\n        allowNull: false\n      },\n      lastName: {\n        type: Sequelize.STRING(20),\n        allowNull: false\n      }\n    })\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable(\"comments\")\n  }\n};\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Kind of documented at: sequelize.org/v5/class/lib/&hellip; on the example. Feels like bad API.","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":160,"estimatedTokens":919}}906{"id":"stack-63726887","source":"stackoverflow","questionId":63726887,"title":"Node Sequelize Postgres - BulkCreate ignore duplicate values for custom fields","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Node Sequelize Postgres - BulkCreate ignore duplicate values for custom fields\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**Goal:** I have a list of objects from another service that I'd like to persist in my own Postgres datastore. The data coming from this other service returns JSON, but doesn't include any ids.\n\n**Current Outcome:**\n\n- When I first run bulkCreate, it syncs the data to my database successfully (see example code below)\n\n- When I get a fresh batch from the other service (i.e. checking for updates) and call bulkCreate again, *new* topics are inserted into the database for each row, even if the title already exists\n\n**Expected Outcome**\n\n- When I first run bulkCreate, it syncs the data to my database successfully (see example code below)\n\n- When I get a fresh batch from the other service (i.e. checking for updates) and call bulkCreate again, only topics with titles not found in the db are inserted, the rest have their 'count' property updated.\n\n**Topic.js**\n\n```\nconst database = require('../../shared/database'); // shared db connection. This works\nconst {DataTypes, Model} = require('sequelize');\n\nclass Topic extends Model { }\n\nTopic.init({\n topicId: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true,\n defaultValue: undefined,\n },\n title: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n count: {\n type: DataTypes.INTEGER,\n allowNull: true,\n },\n}, {\n sequelize: database, \n});\n\nmodule.exports = Topic;\n```\n\n**SyncAPI.js** (1st run) - works as expected\n\n```\nconst url = 'https://....'; // the remote service\nconst topics = await this.http.get(url); // simple example of getting the new data\n// [{ 'title': 'Leadership', 'count': 214 }, \n// { 'title': 'Management', 'count': 51 }]\n\nawait Topic.bulkCreate(topics);\n// [{ 'topicId': 1, 'title': 'Leadership', 'count': 214 }, \n// { 'topicId': 2, 'title': 'Management', 'count': 51 }]\n```\n\n**SyncAPI.js** (2nd run) - creates duplicates\n\n```\nconst url = 'https://....'; // the remote service\nconst topics = await this.http.get(url); // note how the title is the same with updated counts\n// [{ 'title': 'Leadership', 'count': 226 }, \n// { 'title': 'Management', 'count': 54 }]\n\nawait Topic.bulkCreate(topics); // the old, inserted topics remaining, with new entries appended\n// [{ 'topicId': 1, 'title': 'Leadership', 'count': 214 }, \n// { 'topicId': 2, 'title': 'Management', 'count': 51 },\n// [{ 'topicId': 3, 'title': 'Leadership', 'count': 226 }, \n// { 'topicId': 4, 'title': 'Management', 'count': 54 }\n```\n\nI see the sequelize documentation here (https://sequelize.org/master/class/lib/model.js~Model.html#static-method-bulkCreate) which says I can specify a 'ignoreDuplicates' option, but it only works by comparing the primary keys (\"Ignore duplicate values for primary keys).\n\nI'm looking for some way in the bulkCreate() method to specify 'ignoreDuplicates' with my custom key 'title' and then use 'updateOnDuplicate' to update the count.\n\n========================================\n\nTop Answer:\nMy final solution was to actually take the title and convert it into a hash, and then store that as a 'topic_uid' in my database as as UUID.\n\n========================================\n\nCode:\n```text\nconst database = require('../../shared/database'); // shared db connection. This works\nconst {DataTypes, Model} = require('sequelize');\n\nclass Topic extends Model { }\n\nTopic.init({\n  topicId: {\n    type: DataTypes.INTEGER,\n    primaryKey: true,\n    autoIncrement: true,\n    defaultValue: undefined,\n  },\n  title: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  },\n  count: {\n    type: DataTypes.INTEGER,\n    allowNull: true,\n  },\n}, {\n  sequelize: database, \n});\n\nmodule.exports = Topic;\n```\n\n```text\nconst url = 'https://....'; // the remote service\nconst topics = await this.http.get(url); // simple example of getting the new data\n// [{ 'title': 'Leadership', 'count': 214 }, \n// { 'title': 'Management', 'count': 51 }]\n\nawait Topic.bulkCreate(topics);\n// [{ 'topicId': 1, 'title': 'Leadership', 'count': 214 }, \n// { 'topicId': 2, 'title': 'Management', 'count': 51 }]\n```\n\n```text\nconst url = 'https://....'; // the remote service\nconst topics = await this.http.get(url); // note how the title is the same with updated counts\n// [{ 'title': 'Leadership', 'count': 226 }, \n// { 'title': 'Management', 'count': 54 }]\n\nawait Topic.bulkCreate(topics); // the old, inserted topics remaining, with new entries appended\n// [{ 'topicId': 1, 'title': 'Leadership', 'count': 214 }, \n// { 'topicId': 2, 'title': 'Management', 'count': 51 },\n// [{ 'topicId': 3, 'title': 'Leadership', 'count': 226 }, \n// { 'topicId': 4, 'title': 'Management', 'count': 54 }\n```\n\n```text\nconst database = require('../../shared/database'); // shared db connection. This works\nconst {DataTypes, Model} = require('sequelize');\n\nclass Topic extends Model { }\n\nTopic.init({\n  topicId: {\n    type: DataTypes.INTEGER,\n    primaryKey: true,\n    autoIncrement: true,\n    defaultValue: undefined,\n  },\n  title: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  },\n  count: {\n    type: DataTypes.INTEGER,\n    allowNull: true,\n  },\n}, {\n  sequelize: database, \n  indexes: [{\n             unique: true,\n             fields: ['title'] // you can use multiple columns as well here\n           }]\n});\n\nmodule.exports = Topic;\n```\n\n```text\nawait Topic.bulkCreate(topics, {ignoreDuplicates: true);\n```\n\n========================================\n\nComments:\n- Very good answer, thank you! What if I don't want to add a Unique Key, and my Primary Key is UUID?\n- @AreUMinee check this out :) stackoverflow.com/questions/50414899/&hellip;\n- I don't even remember what I was looking for but thanks! :)","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":183,"estimatedTokens":1424}}907{"id":"stack-74231128","source":"stackoverflow","questionId":74231128,"title":"Error running sequelize seeder on typescript based setup","tags":["node.js","typescript","sequelize.js","database-migration","sequelize-cli"],"text":"Title: Error running sequelize seeder on typescript based setup\nTags: node.js, typescript, sequelize.js, database-migration, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI want to use sequelize seeders and migrations on my express api and currently all the models are written in typescript using sequelize-typescript\n\nI tried adding my first seeder file using typescript and I get an error when running it\n\n**20221028050116-feeds.ts** seeder file\n\n```\n'use strict';\n\nimport { QueryInterface } from 'sequelize';\n\nconst feedTypes = [\n { id: 'b871a455-fddb-414c-ac02-2cdee07fa671', name: 'crypto' },\n { id: '68b15f90-19ca-4971-a2c6-67e66dc88f77', name: 'general' },\n];\nconst feeds = [\n {\n id: 1,\n name: 'cointelegraph',\n url: 'https://cointelegraph.com/rss',\n feed_type_id: 'b871a455-fddb-414c-ac02-2cdee07fa671',\n },\n];\n\nmodule.exports = {\n up: (queryInterface: QueryInterface): Promise =>\n queryInterface.sequelize.transaction(async (transaction) => {\n // here go all migration changes\n return Promise.all([\n queryInterface.bulkInsert('feed_types', feedTypes, { transaction }),\n queryInterface.bulkInsert('feeds', feeds, { transaction }),\n ]);\n }),\n\n down: (queryInterface: QueryInterface): Promise =>\n queryInterface.sequelize.transaction(async (transaction) => {\n // here go all migration undo changes\n return Promise.all([\n queryInterface.bulkDelete('feed_types', null, { transaction }),\n queryInterface.bulkDelete('feeds', null, { transaction }),\n ]);\n }),\n};\n```\n\nI added 2 commands in my package.json file to seed\n\n```\n\"apply-seeders\": \"sequelize-cli db:seed:all\",\n\"revert-seeders\": \"sequelize-cli db:seed:undo:all\",\n```\n\nWhen I execute 'npm run apply-seeders', it gives me the following error\n\n```\nSequelize CLI [Node: 16.17.0, CLI: 6.5.1, ORM: 6.23.2]\n\nERROR: Cannot find \"/Users/vr/Desktop/code/ch/api/src/config/index.js\". Have you run \"sequelize init\"?\n\nERROR: Cannot read properties of undefined (reading 'detail')\nsequelize-cli db:seed:all\n\nRun every seeder\n\nOptions:\n --version Show version number [boolean]\n --help Show help [boolean]\n --env The environment to run the command in [string] [default: \"development\"]\n --config The path to the config file [string]\n --options-path The path to a JSON file with additional options [string]\n --migrations-path The path to the migrations folder [string] [default: \"migrations\"]\n --seeders-path The path to the seeders folder [string] [default: \"seeders\"]\n --models-path The path to the models folder [string] [default: \"models\"]\n --url The database connection string to use. Alternative to using --config files [string]\n --debug When available show various debug information [boolean] [default: false]\n\nTypeError: Cannot read properties of undefined (reading 'detail')\n at Object.error (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/helpers/view-helper.js:43:24)\n at /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:48:39\n at async Object.exports.handler (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:24:7)\nvr@vivz api %\n```\n\nI did some digging into it and it turns out that you cannot directly run typescript files with sequelize as per THIS ANSWER here\n\nI modified my .sequelizerc file to run stuff from dist folder instead of src\n\n**.sequelizerc** file\n\n```\nrequire(\"@babel/register\");\n\nconst path = require('path');\n\nmodule.exports = {\n config: path.resolve('dist', 'config', 'index.js'),\n 'migrations-path': path.resolve('dist', 'data', 'migrations'),\n 'models-path': path.resolve('dist', 'data', 'models'),\n 'seeders-path': path.resolve('dist', 'data', 'seeders'),\n};\n```\n\nRunning this now gives me a different type of error\n\n```\nSequelize CLI [Node: 16.17.0, CLI: 6.5.1, ORM: 6.23.2]\n\nERROR: Error reading \"dist/config/index.js\". Error: Error: Cannot find module 'babel-plugin-module-resolver'\nRequire stack:\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/core/lib/config/files/plugins.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/core/lib/config/files/index.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/core/lib/index.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/worker/babel-core.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/worker/handle-message.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/worker-client.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/node.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/nodeWrapper.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/index.js\n- /Users/vr/Desktop/code/ch/api/.sequelizerc\n- /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/core/yargs.js\n- /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/sequelize\n\nERROR: Cannot read properties of undefined (reading 'detail')\nsequelize-cli db:seed:all\n\nRun every seeder\n\nOptions:\n --version Show version number [boolean]\n --help Show help [boolean]\n --env The environment to run the command in [string] [default: \"development\"]\n --config The path to the config file [string]\n --options-path The path to a JSON file with additional options [string]\n --migrations-path The path to the migrations folder [string] [default: \"migrations\"]\n --seeders-path The path to the seeders folder [string] [default: \"seeders\"]\n --models-path The path to the models folder [string] [default: \"models\"]\n --url The database connection string to use. Alternative to using --config files [string]\n --debug When available show various debug information [boolean] [default: false]\n\nTypeError: Cannot read properties of undefined (reading 'detail')\n at Object.error (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/helpers/view-helper.js:43:24)\n at /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:48:39\n at async Object.exports.handler (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:24:7)\n```\n\nThis would be my **tsconfig.json** file\n\n```\n{\n \"compilerOptions\": {\n \"lib\": [\"es2020\"],\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"target\": \"es2020\",\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"noImplicitAny\": false,\n \"outDir\": \"dist\",\n \"experimentalDecorators\": true,\n \"emitDecoratorMetadata\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"server/*\": [\"src/server/*\"],\n \"tests/*\": [\"src/tests/*\"],\n \"data/*\": [\"src/data/*\"],\n \"config\": [\"src/config\"],\n }\n }\n}\n```\n\nCan someone kindly tell me how I can run my seeder and migration files using typescript\n\n**UPDATE 1**\n\nI installed the babel-plugin-module-resolver. Now it gives me a new error. This error doesnt show up if you run the ts files normally. When I console.log I can see all the values but when the program is run, that dialect simply doesnt load it seems from the env file\n\n```\nLoaded configuration file \"dist/config/index.js\".\n\nERROR: Dialect needs to be explicitly supplied as of v4.0.0\n\nERROR: Cannot read properties of undefined (reading 'detail')\n```\n\n**UPDATE 2**\n\nI hardcoded the dialect postgres into the config file and it still gives me the error. I even verified that the transpiled js file has the postgres dialect specified\n\n========================================\n\nTop Answer:\nI had the same issue when running sequelize command, which was installed globally. It was a strange issue because on other projects they were fine (not TypeScript projects).\n\nThis time I tried installing sequelize locally and run them with \"npx\". And it's working great again. For example:\n\n```\nnpm install --save-dev sequelize\nnpx sequelize db:migrate\nnpx sequelize db:migrate:status\n```\n\nMy setup was node 18.10, sequelize 6.25.5, pg 8.8.0.\n\n========================================\n\nCode:\n```text\n'use strict';\n\nimport { QueryInterface } from 'sequelize';\n\nconst feedTypes = [\n  { id: 'b871a455-fddb-414c-ac02-2cdee07fa671', name: 'crypto' },\n  { id: '68b15f90-19ca-4971-a2c6-67e66dc88f77', name: 'general' },\n];\nconst feeds = [\n  {\n    id: 1,\n    name: 'cointelegraph',\n    url: 'https://cointelegraph.com/rss',\n    feed_type_id: 'b871a455-fddb-414c-ac02-2cdee07fa671',\n  },\n];\n\nmodule.exports = {\n  up: (queryInterface: QueryInterface): Promise<number | object> =>\n    queryInterface.sequelize.transaction(async (transaction) => {\n      // here go all migration changes\n      return Promise.all([\n        queryInterface.bulkInsert('feed_types', feedTypes, { transaction }),\n        queryInterface.bulkInsert('feeds', feeds, { transaction }),\n      ]);\n    }),\n\n  down: (queryInterface: QueryInterface): Promise<object | object> =>\n    queryInterface.sequelize.transaction(async (transaction) => {\n      // here go all migration undo changes\n      return Promise.all([\n        queryInterface.bulkDelete('feed_types', null, { transaction }),\n        queryInterface.bulkDelete('feeds', null, { transaction }),\n      ]);\n    }),\n};\n```\n\n```text\n\"apply-seeders\": \"sequelize-cli db:seed:all\",\n\"revert-seeders\": \"sequelize-cli db:seed:undo:all\",\n```\n\n```text\nSequelize CLI [Node: 16.17.0, CLI: 6.5.1, ORM: 6.23.2]\n\n\nERROR: Cannot find \"/Users/vr/Desktop/code/ch/api/src/config/index.js\". Have you run \"sequelize init\"?\n\nERROR: Cannot read properties of undefined (reading 'detail')\nsequelize-cli db:seed:all\n\nRun every seeder\n\nOptions:\n  --version          Show version number                                                                                                                                                                  [boolean]\n  --help             Show help                                                                                                                                                                            [boolean]\n  --env              The environment to run the command in                                                                                                                        [string] [default: \"development\"]\n  --config           The path to the config file                                                                                                                                                           [string]\n  --options-path     The path to a JSON file with additional options                                                                                                                                       [string]\n  --migrations-path  The path to the migrations folder                                                                                                                             [string] [default: \"migrations\"]\n  --seeders-path     The path to the seeders folder                                                                                                                                   [string] [default: \"seeders\"]\n  --models-path      The path to the models folder                                                                                                                                     [string] [default: \"models\"]\n  --url              The database connection string to use. Alternative to using --config files                                                                                                            [string]\n  --debug            When available show various debug information                                                                                                                       [boolean] [default: false]\n\nTypeError: Cannot read properties of undefined (reading 'detail')\n    at Object.error (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/helpers/view-helper.js:43:24)\n    at /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:48:39\n    at async Object.exports.handler (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:24:7)\nvr@vivz api %\n```\n\n```text\nrequire(\"@babel/register\");\n\nconst path = require('path');\n\nmodule.exports = {\n  config: path.resolve('dist', 'config', 'index.js'),\n  'migrations-path': path.resolve('dist', 'data', 'migrations'),\n  'models-path':     path.resolve('dist', 'data', 'models'),\n  'seeders-path':    path.resolve('dist', 'data', 'seeders'),\n};\n```\n\n```text\nSequelize CLI [Node: 16.17.0, CLI: 6.5.1, ORM: 6.23.2]\n\n\nERROR: Error reading \"dist/config/index.js\". Error: Error: Cannot find module 'babel-plugin-module-resolver'\nRequire stack:\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/core/lib/config/files/plugins.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/core/lib/config/files/index.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/core/lib/index.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/worker/babel-core.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/worker/handle-message.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/worker-client.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/node.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/nodeWrapper.js\n- /Users/vr/Desktop/code/ch/api/node_modules/@babel/register/lib/index.js\n- /Users/vr/Desktop/code/ch/api/.sequelizerc\n- /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/core/yargs.js\n- /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/sequelize\n\nERROR: Cannot read properties of undefined (reading 'detail')\nsequelize-cli db:seed:all\n\nRun every seeder\n\nOptions:\n  --version          Show version number                                                                                                                                                                  [boolean]\n  --help             Show help                                                                                                                                                                            [boolean]\n  --env              The environment to run the command in                                                                                                                        [string] [default: \"development\"]\n  --config           The path to the config file                                                                                                                                                           [string]\n  --options-path     The path to a JSON file with additional options                                                                                                                                       [string]\n  --migrations-path  The path to the migrations folder                                                                                                                             [string] [default: \"migrations\"]\n  --seeders-path     The path to the seeders folder                                                                                                                                   [string] [default: \"seeders\"]\n  --models-path      The path to the models folder                                                                                                                                     [string] [default: \"models\"]\n  --url              The database connection string to use. Alternative to using --config files                                                                                                            [string]\n  --debug            When available show various debug information                                                                                                                       [boolean] [default: false]\n\nTypeError: Cannot read properties of undefined (reading 'detail')\n    at Object.error (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/helpers/view-helper.js:43:24)\n    at /Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:48:39\n    at async Object.exports.handler (/Users/vr/Desktop/code/ch/api/node_modules/sequelize-cli/lib/commands/seed.js:24:7)\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"lib\": [\"es2020\"],\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\",\n    \"target\": \"es2020\",\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noImplicitAny\": false,\n    \"outDir\": \"dist\",\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true,\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"server/*\": [\"src/server/*\"],\n      \"tests/*\": [\"src/tests/*\"],\n      \"data/*\": [\"src/data/*\"],\n      \"config\": [\"src/config\"],\n    }\n  }\n}\n```\n\n```text\nLoaded configuration file \"dist/config/index.js\".\n\nERROR: Dialect needs to be explicitly supplied as of v4.0.0\n\nERROR: Cannot read properties of undefined (reading 'detail')\n```\n\n```text\nrequire(\"@babel/register\");\n\nconst path = require('path');\n\nmodule.exports = {\n  config: path.resolve('dist', 'config', 'index.js'),\n  'migrations-path': path.resolve('dist', 'data', 'migrations'),\n  'models-path':     path.resolve('dist', 'data', 'models'),\n  'seeders-path':    path.resolve('dist', 'data', 'seeders'),\n};\n```\n\n```text\nconst config: any = {\n  // if we are running tests we use an in memory db with sqlite\n  dialect: process.env.DB_DIALECT,\n\n  username: process.env.POSTGRES_USER,\n  password: process.env.POSTGRES_PASSWORD,\n  database: process.env.POSTGRES_DB,\n  host: process.env.POSTGRES_HOST,\n  port: Number(process.env.POSTGRES_PORT),\n  define: {\n    underscored: true,\n  },\n  logging: false,\n};\n\nmodule.exports = config;\n```\n\n```text\nimport { QueryInterface } from 'sequelize';\nimport { feedTypes, feeds } from './fixtures';\n\nconst down = (queryInterface: QueryInterface): Promise<object | object> =>\n  queryInterface.sequelize.transaction(async (transaction) => {\n    // here go all migration undo changes\n    return Promise.all([\n      queryInterface.bulkDelete('feed_types', null, { transaction }),\n      queryInterface.bulkDelete('feeds', null, { transaction }),\n    ]);\n  });\n\nconst up = (queryInterface: QueryInterface): Promise<number | object> =>\n  queryInterface.sequelize.transaction(async (transaction) => {\n    // here go all migration changes\n    return Promise.all([\n      queryInterface.bulkInsert('feed_types', feedTypes, {\n        transaction,\n        // @ts-ignore\n        ignoreDuplicates: true,\n      }),\n      queryInterface.bulkInsert('feeds', feeds, {\n        transaction,\n        // @ts-ignore\n        ignoreDuplicates: true,\n      }),\n      queryInterface.sequelize.query(\n        `SELECT setval('feeds_id_seq', (SELECT MAX(id) FROM feeds))`,\n        { transaction },\n      ),\n    ]);\n  });\n\nexport { down, up };\n```\n\n```text\nnpx sequelize-cli seed:generate --name feeds\n npx sequelize-cli seed:generate --name tag_rules\n npx sequelize-cli seed:generate --name users\n```\n\n```text\nnpm i --save-dev babel-plugin-module-resolver\n```\n\n```text\n\"apply-seeders\": \"node -r dotenv-flow/config ./node_modules/.bin/sequelize db:seed:all\",\n\"revert-seeders\": \"node -r dotenv-flow/config ./node_modules/.bin/sequelize db:seed:undo:all\",\n```\n\n```text\n.sequelizerc\n```\n\n```text\ndist\n```\n\n```text\nnpm install --save-dev sequelize\nnpx sequelize db:migrate\nnpx sequelize db:migrate:status\n```\n\n========================================\n\nComments:\n- did you solved it ?\n- @Gagantous yes I did, it worked at a rough glance in a separate demo I created just for this but I am yet to integrate it into the main application. I will update the answer as soon as I get it running on the main one\n- @Gagantous updated my answer, hopefully that fixes the problem on your side","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":479,"estimatedTokens":4859}}908{"id":"stack-55273091","source":"stackoverflow","questionId":55273091,"title":"Why use the uppercase key when creating association model in Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: Why use the uppercase key when creating association model in Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two model User and Post, defined the associated model as below:\n\n```\nPost.belongsTo(models.User)\n```\n\nIt means Post model belongs to User as well as User has many Post. So the posts table in database must have the key userId for this association.\n\nI create the Post assigned to user using this code:\n\n```\nPost.create({\n UserId: 1,\n})\n```\n\nIt would insert the right data to database.\n\nBut It's not work as I change the code:\n\n```\nPost.create({\n userId: 1,\n})\n```\n\nWhy the model use the uppercase UserId instead of userId ?\n\n========================================\n\nCode:\n```text\nPost.belongsTo(models.User)\n```\n\n```text\nPost.create({\n    UserId: 1,\n})\n```\n\n```text\nPost.create({\n    userId: 1,\n})\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const Post = sequelize.define('Post', {\n    //\n    userId: { //this is how you are going to use it on sequelize\n      field: 'user_id', // this is how is goig to save it on the db, underscore for example\n      type: DataTypes.DATE\n    },\n  });\n\n  Post.associate = (models) => {\n    Post.belongsTo(models.User, { as: 'User', foreignKey: 'user_id' });\n  };\n\n  return Post;\n};\n```\n\n```text\nId\n```\n\n========================================\n\nComments:\n- For me I was struggling until I realized I had to add the `foreignKey: 'user_id'` to both the belongsTo AND the hasMany in my case. Hope this helps!\n- The whole documentation does use lowercase names for columns and then the lib itself creates uppercase names for foreign keys. Isn't that a little bit strange?","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":79,"estimatedTokens":416}}909{"id":"stack-55682902","source":"stackoverflow","questionId":55682902,"title":"Node Js sequelize select query by month","tags":["node.js","select","orm","sequelize.js"],"text":"Title: Node Js sequelize select query by month\nTags: node.js, select, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAm new in `Node Js`, In my `Node Js` project am using `sequelize ORM` with `MySql` database.\n\nThis is my query i want to write select query by month.\n\nThis is my query `SELECT * FROM cubbersclosure WHERE MONTH(fromDate) = '04'`\n\nHere `fromDate` field type is `date`\n\nhttps://i.sstatic.net/U5HhY.png \n\nThis my code:\n\n```\nvar fromDate = '2019-04-01'\nvar fromDateMonth = new Date(fromDate);\nvar fromMonth = (fromDateMonth.getMonth()+ 1) { \n res.send(closureData);\n}).catch(error=>{\n res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});\n});\n```\n\n Here `fromMonth` get only month from date, so i want to write code select query by month.\n\n========================================\n\nTop Answer:\nfor those of you looking for postgres, this is a somewhat hacky way to make this work (make sure to unit test this):\n\n```\nconst results = await models.users.findAll({\n where: this.app.sequelize.fn('EXTRACT(MONTH from \"createdAt\") =', 3)\n});\n```\n\nyou can also take this a step further and query multiple attributes like so:\n\n```\nconst results = await models.table.findAll({\n where: {\n [Op.and] : [\n this.app.sequelize.fn('EXTRACT(MONTH from \"createdAt\") =', 3),\n this.app.sequelize.fn('EXTRACT(day from \"createdAt\") =', 3),\n ]\n }\n});\n```\n\n========================================\n\nCode:\n```text\nvar fromDate = '2019-04-01'\nvar fromDateMonth = new Date(fromDate);\nvar fromMonth = (fromDateMonth.getMonth()+ 1) < 10 ? '0' + (fromDateMonth.getMonth()+1) : (fromDateMonth.getMonth()+1);\n\nCubbersClosure.findAll({\n    where:{\n        // select query with Month (04)... //fromMonth\n    }\n}).then(closureData=>{        \n    res.send(closureData);\n}).catch(error=>{\n    res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});\n});\n```\n\n```text\nNode Js\n```\n\n```text\nNode Js\n```\n\n```text\nsequelize ORM\n```\n\n```text\nMySql\n```\n\n```text\nSELECT * FROM cubbersclosure WHERE MONTH(fromDate) = '04'\n```\n\n```text\nfromDate\n```\n\n```text\ndate\n```\n\n```text\nfromMonth\n```\n\n```text\nwhere: {\n  sequelize.where(sequelize.fn(\"month\", sequelize.col(\"fromDate\")), fromMonth)\n}\n```\n\n```text\nconst results = await models.users.findAll({\n   where: this.app.sequelize.fn('EXTRACT(MONTH from \"createdAt\") =', 3)\n});\n```\n\n```text\nconst results = await models.table.findAll({\n   where: {\n     [Op.and] : [\n        this.app.sequelize.fn('EXTRACT(MONTH from \"createdAt\") =', 3),\n        this.app.sequelize.fn('EXTRACT(day from \"createdAt\") =', 3),\n     ]\n   }\n});\n```\n\n========================================\n\nComments:\n- I got error like `D:\\my_project\\choose_cubby\\internal-test\\app\\controller\\cubb&zwnj;&#8203;er\\cubbers.controlle&zwnj;&#8203;r.js:907 sequelize.where()`\n- So change the code like this `where: { $and: sequelize.where(sequelize.fn(\"monthc\", sequelize.col(\"fromDate\")), fromMonth) }` but again it shows error\n- what about replace monthc to month? there was typo\n- This is error `FUNCTION choose_cubby.monthc does not exist`","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":134,"estimatedTokens":776}}910{"id":"stack-60321175","source":"stackoverflow","questionId":60321175,"title":"Github Actions - Unhandled rejection SequelizeConnectionError: no PostgreSQL user name specified in startup packet","tags":["node.js","postgresql","sequelize.js","github-actions"],"text":"Title: Github Actions - Unhandled rejection SequelizeConnectionError: no PostgreSQL user name specified in startup packet\nTags: node.js, postgresql, sequelize.js, github-actions\nSource: Stack Overflow\n\nQuestion:\nI set up a Github Actions for CI/CD but I'm struggling with database connection.\n\nAs sequelize allows to specify another database url ( using \"use_env_variable\" options ), I updated my config like this :\n\n```\n{\n \"test\": {\n \"dialect\": \"postgres\",\n \"schema\": \"exercises_library\",\n \"logging\": false,\n \"use_env_variable\": \"DATABASE_URL\"\n },\n \"production\": {\n \"dialect\": \"postgres\",\n \"schema\": \"exercises_library\",\n \"logging\": false,\n \"use_env_variable\": \"DATABASE_URL\"\n }\n}\n```\n\nSo I wrote my workflow in Github Actions :\n\n```\nname: Source Code CI/CD\n\non:\n push:\n branches:\n - master\n pull_request:\n branches:\n - master\n\njobs:\n ci:\n runs-on: ubuntu-latest\n container:\n image: node:12\n services:\n# More explanation about that here :\n# https://github.com/actions/example-services/blob/master/.github/workflows/postgres-service.yml\n postgres:\n image: postgres:12-alpine\n env:\n POSTGRES_USER: postgres\n POSTGRES_PASSWORD: jy95\n POSTGRES_DB: sourcecode\n ports: [\"5432:5432\"]\n options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5\n env:\n POSTGRES_USER: postgres\n POSTGRES_PASSWORD: jy95\n POSTGRES_DB: sourcecode\n # use postgres for the host here because we have specified a container for the job.\n # If we were running the job on the VM this would be localhost\n POSTGRES_HOST: postgres\n steps:\n - uses: actions/checkout@v2\n - name: Set DB Port\n env:\n POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }}\n run: |\n echo \"::set-env name=POSTGRES_PORT::$POSTGRES_PORT\"\n - name: Install\n run: |\n npm install -g npm@latest\n npm install -g codecov\n npm ci\n - name: Tests\n env:\n DATABASE_URL: '${{ env.POSTGRES_HOST }}://${{ env.POSTGRES_USER}}:${{env.POSTGRES_PASSWORD}}:${{env.POSTGRES_PORT}}/${{env.POSTGRES_DB}}'\n run: |\n npm test\n - name: Upload code coverage\n run: |\n npx codecov\n cd:\n runs-on: ubuntu-latest\n needs: ci\n\n steps:\n - uses: actions/checkout@v2\n - name: Docker login\n run: docker login -u ${{ secrets.DOCKER_USER }} -p ${{ secrets.DOCKER_PASSWORD }}\n - name: Build\n run: docker build -t sourcecode_api .\n - name: Tags\n run: |\n docker tag sourcecode_api ${{ secrets.DOCKER_USER }}/sourcecode_api:${{ github.sha }}\n docker tag sourcecode_api ${{ secrets.DOCKER_USER }}/sourcecode_api:latest\n - name: Push\n run: |\n docker push ${{ secrets.DOCKER_USER }}/sourcecode_api:${{ github.sha }}\n docker push ${{ secrets.DOCKER_USER }}/sourcecode_api:latest\n```\n\nI got this error in my logs : \n\nhttps://i.sstatic.net/9xW22.png\n\nI saw that env variables are correctly set : \n\nhttps://i.sstatic.net/muvez.png\n\nI have read many ressources ( on Github issues or Stackoverflow) but none solved my problem.\n\nThanks in advance\n\n========================================\n\nCode:\n```text\n{\n  \"test\": {\n    \"dialect\": \"postgres\",\n    \"schema\": \"exercises_library\",\n    \"logging\": false,\n    \"use_env_variable\": \"DATABASE_URL\"\n  },\n  \"production\": {\n    \"dialect\": \"postgres\",\n    \"schema\": \"exercises_library\",\n    \"logging\": false,\n    \"use_env_variable\": \"DATABASE_URL\"\n  }\n}\n```\n\n```text\nname: Source Code CI/CD\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\njobs:\n  ci:\n    runs-on: ubuntu-latest\n    container:\n      image: node:12\n    services:\n# More explanation about that here :\n# https://github.com/actions/example-services/blob/master/.github/workflows/postgres-service.yml\n      postgres:\n        image: postgres:12-alpine\n        env:\n          POSTGRES_USER: postgres\n          POSTGRES_PASSWORD: jy95\n          POSTGRES_DB: sourcecode\n        ports: [\"5432:5432\"]\n        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5\n    env:\n      POSTGRES_USER: postgres\n      POSTGRES_PASSWORD: jy95\n      POSTGRES_DB: sourcecode\n      # use postgres for the host here because we have specified a container for the job.\n      # If we were running the job on the VM this would be localhost\n      POSTGRES_HOST: postgres\n    steps:\n      - uses: actions/checkout@v2\n      - name: Set DB Port\n        env:\n          POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }}\n        run: |\n          echo \"::set-env name=POSTGRES_PORT::$POSTGRES_PORT\"\n      - name: Install\n        run: |\n          npm install -g npm@latest\n          npm install -g codecov\n          npm ci\n      - name: Tests\n        env:\n          DATABASE_URL: '${{ env.POSTGRES_HOST }}://${{ env.POSTGRES_USER}}:${{env.POSTGRES_PASSWORD}}:${{env.POSTGRES_PORT}}/${{env.POSTGRES_DB}}'\n        run: |\n          npm test\n      - name: Upload code coverage\n        run: |\n          npx codecov\n  cd:\n    runs-on: ubuntu-latest\n    needs: ci\n\n    steps:\n      - uses: actions/checkout@v2\n      - name: Docker login\n        run: docker login -u ${{ secrets.DOCKER_USER }} -p ${{ secrets.DOCKER_PASSWORD }}\n      - name: Build\n        run: docker build -t sourcecode_api .\n      - name: Tags\n        run: |\n          docker tag sourcecode_api ${{ secrets.DOCKER_USER }}/sourcecode_api:${{ github.sha }}\n          docker tag sourcecode_api ${{ secrets.DOCKER_USER }}/sourcecode_api:latest\n      - name: Push\n        run: |\n          docker push ${{ secrets.DOCKER_USER }}/sourcecode_api:${{ github.sha }}\n          docker push ${{ secrets.DOCKER_USER }}/sourcecode_api:latest\n```\n\n```text\nDATABASE_URL: 'postgresql://${{ env.POSTGRES_USER }}:${{ env.POSTGRES_PASSWORD }}@${{ env.POSTGRES_HOST }}:${{env.POSTGRES_PORT}}/${{env.POSTGRES_DB}}'\n```\n\n========================================\n\nComments:\n- Please consider hiding your environment variables that shouldn't be exposed to the public (such as a password for a service) by setting them as secrets in your GitHub repository's settings.","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":216,"estimatedTokens":1468}}911{"id":"stack-55269989","source":"stackoverflow","questionId":55269989,"title":"Sequelize - Include all children if any one matches","tags":["mysql","sql","sequelize.js"],"text":"Title: Sequelize - Include all children if any one matches\nTags: mysql, sql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two entities, Post and Tag, I am trying to query for all posts that have any one tag passed to the where clause. In addition, I want to include ALL the tags for the final set of Posts.\n\nThe association is defined as so\n\n```\nPost.belongsToMany(\n models.tag,\n {\n through: 'post_tag'\n }\n );\n```\n\nMy query is like so\n\n```\nmodels.post.findAll({\n limit: 20,\n offset: 0,\n attributes: [\n 'id',\n 'name'\n ],\n include: [{\n model: models.tag,\n attributes: ['name'],\n where: {\n name: {\n [Op.in]: ['tagNameHere']\n }\n }\n }],\n where: [{\n active: {\n [Op.not]: 'False'\n }\n }],\n order: [ ['name', 'ASC'] ]\n})\n```\n\nIt does work, but the included tags array is ONLY that one specified within the Op.in. I want ALL the tags to be included \n\nAny better way of going about it?\n\n========================================\n\nCode:\n```text\nPost.belongsToMany(\n      models.tag,\n      {\n        through: 'post_tag'\n      }\n    );\n```\n\n```text\nmodels.post.findAll({\n    limit: 20,\n    offset: 0,\n    attributes: [\n        'id',\n        'name'\n    ],\n    include: [{\n        model: models.tag,\n        attributes: ['name'],\n        where: {\n            name: {\n                [Op.in]: ['tagNameHere']\n            }\n        }\n    }],\n    where: [{\n      active: {\n        [Op.not]: 'False'\n      }\n    }],\n    order: [ ['name', 'ASC'] ]\n})\n```\n\n```text\nmodels.post.belongsToMany(models.tag, {through: models.postTag, foreignKey: 'post_id'} );\nmodels.tag.belongsToMany (models.post,{through: models.postTag, foreignKey: 'tag_id' });\n\nmodels.post.hasOne(Post, {\n   foreignKey: {name: 'id'},\n   as: 'selfJoin'\n});\n```\n\n```text\nmodels.post.addScope('hasParticularTag',\n{\n   attributes: ['id'],\n   include: [\n     {\n       model: models.tag, \n       through: models.postTag,\n       attributes: [],\n       where: {name: 'TAG-YOU-WANT'}   // your parameter here...\n     }]    \n });\n```\n\n```text\nmodels.post.findAll({    \n   attributes: ['id','name'],\n   include: [\n      { // ALL tags\n        model: models.tag, \n        through: models.postTag,\n        attributes: ['name']\n      },\n      { // SELECTED posts\n        model: models.post.scope('hasParticularTag'),\n        required: true,\n        as: 'selfJoin',   // prevents error \"post isn't related to post\"\n        attributes: []\n      }]\n })\n```\n\n========================================\n\nComments:\n- I added the self join association to Post, and updated the query to have an include on that new self association, which has an include on Tag with a where clause. include: [{ model: models.tag, attributes: ['name'] }, { model: models.post, required: true, as: 'selfJoin', include: [{ model: model.tag, where: { name: { [Op.in]: ['tagNameHere'] } } }] }] But now I have an issue where the limit isn't being applied correctly.\n- What's the problem with LIMIT? It looked OK to me (though you need `attributes['id']` for selfJoin to fix a SQL error)\n- LIMIT works, the SQL it generate looks right as well. However, when there is more than one tag, they get grouped and that's when the limit returned varies.","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":136,"estimatedTokens":788}}912{"id":"stack-52227663","source":"stackoverflow","questionId":52227663,"title":"sequelize : cannot seed association values in DB table","tags":["node.js","orm","sequelize.js"],"text":"Title: sequelize : cannot seed association values in DB table\nTags: node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to seed an association into my db using sequelize, the tables being: Users and Admins. For this I am relying on this answer on the forum. so here is my seed:\n\n```\n'use strict';\nconst bcrypt = require('bcryptjs')\nmodule.exports = {\n up: async (queryInterface, Sequelize) => {\n queryInterface.bulkInsert('Users', [{\n firstName: 'someone',\n lastName: 'awesome',\n email: 'someone@somewhere.com',\n password: bcrypt.hashSync('helloWorld', 8),\n type: 'admin',\n createdAt: new Date(),\n updatedAt: new Date()\n }], {});\n\n const users = await queryInterface.sequelize.query(\n 'SELECT id from Users;'\n );\n\n return await queryInterface.bulkInsert('Admins', [{\n id: users[0].id,\n phone: '+9999999999',\n status: true, createdAt: new Date(),\n updatedAt: new Date()\n }]);\n },\n down: async (queryInterface) => {\n await queryInterface.bulkDelete('Admins', null, {});\n await queryInterface.bulkDelete('Users', null, {});\n }\n};\n```\n\nnow, The data in user table is field up perfectly but the admin table remains empty\n\nEDIT: \n\nI tried to print out the users[0].id with the following code: \n\n```\nconst users = await queryInterface.sequelize.query(\n \"SELECT id from Users\"\n);\n\nconsole.log(users[0].id)\n```\n\nthe output was `undefined`\n\nbut the data was once again fed to the table! I know what is happening here, but don't know how to resolve!\n\nP.S.\nI also added await for the very first method of the up, but this changed nothing..\n\n========================================\n\nTop Answer:\nIt took a while to figure this out, Thank you all.\n\nliterature I referred to:\nthis question\nAND\nthis part of official sequelize documentation\n\nHere is the code that works:\n\n```\n'use strict';\nconst bcrypt = require('bcryptjs');\nconst models = require('../models');\nconst User = models.User;\nmodule.exports = {\n up: async (queryInterface, Sequelize) => {\n queryInterface.bulkInsert('Users', [{\n firstName: 'aname',\n lastName: 'alastname',\n email: 'someemail@somewhere.com',\n password: bcrypt.hashSync('poochies', 8),\n type: 'admin',\n createdAt: new Date(),\n updatedAt: new Date()\n }], {});\n\n const user = await User.findOne({\n where: {\n type: 'admin',\n email: 'someemail@somewhere.com'\n },\n });\n\n return await queryInterface.bulkInsert('Admins', [{\n id: user.id,\n phone: '+999999999999',\n status: true,\n createdAt: new Date(),\n updatedAt: new Date()\n }], {});\n },\n down: async (queryInterface) => {\n await queryInterface.bulkDelete('Admins', null, {});\n await queryInterface.bulkDelete('Users', null, {});\n }\n};\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nconst bcrypt = require('bcryptjs')\nmodule.exports = {\n    up: async (queryInterface, Sequelize) => {\n        queryInterface.bulkInsert('Users', [{\n            firstName: 'someone',\n            lastName: 'awesome',\n            email: 'someone@somewhere.com',\n            password: bcrypt.hashSync('helloWorld', 8),\n            type: 'admin',\n            createdAt: new Date(),\n            updatedAt: new Date()\n        }], {});\n\n        const users = await queryInterface.sequelize.query(\n            'SELECT id from Users;'\n        );\n\n        return await queryInterface.bulkInsert('Admins', [{\n            id: users[0].id,\n            phone: '+9999999999',\n            status: true, createdAt: new Date(),\n            updatedAt: new Date()\n        }]);\n    },\n    down: async (queryInterface) => {\n        await queryInterface.bulkDelete('Admins', null, {});\n        await queryInterface.bulkDelete('Users', null, {});\n    }\n};\n```\n\n```text\nconst users = await queryInterface.sequelize.query(\n    \"SELECT id from Users\"\n);\n\nconsole.log(users[0].id)\n```\n\n```text\nundefined\n```\n\n```text\nconst users = await queryInterface.sequelize.query(\n   'SELECT id from Users;'\n);\n```\n\n```text\nawait queryInterface.bulkInsert('Users', [{ // ...\n```\n\n```text\nusers[0].id\n```\n\n```text\nawait\n```\n\n```text\nqueryInterface.bulkInsert\n```\n\n```text\n'use strict';\nconst bcrypt = require('bcryptjs');\nconst models = require('../models');\nconst User = models.User;\nmodule.exports = {\n    up: async (queryInterface, Sequelize) => {\n        queryInterface.bulkInsert('Users', [{\n            firstName: 'aname',\n            lastName: 'alastname',\n            email: 'someemail@somewhere.com',\n            password: bcrypt.hashSync('poochies', 8),\n            type: 'admin',\n            createdAt: new Date(),\n            updatedAt: new Date()\n        }], {});\n\n        const user = await User.findOne({\n            where: {\n                type: 'admin',\n                email: 'someemail@somewhere.com'\n            },\n        });\n\n        return await queryInterface.bulkInsert('Admins', [{\n            id: user.id,\n            phone: '+999999999999',\n            status: true,\n            createdAt: new Date(),\n            updatedAt: new Date()\n        }], {});\n    },\n    down: async (queryInterface) => {\n        await queryInterface.bulkDelete('Admins', null, {});\n        await queryInterface.bulkDelete('Users', null, {});\n    }\n};\n```\n\n```js\n'use strict';\nconst bcrypt = require('bcryptjs');\n\nmodule.exports = {\n    up: async (queryInterface, Sequelize) => {\n        const userId = await queryInterface.bulkInsert('Users', [{\n            firstName: 'someone',\n            lastName: 'awesome',\n            email: 'someone@somewhere.com',\n            password: bcrypt.hashSync('helloWorld', 8),\n            type: 'admin',\n            createdAt: new Date(),\n            updatedAt: new Date()\n        }], {});\n\n        return queryInterface.bulkInsert('Admins', [{\n            id: userId,\n            phone: '+9999999999',\n            status: true,\n            createdAt: new Date(),\n            updatedAt: new Date(),\n        }]);\n    },\n    down: async (queryInterface) => {\n        await queryInterface.bulkDelete('Admins', null, {});\n        await queryInterface.bulkDelete('Users', null, {});\n    }\n};\n```\n\n```text\nawait\n```\n\n```text\nbulkInsert\n```\n\n```text\nuserId\n```\n\n```text\nbulkInsert\n```\n\n```text\nlet ids = await queryInterface.bulkInsert('Users', [{\n                    firstName: 'someone',\n                    lastName: 'awesome',\n                    email: 'someone@somewhere.com',\n                    password: bcrypt.hashSync('helloWorld', 8),\n                    type: 'admin',\n                    createdAt: new Date(),\n                    updatedAt: new Date()\n                }], { returning: ['id'] });\n\nlet adminId = ids[0];\n\n//Insert admin\n```\n\n========================================\n\nComments:\n- Sorry, I was still edditing the soultion. Using `await` on the first `bulkInsert` should do it!\n- I did that, yet, the cli is responding with : `ERROR: Column 'id' cannot be null` ! but the data has been inserted into Users table\n- Maybe you could log the contents of `users` to see what that query is returning\n- You are almost there, with some more debugging and coding, your code will be doing what you expect. My hint is this: check the contents of `users`, not only `users[0].id`, good luck!\n- found the answer and posted it below on this thread! Thanks a lot\n- Be aware that the \"returning\" option is only available with Postgres SQL.","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":293,"estimatedTokens":1808}}913{"id":"stack-57863669","source":"stackoverflow","questionId":57863669,"title":"ReactJS and Node.JS [JSON.parse: unexpected character at line 1 column 1 of the JSON data]","tags":["javascript","node.js","json","reactjs","sequelize.js"],"text":"Title: ReactJS and Node.JS [JSON.parse: unexpected character at line 1 column 1 of the JSON data]\nTags: javascript, node.js, json, reactjs, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm getting struggle with this code, so I need a third eye on this to find a solution.\n\nI'm developing a ReactJS app with a REST API with Node.JS (Express), and I'm getting this error:\n\n SyntaxError: \"JSON.parse: unexpected character at line 1 column 1 of the JSON data\"\n\nI'm using Sequelize ORM to work with Models and Database in Node.JS.\nI'm also using CORS module for Node.JS.\n\nThis implementation works fine.\n\n```\n// Node.js Route for login\nconst router = require('express').Router();\nconst User = require('user');\nrouter.post(\"/login\", async (req, res) => {\n try {\n await User.findOne({\n where: {\n email: req.body.email,\n password: req.body.password,\n }\n }).then((user) => {\n if (!user) {\n return res.send({message: \"Login error!\"});\n } else {\n const userData = {id: user.id, email: user.email};\n res.send({\"user\": userData});\n }\n }).catch((err) => {\n return res.send(err);\n });\n } catch (err) {\n return res.send(err);\n }\n});\n```\n\n```\n// ReactJS for login\nloginFunction(e, data) {\n e.preventDefault();\n fetch('http://localhost:4500/login', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(json => {\n this.setState({'user': json['user']});\n })\n .catch((err) => {\n console.log(err);\n this.setState({errors: \"Login error\"})\n });\n}\n```\n\nOn the other hand, this implementation do not work properly and throws the `SyntaxError` above:\n\n```\n// Node.JS for Posts\nconst router = require('express').Router();\nconst Post = require('post');\nrouter.get(\"/posts\", async (req, res) => {\n try {\n await Post.findAndCountAll()\n .then((posts) => {\n res.send({\"posts\": posts});\n }).catch((err) => {\n return res.send(err);\n });\n } catch (err) {\n return res.send(err);\n }\n});\n```\n\n```\n// ReactJS for Posts\npostsFunction() {\n fetch('http://localhost:4500/posts', {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n .then(response => response.json())\n .then(json => {\n this.setState({'posts': json.posts.rows});\n })\n .catch((err) => {\n console.log(err);\n this.setState({errors: \"Posts error.\"})\n });\n }\n```\n\nAs you can see both implementation have little differences, What am I missing?\n\nPS: When I test the 2nd implementation on Postman, data is retrieving successfully.\n\n========================================\n\nTop Answer:\ntry removing headers when using GET method\n\n```\nheaders: {\n 'Content-Type': 'application/json'\n}\n```\n\n========================================\n\nCode:\n```text\n// Node.js Route for login\nconst router = require('express').Router();\nconst User = require('user');\nrouter.post(\"/login\", async (req, res) => {\n    try {\n        await User.findOne({\n            where: {\n                email: req.body.email,\n                password: req.body.password,\n            }\n        }).then((user) => {\n            if (!user) {\n                return res.send({message: \"Login error!\"});\n            } else {\n                const userData = {id: user.id, email: user.email};\n                res.send({\"user\": userData});\n            }\n        }).catch((err) => {\n            return res.send(err);\n        });\n    } catch (err) {\n        return res.send(err);\n    }\n});\n```\n\n```text\n// ReactJS for login\nloginFunction(e, data) {\n    e.preventDefault();\n    fetch('http://localhost:4500/login', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json'\n        },\n        body: JSON.stringify(data)\n    })\n        .then(response => response.json())\n        .then(json => {\n            this.setState({'user': json['user']});\n        })\n        .catch((err) => {\n            console.log(err);\n            this.setState({errors: \"Login error\"})\n        });\n}\n```\n\n```text\n// Node.JS for Posts\nconst router = require('express').Router();\nconst Post = require('post');\nrouter.get(\"/posts\", async (req, res) => {\n    try {\n        await Post.findAndCountAll()\n            .then((posts) => {\n                res.send({\"posts\": posts});\n            }).catch((err) => {\n                return res.send(err);\n            });\n    } catch (err) {\n        return res.send(err);\n    }\n});\n```\n\n```text\n// ReactJS for Posts\npostsFunction() {\n        fetch('http://localhost:4500/posts', {\n            method: 'GET',\n            headers: {\n                'Content-Type': 'application/json'\n            }\n        })\n            .then(response => response.json())\n            .then(json => {\n                this.setState({'posts': json.posts.rows});\n            })\n            .catch((err) => {\n                console.log(err);\n                this.setState({errors: \"Posts error.\"})\n            });\n    }\n```\n\n```text\nSyntaxError\n```\n\n```text\nResponse: {\n    body: ReadableStream\n    locked: false\n    <prototype>: object { … }\n    bodyUsed: false\n    headers: Headers { }\n    ok: true\n    redirected: false\n    status: 200\n    statusText: \"OK\"\n    type: \"basic\"\n    url: \"http://localhost:3000/admin/undefined/posts\"\n}\n```\n\n```text\nfetch('http://localhost:4500/posts', {\n```\n\n```text\nfetch(process.env.API_URL + '/posts', {\n```\n\n```text\nfetch(process.env.REACT_APP_API_URL + '/posts', {\n```\n\n```text\nresponse\n```\n\n```text\nresponse => response.json()\n```\n\n```text\nresponse\n```\n\n```text\nundefined\n```\n\n```text\n.env\n```\n\n```text\nAPI_URL\n```\n\n```text\nundefined\n```\n\n```text\nREACT_APP_\n```\n\n```text\nheaders: {\n       'Content-Type': 'application/json'\n}\n```\n\n========================================\n\nComments:\n- What's the reason for stringifying the data you just parsed as json? `this.setState({posts: JSON.stringify(json.posts.rows)})`\n- It just kept there when I copied from another router example. Already fixed in the code example. Modify it do not represent positive results.\n- Try to add consoles inside the node's successful query function.\n- you can try to console log `response` instead of `response => response.json()`, maybe the response might be error from your try catch code, not json data\n- @YulioAlemanJimenez, or maybe you can try using `axios` instead of `fetch`\n- When replace `response.json()` by `response` I get this object: `Response: { ​ body: ReadableStream ​​ locked: false ​​ : object { … } ​ bodyUsed: false ​ headers: Headers { } ​ ok: true ​ redirected: false ​ status: 200 ​ statusText: \"OK\" ​ type: \"basic\" ​ url: \"http:&#47;&#47;localhost:3000&#47;admin&#47;undefined&#47;posts\" ​ }` Note the URL, why it is concatenating React URL + `undefined` + Node.JS route path??\n- Neither do i, it is from fetch lib","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":290,"estimatedTokens":1665}}914{"id":"stack-47214607","source":"stackoverflow","questionId":47214607,"title":"sequelize return blob as text","tags":["mysql","node.js","sequelize.js"],"text":"Title: sequelize return blob as text\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize to retrieve data from a legacy mysql database. One of the columns in the table is a blob, so sequelize returns a buffer.\n\nIs it possible to return the blob as text or as a string using Sequelize? Or will i need to loop through the array of objects and convert them?\n\nThanks for the help!\n\nSimilar code:\n\n```\nawait findAll({\n where: {\n date: { $gte: sevenDaysAgo },\n newsSource: sourceList,\n },\n order: ['date'],\n raw: true,\n});\n```\n\n========================================\n\nCode:\n```text\nawait findAll({\n  where: {\n    date: { $gte: sevenDaysAgo },\n    newsSource: sourceList,\n  },\n  order: ['date'],\n  raw: true,\n});\n```\n\n```text\nconst Employee = sequelize.define('employee', {\n    picture: {\n      type: Sequelize.BLOB,\n      allowNull: false,\n      get() {\n        return this.getDataValue('picture').toString('utf8'); // or whatever encoding is right\n      },\n    },\n\n  });\n```\n\n========================================\n\nComments:\n- Is there any way to do this when the raw option is set to true?\n- I'm going to accept the answer since it solves for dataValues. However, a better answer would be if there is a way to handle on the raw json object via sequelize. Not sure if that is supported though","metadata":{"transformedAt":"2026-08-18T18:33:34.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":56,"estimatedTokens":333}}915{"id":"stack-55174362","source":"stackoverflow","questionId":55174362,"title":"SequelizeEagerLoadingError: (parent) is not associated to (child)!","tags":["mysql","node.js","express","sequelize.js","sequelize-cli"],"text":"Title: SequelizeEagerLoadingError: (parent) is not associated to (child)!\nTags: mysql, node.js, express, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am building an application using sequelize. I currently have 3 tables; a User, a Tour, and a Location. The Location has a n:1 relationship with the Tour. The Tour has a n:1 relationship with the user. \n\nWithout the User association, the other two tables work fine. Once I add in the user association (and I have tried to do so through a migration AND by dropping and then recreating my entire database), I get a SequelizeEagerLoadingError: Location is not associated with Tour!\n\nHere are my models: \n\n\r\n\r\n\n```\nmodule.exports = function(sequelize, DataTypes) {\r\n var Location = sequelize.define(\"Location\", {\r\n title: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n },\r\n description: {\r\n type: DataTypes.TEXT,\r\n allowNull: false,\r\n validate: {\r\n len: [500]\r\n }\r\n },\r\n address: {\r\n type: DataTypes.TEXT,\r\n allowNull: false\r\n }\r\n });\r\n\r\n Location.associate = function(models) {\r\n Location.belongsTo(models.Tour, {\r\n onDelete: \"cascade\"\r\n });\r\n };\r\n\r\n return Location;\r\n};\n```\n\n\r\n\r\n\r\n\n\r\n\r\n\n```\nmodule.exports = function(sequelize, DataTypes) {\r\n var Tour = sequelize.define(\"Tour\", {\r\n title: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n },\r\n description: {\r\n type: DataTypes.TEXT,\r\n allowNull: false,\r\n validate: {\r\n len: [1, 1000]\r\n }\r\n },\r\n neighborhood: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n },\r\n URL: {\r\n type: DataTypes.TEXT,\r\n allowNull: false,\r\n validate: {\r\n len: [1, 1000]\r\n }\r\n },\r\n numberOfStops: DataTypes.INTEGER,\r\n duration: {\r\n type: DataTypes.INTEGER,\r\n allowNull: false\r\n },\r\n tags: DataTypes.STRING\r\n });\r\n\r\n Tour.associate = function(models) {\r\n Tour.hasMany(models.Location);\r\n };\r\n\r\n Tour.associate = function(models) {\r\n Tour.belongsTo(models.User);\r\n };\r\n\r\n return Tour;\r\n};\n```\n\n\r\n\r\n\r\n\n\r\n\r\n\n```\nvar bcrypt = require(\"bcrypt-nodejs\");\r\nmodule.exports = function(sequelize, DataTypes) {\r\n var User = sequelize.define(\"User\", {\r\n name: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n },\r\n email: {\r\n type: DataTypes.STRING,\r\n allowNull: false,\r\n unique: true,\r\n validate: {\r\n isEmail: true\r\n }\r\n },\r\n password: {\r\n type: DataTypes.STRING,\r\n allowNull: false\r\n }\r\n });\r\n User.prototype.validPassword = function(password) {\r\n return bcrypt.compareSync(password, this.password);\r\n };\r\n\r\n User.hook(\"beforeCreate\", function(user) {\r\n user.password = bcrypt.hashSync(\r\n user.password,\r\n bcrypt.genSaltSync(10),\r\n null\r\n );\r\n });\r\n\r\n User.associate = function(models) {\r\n User.hasMany(models.Tour);\r\n };\r\n\r\n return User;\r\n};\n```\n\n\r\n\r\n\r\n\nAnd here is the include statement where it is failing, and where we establish the link with the tourId to the location: \n\n\r\n\r\n\n```\napp.get(\"/tour/:id\", function(req, res) {\r\n db.Tour.findOne({\r\n where: { id: req.params.id },\r\n include: [db.Location]\r\n }).then(function(tour) {\r\n res.render(\"tour\", {\r\n tour: tour\r\n });\r\n });\r\n });\n```\n\n\r\n\r\n\r\n\n\r\n\r\n\n```\nvar API = {\r\n saveTour: function(tour) {\r\n return $.ajax({\r\n headers: {\r\n \"Content-Type\": \"application/json\"\r\n },\r\n type: \"POST\",\r\n url: \"api/tours\",\r\n data: JSON.stringify(tour)\r\n });\r\n },\r\n saveLocations: function(locations) {\r\n return $.ajax({\r\n headers: {\r\n \"Content-Type\": \"application/json\"\r\n },\r\n type: \"POST\",\r\n url: \"api/locations\",\r\n data: JSON.stringify(locations)\r\n });\r\n },\r\n getUserId: function() {\r\n return $.ajax({\r\n type: \"GET\",\r\n url: \"api/user_data\"\r\n });\r\n }\r\n};\n```\n\n\r\n\r\n\r\n\n\r\n\r\n\n```\nvar tour = {\r\n Users: thisUser.getUserId(),\r\n title: title,\r\n description: description,\r\n neighborhood: neighborhood,\r\n URL: URL,\r\n duration: duration,\r\n tags: tags\r\n };\r\n\r\n // console.log(tour);\r\n\r\n if (!errors.length) {\r\n // Post our tour to the Tours table, then reveal the form and set our local tour object.\r\n API.saveTour(tour).then(function(tour) {\r\n document.getElementById(\"submit-tour\").remove();\r\n document.getElementById(\"tourstopssection\").style.display = \"block\";\r\n thisTour.setId(tour.id);\r\n });\r\n }\r\n}\r\n\r\n// Function takes in the newly created tour object, grabs DOM values for each.\r\nfunction addTourLocations(e) {\r\n e.preventDefault();\r\n // Grab and process all of our tour stops.\r\n var locationElements = document.getElementsByClassName(\"tourstop\");\r\n var areStopErrors = false;\r\n var locations = [];\r\n\r\n // Loop over every location element on the DOM.\r\n for (var j = 0; j \r\n\r\n\nFinally, this is how the app/db are synced: \n\n\r\n\r\n\n```\nrequire(\"dotenv\").config();\r\nvar express = require(\"express\");\r\nvar session = require(\"express-session\");\r\nvar exphbs = require(\"express-handlebars\");\r\nvar helpers = require(\"./lib/helpers\");\r\n\r\nvar db = require(\"./models\");\r\nvar passport = require(\"./config/passport\");\r\n\r\nvar app = express();\r\nvar PORT = process.env.PORT || 3000;\r\n\r\n// Middleware\r\napp.use(express.urlencoded({ extended: true }));\r\napp.use(express.json());\r\napp.use(express.static(\"public\"));\r\n\r\nvar hbs = exphbs.create({\r\n defaultLayout: \"main\",\r\n helpers: helpers // Require our custom Handlebars helpers.\r\n});\r\n\r\n//Sessions are used to keep track of our user's login status\r\napp.use(\r\n session({ secret: \"keyboard cat\", resave: true, saveUninitialized: true })\r\n);\r\napp.use(passport.initialize());\r\napp.use(passport.session());\r\napp.use(function(req, res, next) {\r\n res.locals.user = req.user; // Set a local variable for our user.\r\n next();\r\n});\r\n\r\n// Handlebars\r\napp.engine(\"handlebars\", hbs.engine);\r\napp.set(\"view engine\", \"handlebars\");\r\n\r\n// Routes\r\nrequire(\"./routes/apiRoutes\")(app);\r\nrequire(\"./routes/htmlRoutes\")(app);\r\n\r\nvar syncOptions = { force: false };\r\n\r\n// If running a test, set syncOptions.force to true\r\n// clearing the `testdb`\r\nif (process.env.NODE_ENV === \"test\") {\r\n syncOptions.force = true;\r\n}\r\n\r\n// Starting the server, syncing our models ------------------------------------/\r\ndb.sequelize.sync(syncOptions).then(function() {\r\n app.listen(PORT, function() {\r\n console.log(\r\n \"==> 🌎 Listening on port %s. Visit http://localhost:%s/ in your browser.\",\r\n PORT,\r\n PORT\r\n );\r\n });\r\n});\r\n\r\nmodule.exports = app;\n```\n\n\r\n\r\n\r\n\nI've been googling for four days....help!\n\n========================================\n\nTop Answer:\nI figured it out - the fact that I had defined the association on the tours model twice was breaking everything. Once I combined them as mentioned above, everything worked perfectly! \n\nOne other thing to note - sequelize automatically assigns the foreign key and the alias, so I left that part out.\n\n========================================\n\nCode:\n```js\nmodule.exports = function(sequelize, DataTypes) {\n  var Location = sequelize.define(\"Location\", {\n    title: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    description: {\n      type: DataTypes.TEXT,\n      allowNull: false,\n      validate: {\n        len: [500]\n      }\n    },\n    address: {\n      type: DataTypes.TEXT,\n      allowNull: false\n    }\n  });\n\n  Location.associate = function(models) {\n    Location.belongsTo(models.Tour, {\n      onDelete: \"cascade\"\n    });\n  };\n\n  return Location;\n};\n```\n\n```js\nmodule.exports = function(sequelize, DataTypes) {\n  var Tour = sequelize.define(\"Tour\", {\n    title: {\n      type: DataTypes.STRING,\n      allowNull: false\n        },\n    description: {\n      type: DataTypes.TEXT,\n      allowNull: false,\n      validate: {\n        len: [1, 1000]\n      }\n    },\n    neighborhood: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    URL: {\n      type: DataTypes.TEXT,\n      allowNull: false,\n      validate: {\n        len: [1, 1000]\n      }\n    },\n    numberOfStops: DataTypes.INTEGER,\n    duration: {\n      type: DataTypes.INTEGER,\n      allowNull: false\n    },\n    tags: DataTypes.STRING\n  });\n\n    Tour.associate = function(models) {\n    Tour.hasMany(models.Location);\n  };\n\n  Tour.associate = function(models) {\n    Tour.belongsTo(models.User);\n  };\n\n  return Tour;\n};\n```\n\n```js\nvar bcrypt = require(\"bcrypt-nodejs\");\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define(\"User\", {\n    name: {\n      type: DataTypes.STRING,\n      allowNull: false\n    },\n    email: {\n      type: DataTypes.STRING,\n      allowNull: false,\n      unique: true,\n      validate: {\n        isEmail: true\n      }\n    },\n    password: {\n      type: DataTypes.STRING,\n      allowNull: false\n    }\n  });\n  User.prototype.validPassword = function(password) {\n    return bcrypt.compareSync(password, this.password);\n  };\n\n  User.hook(\"beforeCreate\", function(user) {\n    user.password = bcrypt.hashSync(\n      user.password,\n      bcrypt.genSaltSync(10),\n      null\n    );\n  });\n\n  User.associate = function(models) {\n    User.hasMany(models.Tour);\n  };\n\n  return User;\n};\n```\n\n```js\napp.get(\"/tour/:id\", function(req, res) {\n    db.Tour.findOne({\n      where: { id: req.params.id },\n      include: [db.Location]\n    }).then(function(tour) {\n      res.render(\"tour\", {\n        tour: tour\n      });\n    });\n  });\n```\n\n```js\nvar API = {\n  saveTour: function(tour) {\n    return $.ajax({\n      headers: {\n        \"Content-Type\": \"application/json\"\n      },\n      type: \"POST\",\n      url: \"api/tours\",\n      data: JSON.stringify(tour)\n    });\n  },\n  saveLocations: function(locations) {\n    return $.ajax({\n      headers: {\n        \"Content-Type\": \"application/json\"\n      },\n      type: \"POST\",\n      url: \"api/locations\",\n      data: JSON.stringify(locations)\n    });\n  },\n  getUserId: function() {\n    return $.ajax({\n      type: \"GET\",\n      url: \"api/user_data\"\n    });\n  }\n};\n```\n\n```js\nvar tour = {\n    Users: thisUser.getUserId(),\n    title: title,\n    description: description,\n    neighborhood: neighborhood,\n    URL: URL,\n    duration: duration,\n    tags: tags\n  };\n\n  // console.log(tour);\n\n  if (!errors.length) {\n    // Post our tour to the Tours table, then reveal the form and set our local tour object.\n    API.saveTour(tour).then(function(tour) {\n      document.getElementById(\"submit-tour\").remove();\n      document.getElementById(\"tourstopssection\").style.display = \"block\";\n      thisTour.setId(tour.id);\n    });\n  }\n}\n\n// Function takes in the newly created tour object, grabs DOM values for each.\nfunction addTourLocations(e) {\n  e.preventDefault();\n  // Grab and process all of our tour stops.\n  var locationElements = document.getElementsByClassName(\"tourstop\");\n  var areStopErrors = false;\n  var locations = [];\n\n  // Loop over every location element on the DOM.\n  for (var j = 0; j < locationElements.length; j++) {\n    var children = locationElements[j].children;\n\n    // Initialize this location with the tour id; we'll pass in data...\n    var thisLocation = {\n      TourId: thisTour.getId()\n    };\n\n    // ... by looping over the DOM children and grabbing their form values.\n    for (var k = 0; k < children.length; k++) {\n      if (\n        children[k].classList.value.includes(\"stoptitle\") &&\n        children[k].value\n      ) {\n        var stopTitle = children[k].value;\n        thisLocation.title = stopTitle;\n      }\n\n      if (\n        children[k].classList.value.includes(\"stopaddress\") &&\n        children[k].value\n      ) {\n        var stopAddress = children[k].value;\n        thisLocation.address = stopAddress;\n      }\n\n      if (\n        children[k].classList.value.includes(\"stopdescription\") &&\n        children[k].value\n      ) {\n        var stopDescription = children[k].value;\n        thisLocation.description = stopDescription;\n      }\n    }\n\n    // Push this location into our locations array.\n    locations.push(thisLocation);\n```\n\n```js\nrequire(\"dotenv\").config();\nvar express = require(\"express\");\nvar session = require(\"express-session\");\nvar exphbs = require(\"express-handlebars\");\nvar helpers = require(\"./lib/helpers\");\n\nvar db = require(\"./models\");\nvar passport = require(\"./config/passport\");\n\nvar app = express();\nvar PORT = process.env.PORT || 3000;\n\n// Middleware\napp.use(express.urlencoded({ extended: true }));\napp.use(express.json());\napp.use(express.static(\"public\"));\n\nvar hbs = exphbs.create({\n  defaultLayout: \"main\",\n  helpers: helpers // Require our custom Handlebars helpers.\n});\n\n//Sessions are used to keep track of our user's login status\napp.use(\n  session({ secret: \"keyboard cat\", resave: true, saveUninitialized: true })\n);\napp.use(passport.initialize());\napp.use(passport.session());\napp.use(function(req, res, next) {\n  res.locals.user = req.user; // Set a local variable for our user.\n  next();\n});\n\n// Handlebars\napp.engine(\"handlebars\", hbs.engine);\napp.set(\"view engine\", \"handlebars\");\n\n// Routes\nrequire(\"./routes/apiRoutes\")(app);\nrequire(\"./routes/htmlRoutes\")(app);\n\nvar syncOptions = { force: false };\n\n// If running a test, set syncOptions.force to true\n// clearing the `testdb`\nif (process.env.NODE_ENV === \"test\") {\n  syncOptions.force = true;\n}\n\n// Starting the server, syncing our models ------------------------------------/\ndb.sequelize.sync(syncOptions).then(function() {\n  app.listen(PORT, function() {\n    console.log(\n      \"==> 🌎  Listening on port %s. Visit http://localhost:%s/ in your browser.\",\n      PORT,\n      PORT\n    );\n  });\n});\n\nmodule.exports = app;\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  var Location = sequelize.define(\"Location\", {\n    //\n  });\n\n  Location.associate = function(models) {\n    Location.belongsTo(models.Tour, { as:'Tour', foreignKey:'tourId', onDelete: \"cascade\"});\n  };\n\n  return Location;\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n  var Tour = sequelize.define(\"Tour\", {\n    //\n  });\n\n  Tour.associate = function(models) {\n    Tour.hasMany(models.Location, { as: 'Locations', foreignKey: 'tourId'});\n    Tour.belongsTo(models.User, { as: 'User', foreignKey: 'userId' });\n  };\n\n\n  return Tour;\n};\n\nmodule.exports = function(sequelize, DataTypes) {\n  var User = sequelize.define(\"User\", {\n    //\n  });\n\n  User.associate = function(models) {\n    User.hasMany(models.Tour, {as: 'Tours', foreignKey: 'userId'});\n  };\n\n  return User;\n};\n```\n\n```text\ndb.Tour.findOne({\n  where: { id: req.params.id },\n  include: [{ \n    model: db.Location,\n    as: 'Locations'\n  }]\n}).then(function(tour) {\n  res.render(\"tour\", {\n    tour: tour\n  });\n});\n```\n\n========================================\n\nComments:\n- On which line is the exception occurring, what is the message? Your fourth code block seems to be pasted together from at least two locations. What is the second half supposed to be, how does it fit together with the app.get definition?\n- Just a guess for now, you may need to define the reverse relationship from Tour to Location as well, that a Tour has multiple Locations. \"hasMany\", just like you have done it for User and Tour.\n- @Christoph - thanks for that! I actually did establish the hasMany in the Tour model, but I had left that out in my copy/paste job last night. I updated the model and added some clarity to that last block - basically the first one (the get route) is where the error is thrown, right on the \"Include: db.Location\" line. The second portion is how we determine the API routing, and the third is how we are actually building the Location and Tours based on the client-side input.\n- thanks very much! To answer your question, I am doing that because I am still very much new to this and It didn't even occur to me that I could combine those two statements...but it is so obvious now! I did notice though that the foreign key and 'as' are assigned automatically by sequelize. Does calling it explicitly in the model make a difference in this case?\n- So it looks like ellebkey figured out the solution, the double association. Then please mark her answer as the correct answer, as is custom here on Stack Overflow.","metadata":{"transformedAt":"2026-08-18T18:33:34.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":688,"estimatedTokens":3898}}916{"id":"stack-47055285","source":"stackoverflow","questionId":47055285,"title":"Sequelize: Unique validation with soft deleted registers","tags":["validation","sequelize.js"],"text":"Title: Sequelize: Unique validation with soft deleted registers\nTags: validation, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize, my model 'users', has a field 'email' that has the unique validation.\nBut when i try to create a new register using the same email of a old register soft deleted, the validation triggers and not allow me to continue.\nIs this a bug, the unique validation need a specific parameter for that or it is supposed to work this way?\n\nEmail on model:\n\n```\nemail: { \n type: Sequelize.STRING(191),\n allowNull: false,\n unique: {\n msg: 'Email já cadastrado.'\n }, \n validate: {\n isEmail: {\n msg: 'Formato de email inválido.'\n },\n notEmpty:{\n msg: 'Email deve ser informado.'\n }\n }\n}\n```\n\nThe version of sequelize i'm using is: 4.17.2\n\n========================================\n\nCode:\n```text\nemail: {    \n    type: Sequelize.STRING(191),\n    allowNull: false,\n    unique: {\n       msg: 'Email já cadastrado.'\n    },    \n    validate: {\n       isEmail: {\n           msg: 'Formato de email inválido.'\n       },\n       notEmpty:{\n           msg: 'Email deve ser informado.'\n       }\n    }\n}\n```\n\n```text\nisDeleted=true\n```\n\n========================================\n\nComments:\n- Got it, i wanted to be certain about the way that is supposed to be. Thanks for the clarification was really helpful.","metadata":{"transformedAt":"2026-08-18T18:33:34.412Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":60,"estimatedTokens":332}}917{"id":"stack-43749759","source":"stackoverflow","questionId":43749759,"title":"Join on specific columns using Sequelize.js","tags":["mysql","sql","node.js","orm","sequelize.js"],"text":"Title: Join on specific columns using Sequelize.js\nTags: mysql, sql, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to do join some tables on specific columns using Sequelize.js.\n\nSo far, my code is something like:\n\n```\ntable_1.findall({\n include: [{\n model: table_2\n attributes: ['id', 'another_id']\n include: [{\n model: table_3\n required: true\n attributes: ['time']\n }]\n }]\n})\n```\n\nwhere each table's primary key is 'id'.\n\nThis seems to be equivalent to the following SQL (I am showing SELECT * for brevity, since that is not the focus of this question):\n\n```\nSELECT *\nFROM table_1 as t1\nLEFT OUTER JOIN table_2 as t2 ON t1.id = t2.t1_id\nINNER JOIN table_3 as t3 ON t2.id = t3.t2_id\n```\n\nand I want to have something like:\n\n```\nSELECT *\nFROM table_1 as t1\nLEFT OUTER JOIN table_2 as t2 ON t1.id = t2.t1_id\nINNER JOIN table_3 as t3 ON t2.another_id = t3.t2_id\n```\n\nIs there a way to force the join between t2 and t3 to use something either than the primary key of t2? \n\nI have found the [options.include[].on]\nin the Sequelize documentation, but do not know what the syntax is for suppling my own ON condition.\n\n========================================\n\nTop Answer:\nYou can also mention like this in you code/controller file:\n\n```\nconst storeModel = model.store;\nconst bookedTicketModel = model.booked_ticket;\nbookedTicketModel.belongsTo (storeModel, {foreignKey: 'storeId'});\nstoreModel.hasMany (bookedTicketModel, {foreignKey: 'id'});\n```\n\n========================================\n\nCode:\n```text\ntable_1.findall({\n  include: [{\n    model: table_2\n    attributes: ['id', 'another_id']\n    include: [{\n      model: table_3\n      required: true\n      attributes: ['time']\n    }]\n  }]\n})\n```\n\n```text\nSELECT *\nFROM table_1 as t1\nLEFT OUTER JOIN table_2 as t2 ON t1.id = t2.t1_id\nINNER JOIN table_3 as t3 ON t2.id = t3.t2_id\n```\n\n```text\nSELECT *\nFROM table_1 as t1\nLEFT OUTER JOIN table_2 as t2 ON t1.id = t2.t1_id\nINNER JOIN table_3 as t3 ON t2.another_id = t3.t2_id\n```\n\n```text\nclassMethods: {\n  associate(models) {\n    this.belongsTo(models.user, {\n      foreignKey: 'created_by_user_id',\n      as: 'created_by',\n    });\n    this.belongsTo(models.user, {\n      foreignKey: 'updated_by_user_id',\n      as: 'updated_by',\n    });\n  },\n},\n```\n\n```text\nclassMethods\n```\n\n```text\nusers\n```\n\n```text\nfindAll\n```\n\n```text\nconst storeModel = model.store;\nconst bookedTicketModel = model.booked_ticket;\nbookedTicketModel.belongsTo (storeModel, {foreignKey: 'storeId'});\nstoreModel.hasMany (bookedTicketModel, {foreignKey: 'id'});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":124,"estimatedTokens":638}}918{"id":"stack-50921788","source":"stackoverflow","questionId":50921788,"title":"filter Sequelize belongsToMany get association table","tags":["javascript","mysql","sequelize.js","has-and-belongs-to-many"],"text":"Title: filter Sequelize belongsToMany get association table\nTags: javascript, mysql, sequelize.js, has-and-belongs-to-many\nSource: Stack Overflow\n\nQuestion:\nI am working with Sequelize 4.37.10 and it works great.\nUnfortunately the documentation is not perfect in my opinion. So it lacks a bit of describing the belongsToMany possibilities.\n\nI have the following problem:\n\nI defined my tables like this:\n\n```\nconst Department = db.define('department', {\n name: {type: Sequelize.STRING, allowNull: false},\n shortName: {type: Sequelize.STRING, allowNull: false}\n})\n\nconst Employee = db.define('employee', {\n title: {type: Sequelize.STRING},\n name: {type: Sequelize.STRING, allowNull: false},\n surname: {type: Sequelize.STRING, allowNull: false},\n .\n .\n role: {type: Sequelize.STRING}\n})\n```\n\nThen I associated the tables like this:\n\n```\nconst EmployeeDepartments = db.define('employeeDepartments', {\n manager: {type: Sequelize.BOOLEAN, allowNull: false}\n})\n\nDepartment.belongsToMany(Employee, {through: EmployeeDepartments})\nEmployee.belongsToMany(Department, {through: EmployeeDepartments})\n```\n\nNow i want to get all department employees with the manager field set to true.\nThe creation was no problem, but the select is a problem for me.\n\nI tried the following with no luck:\n\n```\ndepartment.getEmployees({where: {manager: true}})\n```\n\nI also thought of scopes but I don't know how to design that properly.\n\nCan you help me with that?\n\n========================================\n\nTop Answer:\n```\ndepartment.getEmployees({where: {manager: true}})\n```\n\n**change this code with this.**\n\n```\ndepartment.getEmployees( \n include:{\n model: employeedepartments, // your employee departments model name\n {where: {manager: true}, \n required:true, \n }\n})\n```\n\n**You have to just add include in your query**\n\n========================================\n\nCode:\n```js\nconst Department = db.define('department', {\n  name: {type: Sequelize.STRING, allowNull: false},\n  shortName: {type: Sequelize.STRING, allowNull: false}\n})\n\nconst Employee = db.define('employee', {\n  title: {type: Sequelize.STRING},\n  name: {type: Sequelize.STRING, allowNull: false},\n  surname: {type: Sequelize.STRING, allowNull: false},\n  .\n  .\n  role: {type: Sequelize.STRING}\n})\n```\n\n```js\nconst EmployeeDepartments = db.define('employeeDepartments', {\n  manager: {type: Sequelize.BOOLEAN, allowNull: false}\n})\n\nDepartment.belongsToMany(Employee, {through: EmployeeDepartments})\nEmployee.belongsToMany(Department, {through: EmployeeDepartments})\n```\n\n```js\ndepartment.getEmployees({where: {manager: true}})\n```\n\n```text\ndepartment.getEmployees({ through: { where: { manager: true } } })\n```\n\n```text\nconst department = Department.build( { id: departmentId } );\n// proceed as above\n```\n\n```text\ndepartment\n```\n\n```text\nid\n```\n\n```text\ndepartment.getEmployees({where: {manager: true}})\n```\n\n```text\ndepartment.getEmployees(      \n  include:{\n    model: employeedepartments, // your employee departments model name\n    {where: {manager: true},      \n    required:true, \n  }\n})\n```\n\n```text\ndepartment.getEmployees({where: {'$employeeDepartments.manager$': true}})\n```\n\n```text\nbelongsToMany\n```\n\n========================================\n\nComments:\n- include expects an array\n- Nice! Sad to know that the Sequelize docs does not tell anything about the `through` option. Thank you! In my opinion, the second code line is easier by using `Department.findById(departmentId)`\n- The problem with that approach is that you hit the DB. The `build` doesn't.\n- Also, you may run into this problem that you cannot really remove the association field `departmentEmployee` from the resulting employees (see this issue: github.com/sequelize/sequelize/issues/3664). I solved this with `employees.forEach( e => delete e.dataValues['department_employee'] )`","metadata":{"transformedAt":"2026-08-18T18:33:34.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":151,"estimatedTokens":948}}919{"id":"stack-48778789","source":"stackoverflow","questionId":48778789,"title":"Addition and Subtraction Assignment Operator With Sequelize","tags":["node.js","sequelize.js","variable-assignment","addition","subtraction"],"text":"Title: Addition and Subtraction Assignment Operator With Sequelize\nTags: node.js, sequelize.js, variable-assignment, addition, subtraction\nSource: Stack Overflow\n\nQuestion:\nI would like to do an update by doing a simple addition on Sequelize.\n\ntable: \n\n```\nid || data\n 1 || 10\n```\n\nsample:\n\n```\ndb.table.update({ data : 1 }, { where: { id: 1 }});\n```\n\nafter this query \n\n```\nid || data\n 1 || 11\n```\n\nI know it's a simple question, but I could not find the solution. \n\nWhich operator can I add and subtract? Thank you\n\n========================================\n\nTop Answer:\nSequelize increment & decrement\n\n```\nmyIncrementFunc(id, incrementor) {\n User.findById(id).then(user => {\n return user.increment('tableColumnName', {by: incrementor})\n }).then(user => {})\n}\n```\n\nCode taken form sequelize Instances tutorial for Incrementing & Decrementing:\nhttp://docs.sequelizejs.com/manual/tutorial/instances.html\n\n========================================\n\nCode:\n```text\nid || data\n 1 ||  10\n```\n\n```text\ndb.table.update({ data : 1 }, { where: { id: 1 }});\n```\n\n```text\nid || data\n 1 ||  11\n```\n\n```text\ndb.table.update({ field: Sequelize.literal('data + 1') }, { where: { id: 1 }}))\n```\n\n```text\nUser.findById(1).then(user => {\n  // -----> First Way\n  return user.increment('my-integer-field', {by: 2});\n  // -----> Second Way\n  return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2})\n  // -----> Third Way\n  return user.increment({\n     'my-integer-field':    2,\n     'my-very-other-field': 3\n  })\n});\n```\n\n```text\nawait User.increment({age: 5}, { where: { id: 1 } }) // Will increase age to 15\nawait User.increment({age: -5}, { where: { id: 1 } }) // Will decrease age to 5\n```\n\n```text\ndecrement\n```\n\n```text\nincrement\n```\n\n```text\ndecrement\n```\n\n```text\nmyIncrementFunc(id, incrementor) {\n  User.findById(id).then(user => {\n    return user.increment('tableColumnName', {by: incrementor})\n  }).then(user => {})\n}\n```\n\n========================================\n\nComments:\n- update the docs link please\n- can't access the link","metadata":{"transformedAt":"2026-08-18T18:33:34.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":112,"estimatedTokens":510}}920{"id":"stack-40294776","source":"stackoverflow","questionId":40294776,"title":"Query self-join with Sequelize, including related record","tags":["node.js","join","foreign-keys","relationship","sequelize.js"],"text":"Title: Query self-join with Sequelize, including related record\nTags: node.js, join, foreign-keys, relationship, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWe're using Postgres for a Node.js app and have a Sequelize model `Entry` which is roughly defined as:\n\n```\nconst entriesModel = sequelize.define('Entry',\n {\n id: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n post_date: {\n type: DataTypes.DATE,\n allowNull: false,\n defaultValue: () => new Date()\n }\n /* ...more fields here, etc, etc... */\n }, {\n classMethods: {\n associate: (models) => {\n entriesModel.hasOne(models.Entry, {\n onDelete: 'CASCADE',\n foreignKey: {\n name: 'parent_id',\n allowNull: true\n },\n as: 'ParentEntry'\n });\n }\n }\n }\n);\n```\n\nBasically, an entry may have a corresponding parent entry. I want to retrieve all of the entries and pull through their parent entries, but when I try:\n\n```\nreturn models.Entry.findById(id, {\n include: [\n {\n model: models.Entry,\n where: {\n parent_id: id\n }\n }\n ]\n})\n.then(entry => Promise.resolve(cb(null, entry)))\n.catch(error => Promise.resolve(cb(error)));\n```\n\nI get the error: \"Entry is not associated to Entry!\"\n\n**How can I do this query and pull through this related data from another record in the same table?**\n\n========================================\n\nCode:\n```text\nconst entriesModel = sequelize.define('Entry',\n    {\n        id: {\n            type: DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        post_date: {\n            type: DataTypes.DATE,\n            allowNull: false,\n            defaultValue: () => new Date()\n        }\n        /* ...more fields here, etc, etc... */\n    }, {\n        classMethods: {\n            associate: (models) => {\n                entriesModel.hasOne(models.Entry, {\n                    onDelete: 'CASCADE',\n                    foreignKey: {\n                        name: 'parent_id',\n                        allowNull: true\n                    },\n                    as: 'ParentEntry'\n                });\n            }\n        }\n    }\n);\n```\n\n```text\nreturn models.Entry.findById(id, {\n    include: [\n        {\n            model: models.Entry,\n            where: {\n                parent_id: id\n            }\n        }\n    ]\n})\n.then(entry => Promise.resolve(cb(null, entry)))\n.catch(error => Promise.resolve(cb(error)));\n```\n\n```text\nEntry\n```\n\n```text\nreturn models.Entry.findById(id, {\n    include: [{\n        model: models.Entry,\n        as: 'ParentEntry'\n    }]\n})\n```\n\n```text\nas\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":124,"estimatedTokens":629}}921{"id":"stack-42537184","source":"stackoverflow","questionId":42537184,"title":"Sequelize create through association","tags":["node.js","associations","sequelize.js"],"text":"Title: Sequelize create through association\nTags: node.js, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on a create method for an association between two classes. The sequelize documentation indicates that this can be done in one step using includes\n\n```\nIntramuralAthlete.create(intramuralAthlete,{\n include: [Person]\n }).then((data,err)=>{\n if(data)res.json(data);\n else res.status(422).json(err);\n }).catch(function(error) {\n res.status(422).json({message: \"failed to create athlete\", error: error.message});\n});\n```\n\nMy model association looks like this \n\n```\nvar Person = require('../models').person;\nvar IntramuralAthlete = require('../models').intramuralAthlete;\n\nIntramuralAthlete.belongsTo(Person);\n```\n\nAnd the value of intramural athlete when I log it is \n\n```\n{ \n person: \n { firstName: 'Test',\n lastName: 'User',\n email: 'test@user.com'\n },\n grade: '12th',\n organizationId: 1 \n}\n```\n\nBut I get the error `notNull Violation: personId cannot be null`. This error makes it sound like something is wrong with the way I'm indicating to Sequelize that I'm intending to create the personId in that same call. \n\nIs there something wrong in the way I indicate to the `create` statement what associated tables to create with the IntramuralAthlete?\n\nThanks!\n\nEDIT:\nI have also tried with the following structure with the same result\n\n```\n{ \n Person: { \n firstName: 'Test',\n lastName: 'User',\n email: 'test@user.com'\n },\n grade: '12th',\n organizationId: 1 \n}\n```\n\nMy model is as follows:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('intramuralAthlete', {\n id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n createdAt: {\n type: DataTypes.DATE,\n allowNull: false,\n defaultValue: sequelize.literal('CURRENT_TIMESTAMP')\n },\n updatedAt: {\n type: DataTypes.DATE,\n allowNull: false,\n defaultValue: sequelize.literal('CURRENT_TIMESTAMP')\n },\n grade: {\n type: DataTypes.STRING,\n allowNull: true\n },\n age: {\n type: DataTypes.INTEGER(11),\n allowNull: true\n },\n school: {\n type: DataTypes.STRING,\n allowNull: true\n },\n notes: {\n type: DataTypes.STRING,\n allowNull: true\n },\n guardianId: {\n type: DataTypes.INTEGER(11),\n allowNull: true,\n references: {\n model: 'contact',\n key: 'id'\n }\n },\n personId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'person',\n key: 'id'\n }\n },\n mobileAthleteId: {\n type: DataTypes.INTEGER(11),\n allowNull: true,\n references: {\n model: 'mobileAthlete',\n key: 'id'\n }\n },\n organizationId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'organization',\n key: 'id'\n }\n }\n }, {\n tableName: 'intramuralAthlete'\n });\n};\n```\n\n========================================\n\nTop Answer:\nfirst of all, when you associatea a model with **belongsTo**, sequelize will add automatically the target model primary key as a foreign key in the source model. in most of cases you don't need to define it by yourself, so in your case when you define `IntramuralAthlete.belongsTo(Person)` sequelize adds `PersonId` as a foreign key in `IntramuralAthlete`. your `IntramuralAthlete` model should looks like:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define('intramuralAthlete', {\n grade: {\n type: DataTypes.STRING,\n allowNull: true\n },\n age: {\n type: DataTypes.INTEGER(11),\n allowNull: true\n },\n school: {\n type: DataTypes.STRING,\n allowNull: true\n },\n notes: {\n type: DataTypes.STRING,\n allowNull: true\n }\n });\n};\n```\n\nnow you can create an `intramuralAthlete` like your code above. for example:\n\n```\nlet data = {\n Person: {\n firstName: 'Test',\n lastName: 'User',\n email: 'test@user.com'\n },\n grade: '12th',\n notes: 'test notes'\n }\nIntramuralAthlete.create(data, {include: [Person]}).then((result) => {\n// both instances should be created now\n});\n```\n\nbe carefull with the model name. \nsecond I suppose that your `IntramuralAthlete` model has more than one `belongsTo` association. just you need to define them as the previous one association and sequelize will add their primary keys as foreign keys in the `IntramuralAthlete` model. \n\nthird, when you define a model, sequelize adds automatically an `id` datafield as a primary key and autoincrement and also adds `createdAt` and `updatedAt` datafields with a default `CURRENT_TIMESTAMP` value, so you don't need to define them in your model\n\n========================================\n\nCode:\n```text\nIntramuralAthlete.create(intramuralAthlete,{\n         include: [Person]\n    }).then((data,err)=>{\n         if(data)res.json(data);\n         else res.status(422).json(err);\n    }).catch(function(error) {\n         res.status(422).json({message: \"failed to create athlete\", error: error.message});\n});\n```\n\n```text\nvar Person = require('../models').person;\nvar IntramuralAthlete = require('../models').intramuralAthlete;\n\nIntramuralAthlete.belongsTo(Person);\n```\n\n```text\n{ \n   person: \n   { firstName: 'Test',\n     lastName: 'User',\n     email: 'test@user.com'\n  },\n  grade: '12th',\n  organizationId: 1 \n}\n```\n\n```text\n{ \n  Person: { \n    firstName: 'Test',\n    lastName: 'User',\n    email: 'test@user.com'\n },\n grade: '12th',\n organizationId: 1 \n}\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('intramuralAthlete', {\n    id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    createdAt: {\n      type: DataTypes.DATE,\n      allowNull: false,\n      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')\n    },\n    updatedAt: {\n      type: DataTypes.DATE,\n      allowNull: false,\n      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')\n    },\n    grade: {\n      type: DataTypes.STRING,\n      allowNull: true\n    },\n    age: {\n      type: DataTypes.INTEGER(11),\n      allowNull: true\n    },\n    school: {\n      type: DataTypes.STRING,\n      allowNull: true\n    },\n    notes: {\n      type: DataTypes.STRING,\n      allowNull: true\n    },\n    guardianId: {\n      type: DataTypes.INTEGER(11),\n      allowNull: true,\n      references: {\n        model: 'contact',\n        key: 'id'\n      }\n    },\n    personId: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      references: {\n        model: 'person',\n        key: 'id'\n      }\n    },\n    mobileAthleteId: {\n      type: DataTypes.INTEGER(11),\n      allowNull: true,\n      references: {\n        model: 'mobileAthlete',\n        key: 'id'\n      }\n    },\n    organizationId: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      references: {\n        model: 'organization',\n        key: 'id'\n      }\n    }\n  }, {\n    tableName: 'intramuralAthlete'\n  });\n};\n```\n\n```text\nnotNull Violation: personId cannot be null\n```\n\n```text\ncreate\n```\n\n```text\n{\n    Person: {\n        firstName: 'Test',\n        lastName: 'User',\n        email: 'test@user.com'\n    },\n    grade: '12th',\n    organizationId: 1 \n}\n```\n\n```text\nIntramuralAthlete.belongsTo(Person, { as: 'person' });\n```\n\n```text\nIntramuralAthlete.create(data, {\n    include: [\n        { model: Person, as: 'person' }\n    ]\n}).then((result) => {\n    // both instances should be created now\n});\n```\n\n```js\n{\n    person: {\n        // person data\n    },\n    personId: '', // whatever value - empty string, empty object etc.\n    grade: '12th',\n    organizationId: 1\n}\n```\n\n```js\nIntramuralAthlete.create(data, {\n    include: [\n        { model: Person, as: 'person' }\n    ],\n    validate: false\n}).then((result) => {\n    // both instances should be created now\n});\n```\n\n```text\nPerson\n```\n\n```text\nIntramuralAthlete\n```\n\n```text\nsequelize.define\n```\n\n```text\nas\n```\n\n```text\ncreate\n```\n\n```text\nperson\n```\n\n```text\ncreate\n```\n\n```text\ninclude\n```\n\n```text\noptions\n```\n\n```text\nsave()\n```\n\n```text\npersonId\n```\n\n```text\nallowNull: false\n```\n\n```text\npersonId\n```\n\n```text\ndata\n```\n\n```text\npersonId\n```\n\n```text\nnull\n```\n\n```text\nsave()\n```\n\n```text\nnull\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('intramuralAthlete', {\n    grade: {\n      type: DataTypes.STRING,\n      allowNull: true\n    },\n    age: {\n      type: DataTypes.INTEGER(11),\n      allowNull: true\n    },\n    school: {\n      type: DataTypes.STRING,\n      allowNull: true\n    },\n    notes: {\n      type: DataTypes.STRING,\n      allowNull: true\n    }\n });\n};\n```\n\n```text\nlet data = {\n   Person: {\n     firstName: 'Test',\n     lastName: 'User',\n     email: 'test@user.com'\n   },\n   grade: '12th',\n   notes: 'test notes'\n }\nIntramuralAthlete.create(data, {include: [Person]}).then((result) => {\n// both instances should be created now\n});\n```\n\n```text\nIntramuralAthlete.belongsTo(Person)\n```\n\n```text\nPersonId\n```\n\n```text\nIntramuralAthlete\n```\n\n```text\nIntramuralAthlete\n```\n\n```text\nintramuralAthlete\n```\n\n```text\nIntramuralAthlete\n```\n\n```text\nbelongsTo\n```\n\n```text\nIntramuralAthlete\n```\n\n```text\nid\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nCURRENT_TIMESTAMP\n```\n\n========================================\n\nComments:\n- What you have said makes sense, but I tried the suggested change to the object structure (included as an edit in my question), and it fails with the same error.\n- Yup, that might also happen. Could you also add the `IntramuralAthlete` model definition code?\n- Added model as requested\n- I didn't take it into consideration at first - my answer would work if the `personId` would not have the `allowNull: false` attribute. In such a case I need to rethink it. Will let you know if got something useful :)\n- Yep, that was it. Not super pleased that in order to do a one call create, you have to remove contraints on the foreign key, but it's better than giant nested chains of promises in our situation. Appreciate your help.\n- I edited the answer with some workaround for the problem, maybe it will satisfy you.\n- I like this much better. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":44,"totalLines":529,"estimatedTokens":2464}}922{"id":"stack-46390150","source":"stackoverflow","questionId":46390150,"title":"Sequelize not accepting valid moment.js object in where clause","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: Sequelize not accepting valid moment.js object in where clause\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following sequelize query:\n\n```\nlet prms = periods.map((period, index, arr) => {\n if (arr[index + 1]) {\n return sequelize.models.Result.aggregate('value', 'avg', {\n where: {\n createdAt: {\n $lt: arr[index + 1],\n $gt: period\n },\n type: hook.params.headers.type,\n entityId: hook.params.headers.entity\n }\n }).catch(err => console.log('err'));\n }\n})\n```\n\nNow, the `createdAt` property on the where object is causing me this problem:\n\n error: Error: Invalid value 1506211200000\n at Object.escape (C:\\Users\\George\\Source\\Repos\\myProj\\node_modules\\sequelize\\lib\\sql-string.js:50:11)\n at Object.escape (C:\\Users\\George\\Source\\Repos\\myProj\\node_modules\\sequelize\\lib\\dialects\\abstract\\query-generator.js:917:22)\n\nNow I don't have any idea where the `1506211200000` number is coming from, both `arr[index + 1]` and `period` are moment.js objects, and I can verify this by doing `console.log(arr[index + 1].isValid(), period.isValid());` which prints `true true`. If remove the createdAt restriction, there is no issue. \n\nAny idea what is going on here?\n\nNB: I am using Postgres\n\n========================================\n\nTop Answer:\nTo complement on the accepted answer: If you need it to be timezone aware, you will probably need to use the `format` method from the moment object. Like so:\n\n```\n...\nwhere: {\n createdAt: {\n Op.lt: arr[index + 1].format(),\n Op.gt: period.format()\n }\n...\n}\n```\n\nUsing the `toDate` method, it will use the local timezone, so you might get seemingly byzantine errors when deploying code to production, as the machine where you're deploying might have a different timezone from your local machine.\n\nYou can read further regarding this topic here.\n\n========================================\n\nCode:\n```text\nlet prms = periods.map((period, index, arr) => {\n    if (arr[index + 1]) {\n        return sequelize.models.Result.aggregate('value', 'avg', {\n            where: {\n                createdAt: {\n                    $lt: arr[index + 1],\n                    $gt: period\n                },\n                type: hook.params.headers.type,\n                entityId: hook.params.headers.entity\n            }\n        }).catch(err => console.log('err'));\n    }\n})\n```\n\n```text\ncreatedAt\n```\n\n```text\n1506211200000\n```\n\n```text\narr[index + 1]\n```\n\n```text\nperiod\n```\n\n```text\nconsole.log(arr[index + 1].isValid(), period.isValid());\n```\n\n```text\ntrue true\n```\n\n```text\n...\ncreatedAt: {\n  $lt: arr[index + 1].toDate(),\n  $gt: period.toDate()\n},\n```\n\n```text\nmoment\n```\n\n```text\nDate\n```\n\n```text\nmoment#toDate\n```\n\n```js\n...\nwhere: {\n  createdAt: {\n    Op.lt: arr[index + 1].format(),\n    Op.gt: period.format()\n  }\n...\n}\n```\n\n```text\nformat\n```\n\n```text\ntoDate\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":138,"estimatedTokens":711}}923{"id":"stack-37668376","source":"stackoverflow","questionId":37668376,"title":"Sequelize: Change column type to ENUM","tags":["node.js","postgresql","enums","sequelize.js","sequelize-cli"],"text":"Title: Sequelize: Change column type to ENUM\nTags: node.js, postgresql, enums, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI cannot seem to find the proper way to change a column from a String type to an ENUM while persisting the data in that column.\n\nI've also attempted to create a new column with the ENUM type and then copy the data between columns:\n\n```\n// migrations/20160606170538-change-column.js\n\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.addColumn('time', 'newcolumn', {\n allowNull: true,\n type: Sequelize.ENUM('1-day', '7-day', '1-month', '3-month', '6-month', '1-year')\n }).then(function () {\n return queryInterface.sequelize.query(\"UPDATE time SET newcolum = oldcolumn\");\n });\n },\n\n down: function (queryInterface, Sequelize) {\n }\n};\n```\n\nBut I return the following error on migration:\n\n error: column \"newcolumn\" is of type enum_time_newcolumn but expression is of type character varying]\n\n========================================\n\nCode:\n```text\n// migrations/20160606170538-change-column.js\n\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.addColumn('time', 'newcolumn', {\n      allowNull: true,\n      type: Sequelize.ENUM('1-day', '7-day', '1-month', '3-month', '6-month', '1-year')\n    }).then(function () {\n      return queryInterface.sequelize.query(\"UPDATE time SET newcolum = oldcolumn\");\n    });\n  },\n\n  down: function (queryInterface, Sequelize) {\n  }\n};\n```\n\n```text\nreturn queryInterface.sequelize.query(\"UPDATE time SET newcolum = oldcolumn::enum_time_newcolumn\");\n```\n\n```text\noldcolumn\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":63,"estimatedTokens":413}}924{"id":"stack-28990573","source":"stackoverflow","questionId":28990573,"title":"Sequelize.js many to many eager loading","tags":["database","node.js","many-to-many","sequelize.js","eager-loading"],"text":"Title: Sequelize.js many to many eager loading\nTags: database, node.js, many-to-many, sequelize.js, eager-loading\nSource: Stack Overflow\n\nQuestion:\nI have 2 models: `User` and `Team`\n\nThere are multiple kinds of users (in this case Mentors and Moderators) which are differentiated using an attribute in the `User` model(). The associations between `User` and `Team` are as below:\n\n```\nUser.hasMany(models.Team, {as: 'Mentors', through: models.TeamMentor, foreignKey: 'mentorId'});\nUser.hasMany(models.Team, {as: 'Moderators', through: models.TeamModerator, foreignKey: 'moderatorId'});\n\nTeam.hasMany(models.User, {through: models.TeamMentor, foreignKey: 'teamId'});\nTeam.hasMany(models.User, {through: models.TeamModerator, foreignKey: 'teamId'});\n```\n\nNow I am trying to get the details of the team along with separate objects for all the mentors and moderators that are assigned to the teams. I came to know about the getters and setters for many to many relationships from the documentation but I am not sure how to use the method since there are two different kinds of associations between two models here: \n\n- Team - Mentor (User)\n\n- Team - Moderator (User)\n\nHow to correctly query for a team's details in this case?\n\nPS: `TeamMentor` and `TeamModerator` are empty models to help the many to many joins\n\n========================================\n\nCode:\n```text\nUser.hasMany(models.Team, {as: 'Mentors', through: models.TeamMentor, foreignKey: 'mentorId'});\nUser.hasMany(models.Team, {as: 'Moderators', through: models.TeamModerator, foreignKey: 'moderatorId'});\n\n\nTeam.hasMany(models.User, {through: models.TeamMentor, foreignKey: 'teamId'});\nTeam.hasMany(models.User, {through: models.TeamModerator, foreignKey: 'teamId'});\n```\n\n```text\nUser\n```\n\n```text\nTeam\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nTeam\n```\n\n```text\nTeamMentor\n```\n\n```text\nTeamModerator\n```\n\n```text\nUser ---mentors many---> Teams\nUser --moderates many--> Teams\n\nTeam --is moderated by many--> Users\nTeam --is mentored by many---> Users\n```\n\n```text\nTeam.hasMany(models.User, {as: 'mentors', through: models.TeamMentor, foreignKey: 'teamId'});\nTeam.hasMany(models.User, {as: 'moderators', through: models.TeamModerator, foreignKey: 'teamId'});\n```\n\n```text\nTeam.findAll({\n  where: {...},\n  include: [\n    {model: User, as: `moderators` },\n    {model: User, as: `mentors` }\n\n    // or just use this to include everything:\n    // include: [{all:true}]\n  ]\n}).then(function(teams) {\n  console.log(JSON.stringify(teams));\n  // oneTeam.moderators: [array of User]\n  // oneTeam.mentors: [array of User]\n});\n```\n\n```text\nas\n```\n\n```text\nUser.hasMany(Team)\n```\n\n```text\nTeam.hasMany(User)\n```\n\n========================================\n\nComments:\n- Worked like a charm! I was missing the `as` option in the associations. Thanks :) Sequelize devs need to improve the documentation a lot! Most of the things are not even documented.","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":113,"estimatedTokens":726}}925{"id":"stack-69651891","source":"stackoverflow","questionId":69651891,"title":"Why does Sequelize pluralize 'media' to medium","tags":["javascript","node.js","sequelize.js"],"text":"Title: Why does Sequelize pluralize 'media' to medium\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm having a really big issue with sequelize trying to give me its best guess at what it thinks my table name is.\n\nI have 3 tables. Properties, Media and a junction table PropertyMedia\n\nFor some reason when I do a join query with sequelize it gives me the error\n\n`error: column Properties->PropertyMedia.medium_id does not exist`\n\nI have done a global search to make sure that I don't have the word medium anywhere and I don't\n\n```\nlet Media = sequelize.define('Media', {\n url: DataTypes.STRING,\n isVideo: DataTypes.BOOLEAN\n}, { freezeTableName: true, tableName: 'media' });\n\nlet PropertyMedia = sequelize.define('PropertyMedia', {\n propertyId: DataTypes.INTEGER,\n mediaId: DataTypes.INTEGER\n}, { freezeTableName: true, tableName: 'property_media' });\n```\n\n========================================\n\nCode:\n```text\nlet Media = sequelize.define('Media', {\n    url: DataTypes.STRING,\n    isVideo: DataTypes.BOOLEAN\n}, { freezeTableName: true, tableName: 'media' });\n\nlet PropertyMedia = sequelize.define('PropertyMedia', {\n    propertyId: DataTypes.INTEGER,\n    mediaId: DataTypes.INTEGER\n}, { freezeTableName: true, tableName: 'property_media' });\n```\n\n```text\nerror: column Properties->PropertyMedia.medium_id does not exist\n```\n\n```text\nuser_id\n```\n\n```text\nusers\n```\n\n```text\nmedium_id\n```\n\n```text\nmedia_id\n```\n\n```text\nmedia\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":65,"estimatedTokens":365}}926{"id":"stack-45130037","source":"stackoverflow","questionId":45130037,"title":"sequelize-typescript many-to-many relationship model data with","tags":["postgresql","typescript","many-to-many","sequelize.js"],"text":"Title: sequelize-typescript many-to-many relationship model data with\nTags: postgresql, typescript, many-to-many, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using sequelize with sequelize-typescript library, and am trying to achieve the following relationship:\n\nTeam.ts \n\n```\n@Scopes({\n withPlayers: {\n include: [{model: () => User}]\n }\n})\n@Table\nexport default class Team extends Model {\n\n @AllowNull(false)\n @Column\n name: string;\n\n @BelongsToMany(() => User, () => TeamPlayer)\n players: User[];\n}\n```\n\nUser.ts\n\n```\n@Scopes({\n withTeams: {\n include: [{model: () => Team, include: [ () => User ]}]\n }\n})\n@Table\nexport default class User extends Model {\n\n @AllowNull(false)\n @Column\n firstName: string;\n\n @AllowNull(false)\n @Column\n lastName: string;\n\n @BelongsToMany(() => Team, () => TeamPlayer)\n teams: Team[];\n}\n```\n\nTeamPlayer.ts\n\n```\n@DefaultScope({\n include: [() => Team, () => User],\n attributes: ['number']\n})\n@Table\nexport default class TeamPlayer extends Model {\n\n @ForeignKey(() => User)\n @Column\n userId: number;\n\n @ForeignKey(() => Team)\n @Column\n teamId: number;\n\n @Unique\n @Column\n number: number;\n}\n```\n\nNow when querying for player, you get the object with the following data:\n\n```\n{\n \"id\": 1,\n \"name\": \"Doe's Team\",\n \"players\": [\n {\n \"id\": 1,\n \"firstName\": \"John\",\n \"lastName\": \"Doe\",\n \"TeamPlayer\": {\n \"userId\": 1,\n \"teamId\": 1,\n \"number\": 32\n }\n }]\n}\n```\n\nNow there are couple of things that I cannot get done..\n\n1) I want to rename the `TeamPlayer` to something like \"membership\"; but not by changing the name of the class\n2) the content of `TeamPlayer` should not have the id`s, but I want it to contain the data of the team, for example:\n\n```\n{\n \"firstName\": \"John\",\n \"lastName\": \"Doe\"\n \"membership\": {\n \"number\": 32\n }\n```\n\nIn the above classes, I tried to set a scope to the `TeamPlayer` class to only include `number` inside the `TeamMember` inclusion, but no effect.\n\nI used to have the `TeamPlayer` class have direct memberships to `team` and `player`, but that solution added redundant `id` to the `TeamPlayer` class, and also did not prevent duplicate memberships in the team. I could indeed manually (= in code) prevent duplicates in these situations, but that does not feel elegant.\n\n========================================\n\nCode:\n```text\n@Scopes({\n  withPlayers: {\n    include: [{model: () => User}]\n  }\n})\n@Table\nexport default class Team extends Model<Team> {\n\n  @AllowNull(false)\n  @Column\n  name: string;\n\n  @BelongsToMany(() => User, () => TeamPlayer)\n  players: User[];\n}\n```\n\n```text\n@Scopes({\n  withTeams: {\n    include: [{model: () => Team, include: [ () => User ]}]\n  }\n})\n@Table\nexport default class User extends Model<User> {\n\n  @AllowNull(false)\n  @Column\n  firstName: string;\n\n  @AllowNull(false)\n  @Column\n  lastName: string;\n\n  @BelongsToMany(() => Team, () => TeamPlayer)\n  teams: Team[];\n}\n```\n\n```text\n@DefaultScope({\n  include: [() => Team, () => User],\n  attributes: ['number']\n})\n@Table\nexport default class TeamPlayer extends Model<TeamPlayer> {\n\n  @ForeignKey(() => User)\n  @Column\n  userId: number;\n\n  @ForeignKey(() => Team)\n  @Column\n  teamId: number;\n\n  @Unique\n  @Column\n  number: number;\n}\n```\n\n```text\n{\n  \"id\": 1,\n  \"name\": \"Doe's Team\",\n  \"players\": [\n    {\n      \"id\": 1,\n      \"firstName\": \"John\",\n      \"lastName\": \"Doe\",\n      \"TeamPlayer\": {\n        \"userId\": 1,\n        \"teamId\": 1,\n        \"number\": 32\n    }\n }]\n}\n```\n\n```text\n{\n  \"firstName\": \"John\",\n  \"lastName\": \"Doe\"\n  \"membership\": {\n     \"number\": 32\n }\n```\n\n```text\nTeamPlayer\n```\n\n```text\nTeamPlayer\n```\n\n```text\nTeamPlayer\n```\n\n```text\nnumber\n```\n\n```text\nTeamMember\n```\n\n```text\nTeamPlayer\n```\n\n```text\nteam\n```\n\n```text\nplayer\n```\n\n```text\nid\n```\n\n```text\nTeamPlayer\n```\n\n```text\n@Table\nexport default class TeamPlayer extends Model<TeamPlayer> {\n\n  @BelongsTo(() => Team)\n  team: Team;\n\n  @ForeignKey(() => Team)\n  @PrimaryKey\n  @Column\n  teamId: number;\n\n  @BelongsTo(() => User)\n  user: User;\n\n  @ForeignKey(() => User)\n  @PrimaryKey\n  @Column\n  userId: number;\n\n  @Column\n  number: number;\n}\n```\n\n```text\n@Table\nexport default class User extends Model<User> {\n\n  @AllowNull(false)\n  @Column\n  firstName: string;\n\n  @AllowNull(false)\n  @Column\n  lastName: string;\n\n  @HasMany(() => TeamPlayer)\n  teams: TeamPlayer[];\n}\n```\n\n```text\nexport default class Team extends Model<Team> {\n  @AllowNull(false)\n  @Column\n  name: string;\n\n  @HasMany(() => TeamPlayer)\n  players: TeamPlayer[];\n}\n```\n\n```text\nTeamPlayer\n```\n\n```text\nUser\n```\n\n```text\nTeam\n```\n\n```text\nteamId\n```\n\n```text\nuserId\n```\n\n```text\n@ForeignKey\n```\n\n========================================\n\nComments:\n- I think `teams` column of User model should be `@HasMany(() => Team)` instead of `TeamPlayer`. Is it correct?","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":326,"estimatedTokens":1182}}927{"id":"stack-24421151","source":"stackoverflow","questionId":24421151,"title":"Can Sequelize.js for Node.js define a table where the Primary Key is not named 'id'?","tags":["javascript","mysql","sql","node.js","sequelize.js"],"text":"Title: Can Sequelize.js for Node.js define a table where the Primary Key is not named 'id'?\nTags: javascript, mysql, sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a simple MySQL table named `things`. My `things` table has three columns:\n\n```\nColumn Name Data Type\n=========== ============\nthing_id INT // The auto increment Primary Key\nthing_name VARCHAR(255)\nthing_size INT\n```\n\nAs far as I can tell Sequelize.js expects/requires the Primary Key be named 'id'.\n\nIs there a way to use the standard `sequelize.define()` call to define the my `things` table? If not, is there another way?\n\n========================================\n\nCode:\n```text\nColumn Name  Data Type\n===========  ============\nthing_id     INT           // The auto increment Primary Key\nthing_name   VARCHAR(255)\nthing_size   INT\n```\n\n```text\nthings\n```\n\n```text\nthings\n```\n\n```text\nsequelize.define()\n```\n\n```text\nthings\n```\n\n```text\nvar Test = sequelize.define( 'things', {\n    thing_id   : {type: Sequelize.INTEGER(11), primaryKey: true, autoIncrement: true},\n    thing_name          : {type: Sequelize.STRING(255)},\n    thing_size      : {type: Sequelize.INTEGER}\n},{\n});\n\nTest.sync()\n.success(function(){\n    console.log('table created');\n})\n.error(function(error){\n    console.log('failed', error)\n})\n```\n\n========================================\n\nComments:\n- Sequelize earlier only supported \"id\" as PK but in later versions should fully support custom primary keys.","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":67,"estimatedTokens":366}}928{"id":"stack-15559679","source":"stackoverflow","questionId":15559679,"title":"What Node.js frameworks utilize the Sequelize ORM","tags":["node.js","sequelize.js"],"text":"Title: What Node.js frameworks utilize the Sequelize ORM\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm contemplating giving node.js a try and have been trying to find an environment that is similar to Rails and Activerecord. After a lot of research and googling, I've come to the conclusion that the Sequelize ORM is a pretty good starting point. What I can't quite figure out is what Node.js frameworks utilize Sequelize or does adopting Sequelize mean that I forego the framework all together. \n\nI know that Metamarkets has adopted Sequelize. I'd be interested in hearing from anyone who is using Sequelize and to learn what your development stack is. Any color you can offer on the environment and your experience would be greatly appreciated.\n\n========================================\n\nComments:\n- +1 for sharing my opinion about foreign key constraints not actually being enforce\n- I just want to add that those features are planned for 1.7.0: github.com/sequelize/sequelize#170","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":14,"estimatedTokens":251}}929{"id":"stack-67919370","source":"stackoverflow","questionId":67919370,"title":"Array of values ILIKE some value","tags":["sql","postgresql","sequelize.js"],"text":"Title: Array of values ILIKE some value\nTags: sql, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLets say I have an array of strings returned by some subquery. And I want to make sure that at least one of the elements is matching with string (for example: ILIKE \"%alex%\"). What should I do for that?\nMy code:\n\n```\nANY(ARRAY[\"Alexander\", \"Michael\", \"John\"]) ILIKE \"%alex%\"\n```\n\nis not working at all.\nI need a solution which will return true in my case, because one of the elements(Alexander) is ILIKE \"%alex%\".\n\n========================================\n\nCode:\n```text\nANY(ARRAY[\"Alexander\", \"Michael\", \"John\"]) ILIKE \"%alex%\"\n```\n\n```text\nwhere exists (select 1 from unnest(ARRAY['Alexander', 'Michael', 'John']) el where el ILIKE '%alex%')\n```\n\n```text\nexists\n```\n\n========================================\n\nComments:\n- Are you using MySQL or Postgresql?\n- I'm using Postgresql\n- like this? dba.stackexchange.com/questions/228235/&hellip; ?\n- Took me way too long to find this. In my case my column was the array so all the basic results on google didn't work. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":37,"estimatedTokens":271}}930{"id":"stack-62623432","source":"stackoverflow","questionId":62623432,"title":"Should I keep Sequelize instance throughout server running time?","tags":["node.js","sequelize.js"],"text":"Title: Should I keep Sequelize instance throughout server running time?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a Sequelize instance and it is exported in a file to be accessed when doing DB operations.\n\n```\nconst sequelize = new Sequelize('database', 'username', null, {\n dialect: 'mysql'\n});\nmodule.exports = sequelize;\n```\n\nSo the instance is created when the expressjs server starts and never destroys. I wonder if this is the correct way to do, or should I call `new Sequelize` every time I use the DB operation?\n\nI think it should be kept alive because that's how DB pooling could take effect. Right?\n\n========================================\n\nCode:\n```js\nconst sequelize = new Sequelize('database', 'username', null, {\n  dialect: 'mysql'\n});\nmodule.exports = sequelize;\n```\n\n```text\nnew Sequelize\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":31,"estimatedTokens":209}}931{"id":"stack-22083959","source":"stackoverflow","questionId":22083959,"title":"How do I implement sequelize migration down functionality for databases?","tags":["javascript","database","node.js","database-migration","sequelize.js"],"text":"Title: How do I implement sequelize migration down functionality for databases?\nTags: javascript, database, node.js, database-migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn Sequelize.js, i have created an example migration file: \n\n```\nmodule.exports = {\n up: function(migration, DataTypes, done) {\n // add altering commands here, calling 'done' when finished\n migration.createTable('Users', {\n id: {\n type: DataTypes.INTEGER, \n primaryKey: true, \n autoIncrement: true, \n }, \n createdAt: {\n type: DataTypes.DATE\n },\n updatedAt: {\n type: DataTypes.DATE\n },\n firstname: DataTypes.STRING, \n lastname: DataTypes.STRING,\n email: DataTypes.STRING, \n password: DataTypes.STRING,\n });\n done()\n },\n down: function(migration, DataTypes, done) {\n // add reverting commands here, calling 'done' when finished\n done()\n }\n}\n```\n\nCould someone explain the use cases and possible implementation of both up and down functionality? \n\nThank you!\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  up: function(migration, DataTypes, done) {\n    // add altering commands here, calling 'done' when finished\n    migration.createTable('Users', {\n        id: {\n            type: DataTypes.INTEGER, \n            primaryKey: true, \n            autoIncrement: true, \n        }, \n        createdAt: {\n          type: DataTypes.DATE\n        },\n        updatedAt: {\n          type: DataTypes.DATE\n        },\n        firstname: DataTypes.STRING, \n        lastname: DataTypes.STRING,\n        email: DataTypes.STRING, \n        password: DataTypes.STRING,\n    });\n    done()\n  },\n  down: function(migration, DataTypes, done) {\n    // add reverting commands here, calling 'done' when finished\n    done()\n  }\n}\n```\n\n```text\nmodule.exports = {\n\n    up: function(migration, DataTypes, done) {\n\n        // add altering commands here, calling 'done' when finished\n        migration.createTable( 'Users', {\n\n            id: {\n                type: DataTypes.INTEGER,\n                primaryKey: true,\n                autoIncrement: true,\n            },\n            createdAt: {\n                type: DataTypes.DATE\n            },\n            updatedAt: {\n                type: DataTypes.DATE\n            },\n            firstname: DataTypes.STRING,\n            lastname: DataTypes.STRING,\n            email: DataTypes.STRING,\n            password: DataTypes.STRING,\n\n        })\n        .nodeify( done );\n    },\n\n    down: function(migration, DataTypes, done) {\n    // add reverting commands here, calling 'done' when finished\n\n        migration.dropTable('Users')\n        .nodeify( done );\n\n    }\n\n};\n```\n\n```text\nUsers\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nUsers\n```\n\n```text\nsequelize db:migrate:undo\n```\n\n```text\nUsers\n```\n\n```text\nUsers\n```\n\n========================================\n\nComments:\n- If you not see cases in your project, don't use this function. Keep it short and simple. For example: create dbsync script and run it when you update the model.\n- Hi, I am unaware of possible use cases. Sequelize Documentation does not explain this thoroughly. Could you show me an example? Thank you!\n- What's your question exactly? I don't understand it quite well.... If you mean what's up and what's down: - up: all commands will be executed when running sequelize db:migrate - down: all commands will be executed when running sequelize db:migrate:undo. Sequelize also says the development environment is default, but I experienced problems with this. So I have to execute all commands with --env development at the end.","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":143,"estimatedTokens":883}}932{"id":"stack-67249534","source":"stackoverflow","questionId":67249534,"title":"heroku sequelize: command not found","tags":["mysql","node.js","heroku","sequelize.js"],"text":"Title: heroku sequelize: command not found\nTags: mysql, node.js, heroku, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have installed sequelize cli using the following command\n\n```\nnpm install -g sequelize-cli\n```\n\nIt works fine on localhost\n\nBut when I deploy to heroku and try to run migrations\n\nI get error\n\n```\nsequelize: command not found\n```\n\n========================================\n\nTop Answer:\nAs for me I was trying to run sequelize DB migration to heroku postgress database. As per earlier documentations, or maybe what you tried, was to run the command `heroku run sequelize db:migrate`\n\nThis however is what seems to work now `heroku run npx sequelize-cli db:migrate`\n\n========================================\n\nCode:\n```text\nnpm install -g sequelize-cli\n```\n\n```text\nsequelize: command not found\n```\n\n```text\nsequelize-cli\n```\n\n```text\nscript\n```\n\n```text\nHeroku CLI\n```\n\n```text\nHeroku CLI\n```\n\n```text\nHeroku\n```\n\n```text\npackage\n```\n\n```text\nHeroku\n```\n\n```text\ndb:migrate\n```\n\n```text\nsequelize-cli\n```\n\n```text\nsequelize-cli\n```\n\n```text\ndependency\n```\n\n```text\npackage.json\n```\n\n```text\nmigrate: \"sequelize db:migrate\"\n```\n\n```text\nHeroku\n```\n\n```text\nHeroku\n```\n\n```text\nheroku run sequelize db:migrate\n```\n\n```text\nheroku run npx sequelize-cli db:migrate\n```\n\n========================================\n\nComments:\n- Or also you can define in your Procfile: `release: npx sequelize-cli db:migrate`, in order to run this everytime you deploy","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":111,"estimatedTokens":366}}933{"id":"stack-69836342","source":"stackoverflow","questionId":69836342,"title":"How to use both 'include' and 'attributes' in 'findByPk' statement in Sequelize?","tags":["node.js","postgresql","express","orm","sequelize.js"],"text":"Title: How to use both 'include' and 'attributes' in 'findByPk' statement in Sequelize?\nTags: node.js, postgresql, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow to use both 'include' and 'attributes' in 'findByPk' statement in Sequelize. This is my code:\n\n```\nexports.findOne = (req, res) => {\n var id = req.params.id;\n\n User.findByPk(id, \n \n {\n include: [\"roles\"] \n }, \n {\n attributes: {\n exclude: ['password']\n }\n }\n )\n .then(data => {\n res.send({\"data\": data, \"resultCode\": 1, \"message\": \"\"});\n })\n .catch(err => {\n res.status(500).send({\n message:\n err.message || \"Some error occurred while retrieving users.\"\n });\n });;\n\n}\n```\n\nBut it only works when I use 1 of 2 only.\nIf I just use: `attributes: { exclude: ['password']}` the result is as follows:\n\n```\n{\n \"data\": {\n \"id\": 1,\n \"username\": \"admin\",\n \"email\": \"admin@gmail.com\",\n \"createdAt\": \"2021-09-27T04:22:56.660Z\",\n \"updatedAt\": \"2021-09-27T04:22:56.660Z\"\n },\n \"resultCode\": 1,\n \"message\": \"\"\n}\n```\n\nIf I just use: `{include: [\"roles\"]}` so the result is as follows\n\n```\n{\n \"data\": {\n \"id\": 1,\n \"username\": \"admin\",\n \"email\": \"admin@gmail.com\",\n \"password\": \"$2a$08$m54ioIwzpZRVC9/HqkHyqezOornjmvT9pDEJcOhHbNcSmLOfw3Sg.\",\n \"createdAt\": \"2021-09-27T04:22:56.660Z\",\n \"updatedAt\": \"2021-09-27T04:22:56.660Z\",\n \"roles\": [\n {\n \"id\": 2,\n \"name\": \"moderator\",\n \"createdAt\": \"2021-09-27T04:20:46.956Z\",\n \"updatedAt\": \"2021-09-27T04:20:46.956Z\",\n \"user_roles\": {\n \"createdAt\": \"2021-09-27T04:22:56.791Z\",\n \"updatedAt\": \"2021-09-27T04:22:56.791Z\",\n \"roleId\": 2,\n \"userId\": 1\n }\n },\n {\n \"id\": 3,\n \"name\": \"admin\",\n \"createdAt\": \"2021-09-27T04:20:46.956Z\",\n \"updatedAt\": \"2021-09-27T04:20:46.956Z\",\n \"user_roles\": {\n \"createdAt\": \"2021-09-27T04:22:56.791Z\",\n \"updatedAt\": \"2021-09-27T04:22:56.791Z\",\n \"roleId\": 3,\n \"userId\": 1\n }\n }\n ]\n },\n \"resultCode\": 1,\n \"message\": \"\"\n}\n```\n\nHow to use both in my code? Because I dont want to show 'password' field in my result but I want to show the roles of user in my result. How to do like that. Thanks you in advanced\n\n========================================\n\nCode:\n```text\nexports.findOne = (req, res) => {\n  var id = req.params.id;\n\n  User.findByPk(id, \n    \n    {\n      include: [\"roles\"] \n    }, \n    {\n      attributes: {\n         exclude: ['password']\n      }\n    }\n    )\n      .then(data => {\n        res.send({\"data\": data, \"resultCode\": 1, \"message\": \"\"});\n      })\n      .catch(err => {\n        res.status(500).send({\n          message:\n            err.message || \"Some error occurred while retrieving users.\"\n        });\n      });;\n\n}\n```\n\n```text\n{\n    \"data\": {\n        \"id\": 1,\n        \"username\": \"admin\",\n        \"email\": \"admin@gmail.com\",\n        \"createdAt\": \"2021-09-27T04:22:56.660Z\",\n        \"updatedAt\": \"2021-09-27T04:22:56.660Z\"\n    },\n    \"resultCode\": 1,\n    \"message\": \"\"\n}\n```\n\n```text\n{\n    \"data\": {\n        \"id\": 1,\n        \"username\": \"admin\",\n        \"email\": \"admin@gmail.com\",\n        \"password\": \"$2a$08$m54ioIwzpZRVC9/HqkHyqezOornjmvT9pDEJcOhHbNcSmLOfw3Sg.\",\n        \"createdAt\": \"2021-09-27T04:22:56.660Z\",\n        \"updatedAt\": \"2021-09-27T04:22:56.660Z\",\n        \"roles\": [\n            {\n                \"id\": 2,\n                \"name\": \"moderator\",\n                \"createdAt\": \"2021-09-27T04:20:46.956Z\",\n                \"updatedAt\": \"2021-09-27T04:20:46.956Z\",\n                \"user_roles\": {\n                    \"createdAt\": \"2021-09-27T04:22:56.791Z\",\n                    \"updatedAt\": \"2021-09-27T04:22:56.791Z\",\n                    \"roleId\": 2,\n                    \"userId\": 1\n                }\n            },\n            {\n                \"id\": 3,\n                \"name\": \"admin\",\n                \"createdAt\": \"2021-09-27T04:20:46.956Z\",\n                \"updatedAt\": \"2021-09-27T04:20:46.956Z\",\n                \"user_roles\": {\n                    \"createdAt\": \"2021-09-27T04:22:56.791Z\",\n                    \"updatedAt\": \"2021-09-27T04:22:56.791Z\",\n                    \"roleId\": 3,\n                    \"userId\": 1\n                }\n            }\n        ]\n    },\n    \"resultCode\": 1,\n    \"message\": \"\"\n}\n```\n\n```text\nattributes: { exclude: ['password']}\n```\n\n```text\n{include: [\"roles\"]}\n```\n\n```text\nUser.findByPk(id, \n{\n  include: [\"roles\"],\n  attributes: {\n     exclude: ['password']\n  }\n})\n```\n\n========================================\n\nComments:\n- Thanks you so much","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":205,"estimatedTokens":1083}}934{"id":"stack-68031222","source":"stackoverflow","questionId":68031222,"title":"How to use a function in select along with all the records in Sequalize?","tags":["sql","sequelize.js"],"text":"Title: How to use a function in select along with all the records in Sequalize?\nTags: sql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHere is a Sequalize query below which retrieves a transformed value based on the table column value.\n\n```\ncourses.findAll({\n attributes: [ [sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days']]\n});\n```\n\nThe above sequlaize query will return result equal to as followed SQL query.\n\n```\nselect to_char(bs.session_date, 'Day') as days from courses bs;\n```\n\n**Expected output:**\n\nI want the transformed value which is in attributes along with all records like below. I know we can mention all the column names in attributes array but it is a tedious job. Any shortcut similar to asterisk in SQL query.\n\n```\nselect to_char(bs.session_date, 'Day') as days,* from courses bs;\n```\n\nI tried the below sequalize query but no luck.\n\n```\ncourses.findAll({\n attributes: [ [sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days'],'*']\n});\n```\n\n========================================\n\nTop Answer:\nThere is one shortcut to achieve the asterisk kind of selection in Sequalize. Which can be done as follows...\n\n```\n// To get all the column names in an array\nlet attributes = Object.keys(yourModel.rawAttributes);\ncourses.findAll({\n attributes: [...attributes ,\n[sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days']]\n});\n```\n\nThis is a work around there may be a different option.\n\n========================================\n\nCode:\n```text\ncourses.findAll({\n  attributes: [ [sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days']]\n});\n```\n\n```sql\nselect to_char(bs.session_date, 'Day') as days from courses bs;\n```\n\n```sql\nselect to_char(bs.session_date, 'Day') as days,* from courses bs;\n```\n\n```text\ncourses.findAll({\n  attributes: [ [sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days'],'*']\n});\n```\n\n```js\ncourses.findAll({\n    attributes: {\n        include: [\n            [ sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days' ]\n        ]\n    }\n});\n```\n\n```text\nattributes\n```\n\n```text\ninclude\n```\n\n```text\ncourses.*\n```\n\n```text\nexclude\n```\n\n```text\nattributes\n```\n\n```text\ncourses.*\n```\n\n```text\n// To get all the column names in an array\nlet attributes = Object.keys(yourModel.rawAttributes);\ncourses.findAll({\n  attributes: [...attributes ,\n[sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days']]\n});\n```\n\n========================================\n\nComments:\n- Thanks even this worked but the official way is Include according to the doc.","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":121,"estimatedTokens":646}}935{"id":"stack-56922523","source":"stackoverflow","questionId":56922523,"title":"Run Sequelize migration files from separate third-party Node module?","tags":["node.js","orm","sequelize.js","node-modules","sequelize-cli"],"text":"Title: Run Sequelize migration files from separate third-party Node module?\nTags: node.js, orm, sequelize.js, node-modules, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am working on third-party NODE module which deal with sending emails and storing them in DB, so let's call it mail-module. In order for someone to use its functionalities, it should be enough to import it in his project and use its functions for sending and storing emails.\n\nWhat makes problem here is that someone who imports mail-module, he needs manually to create DB tables for storing emails because Sequelize CLI does not see migration scripts in separate modules. In mail-module there are Sequelize migration scripts but it's cumbersome for developers to look for it in module, than copy it in his own project and run as it's part of his project.\n\nIs there any way to avoid this manual work and make configuration such that when developer (user of mail-module) run his own migrations scripts, mail-module migration scripts are performed too?\n\n========================================\n\nCode:\n```text\n{\n  ...\n  \"scripts\": {\n    \"dbs-migrate\": \"./node_modules/.bin/sequelize db:migrate && ./node_modules/.bin/sequelize db:migrate --migrations-path ./node_modules/mail-module/lib/migrations\"\n  }\n}\n```\n\n```text\n--migrations-path\n```\n\n```text\ndb:migrate\n```\n\n```text\n./node_modules/.bin/sequelize db:migrate\n```\n\n```text\nnode_modules/main-module/lib/migrations\n```\n\n```text\npackage.json\n```\n\n```text\nnpm run dbs-migrate\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":46,"estimatedTokens":375}}936{"id":"stack-62525598","source":"stackoverflow","questionId":62525598,"title":"Sequelize [ES6] Separate files circular reference","tags":["node.js","ecmascript-6","sequelize.js"],"text":"Title: Sequelize [ES6] Separate files circular reference\nTags: node.js, ecmascript-6, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThere are two files, one called\n\n***customer.model.js***\n\n```\nimport DbContext from '../databaseContext'\nimport Sequelize from 'sequelize'\nimport LeaseModel from './lease.model';\n\nconst CustomerModel = DbContext.define('customer', {\n first_name: {\n type: Sequelize.STRING(50)\n },\n middle_name: {\n type: Sequelize.STRING\n },\n last_name: {\n type: Sequelize.STRING(50)\n },\n email: {\n type: Sequelize.STRING(62)\n }\n})\n\nCustomerModel.hasMany(LeaseModel)\n\nexport default CustomerModel\n```\n\n***lease.model.js***\n\n```\nimport Sequelize from 'sequelize'\n\nconst LeaseModel = DbContext.define('lease', {\n lease_name: {\n type: Sequelize.STRING(50)\n },\n customer_id: {\n type: Sequelize.IndexHints\n }\n})\n\nexport default LeaseModel\n```\n\nIf I add the following `Lease.belongsTo(CustomerModel)` to ***lease.model.js*** to indicate foreign key relationship I will get circular reference what is the good way to solve this?\n\n========================================\n\nTop Answer:\nCreate an `index.js` file. Import all models in this file and associate them. After this, re-export these models.\n\nE.g.\n\n`models/customer.model.js`:\n\n```\nimport DbContext from '../databaseContext'\nimport Sequelize from 'sequelize'\n\nconst CustomerModel = DbContext.define('customer', {\n first_name: {\n type: Sequelize.STRING(50)\n },\n middle_name: {\n type: Sequelize.STRING\n },\n last_name: {\n type: Sequelize.STRING(50)\n },\n email: {\n type: Sequelize.STRING(62)\n }\n});\n\nexport default CustomerModel;\n```\n\n`models/lease.model.js`:\n\n```\nimport Sequelize from 'sequelize'\nimport DbContext from '../databaseContext'\n\nconst LeaseModel = DbContext.define('lease', {\n lease_name: {\n type: Sequelize.STRING(50)\n },\n customer_id: {\n type: Sequelize.IndexHints\n }\n})\n\nexport default LeaseModel\n```\n\n`models/index.js`:\n\n```\nimport CustomerModel from './customer.model'\nimport LeaseModel from './lease.model';\n// import other models...\n\nCustomerModel.hasMany(LeaseModel);\nLeaseModel.belongsTo(CustomerModel);\n// associate other models...\n\nexport {CustomerModel, LeaseModel}\n```\n\n========================================\n\nCode:\n```text\nimport DbContext from '../databaseContext'\nimport Sequelize from 'sequelize'\nimport LeaseModel from './lease.model';\n\nconst CustomerModel = DbContext.define('customer', {\n  first_name: {\n    type: Sequelize.STRING(50)\n  },\n  middle_name: {\n    type: Sequelize.STRING\n  },\n  last_name: {\n    type: Sequelize.STRING(50)\n  },\n  email: {\n    type: Sequelize.STRING(62)\n  }\n})\n\nCustomerModel.hasMany(LeaseModel)\n\n\nexport default CustomerModel\n```\n\n```text\nimport Sequelize from 'sequelize'\n\nconst LeaseModel = DbContext.define('lease', {\n  lease_name: {\n    type: Sequelize.STRING(50)\n  },\n  customer_id: {\n    type: Sequelize.IndexHints\n  }\n})\n\nexport default LeaseModel\n```\n\n```text\nLease.belongsTo(CustomerModel)\n```\n\n```text\nSequelize\n```\n\n```js\nimport DbContext from '../databaseContext'\nimport Sequelize from 'sequelize'\n\nconst CustomerModel = DbContext.define('customer', {\n  first_name: {\n    type: Sequelize.STRING(50)\n  },\n  middle_name: {\n    type: Sequelize.STRING\n  },\n  last_name: {\n    type: Sequelize.STRING(50)\n  },\n  email: {\n    type: Sequelize.STRING(62)\n  }\n});\n\nexport default CustomerModel;\n```\n\n```js\nimport Sequelize from 'sequelize'\nimport DbContext from '../databaseContext'\n\nconst LeaseModel = DbContext.define('lease', {\n  lease_name: {\n    type: Sequelize.STRING(50)\n  },\n  customer_id: {\n    type: Sequelize.IndexHints\n  }\n})\n\nexport default LeaseModel\n```\n\n```js\nimport CustomerModel from './customer.model'\nimport LeaseModel from './lease.model';\n// import other models...\n\nCustomerModel.hasMany(LeaseModel);\nLeaseModel.belongsTo(CustomerModel);\n// associate other models...\n\nexport {CustomerModel, LeaseModel}\n```\n\n```text\nindex.js\n```\n\n```text\nmodels/customer.model.js\n```\n\n```text\nmodels/lease.model.js\n```\n\n```text\nmodels/index.js\n```\n\n========================================\n\nComments:\n- interesting, my only challenge is that there could be 100 tables and those relationships will ad up\n- @eugenekgn This is the method I used in combination with typescript in the project. I have 30 tables more or less.","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":239,"estimatedTokens":1063}}937{"id":"stack-58778878","source":"stackoverflow","questionId":58778878,"title":"Node.js - How to use Sequelize transaction","tags":["javascript","mysql","node.js","transactions","sequelize.js"],"text":"Title: Node.js - How to use Sequelize transaction\nTags: javascript, mysql, node.js, transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am a beginner with `sequelize` and cannot get the transactions to work. Documentation is unclear and makes the following example not able to adapt to my requirements. \n\n```\nreturn sequelize.transaction(t => {\n // chain all your queries here. make sure you return them.\n return User.create({\n firstName: 'Abraham',\n lastName: 'Lincoln'\n }, {transaction: t}).then(user => {\n return user.setShooter({\n firstName: 'John',\n lastName: 'Boothe'\n }, {transaction: t});\n });\n\n}).then(result => {\n // Transaction has been committed\n // result is whatever the result of the promise chain returned to the transaction callback\n}).catch(err => {\n // Transaction has been rolled back\n // err is whatever rejected the promise chain returned to the transaction callback\n});\n```\n\nFirst I have to insert a tuple in 'Conto', then insert another tuple in 'Preferenze' and finally based on the 'tipo' attribute insert a tuple in 'ContoPersonale' or 'ContoAziendale'. \n\nIf only one of these queries fails, the transaction must make a total rollback, commit.\n\nThe queries are:\n\n```\nConto.create({\n id: nextId(),\n mail: reg.email,\n password: reg.password,\n tipo: reg.tipo,\n telefono: reg.telefono,\n idTelegram: reg.telegram,\n saldo: saldoIniziale,\n iban: generaIBAN()\n })\n\nPreferenze.create({\n refConto: 68541\n })\n\nif (tipo == 0) {\n ContoPersonale.create({\n nomeint: reg.nome,\n cognomeint: reg.cognome,\n dataN: reg.datan,\n cf: reg.cf,\n refConto: nextId()\n }) \n }\nelse if (tipo == 1) { \n ContoAziendale.create({\n pIva: reg.piva,\n ragioneSociale: reg.ragsoc,\n refConto: nextId()\n })\n }\n```\n\n========================================\n\nCode:\n```text\nreturn sequelize.transaction(t => {\n  // chain all your queries here. make sure you return them.\n  return User.create({\n    firstName: 'Abraham',\n    lastName: 'Lincoln'\n  }, {transaction: t}).then(user => {\n    return user.setShooter({\n      firstName: 'John',\n      lastName: 'Boothe'\n    }, {transaction: t});\n  });\n\n}).then(result => {\n  // Transaction has been committed\n  // result is whatever the result of the promise chain returned to the transaction callback\n}).catch(err => {\n  // Transaction has been rolled back\n  // err is whatever rejected the promise chain returned to the transaction callback\n});\n```\n\n```text\nConto.create({\n        id: nextId(),\n        mail: reg.email,\n        password: reg.password,\n        tipo: reg.tipo,\n        telefono: reg.telefono,\n        idTelegram: reg.telegram,\n        saldo: saldoIniziale,\n        iban: generaIBAN()\n    })\n\nPreferenze.create({\n        refConto: 68541\n    })\n\nif (tipo == 0) {\n        ContoPersonale.create({\n        nomeint: reg.nome,\n        cognomeint: reg.cognome,\n        dataN: reg.datan,\n        cf: reg.cf,\n        refConto: nextId()\n        }) \n        }\nelse if (tipo == 1) { \n        ContoAziendale.create({\n        pIva: reg.piva,\n        ragioneSociale: reg.ragsoc,\n        refConto: nextId()\n        })\n        }\n```\n\n```text\nsequelize\n```\n\n```text\nsequelize.transaction((transaction) => {\n  // execute all queries, pass in transaction\n  return Promise.all([\n    Conto.create({\n      id: nextId(),\n      mail: reg.email,\n      password: reg.password,\n      tipo: reg.tipo,\n      telefono: reg.telefono,\n      idTelegram: reg.telegram,\n      saldo: saldoIniziale,\n      iban: generaIBAN()\n    }, { transaction }),\n\n    Preferenze.create({\n      refConto: 68541\n    }, { transaction }),\n\n    // this query is determined by \"tipo\"\n    tipo === 0\n      ? ContoPersonale.create({\n          nomeint: reg.nome,\n          cognomeint: reg.cognome,\n          dataN: reg.datan,\n          cf: reg.cf,\n          refConto: nextId()\n        }, { transaction })\n      : ContoAziendale.create({\n          pIva: reg.piva,\n          ragioneSociale: reg.ragsoc,\n          refConto: nextId()\n        }, { transaction })\n  ]);\n\n  // if we get here it will auto commit\n  // if there is an error it with automatically roll back.\n\n})\n.then(() => {\n  console.log('queries ran successfully');\n})\n.catch((err) => {\n  console.log('queries failed', err);\n});\n```\n\n```text\nlet transaction;\ntry {\n  // start a new transaction\n  transaction = await sequelize.transaction();\n\n  // run queries, pass in transaction\n  await Promise.all([\n    Conto.create({\n      id: nextId(),\n      mail: reg.email,\n      password: reg.password,\n      tipo: reg.tipo,\n      telefono: reg.telefono,\n      idTelegram: reg.telegram,\n      saldo: saldoIniziale,\n      iban: generaIBAN()\n    }, { transaction }),\n\n    Preferenze.create({\n      refConto: 68541\n    }, { transaction }),\n\n    // this query is determined by \"tipo\"\n    tipo === 0\n      ? ContoPersonale.create({\n          nomeint: reg.nome,\n          cognomeint: reg.cognome,\n          dataN: reg.datan,\n          cf: reg.cf,\n          refConto: nextId()\n        }, { transaction })\n      : ContoAziendale.create({\n          pIva: reg.piva,\n          ragioneSociale: reg.ragsoc,\n          refConto: nextId()\n        }, { transaction })\n  ]);\n\n  // if we get here they ran successfully, so...\n  await transaction.commit();\n} catch (err) {\n  // if we got an error and we created the transaction, roll it back\n  if (transaction) {\n    await transaction.rollback();\n  }\n  console.log('Err', err);\n}\n```\n\n```text\ntransaction.commit()\n```\n\n```text\ntransaction.rollback()\n```\n\n```text\nasync/await\n```\n\n```text\nPromise.all()\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":244,"estimatedTokens":1369}}938{"id":"stack-60830587","source":"stackoverflow","questionId":60830587,"title":"greater than and less than a date gives no records in sequelize but works with heidisql","tags":["mysql","node.js","sequelize.js"],"text":"Title: greater than and less than a date gives no records in sequelize but works with heidisql\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIt's really weird, I can't debug the issue. I also don't know what's causing the issue.\n\nI have a query like below:\n\n```\nconst sequelize = require('sequelize')\nconst Op = sequelize.Op\nconst TODAY_START = new Date().setHours(0, 0, 0, 0)\nconst NOW = new Date()\n\n const data = await AssignedJob.findAll({\n where: {\n created_on: {\n [Op.gt]: TODAY_START,\n [Op.lt]: NOW\n }\n }\n })\n```\n\nIt generates a query like below.\n\n```\nSELECT `id`, `emp_id`, `zone_id`, `job_id`, `status`, `commission`, `rating`,\n`created_by`, `updated_by`, `created_on`, `updated_on` \nFROM `assigned_jobs` AS `AssignedJob` \nWHERE (`AssignedJob`.`created_on` > '2020-03-24 00:00:00' AND `AssignedJob`.`created_on` But `data` is just an `[]` empty array.\n\nI also tried using `[Op.between]: [START_DATE, NOW]`, but still I didn't get any record.\n\nI copied the same query to heidsql and ran it, I get the result there.\n\nWhat's happening here? Can someone explain?\n\nData type of `created_on` and `updated_on` in sequelize is `DATE`, in the table it's `TIMESTAMP`\n\n========================================\n\nTop Answer:\nUse moment.js to format the date in `'YYYY-MM-DD HH:mm:ss'`\n\n```\nconst sequelize = require('sequelize')\nconst moment = require('moment');\nconst Op = sequelize.Op\n\nfunction getDate(withoutTime) {\n const date = new Date();\n if (withoutTime) date.setHours(0, 0, 0, 0);\n return moment(date).format('YYYY-MM-DD HH:mm:ss');\n}\n\nconst TODAY_START = getDate(true); // '2020-03-24 00:00:00'\nconst NOW = getDate(); // '2020-03-24 17:47:41'\n```\n\nProblem `const TODAY_START = new Date().setHours(0, 0, 0, 0)` will result in Unix time i.e seconds after 1st Jan 1970\n\n\r\n\r\n\n```\nconst date = new Date().setHours(0, 0, 0, 0)\r\n\r\nconsole.log(date); // return seconds after 1970 \r\n\r\nconst date1 = new Date();\r\ndate1.setHours(0, 0, 0, 0);\r\n\r\nconsole.log(date1); // return date\n```\n\n========================================\n\nCode:\n```text\nconst sequelize = require('sequelize')\nconst Op = sequelize.Op\nconst TODAY_START = new Date().setHours(0, 0, 0, 0)\nconst NOW = new Date()\n\n    const  data = await AssignedJob.findAll({\n        where: {\n            created_on: {\n                [Op.gt]: TODAY_START,\n                [Op.lt]: NOW\n            }\n        }\n    })\n```\n\n```text\nSELECT `id`, `emp_id`, `zone_id`, `job_id`, `status`, `commission`, `rating`,\n`created_by`, `updated_by`, `created_on`, `updated_on` \nFROM `assigned_jobs` AS `AssignedJob` \nWHERE (`AssignedJob`.`created_on` > '2020-03-24 00:00:00' AND `AssignedJob`.`created_on` < '2020-03-24 17:18:15');\n```\n\n```text\ndata\n```\n\n```text\n[]\n```\n\n```text\n[Op.between]: [START_DATE, NOW]\n```\n\n```text\ncreated_on\n```\n\n```text\nupdated_on\n```\n\n```text\nDATE\n```\n\n```text\nTIMESTAMP\n```\n\n```text\nconst moment = require('moment')\nconst now = moment()\nconst  todayAssignedJobs = await AssignedJob.findAll({\n         where: {\n            created_on: {\n                 [Op.gt]: now.startOf('day').toString(),\n                 [Op.lt]: now.endOf('day').toString()\n              },\n            status: 1\n           }\n     })\n```\n\n```text\nSELECT `id`, `emp_id`, `zone_id`, `job_id`, `status`, `commission`, `rating`, `created_by`, `updated_by`, `created_on`, `updated_on` FROM \n`assigned_jobs` AS `AssignedJob`\nWHERE \n(`AssignedJob`.`created_on` > '2020-03-24 00:00:00' AND `AssignedJob`.`created_on` <'2020-03-24 23:59:59') \nAND `AssignedJob`.`status` = 1;\n```\n\n```text\nmomentjs\n```\n\n```js\nconst sequelize = require('sequelize')\nconst moment = require('moment');\nconst Op = sequelize.Op\n\nfunction getDate(withoutTime) {\n    const date = new Date();\n    if (withoutTime) date.setHours(0, 0, 0, 0);\n    return moment(date).format('YYYY-MM-DD HH:mm:ss');\n}\n\nconst TODAY_START = getDate(true); // '2020-03-24 00:00:00'\nconst NOW = getDate(); // '2020-03-24 17:47:41'\n```\n\n```js\nconst date = new Date().setHours(0, 0, 0, 0)\n\nconsole.log(date); // return seconds after 1970 \n\nconst date1 = new Date();\ndate1.setHours(0, 0, 0, 0);\n\nconsole.log(date1); // return date\n```\n\n```text\n'YYYY-MM-DD  HH:mm:ss'\n```\n\n```text\nconst TODAY_START = new Date().setHours(0, 0, 0, 0)\n```\n\n========================================\n\nComments:\n- I need records between start of the day and end of the day. `getDateWithoutTime()` will convert both to same date.\n- No I didnt' try. If I have to use momentjs, I dont' see any reason to write functions instead of using that it already has.","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":196,"estimatedTokens":1132}}939{"id":"stack-56379980","source":"stackoverflow","questionId":56379980,"title":"Using case-when in aggregate function in Sequelize.js","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Using case-when in aggregate function in Sequelize.js\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to build the below query on a Model instead of using sequilize.query() for raw sql\n\n```\nselect \n queue,\n count(*) total,\n sum(case when type = 'Proactive' then 1 else 0 end) proactive,\n sum(case when type = 'Reactive' then 1 else 0 end) reactive\nfrom \"OpenIncidents\" \ngroup by queue\norder by total DESC;\n```\n\nI tired using sequelize.fn() for aggregate function, but found nothing in the docs regarding CASE WHEN support in aggregate function.\n\nI currently using raw query \n\n```\nreturn sequelize.query(\n `\n SELECT \n queue, \n COUNT(*) total, \n SUM(CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END) proactive, \n SUM(CASE WHEN type = 'Reactive' THEN 1 ELSE 0 END) reactive \n FROM \"OpenIncidents\" \n GROUP BY queue \n ORDER BY total DESC;\n `, \n { type: sequelize.QueryTypes.SELECT })\n .then(queues => res.json(queues))\n .catch(err => res.status(400).json(err));\n```\n\nIs there any way to do it directly on a Sequelize Model, like below\n\n```\nreturn OpenIncident.findAll({\n attributes:[\n 'queue',\n [sequelize.fn('COUNT', sequelize.col('id')), 'total'],\n [sequelize.fn('SUM', CASE_WHEN_STATEMENT, 'proactive'],\n [sequelize.fn('SUM', CASE_WHEN_STATEMENT), 'reactive']\n ],\n group: ['queue'],\n order: [sequelize.fn('COUNT', sequelize.col('id')), 'DESC']\n})\n```\n\n========================================\n\nTop Answer:\nIn case you are running into issues with the parsing following should work as of Dec 2022 Sequelize version.\n\n```\n[sequelize.fn('SUM', sequelize.literal(\"CASE WHEN status = 'PENDING' THEN 1 ELSE 0 END\")), 'pending_count'],\n```\n\n========================================\n\nCode:\n```sql\nselect \n  queue,\n  count(*) total,\n  sum(case when type = 'Proactive' then 1 else 0 end) proactive,\n  sum(case when type = 'Reactive' then 1 else 0 end) reactive\nfrom \"OpenIncidents\" \ngroup by queue\norder by total DESC;\n```\n\n```text\nreturn sequelize.query(\n    `\n    SELECT \n      queue, \n      COUNT(*) total, \n      SUM(CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END) proactive, \n      SUM(CASE WHEN type = 'Reactive' THEN 1 ELSE 0 END) reactive \n    FROM \"OpenIncidents\" \n    GROUP BY queue \n    ORDER BY total DESC;\n    `, \n    { type: sequelize.QueryTypes.SELECT })\n  .then(queues => res.json(queues))\n  .catch(err => res.status(400).json(err));\n```\n\n```text\nreturn OpenIncident.findAll({\n  attributes:[\n    'queue',\n    [sequelize.fn('COUNT', sequelize.col('id')), 'total'],\n    [sequelize.fn('SUM', CASE_WHEN_STATEMENT, 'proactive'],\n    [sequelize.fn('SUM', CASE_WHEN_STATEMENT), 'reactive']\n  ],\n  group: ['queue'],\n  order: [sequelize.fn('COUNT', sequelize.col('id')), 'DESC']\n})\n```\n\n```text\n[Sequelize.fn('SUM', Sequelize.literal('CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END')), 'proactive']\n```\n\n```text\n[sequelize.fn('SUM', sequelize.literal(\"CASE WHEN status = 'PENDING' THEN 1 ELSE 0 END\")), 'pending_count'],\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":114,"estimatedTokens":742}}940{"id":"stack-59118323","source":"stackoverflow","questionId":59118323,"title":"The right way to insert a parent/child record in sequelize with the same transaction (get parent ID)","tags":["node.js","sequelize.js"],"text":"Title: The right way to insert a parent/child record in sequelize with the same transaction (get parent ID)\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn sequelize how do we get the parent id to update the child record in the same transactions. I am trying this way but it just fails to get the ID of the parent. \n\n```\ndb.sequelize.transaction(function (t) {\n return db.Employee.create(employeeData, {transaction:t}).then(function(newEmployee)\n {\n//how to get the parent ID here?\n var empDetailData = {x: \"\", y: \"\", emp_id:newEmployee.id};\n return db.EmployeeDetails.create(empDetailData, {transaction:t}).then(function(newDetail)\n {\n res.json(newEmployee);\n });\n });\n});\n```\n\n**DB relation**\n\n```\nEmployee.hasMany(EmployeeDetails, {foreignKey:'emp_id'});\n```\n\nIt errors out saying emp_id cannot be null. Any pointers in the right direction would be greatly appreciated. How can I get the id so the transaction can work. \n\n**SOLVED**: The actual issue was the db code was missing autoIncrement: true\n\n```\nid: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n **autoIncrement: true** was missing. \n},\n```\n\n========================================\n\nTop Answer:\n```\ncreateUserWithDetails = async(data) => {\n try {\n const transaction = await db.sequelize.transaction(async (t) => {\n let newEmp = await db.Employee.create(employeeData,{transaction:t});\n let empDetailData = {x: \"\", y: \"\", emp_id: newEmp.id};\n let details = await db.EmployeeDetails.create(empDetailData, {transaction:t});\n\n // If you've made it so far everything is ok and\n // the transaction will be automatically committed.\n res.json(newEmp);\n\n });\n\n return transaction;\n }\n catch(error) {\n // Handle Error\n // The transaction is automatically rollbacked!\n }\n```\n\n========================================\n\nCode:\n```text\ndb.sequelize.transaction(function (t) {\n  return db.Employee.create(employeeData, {transaction:t}).then(function(newEmployee)\n  {\n//how to get the parent ID here?\n    var empDetailData = {x: \"\", y: \"\", emp_id:newEmployee.id};\n    return db.EmployeeDetails.create(empDetailData, {transaction:t}).then(function(newDetail)\n    {\n        res.json(newEmployee);\n    });\n  });\n});\n```\n\n```text\nEmployee.hasMany(EmployeeDetails, {foreignKey:'emp_id'});\n```\n\n```text\nid: {\n  type:  Sequelize.INTEGER,\n  primaryKey: true,\n  **autoIncrement: true** was missing. \n},\n```\n\n```text\nasync function createUser(employeeData) {\n  let transaction;\n  try {\n\n    transaction = await db.sequelize.transaction();\n\n    const newEmployee = await db.Employee.create( employeeData, {\n      transaction: transaction\n    })\n    const empDetailData = {\n      x: \"\",\n      y: \"\",\n      emp_id:newEmployee.id\n    };\n    await db.EmployeeDetails.create(empDetailData, {\n      transaction: transaction\n    })\n\n    await transaction.commit()\n\n    res.json(newEmployee)\n\n  } catch(error) {\n    if(transaction) {\n      await transaction.rollback()\n    }\n    // HANDLE THE ERROR AS YOU MANAGE IN YOUR PROJECT\n  }\n}\n```\n\n```text\nt.commit()\n```\n\n```text\nt.rollback()\n```\n\n```text\nnewEmployee\n```\n\n```text\nnewDetails\n```\n\n```text\nAsync/Await\n```\n\n```text\nt.commit()\n```\n\n```text\nt.rollback()\n```\n\n```text\ncreateUserWithDetails = async(data) => {\n        try {\n            const transaction = await db.sequelize.transaction(async (t) => {\n                      let newEmp = await db.Employee.create(employeeData,{transaction:t});\n                      let empDetailData = {x: \"\", y: \"\", emp_id: newEmp.id};\n                      let details = await db.EmployeeDetails.create(empDetailData, {transaction:t});\n\n            // If you've made it so far everything is ok and\n            // the transaction will be automatically committed.\n            res.json(newEmp);\n\n            });\n\n            return transaction;\n        }\n        catch(error) {\n            // Handle Error\n            // The transaction is automatically rollbacked!\n        }\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":174,"estimatedTokens":977}}941{"id":"stack-59796832","source":"stackoverflow","questionId":59796832,"title":"PostgreSQL Crashes When Doing Bulk Inserts with Node.js/Sequelize","tags":["node.js","postgresql","docker","sequelize.js","timescaledb"],"text":"Title: PostgreSQL Crashes When Doing Bulk Inserts with Node.js/Sequelize\nTags: node.js, postgresql, docker, sequelize.js, timescaledb\nSource: Stack Overflow\n\nQuestion:\nA Node.js app using Sequelize.js ORM is performing bulk inserts to a PostgreSQL 11.2 server running inside a Docker container on a Mac OSX host system. Each bulk insert typically consists of about 1000-4000 rows, with a bulk insert concurrency of 30, so there is a max of 30 active insert operations at any time.\n\n```\nconst bulkInsert = async (payload) => {\n try {\n await sequelizeModelInstance.bulkCreate(payload);\n } catch (e) {\n console.log(e);\n }\n}\n\npLimit = require('p-limit')(30);\n\n(function() => {\n const promises = data.map(d => pLimit(() => bulkInsert(d))) // pLimit() controls Promise concurrency\n const result = await Promise.all(promises)\n})();\n```\n\nAfter some time, the PostgreSQL server will start giving errors `Connection terminated unexpectedly`, followed by `the database system is in recovery mode`. \n\nAfter repeating this several times and checking my logs, it appears that this error usually occurs when performing a batch of 30 bulk inserts where several bulk inserts contain over 100,000 row each. For example, one particular crash occurs when attempting to make 3 bulk inserts of 190000, 650000 and 150000 rows together with 27 inserts of 1000-4000 rows each.\n\nSystem memory is not full, CPU load is normal, sufficient disk space is available.\n\n**Question:** Is it normal to expect PostgreSQL to crash under such circumstances? If so, is there a PostgreSQL setting we can tune to allow larger bulk inserts? If this is because of the large bulk inserts, does Sequelize.js have a function to split up the bulk inserts for us?\n\n*Running on PostgreSQL 11.2 in docker container, TimescaleDB 1.5.1, node v12.6.0, sequelize 5.21.3, Mac Catalina 10.15.2*\n\n**PostgreSQL Logs Right After Problem Occurs**\n\n```\n2020-01-18 00:58:26.094 UTC [1] LOG: server process (PID 199) was terminated by signal 9\n2020-01-18 00:58:26.094 UTC [1] DETAIL: Failed process was running: INSERT INTO \"foo\" (\"id\",\"opId\",\"unix\",\"side\",\"price\",\"amount\",\"b\",\"s\",\"serverTimestamp\") VALUES (89880,'5007564','1579219200961','front','0.0000784','35','undefined','undefined','2020-01-17 00:00:01.038 +00:00'),.........\n2020-01-18 00:58:26.108 UTC [1] LOG: terminating any other active server processes\n2020-01-18 00:58:26.110 UTC [220] WARNING: terminating connection because of crash of another server process\n2020-01-18 00:58:26.110 UTC [220] DETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.\n2020-01-18 00:58:26.110 UTC [220] HINT: In a moment you should be able to reconnect to the database and repeat your command.\n2020-01-18 00:58:26.148 UTC [214] WARNING: terminating connection because of crash of another server process\n2020-01-18 00:58:26.148 UTC [214] DETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.\n2020-01-18 00:58:26.148 UTC [214] HINT: In a moment you should be able to reconnect to the database and repeat your command.\n2020-01-18 00:58:26.149 UTC [203] WARNING: terminating connection because of crash of another server process\n2020-01-18 00:58:26.149 UTC [203] DETAIL: The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.\n\n...\n\n2020-01-18 00:58:30.098 UTC [1] LOG: all server processes terminated; reinitializing\n2020-01-18 00:58:30.240 UTC [223] FATAL: the database system is in recovery mode\n2020-01-18 00:58:30.241 UTC [222] LOG: database system was interrupted; last known up at 2020-01-18 00:50:13 UTC\n2020-01-18 00:58:30.864 UTC [224] FATAL: the database system is in recovery mode\n2020-01-18 00:58:31.604 UTC [225] FATAL: the database system is in recovery mode\n2020-01-18 00:58:32.297 UTC [226] FATAL: the database system is in recovery mode\n2020-01-18 00:58:32.894 UTC [227] FATAL: the database system is in recovery mode\n2020-01-18 00:58:33.394 UTC [228] FATAL: the database system is in recovery mode\n2020-01-18 01:00:55.911 UTC [222] LOG: database system was not properly shut down; automatic recovery in progress\n2020-01-18 01:00:56.856 UTC [222] LOG: redo starts at 0/197C610\n2020-01-18 01:01:55.662 UTC [229] FATAL: the database system is in recovery mode\n```\n\n========================================\n\nTop Answer:\nI had a similar problem while running migrations, but the solution can be applied to this question. \n\nThe idea is to splice your payload into manageable chunks. In my case, 100 records at a time seemed manageable.\n\n```\nconst payload = require(\"./seeds/big-mama.json\"); //around 715.000 records\n\nmodule.exports = {\n up: (queryInterface) => {\n const records = payload.map(function (record) {\n record.createdAt = new Date();\n record.updatedAt = new Date();\n return record;\n });\n\n let lastQuery;\n while (records.length > 0) {\n lastQuery = queryInterface.bulkInsert(\n \"Products\",\n records.splice(0, 100),\n {}\n );\n }\n\n return lastQuery;\n },\n\n down: (queryInterface) => {\n return queryInterface.bulkDelete(\"Products\", null, {});\n }\n};\n```\n\n========================================\n\nCode:\n```text\nconst bulkInsert = async (payload) => {\n    try {\n        await sequelizeModelInstance.bulkCreate(payload);\n    } catch (e) {\n        console.log(e);\n    }\n}\n\npLimit = require('p-limit')(30);\n\n(function() => {\n    const promises = data.map(d => pLimit(() => bulkInsert(d))) // pLimit() controls Promise concurrency\n    const result = await Promise.all(promises)\n})();\n```\n\n```text\n2020-01-18 00:58:26.094 UTC [1] LOG:  server process (PID 199) was terminated by signal 9\n2020-01-18 00:58:26.094 UTC [1] DETAIL:  Failed process was running: INSERT INTO \"foo\" (\"id\",\"opId\",\"unix\",\"side\",\"price\",\"amount\",\"b\",\"s\",\"serverTimestamp\") VALUES (89880,'5007564','1579219200961','front','0.0000784','35','undefined','undefined','2020-01-17 00:00:01.038 +00:00'),.........\n2020-01-18 00:58:26.108 UTC [1] LOG:  terminating any other active server processes\n2020-01-18 00:58:26.110 UTC [220] WARNING:  terminating connection because of crash of another server process\n2020-01-18 00:58:26.110 UTC [220] DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.\n2020-01-18 00:58:26.110 UTC [220] HINT:  In a moment you should be able to reconnect to the database and repeat your command.\n2020-01-18 00:58:26.148 UTC [214] WARNING:  terminating connection because of crash of another server process\n2020-01-18 00:58:26.148 UTC [214] DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.\n2020-01-18 00:58:26.148 UTC [214] HINT:  In a moment you should be able to reconnect to the database and repeat your command.\n2020-01-18 00:58:26.149 UTC [203] WARNING:  terminating connection because of crash of another server process\n2020-01-18 00:58:26.149 UTC [203] DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.\n\n...\n\n2020-01-18 00:58:30.098 UTC [1] LOG:  all server processes terminated; reinitializing\n2020-01-18 00:58:30.240 UTC [223] FATAL:  the database system is in recovery mode\n2020-01-18 00:58:30.241 UTC [222] LOG:  database system was interrupted; last known up at 2020-01-18 00:50:13 UTC\n2020-01-18 00:58:30.864 UTC [224] FATAL:  the database system is in recovery mode\n2020-01-18 00:58:31.604 UTC [225] FATAL:  the database system is in recovery mode\n2020-01-18 00:58:32.297 UTC [226] FATAL:  the database system is in recovery mode\n2020-01-18 00:58:32.894 UTC [227] FATAL:  the database system is in recovery mode\n2020-01-18 00:58:33.394 UTC [228] FATAL:  the database system is in recovery mode\n2020-01-18 01:00:55.911 UTC [222] LOG:  database system was not properly shut down; automatic recovery in progress\n2020-01-18 01:00:56.856 UTC [222] LOG:  redo starts at 0/197C610\n2020-01-18 01:01:55.662 UTC [229] FATAL:  the database system is in recovery mode\n```\n\n```text\nConnection terminated unexpectedly\n```\n\n```text\nthe database system is in recovery mode\n```\n\n```js\nconst payload = require(\"./seeds/big-mama.json\"); //around 715.000 records\n\nmodule.exports = {\n    up: (queryInterface) => {\n        const records = payload.map(function (record) {\n            record.createdAt = new Date();\n            record.updatedAt = new Date();\n            return record;\n        });\n\n        let lastQuery;\n        while (records.length > 0) {\n            lastQuery = queryInterface.bulkInsert(\n                \"Products\",\n                records.splice(0, 100),\n                {}\n            );\n        }\n\n        return lastQuery;\n    },\n\n    down: (queryInterface) => {\n        return queryInterface.bulkDelete(\"Products\", null, {});\n    }\n};\n```\n\n========================================\n\nComments:\n- Postgresql seems to be getting killed by an external force, maybe it's the OOM Killer from your OS, have you tried disabling it? (You mentioned Docker, it could also be the OOMK inside the ran image).\n- @NickLeBlanc For Docker OOMK, should we use `--oom-kill-disable=true` flag or increase the Docker container memory limit from 2 GB to 4 GBusing `--memory=4g`?\n- @NickLeBlanc Cant seem to find anything about an OOMK for Mac, only for Linux.\n- \"System memory is not full\" How do you know that? What tools did you use? It could go from not full to full to not full again very quickly. In less than a typical monitoring interval. and why is this tagged with \"mysql\"?\n- @jjanes You are correct, I am unable to determine whether the peak memory usage of the app/database causes the system's memory usage to be fully utilized and causing an OOM scenario. I have replaced the *mysql* tag with *docker*.\n- @NickLeBlanc jjanes Increasing the Docker's memory limit to 12 GB avoided the Postgres from getting OOMK until it hits a 2M row bulk insert. Appears that it will be best to split large bulk inserts into multiple smaller ones to not have to further increase the memory limit? Maybe reduce them to 100k chunks...\n- Chunking the large batch inserts to 200k chunks successfully mitigated the database crashes. Getting only time out error `SequelizeConnectionAcquireTimeoutError`, maybe because it is swapping 6 GB worth of data.\n- @Nyxynyx Glad you managed to fix, you can always tune Postgresql cache size and specially work_mem to your needs. I suggest further reading on both.\n- @NickLeBlanc Thank you I will investigate your suggestions further. My final solution that fixed all problems were to increase the Docker for Mac's memory limit to 12 GB, reduced concurrency to 5 bulk inserts at once, and to chunk up large bulk inserts into smaller chunks of 200k rows.\n- This worked for me! Except I added an `await lastQuery` so the queries would execute sequentially, and not time out or overwhelm postgres. Also it may be better to do a 'await all' or something on all the queries, but it's not necessary","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":198,"estimatedTokens":2854}}942{"id":"stack-57011642","source":"stackoverflow","questionId":57011642,"title":"How do I set a default value or options of a Foreign Key in a 'BelongsTo' association in Sequelize?","tags":["sql","sequelize.js","sequelize-typescript"],"text":"Title: How do I set a default value or options of a Foreign Key in a 'BelongsTo' association in Sequelize?\nTags: sql, sequelize.js, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI have a seemingly common problem with sequelize. For context I am trying to assign a default `role` to each `user` that is created. Essentially each `user`'s role should be set to `default user` when they are first registered. \n\nI would like to be able to simply define this default value in my Models file as you would with normal fields but, I can't seem to find the correct syntax. \n\nThis is what my User model currently looks like: \n\n```\n'use strict';\n\nimport { Sequelize } from 'sequelize';\n\nexport default (sequelize: Sequelize) => {\n const Users = sequelize.define(\n 'Users',\n {\n email: {\n type: Sequelize.STRING,\n allowNull: false\n },\n some_foreign_id: {\n type: Sequelize.STRING,\n allowNull: false\n }\n },\n {}\n );\n Users.associate = models => {\n // associations can be defined here\n Users.belongsTo(models.Roles, { as: 'Role' });\n };\n return Users;\n};\n```\n\nCurrently I am just making a query to find the `role` with the name `default role` and adding it to my user as it is created. However, I feel that query is unnecessary. \n\nBased on the google autofill suggestions it seems like a lot of people have this problem without any clear solution.\n\n[EDIT]\n\nMy `role` model (heh) currently looks like this:\n\n```\nimport { Sequelize } from 'sequelize';\n\nexport default (sequelize: Sequelize) => {\n const Roles = sequelize.define(\n 'Roles',\n {\n name: {\n type: Sequelize.STRING,\n allowNull: false\n }\n },\n {}\n );\n Roles.associate = models => {\n // associations can be defined here\n // SO note: This association is for my permissions. Should have nothing to do with my User association. \n Roles.belongsToMany(models.Permissions, { through: 'RolePermission' });\n };\n return Roles;\n};\n```\n\n========================================\n\nTop Answer:\nWhen you query for User, just do an include\n\n```\nUser.find({\n where: {\n id: 1\n },\n include: [{\n model: Role,\n as: 'Role'\n }]\n}).then(foundUserWithRole => {\n// do something here\n}).catch(err => {});\n```\n\nThis will return the role attached to the User every time you query for the user. Therefore you don't need to make a separate query for role.\n\n========================================\n\nCode:\n```text\n'use strict';\n\nimport { Sequelize } from 'sequelize';\n\nexport default (sequelize: Sequelize) => {\n  const Users = sequelize.define(\n    'Users',\n    {\n      email: {\n        type: Sequelize.STRING,\n        allowNull: false\n      },\n      some_foreign_id: {\n        type: Sequelize.STRING,\n        allowNull: false\n      }\n    },\n    {}\n  );\n  Users.associate = models => {\n    // associations can be defined here\n    Users.belongsTo(models.Roles, { as: 'Role' });\n  };\n  return Users;\n};\n```\n\n```text\nimport { Sequelize } from 'sequelize';\n\nexport default (sequelize: Sequelize) => {\n  const Roles = sequelize.define(\n    'Roles',\n    {\n      name: {\n        type: Sequelize.STRING,\n        allowNull: false\n      }\n    },\n    {}\n  );\n  Roles.associate = models => {\n    // associations can be defined here\n    // SO note: This association is for my permissions. Should have nothing to do with my User association. \n    Roles.belongsToMany(models.Permissions, { through: 'RolePermission' });\n  };\n  return Roles;\n};\n```\n\n```text\nrole\n```\n\n```text\nuser\n```\n\n```text\nuser\n```\n\n```text\ndefault user\n```\n\n```text\nrole\n```\n\n```text\ndefault role\n```\n\n```text\nrole\n```\n\n```text\n// importing sequelize and stuff..\n\nUser.init({\n  id: {\n    type: INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: {\n    type: STRING,\n    allowNull: false\n  },\n  email: {\n    type: STRING,\n    allowNull: false,\n    unique: true,\n    validation: {\n      isEmail: {\n        msg: 'Not a valid email address'\n      }\n    } \n  },\n  password: {\n    type: STRING,\n    allowNull: false\n  },\n  RoleId: {\n    type: INTEGER,\n    allowNull: false,\n    defaultValue: 2\n  }\n}, {/* stuff */})\n```\n\n```text\nRole.init({\n  id: {\n    type: INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  name: {\n    type: STRING,\n    allowNull: false\n  },\n  level: {\n    type: INTEGER,\n    allowNull: false\n  }\n}, {/* stuff */})\n```\n\n```text\n// POST /users\n  create(req, res) {\n    const { name, email, password } = req.body\n    return User.create({ name, email, password })\n      .then(createdUser => res.json(createdUser))\n      .catch(err => res.status(503).json({ msg: err }))\n  }\n```\n\n```text\nUser.belongsTo(Role, {\n  foreignKey: {\n    /* use this like `sequelize.define(...)` */\n    allowNull: false,\n    defaultValue: 2\n  }\n})\n```\n\n```text\nuser\n```\n\n```text\ndefaultValue\n```\n\n```text\nRoleId\n```\n\n```text\nrole\n```\n\n```text\nPOST /login\n```\n\n```text\nuser\n```\n\n```text\nsequelize\n```\n\n```text\ncamelCase\n```\n\n```text\nPascalCase\n```\n\n```text\n5.15.0\n```\n\n```text\nUser.find({\n  where: {\n    id: 1\n  },\n  include: [{\n    model: Role,\n    as: 'Role'\n  }]\n}).then(foundUserWithRole => {\n// do something here\n}).catch(err => {});\n```\n\n========================================\n\nComments:\n- What does your `Role` model look like? Specifically any associations set to the `User` model\n- @Rastalamm I've updated the OP with my `role` model. Currently there are no associations defined in that model as the one to many relationship is defined in the `user`'s model. If you have any insight I would definitely appreciate it! Does not necessarily have to be a complete answer haha\n- It's been a month since you posted this, do you find any solution? I know a few *\"work around\"* however it would be nice to know about this as well, been looking for it for a while.\n- I did not and ended up using TypeORM instead of sequelize. However, it does look like the answer you posted is valid provided the screenshots so I'm going to mark that as the answer. Thank you for your help!\n- aye that is good for finding a `user` with a `role`. Maybe my post wasn't clear but, I'm trying to set a default `role` when *creating* a user. If there is anything I can do to clarify my problem please let me know!\n- Perfect! I just needed the TL;DR part :) I'm a super newbie in node-express. Thanks!\n- @Glenn glad I helped you. But if you only read the tldr part you have a good chance of missing my joke. XD\n- Haha! Can you help me with my question? stackoverflow.com/q/61718082/3231194\n- @Glenn sorry, at the time I was working, but it seems that you got your question answered at this time. I'm glad it has been answered. :)","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":312,"estimatedTokens":1624}}943{"id":"stack-40784299","source":"stackoverflow","questionId":40784299,"title":"Why I cannot modify the result object","tags":["sequelize.js"],"text":"Title: Why I cannot modify the result object\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhy the objects returned by sequelize `findAll` and the likes cannot be modified like regular objects? I checked if they are frozen or locked, but `Object.isFrozen()` returns false. Does it use getters instead of real properties (how do I check that?)\n\nSo far my only option to modify the results is to do `JSON.parse(JSON.strigify(result))` which is OK, but incurs performance price.\n\n========================================\n\nCode:\n```text\nfindAll\n```\n\n```text\nObject.isFrozen()\n```\n\n```text\nJSON.parse(JSON.strigify(result))\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":23,"estimatedTokens":158}}944{"id":"stack-46973120","source":"stackoverflow","questionId":46973120,"title":"How to catch all types of sequelize Error","tags":["node.js","sequelize.js"],"text":"Title: How to catch all types of sequelize Error\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using sequelize@4.8.0 with expressJS.\n\nI understand how to catch a specific type of sequelize Error and It works well.\n\n```\nreturn db.mySequel.transaction(t => {\n return db.users.findOrCreate({\n ...,\n transaction: t\n }).spread((rs, created) => {\n if (created == false) throw new Error(\"00001\");\n return db.misc.bulkCreate([\n {\n ...\n },\n {\n ...\n }\n ], {\n transaction: t,\n raw: true\n });\n })\n}).then(rs => {\n res.json(rs);\n}).catch(db.mySequel.ForeignKeyConstraintError, err => {\n ... \n}).catch(err => {\n ...\n});\n```\n\nBut this query transaction process throw custom error instances too. So I want to catch all types of Sequelize Error separately from my errors.\n\nMaybe I could make more catch chains, It seems verbose.\nI tried `.catch(db.mySequel.BaseError` but not so helpful.\n\n========================================\n\nTop Answer:\nInstead of using multiple catch blocks use a single one and then test the `instanceof` of the object to determine how to handle the exception.\n\n```\n.catch(err => {\n if (err instanceof db.mySequel.ForeignKeyConstraintError) {\n // handle foreign key constraint\n } else {\n // handle other error\n }\n});\n```\n\n========================================\n\nCode:\n```text\nreturn db.mySequel.transaction(t => {\n    return db.users.findOrCreate({\n        ...,\n        transaction: t\n    }).spread((rs, created) => {\n        if (created == false) throw new Error(\"00001\");\n        return db.misc.bulkCreate([\n            {\n                ...\n            },\n            {\n                ...\n            }\n        ], {\n            transaction: t,\n            raw: true\n        });\n    })\n}).then(rs => {\n    res.json(rs);\n}).catch(db.mySequel.ForeignKeyConstraintError, err => {\n   ... \n}).catch(err => {\n   ...\n});\n```\n\n```text\n.catch(db.mySequel.BaseError\n```\n\n```text\nvar names = [];\n(function p (inst) {\n    if (inst != null) {\n        var ofProto = Object.getPrototypeOf(inst);\n        names.push(ofProto.constructor.name);\n        p(ofProto);\n    }\n})(err);\nconsole.log(names)\n// [\"ForeignKeyConstraintError\", \"DatabaseError\", \"BaseError\", \"Error\", \"Object\"]\n```\n\n```text\nObject.getInstanceOf()\n```\n\n```text\n__proto__\n```\n\n```text\n.catch(err => {\n  if (err instanceof db.mySequel.ForeignKeyConstraintError) {\n    // handle foreign key constraint\n  } else {\n    // handle other error\n  }\n});\n```\n\n```text\ninstanceof\n```\n\n========================================\n\nComments:\n- This is the error class in Sequelize implementation. You can view everything there: github.com/sequelize/sequelize/blob/&hellip;\n- I think an important point is to clarify that `instanceof` will check the object's whole prototype chain, so you can use the answer here in place of @BaroqueCode's more verbose answer below. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":132,"estimatedTokens":726}}945{"id":"stack-55762448","source":"stackoverflow","questionId":55762448,"title":"How to make the return values of findOrCreate available to router","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: How to make the return values of findOrCreate available to router\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo in my express app I have a separate file database.js, which contains all the models and functions for inserting, deleting, updating etc. I also have a separate controller for each model.\n\ndatabase.js\n\n```\nmodule.exports = {\n createUser: function (username, email, password) {\n return sequelize.sync().then(function () {\n User.findOrCreate({\n where: {\n username: name,\n email: email\n },\n defaults: {\n username: username,\n password: password,\n email: email\n }\n }).then(([user, created]) => {\n console.log(user.get({plain:true}));\n console.log(created)\n });\n });\n }\n };\n```\n\ncontrollers/user.js\n\n```\nconst database = require(\"../database.js\");\nmodule.exports = {\n register: function (req, res) {\n database.createUser(req.body.username, req.body.email, req.body.password);\n res.json({...\n })\n\n }\n};\n```\n\nSo basically I wanna get the user object and the boolean that tells me if it was created to the router so I can check if the user was created and make an appropriate response.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n    createUser: function (username, email, password) {\n        return sequelize.sync().then(function () {\n            User.findOrCreate({\n                where: {\n                    username: name,\n                    email: email\n                },\n                defaults: {\n                    username: username,\n                    password: password,\n                    email: email\n                }\n            }).then(([user, created]) => {\n                console.log(user.get({plain:true}));\n                console.log(created)\n                });\n            });\n        }\n    };\n```\n\n```text\nconst database = require(\"../database.js\");\nmodule.exports = {\n    register: function (req, res) {\n        database.createUser(req.body.username, req.body.email, req.body.password);\n        res.json({...\n        })\n\n    }\n};\n```\n\n```text\nmodule.exports = {\n    createUser: function (username, email, password) {\n        return User.findOrCreate({\n                where: {\n                    username: name,\n                    email: email\n                },\n                defaults: {\n                    username: username,\n                    password: password,\n                    email: email\n                }\n            })\n    };\n```\n\n```text\nconst database = require(\"../database.js\");\nmodule.exports = {\n    register: function (req, res) {\n        database.createUser(req.body.username, req.body.email, req.body.password)\n            .then((result) => {\n                const [ object, created ] = result;\n                res.json({ user_is_created: created })\n            })\n    }\n};\n```\n\n```text\nthen\n```\n\n========================================\n\nComments:\n- Why do you even call `sequalize.sync()` in `createUser`? This is wrong. You shouldn't be calling it in app at all. You can unintenionally mess up your database (if you put somewhere `force: true` flag, then you are doomed), not to mention the sync overhead. The `sequalize.sync()` should run only during migrations.\n- Also Promises can chain return value: your final `.then` in `createUser` can simply `return [user, created];` to make it available in `user.js` via `.then()`.","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":125,"estimatedTokens":843}}946{"id":"stack-53631883","source":"stackoverflow","questionId":53631883,"title":"Double include in sequelize, node.js","tags":["node.js","sequelize.js"],"text":"Title: Double include in sequelize, node.js\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to include another Model to my User.findAll function. The SurveyResult model belongs the Model Survey. How can i include the Model Survey to show the Survey whitch belongs to the SurveyResult\n\n```\nasync index (req, res) {\n try {\n const userData = await User.findAll({\n include: [ UserStatus, SurveyResult\n ]\n })\n .map(user => user.toJSON())\n \n res.send(userData)\n } catch (err) {\n console.log(err)\n }\n \n}\n```\n\nHere is my json i get back:\n\n```\n{\n \"id\": 3,\n \"email\": \"testing@gmail.com\",\n \"password\": \"$2a$08$Y22dOOIgyGhLAOokYluGxupKHRv8zRcbAVK1YEvWVUtoBl7dOsAYK\",\n \"name\": \"test\",\n \"forename\": \"test\",\n \"createdAt\": \"2018-12-05T11:25:30.000Z\",\n \"updatedAt\": \"2018-12-05T11:25:30.000Z\",\n \"AdminId\": 1,\n \"UserStatuses\": [\n {\n \"id\": 3,\n \"sendEmail\": false,\n \"sendResult\": true,\n \"createdAt\": \"2018-12-05T11:25:31.000Z\",\n \"updatedAt\": \"2018-12-05T11:25:31.000Z\",\n \"UserId\": 3\n }\n```\n\ni tried that but it dont work:\n\n```\nconst userData = await User.findAll({\n include: [\n { UserStatus, SurveyResult, include: [Survey] }\n ]\n })\n .map(user => user.toJSON())\n```\n\n========================================\n\nCode:\n```text\nasync index (req, res) {\n    try {\n        const userData = await User.findAll({\n            include: [ UserStatus, SurveyResult\n            ]\n        })\n            .map(user => user.toJSON())\n        \n        res.send(userData)\n    } catch (err) {\n        console.log(err)\n    }\n    \n}\n```\n\n```text\n{\n    \"id\": 3,\n    \"email\": \"testing@gmail.com\",\n    \"password\": \"$2a$08$Y22dOOIgyGhLAOokYluGxupKHRv8zRcbAVK1YEvWVUtoBl7dOsAYK\",\n    \"name\": \"test\",\n    \"forename\": \"test\",\n    \"createdAt\": \"2018-12-05T11:25:30.000Z\",\n    \"updatedAt\": \"2018-12-05T11:25:30.000Z\",\n    \"AdminId\": 1,\n    \"UserStatuses\": [\n        {\n            \"id\": 3,\n            \"sendEmail\": false,\n            \"sendResult\": true,\n            \"createdAt\": \"2018-12-05T11:25:31.000Z\",\n            \"updatedAt\": \"2018-12-05T11:25:31.000Z\",\n            \"UserId\": 3\n        }\n```\n\n```text\nconst userData = await User.findAll({\n    include: [\n      { UserStatus, SurveyResult, include: [Survey] }\n    ]\n  })\n    .map(user => user.toJSON())\n```\n\n```text\nconst userData = await User.findAll({\n    include: [\n        { model : UserStatus }\n        { model : SurveyResult ,\n            include: {\n                model : Survey\n            } \n        }\n    ]\n})\n\n// OR ( Shorthand )\n\nconst userData = await User.findAll({\n    include: [ UserStatus , { model : SurveyResult , include: [Survey] }]\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":126,"estimatedTokens":646}}947{"id":"stack-50678290","source":"stackoverflow","questionId":50678290,"title":"How to return the result from a raw query (Sequelize) to GraphQL","tags":["mysql","node.js","sequelize.js","graphql"],"text":"Title: How to return the result from a raw query (Sequelize) to GraphQL\nTags: mysql, node.js, sequelize.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm newbie with GraphQL and Sequelize but I have developed a test where I can make querys and get results from Graphiql using the functions of Sequalize, but I'm interested in making more complex querys with querys with several tables.\n\nNow, this code works fine:\n\n**schema.js**\n\n```\nimport {\n GraphQLObjectType,\n GraphQLNonNull,\n GraphQLID,\n GraphQLInt,\n GraphQLString,\n GraphQLFloat,\n GraphQLList,\n GraphQLSchema\n} from \"graphql\";\nimport { DB } from \"../db\";\nimport {DateTime} from \"../scalar/dateTime\";\nimport {Player} from \"./Player\";\nimport {League} from \"./League\";\nimport {Group} from \"./Group\";\nimport {Season} from \"./Season\";\n\nconst Query = new GraphQLObjectType({\n name: \"Query\",\n description: \"This is root query\",\n fields: () => {\n return {\n players: {\n type: GraphQLList(Player),\n args: {\n id: {\n type: GraphQLID\n }\n },\n resolve(root, args){\n return DB.db.models.tbl003_player.findAll({where: args});\n }\n },\n leagues: {\n type: GraphQLList(League),\n args: {\n id: {\n type: GraphQLID\n }\n },\n resolve(root, args){\n return DB.db.models.tbl001_league.findAll({where: args});\n }\n },\n groups: {\n type: GraphQLList(Group),\n args: {\n id: {\n type: GraphQLID\n }\n },\n resolve(root, args){\n return DB.db.models.tbl024_group.findAll({where: args});\n }\n },\n seasons: {\n type:GraphQLList(Season),\n args: {\n id: {\n type: GraphQLID\n } \n },\n resolve(root, args){\n return DB.db.models.tbl015_seasons.findAll({where: args})\n }\n }\n }\n }\n});\n\nconst Schema = new GraphQLSchema({\n query: Query\n});\n\nmodule.exports.Schema = Schema;\n```\n\nSo, I would like to make an easy test to know how to return the data from a raw query to GraphQL. I have read that resolve method returns a promise, and I have tried to return a promise with the result of the query, but it doesn't work. \n\n```\nplayers: {\n type: GraphQLList(Player),\n args: {\n id: {\n type: GraphQLID\n }\n },\n resolve(root, args){\n DB.db.query(\"select * from tbl003_player where id = 14\",\n {raw: true, type: DB.db.QueryTypes.SELECT}).then((players)=>{\n let myPromise = new Promise((resolve, reject)=>{\n resolve(players);\n });\n return myPromise;\n }).catch((reject)=>{\n console.log(\"Error: \" + reject);\n });\n }\n },\n```\n\nTherefore, how can I return data from a query with Sequelize to GraphQL?\n\n========================================\n\nCode:\n```text\nimport {\n    GraphQLObjectType,\n    GraphQLNonNull,\n    GraphQLID,\n    GraphQLInt,\n    GraphQLString,\n    GraphQLFloat,\n    GraphQLList,\n    GraphQLSchema\n} from \"graphql\";\nimport { DB } from \"../db\";\nimport {DateTime} from \"../scalar/dateTime\";\nimport {Player} from \"./Player\";\nimport {League} from \"./League\";\nimport {Group} from \"./Group\";\nimport {Season} from \"./Season\";\n\nconst Query = new GraphQLObjectType({\n    name: \"Query\",\n    description: \"This is root query\",\n    fields: () => {\n        return {\n            players: {\n                type: GraphQLList(Player),\n                args: {\n                    id: {\n                        type: GraphQLID\n                    }\n                },\n                resolve(root, args){\n                    return DB.db.models.tbl003_player.findAll({where: args});\n                }\n            },\n            leagues: {\n                type: GraphQLList(League),\n                args: {\n                    id: {\n                        type: GraphQLID\n                    }\n                },\n                resolve(root, args){\n                    return DB.db.models.tbl001_league.findAll({where: args});\n                }\n            },\n            groups: {\n                type: GraphQLList(Group),\n                args: {\n                    id: {\n                        type: GraphQLID\n                    }\n                },\n                resolve(root, args){\n                    return DB.db.models.tbl024_group.findAll({where: args});\n                }\n            },\n            seasons: {\n                type:GraphQLList(Season),\n                args: {\n                    id: {\n                        type: GraphQLID\n                    } \n                },\n                resolve(root, args){\n                    return DB.db.models.tbl015_seasons.findAll({where: args})\n                }\n            }\n        }\n    }\n});\n\nconst Schema = new GraphQLSchema({\n    query: Query\n});\n\nmodule.exports.Schema = Schema;\n```\n\n```text\nplayers: {\n        type: GraphQLList(Player),\n        args: {\n            id: {\n                type: GraphQLID\n            }\n        },\n        resolve(root, args){\n            DB.db.query(\"select * from tbl003_player where id = 14\",\n            {raw: true, type: DB.db.QueryTypes.SELECT}).then((players)=>{\n                let myPromise = new Promise((resolve, reject)=>{\n                    resolve(players);\n                });\n                return myPromise;\n            }).catch((reject)=>{\n                console.log(\"Error: \" + reject);\n            });\n        }\n    },\n```\n\n```text\nresolve(root, args){\n  return DB.db.query(\n    \"select * from tbl003_player where id = 14\",\n    { raw: true, type: DB.db.QueryTypes.SELECT }\n  );\n}\n```\n\n========================================\n\nComments:\n- OMG!!! It works!!! Thank you so much for your apreciated help @Herku!!!!\n- My pleasure! Now it's on you to understand why it works :)","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":232,"estimatedTokens":1345}}948{"id":"stack-46551060","source":"stackoverflow","questionId":46551060,"title":"How to Perform Multiple Inner Joins in Sequelize Postgresql","tags":["node.js","postgresql","join","sequelize.js"],"text":"Title: How to Perform Multiple Inner Joins in Sequelize Postgresql\nTags: node.js, postgresql, join, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nAm newbie to RDBMS and Sequelize as well wanted to explore more in those now am struck up with JOINS. I don't know how to perform JOINS via SEQUELIZE. I have 3 tables USERS,ORDERS,PRODUCTS ORDERS table contains USERS,PRODUCTS primary key as its foreign key. Am attaching my model code below\nUser Model\n\n```\nconst Sequelize = require('sequelize');\nconst sequelize = require('../config');\nlet Users = sequelize.define('users', {\n id : {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n username: {\n type: Sequelize.STRING,\n },\n password: {\n type: Sequelize.STRING\n }\n});\nmodule.exports = Users;\n```\n\nProducts Model\n\n```\nconst Sequelize = require('sequelize');\nconst sequelize = require('../config');\nlet products=sequelize.define('products', {\n id : {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n category : {\n type: Sequelize.STRING,\n allowNull: false\n },\n name : {\n type: Sequelize.STRING,\n allowNull: false\n },\n price: {\n type: Sequelize.INTEGER,\n allowNull: false\n }\n});\nmodule.exports= products;\n```\n\nOrders Model\n\n```\nconst Sequelize = require('sequelize');\nconst sequelize = require('../config');\nlet users=require('./user');\nlet products=require('./product');\nlet orders=sequelize.define('orders', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n user_id: {\n type: Sequelize.INTEGER,\n references: {\n model: 'users',\n key: 'id'\n }\n },\n product_id: {\n type: Sequelize.INTEGER,\n references: {\n model: 'products',\n key: 'id'\n }\n },\n price: {\n type: Sequelize.INTEGER,\n allowNull: false\n }\n});\nmodule.exports= orders;\n```\n\nI want this following raw query to be performed via SEQUELIZE \n\n```\nSELECT * FROM ((orders INNER JOIN users ON users.id=orders.user_id) INNER JOIN products ON products.id=orders.product_id);\n```\n\nI have looked at the documentation but i couldn't figure out how to do it. ANy help is appreciated. Thanks\n\n========================================\n\nTop Answer:\n```\nlet users=require('./user');\nlet products=require('./product');\n\nexport function getOrders(req, res) {\n return order.findAndCountAll({\n include: [\n {model: users, required: true}, // true for INNER JOIN\n {model: products, required: false} // false for LEFT OUTER JOIN\n ],\nthem all\n \n }) \n}\n```\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = require('../config');\nlet Users = sequelize.define('users', {\n  id : {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  username: {\n    type: Sequelize.STRING,\n  },\n  password: {\n    type: Sequelize.STRING\n  }\n});\nmodule.exports = Users;\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = require('../config');\nlet products=sequelize.define('products', {\n  id : {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  category : {\n    type: Sequelize.STRING,\n    allowNull: false\n  },\n  name : {\n    type: Sequelize.STRING,\n    allowNull: false\n  },\n  price: {\n    type: Sequelize.INTEGER,\n    allowNull: false\n  }\n});\nmodule.exports= products;\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = require('../config');\nlet users=require('./user');\nlet products=require('./product');\nlet orders=sequelize.define('orders', {\n  id: {\n    type: Sequelize.INTEGER,\n    primaryKey: true,\n    autoIncrement: true\n  },\n  user_id: {\n    type: Sequelize.INTEGER,\n    references: {\n        model: 'users',\n        key: 'id'\n    }\n  },\n  product_id: {\n    type: Sequelize.INTEGER,\n    references: {\n        model: 'products',\n        key: 'id'\n    }\n  },\n  price: {\n    type: Sequelize.INTEGER,\n    allowNull: false\n  }\n});\nmodule.exports= orders;\n```\n\n```text\nSELECT * FROM ((orders INNER JOIN users ON users.id=orders.user_id) INNER JOIN products ON products.id=orders.product_id);\n```\n\n```text\nexport function getRequestsByWeek(req, res) {\n  return order.findAll({\n    include: [\n      {model: users, attributes: []}, // nothing in attributes here in order to not import columns from users\n      {model: products} // nothing in attributes here in order to not import columns from products\n    ],\n    attributes: ['id'], //in quotes specify what columns you want, otherwise you will pull them all\n    // Otherwise remove attributes above this line to import everything. \n  })\n    .then(respondWithResult(res))\n    .catch(handleError(res));\n}\n```\n\n```text\nlet users=require('./user');\nlet products=require('./product');\n\nexport function getOrders(req, res) {\n  return order.findAndCountAll({\n    include: [\n      {model: users, required: true}, // true for INNER JOIN\n      {model: products, required: false} // false for LEFT OUTER JOIN\n    ],\nthem all\n    \n  })   \n}\n```\n\n========================================\n\nComments:\n- Hi thanks allot for your detailed response but am having few queries don't we need to associate the orders table and products table? Why because i want to fetch few details from product tables such as category,name. So can you help me out?\n- I have tried running without associating orders with products it thrown me an error \"products not associated with orders\"\n- That error is because you have not set up the association between Products and Orders. Set it up similar to the way I showed you how to set it up for Users and Orders, but between Product and orders.\n- Thanks its working now i got the solution which i was looking for. But an user can order many products at a time. So how can i make M:M association. Am a newbie to RDBMS so i don't know much about associations and relations too. It would be great help if you send me some tutorials for that\n- There are a couple of things to take into account. A user can have many orders, but an order can not have many users. Yes there can be many orders, but each order is only bound to one user. If you were to change this to many to many. That would mean an single order has many users in it, but this is not the case. One user has many orders, one order belongs to a single user. Same with the product. You can watch this video here youtube.com/watch?v=isk0JR0t_VQ&t=514s\n- Hi, welcome to StackOverflow! Could you add a description of why your answer solves the problem in the question? I also notice \"them all\" in your code which is probably a typo.","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":240,"estimatedTokens":1612}}949{"id":"stack-49613328","source":"stackoverflow","questionId":49613328,"title":"Sequelize: How to reverse query in hasMany?","tags":["sequelize.js"],"text":"Title: Sequelize: How to reverse query in hasMany?\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following models:\n\n```\nconst Users = sequelize.define('User', {/* ... */})\nconst Articles = sequelize.define('Articles', {/* ... */})\n```\n\nI have a association between them as :\n\n```\nUsers.hasMany(Articles, { as: 'Post' })\n```\n\nwhich adds a foreignKey 'userId' in the Articles table.\n\nNow I can eager load the articles when querying via the User model as:\n\n```\nUsers.findOne({ where: { id: 'user_one'}, includes: [{ model: Articles }] })\n```\n\nBut how can I do the reverse i.e:\n\n```\nArticles.findAll({ where: { id: 'user_one', includes: [{ model: Users }] }})\n```\n\n========================================\n\nTop Answer:\nJust use, `include` instead if `includes`\n\n```\nArticles.findAll({\n include: [{\n model: Users,\n where: { id: 'user_one' }\n }]\n})\n```\n\nIn the above, `id` is primary key in that `Articles` table.\n\nHere is a good discussion for that\n\n========================================\n\nCode:\n```text\nconst Users = sequelize.define('User', {/* ... */})\nconst Articles = sequelize.define('Articles', {/* ... */})\n```\n\n```text\nUsers.hasMany(Articles, { as: 'Post' })\n```\n\n```text\nUsers.findOne({ where: { id: 'user_one'}, includes: [{ model: Articles }] })\n```\n\n```text\nArticles.findAll({ where: { id: 'user_one', includes: [{ model: Users }] }})\n```\n\n```text\nArticles.findAll({\n    where: { userID: 'user_one' },\n    include: [{\n        model: Users,\n        required: true\n    }]\n})\n```\n\n```text\nUsers.hasMany(Articles, { foreignKey: 'userID' });\nArticles.belongsTo(Users, { foreignKey: 'userID' });\n```\n\n```text\nArticles.findAll({\n    include: [{\n        model: Users,\n        where: { id: 'user_one' }\n    }]\n})\n```\n\n```text\ninclude\n```\n\n```text\nincludes\n```\n\n```text\nid\n```\n\n```text\nArticles\n```\n\n========================================\n\nComments:\n- So, what you want here is to find all articles by a certain user?\n- no. i want the associated user detail when i retrieve the article list.\n- thanks. it worked after adding the belongsTo relation","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":116,"estimatedTokens":517}}950{"id":"stack-52813078","source":"stackoverflow","questionId":52813078,"title":"Sequelize ES6 Model Methods No Existing","tags":["javascript","node.js","express","orm","sequelize.js"],"text":"Title: Sequelize ES6 Model Methods No Existing\nTags: javascript, node.js, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhile trying to use Sequelize JS v4 with ES6 classes I'm having trouble with the execution of the instance methods. For some reason, they seem to not exist although being defined in code.\n\nHere's an example - \n\nModel File\n\n```\n'use strict';\nconst Sequelize = require(\"sequelize\");\n\nclass Model extends Sequelize.Model {\n\n static init(sequelize, DataTypes) {\n return super.init(\n {\n // properties\n },\n { sequelize }\n );\n }\n\n static associate(models) {\n }\n\n async modelMethod() {\n\n }\n\n}\n\nmodule.exports = Model;\n```\n\nModel Initiation\n\n```\nlet modelClass = require('../models/' + modelFile);\n\nlet model = modelClass.init(sequelize, Sequelize);\n```\n\nThe model is then being called in a controller file as being the controller's property\n\n```\nasync controllerMethod(req, res) {\n let info = await this.model.modelMethod();\n res.send(info);\n}\n```\n\nAnd the error which I receive -\n\n TypeError: this.model.modelMethod is not a function at\n Controller.controllerMethod (/usr/app/controllers/controller.js:83:41) at\n Layer.handle [as handle_request]\n (/usr/app/node_modules/express/lib/router/layer.js:95:5) at next\n (/usr/app/node_modules/express/lib/router/route.js:137:13) at\n Route.dispatch\n (/usr/app/node_modules/express/lib/router/route.js:112:3) at\n Layer.handle [as handle_request]\n (/usr/app/node_modules/express/lib/router/layer.js:95:5) at\n /usr/app/node_modules/express/lib/router/index.js:281:22 at param\n (/usr/app/node_modules/express/lib/router/index.js:354:14) at param\n (/usr/app/node_modules/express/lib/router/index.js:365:14) at param\n (/usr/app/node_modules/express/lib/router/index.js:365:14) at\n Function.process_params\n (/usr/app/node_modules/express/lib/router/index.js:410:3) at next\n (/usr/app/node_modules/express/lib/router/index.js:275:10) at\n sequelize.models.Session.findOne.then (/usr/app/app.js:44:24) at\n tryCatcher (/usr/app/node_modules/bluebird/js/release/util.js:16:23) \n at Promise._settlePromiseFromHandler\n (/usr/app/node_modules/bluebird/js/release/promise.js:512:31) at\n Promise._settlePromise\n (/usr/app/node_modules/bluebird/js/release/promise.js:569:18) at\n Promise._settlePromise0\n (/usr/app/node_modules/bluebird/js/release/promise.js:614:10) at\n Promise._settlePromises\n (/usr/app/node_modules/bluebird/js/release/promise.js:693:18) at\n Async._drainQueue\n (/usr/app/node_modules/bluebird/js/release/async.js:133:16) at\n Async._drainQueues\n (/usr/app/node_modules/bluebird/js/release/async.js:143:10) at\n Immediate.Async.drainQueues\n (/usr/app/node_modules/bluebird/js/release/async.js:17:14) at\n Immediate.args.(anonymous function) [as _onImmediate]\n (/usr/local/lib/node_modules/pm2/node_modules/event-loop-inspector/index.js:133:29)\n at runCallback (timers.js:810:20)\n\nTrying to output the classes' methods gets this - \n\n```\nconsole.log(Object.getOwnPropertyNames(this.model));\n\n[ 'length',\n 'prototype',\n 'init',\n 'associate',\n 'name',\n 'sequelize',\n 'options',\n 'associations',\n 'underscored',\n 'tableName',\n '_schema',\n '_schemaDelimiter',\n 'rawAttributes',\n 'primaryKeys',\n '_timestampAttributes',\n '_readOnlyAttributes',\n '_hasReadOnlyAttributes',\n '_isReadOnlyAttribute',\n '_dataTypeChanges',\n '_dataTypeSanitizers',\n '_booleanAttributes',\n '_dateAttributes',\n '_hstoreAttributes',\n '_rangeAttributes',\n '_jsonAttributes',\n '_geometryAttributes',\n '_virtualAttributes',\n '_defaultValues',\n 'fieldRawAttributesMap',\n 'fieldAttributeMap',\n 'uniqueKeys',\n '_hasBooleanAttributes',\n '_isBooleanAttribute',\n '_hasDateAttributes',\n '_isDateAttribute',\n '_hasHstoreAttributes',\n '_isHstoreAttribute',\n '_hasRangeAttributes',\n '_isRangeAttribute',\n '_hasJsonAttributes',\n '_isJsonAttribute',\n '_hasVirtualAttributes',\n '_isVirtualAttribute',\n '_hasGeometryAttributes',\n '_isGeometryAttribute',\n '_hasDefaultValues',\n 'attributes',\n 'tableAttributes',\n 'primaryKeyAttributes',\n 'primaryKeyAttribute',\n 'primaryKeyField',\n '_hasPrimaryKeys',\n '_isPrimaryKey',\n 'autoIncrementAttribute',\n '_scope',\n '_scopeNames' ]\n```\n\n========================================\n\nTop Answer:\nThe `static init` function isn't a constructor. It \"initializes\" the class by setting up its functionality, and returns then returns the class itself.\n\nHere's some sample code to illustrate this:\n\n```\nclass User extends Sequelize.Model {\n static init(sequelize, DataTypes) {\n return super.init({\n firstName: {\n type: DataTypes.STRING\n },\n lastName: {\n type: DataTypes.STRING\n }\n }, {\n sequelize\n });\n }\n\n fullname() {\n return `${this.firstName} ${this.lastName}`;\n }\n}\n\n// You don't need to capture the return here, I'm just doing it to show what it is.\nconst result = User.init(sequelize, Sequelize);\nconsole.log(result === User); // true\n\nconst user = new User();\nconsole.log(typeof user.fullname === 'function'); // true\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nconst Sequelize = require(\"sequelize\");\n\nclass Model extends Sequelize.Model {\n\n  static init(sequelize, DataTypes) {\n    return super.init(\n      {\n        // properties\n      },\n      { sequelize }\n    );\n  }\n\n  static associate(models) {\n  }\n\n\n  async modelMethod() {\n\n  }\n\n}\n\nmodule.exports = Model;\n```\n\n```text\nlet modelClass = require('../models/' + modelFile);\n\nlet model = modelClass.init(sequelize, Sequelize);\n```\n\n```text\nasync controllerMethod(req, res) {\n    let info = await this.model.modelMethod();\n    res.send(info);\n}\n```\n\n```text\nconsole.log(Object.getOwnPropertyNames(this.model));\n\n\n[ 'length',\n  'prototype',\n  'init',\n  'associate',\n  'name',\n  'sequelize',\n  'options',\n  'associations',\n  'underscored',\n  'tableName',\n  '_schema',\n  '_schemaDelimiter',\n  'rawAttributes',\n  'primaryKeys',\n  '_timestampAttributes',\n  '_readOnlyAttributes',\n  '_hasReadOnlyAttributes',\n  '_isReadOnlyAttribute',\n  '_dataTypeChanges',\n  '_dataTypeSanitizers',\n  '_booleanAttributes',\n  '_dateAttributes',\n  '_hstoreAttributes',\n  '_rangeAttributes',\n  '_jsonAttributes',\n  '_geometryAttributes',\n  '_virtualAttributes',\n  '_defaultValues',\n  'fieldRawAttributesMap',\n  'fieldAttributeMap',\n  'uniqueKeys',\n  '_hasBooleanAttributes',\n  '_isBooleanAttribute',\n  '_hasDateAttributes',\n  '_isDateAttribute',\n  '_hasHstoreAttributes',\n  '_isHstoreAttribute',\n  '_hasRangeAttributes',\n  '_isRangeAttribute',\n  '_hasJsonAttributes',\n  '_isJsonAttribute',\n  '_hasVirtualAttributes',\n  '_isVirtualAttribute',\n  '_hasGeometryAttributes',\n  '_isGeometryAttribute',\n  '_hasDefaultValues',\n  'attributes',\n  'tableAttributes',\n  'primaryKeyAttributes',\n  'primaryKeyAttribute',\n  'primaryKeyField',\n  '_hasPrimaryKeys',\n  '_isPrimaryKey',\n  'autoIncrementAttribute',\n  '_scope',\n  '_scopeNames' ]\n```\n\n```text\nlet model = ModelClass.init(sequelize, Sequelize);\nmodel = new model();\n```\n\n```js\nclass User extends Sequelize.Model {\n  static init(sequelize, DataTypes) {\n    return super.init({\n      firstName: {\n        type: DataTypes.STRING\n      },\n      lastName: {\n        type: DataTypes.STRING\n      }\n    }, {\n      sequelize\n    });\n  }\n\n  fullname() {\n    return `${this.firstName} ${this.lastName}`;\n  }\n}\n\n// You don't need to capture the return here, I'm just doing it to show what it is.\nconst result = User.init(sequelize, Sequelize);\nconsole.log(result === User); // true\n\nconst user = new User();\nconsole.log(typeof user.fullname === 'function'); // true\n```\n\n```text\nstatic init\n```\n\n========================================\n\nComments:\n- Try removing the custom `init` place in the class and directly call the `init` method of the parent. Also, to use the method, you would need to initialize the class, with something such as `new Model` or `Model.build({})` which would initialize the model and enable you to use the method.\n- @ManishMDemblani The init method calls the super's method so I assume that that's not the problem, as for new Model I've been trying that without success, but now trying to call new on the return value of init might do the trick. I'll update it if it works\n- The reason this is because Sequelize works on the basis of ActiveRecord pattern, which lets you use the same model, when uninitialized to query the database and also contain instances of data from the database once fetched and initialized.\n- I might need to dig in to it in order to understand it better, thanks! @ManishMDemblani","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":341,"estimatedTokens":2095}}951{"id":"stack-37606546","source":"stackoverflow","questionId":37606546,"title":"Sequelize, Validate length of field with blank value","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: Sequelize, Validate length of field with blank value\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize as ORM with express.\n\nIn Sequelize Model, their is field that accepts the null value. I want to validate this field by defining the length of the input with `len` if any value is provided.\n\nCode:\n\n```\nfield: {\n type: DataTypes.TEXT,\n allowNull: true,\n validate: {\n len: {\n args: [50, 200],\n msg: 'Please provide field within 50 to 200 characters.'\n }\n }\n}\n```\n\nBut, Sequelize throw error when field is empty. So, How do i allow the empty value, and just validate only when value is provided.\n\n========================================\n\nCode:\n```text\nfield: {\n  type: DataTypes.TEXT,\n  allowNull: true,\n  validate: {\n    len: {\n      args: [50, 200],\n      msg: 'Please provide field within 50 to 200 characters.'\n    }\n  }\n}\n```\n\n```text\nlen\n```\n\n```text\nfield: {\n  type: DataTypes.TEXT,\n  allowNull: true,\n  validate: {\n    notEmpty: false,\n    len: {\n      args: [50, 200],\n      msg: 'Please provide field within 50 to 200 characters.'\n    }\n  }\n}\n```\n\n```text\nnotEmpty: false\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":63,"estimatedTokens":287}}952{"id":"stack-35352761","source":"stackoverflow","questionId":35352761,"title":"how to yield multiple constants with one declaration","tags":["javascript","node.js","sequelize.js","es6-promise"],"text":"Title: how to yield multiple constants with one declaration\nTags: javascript, node.js, sequelize.js, es6-promise\nSource: Stack Overflow\n\nQuestion:\nI have a function `makeThings(n)` that returns a Promise to create n number of items (through Sequelize).\n\nIt was suggested to me to use this format for retrieving values:\n\n`const [thing1, thing2] = yield makeThings(2);`\n\nI can't find anything on the internet about assigning constants/variables in this way. Have you seen this? How does it work? My machine doesn't like it and spits out an unexpected token \"[\" error.\n\nMaybe it might be a npm package that I don't know about?\n\nUsing Node.js 5.1.0, ES6\n\n========================================\n\nCode:\n```text\nmakeThings(n)\n```\n\n```text\nconst [thing1, thing2] = yield makeThings(2);\n```\n\n```text\nvar list = [ 1, 2, 3 ]\nvar [ a, , b ] = list\n[ b, a ] = [ a, b ]\n```\n\n```text\nvar list = [ 1, 2, 3 ];\nvar a = list[0], b = list[2];\nvar tmp = a; a = b; b = tmp;\n```\n\n========================================\n\nComments:\n- You need to pass `--harmony_destructuring` to nodejs to enable destructuring.","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":44,"estimatedTokens":273}}953{"id":"stack-30953949","source":"stackoverflow","questionId":30953949,"title":"Sequelize ORM include model only if active = true","tags":["node.js","postgresql","orm","sequelize.js"],"text":"Title: Sequelize ORM include model only if active = true\nTags: node.js, postgresql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nhow can I findAll orders with id: 1 and include items only if this item has active = true? Otherwise there will be empty array...\n\n```\nOrder.findAll({\n where: { id: 1 },\n include: [\n { model: Item, where: sequelize.and({'active' : true }) }\n ]\n}).then(function(order) {\n callback(null, order);\n});\n```\n\nThis shows me only orders where are some items with active = true. I wanted to show all orders with id: 1 and items as a sub-array ...\n\n========================================\n\nCode:\n```text\nOrder.findAll({\n    where: { id: 1 },\n    include: [\n      { model: Item, where: sequelize.and({'active' : true }) }\n    ]\n}).then(function(order) {\n    callback(null, order);\n});\n```\n\n```text\nOrder.findAll({\n    where: { id: 1 },\n    include: [\n      { model: Item, \n        where: sequelize.and({'active' : true }),\n        required: false \n      }\n    ]\n}).then(function(order) {\n    callback(null, order);\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":47,"estimatedTokens":262}}954{"id":"stack-40019598","source":"stackoverflow","questionId":40019598,"title":"Sequelize mysql query where attribute is null","tags":["mysql","sequelize.js"],"text":"Title: Sequelize mysql query where attribute is null\nTags: mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an address and I want to see if it's in the db already, if not, create a new one. I know I can use `findOrCreate()` here, but let's make it easy and just check why I can't even find the existing address.\n\n```\nvar address = {\n name: req.body.name,\n address1: req.body.address1,\n address2: req.body.address2,\n zip: req.body.zip,\n city: req.body.city,\n country: req.body.country,\n user_id: req.body.user_id\n };\n\n Address.find({where: address}).then(function(result){\n console.log(result);\n }).catch(function(err){\n console.error(err);\n });\n```\n\nThe generated query asks for `... AND user_id = NULL`which is wrong. It should ask `... AND user_id IS NULL`. How can I let sequelize do it right for me? Thanks.\n\n========================================\n\nCode:\n```text\nvar address = {\n    name: req.body.name,\n    address1: req.body.address1,\n    address2: req.body.address2,\n    zip: req.body.zip,\n    city: req.body.city,\n    country: req.body.country,\n    user_id: req.body.user_id\n  };\n\n  Address.find({where: address}).then(function(result){\n    console.log(result);\n  }).catch(function(err){\n    console.error(err);\n  });\n```\n\n```text\nfindOrCreate()\n```\n\n```text\n... AND user_id = NULL\n```\n\n```text\n... AND user_id IS NULL\n```\n\n```text\nvar address = {\n    name: req.body.name,\n    address1: req.body.address1,\n    address2: req.body.address2,\n    zip: req.body.zip,\n    city: req.body.city,\n    country: req.body.country,\n    user_id: req.body.user_id || null\n};\n```\n\n```text\n... user_id IS NULL\n```\n\n```text\nmodel.findAll( { where: { some_column : undefined } } );\n```\n\n```text\n... WHERE `some_column` = NULL\n```\n\n========================================\n\nComments:\n- Thanks for your reply, I will test this soon.\n- upvoted. btw you can also use `null` directly: `model.findAll( { where: { some_column : null } } );`\n- Must use \"null\"","metadata":{"transformedAt":"2026-08-18T18:33:34.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":90,"estimatedTokens":489}}955{"id":"stack-20326400","source":"stackoverflow","questionId":20326400,"title":"Sequelize JS building associations","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize JS building associations\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am building a user and role association using sequelizejs with postgres. Each user can have one role and each role belongs to many users.\n\nI have setup the associations like this \n\n```\nglobal.db.User.belongsTo(global.db.Role, {foreignKey: 'role_id', as: 'Role'});\n\nglobal.db.Role.hasMany(global.db.User, {foreignKey: 'role_id'});\n```\n\nNow, when I am setting up the objects and syncing sequelize like this in app.js it's not working:\n\n```\nvar role = Role.build({ name: 'foo', permissions: 'bar'});\nvar user = User.build({username: 'sultansaadat', email: 'abc@abc.com', password: 'sultan123', isActive: true});\ndb.sequelize.sync().complete(function (err) {\nif (err) {\n throw err\n} else {\n role.save();\n user.setRole(role);\n user.save();\n}\n```\n\n});\n\nI was expecting sequelize to behave like all normal ORMs do but I think there is something wrong here or either I'm doing something wrong.\n\n========================================\n\nCode:\n```text\nglobal.db.User.belongsTo(global.db.Role, {foreignKey: 'role_id', as: 'Role'});\n\nglobal.db.Role.hasMany(global.db.User, {foreignKey: 'role_id'});\n```\n\n```text\nvar role = Role.build({ name: 'foo', permissions: 'bar'});\nvar user = User.build({username: 'sultansaadat', email: 'abc@abc.com', password: 'sultan123', isActive: true});\ndb.sequelize.sync().complete(function (err) {\nif (err) {\n    throw err\n} else {\n    role.save();\n    user.setRole(role);\n    user.save();\n}\n```\n\n```text\nrole.save().done(function (err, role) {\n    user.save().done(function (err, user) {\n        user.setRole(role);\n    });\n});\n```\n\n========================================\n\nComments:\n- I understand the async nature of things but the events were not firing up for me.\n- I wish sequelizejs documentation was better. Thanks for the answer :)","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":69,"estimatedTokens":470}}956{"id":"stack-33418459","source":"stackoverflow","questionId":33418459,"title":"using sequelize-cli db:seed, schema is ignored when accessing Postgres","tags":["postgresql","express","sequelize.js","seeding"],"text":"Title: using sequelize-cli db:seed, schema is ignored when accessing Postgres\nTags: postgresql, express, sequelize.js, seeding\nSource: Stack Overflow\n\nQuestion:\ni am building a web service using express.js and Sequilize with a Postgres DB. \n\nDatabase holds a table 'country' under schema 'schema1'. Table 'country' has fields 'name', 'isoCode'.\n\nCreated a seed file to insert a list of countries inside table 'country'.\n\nSeed file looks like :\n\n```\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert(\n 'country', \n [\n {\n \"name\":\"Afghanistan\",\n \"isoCode\":\"AF\"\n },\n {\n \"name\":\"Åland Islands\",\n \"isoCode\":\"AX\"\n },\n {\n \"name\":\"Albania\",\n \"isoCode\":\"AL\"\n },\n {\n \"name\":\"Algeria\",\n \"isoCode\":\"DZ\"\n },\n {\n \"name\":\"American Samoa\",\n \"isoCode\":\"AS\"\n },\n {\n \"name\":\"Andorra\",\n \"isoCode\":\"AD\"\n }\n ], \n {\n schema : 'schema1'\n }\n );\n },\n\n down: function (queryInterface, Sequelize) {\n\n }\n};\n```\n\nWhile running seed i get this error :\n\n```\nnode_modules/sequelize-cli/bin/sequelize --url postgres://user:password@localhost:5432/database db:seed\n\n Sequelize [Node: 0.12.6, CLI: 2.0.0, ORM: 3.11.0, pg: ^4.4.2]\n\n Parsed url postgres://user:*****@localhost:5432/database \n Starting 'db:seed'...\n Finished 'db:seed' after 165 ms\n == 20151029161319-Countries: migrating =======\n Unhandled rejection SequelizeDatabaseError: relation \"country\" does not exist\n at Query.formatError (node_modules/sequelize/lib/dialects/postgres/query.js:437:14)\n at null. (node_modules/sequelize/lib/dialects/postgres/query.js:112:19)\n at emit (events.js:107:17)\n at Query.handleError (node_modules/pg/lib/query.js:108:8)\n at null. (node_modules/pg/lib/client.js:171:26)\n at emit (events.js:107:17)\n at Socket. (node_modules/pg/lib/connection.js:109:12)\n at Socket.emit (events.js:107:17)\n at readableAddChunk (_stream_readable.js:163:16)\n at Socket.Readable.push (_stream_readable.js:126:10)\n at TCP.onread (net.js:538:20)\n```\n\nI think i am stuck on this. I would appreciate any provided help / guidance etc.\n\nThank you for your time.\n\n========================================\n\nTop Answer:\nYou can actually specify the schema and table name via object like is explained in this Github issue:\n\n```\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.bulkInsert(\n { tableName: 'account', schema: 'crm' },\n {\n name: 'Michael'\n },\n {}\n );\n },\n\n down: function (queryInterface, Sequelize) {\n return queryInterface.bulkDelete({ tableName: 'account', schema: 'crm' }, null, {});\n }\n};\n```\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.bulkInsert(\n        'country', \n        [\n          {\n            \"name\":\"Afghanistan\",\n            \"isoCode\":\"AF\"\n          },\n          {\n            \"name\":\"Åland Islands\",\n            \"isoCode\":\"AX\"\n          },\n          {\n            \"name\":\"Albania\",\n            \"isoCode\":\"AL\"\n          },\n          {\n            \"name\":\"Algeria\",\n            \"isoCode\":\"DZ\"\n          },\n          {\n            \"name\":\"American Samoa\",\n            \"isoCode\":\"AS\"\n          },\n          {\n            \"name\":\"Andorra\",\n            \"isoCode\":\"AD\"\n          }\n        ], \n        {\n            schema : 'schema1'\n        }\n    );\n  },\n\n  down: function (queryInterface, Sequelize) {\n\n  }\n};\n```\n\n```text\nnode_modules/sequelize-cli/bin/sequelize --url postgres://user:password@localhost:5432/database db:seed\n\n    Sequelize [Node: 0.12.6, CLI: 2.0.0, ORM: 3.11.0, pg: ^4.4.2]\n\n    Parsed url postgres://user:*****@localhost:5432/database        \n    Starting 'db:seed'...\n    Finished 'db:seed' after 165 ms\n    == 20151029161319-Countries: migrating =======\n    Unhandled rejection SequelizeDatabaseError: relation \"country\" does not exist\n        at Query.formatError (node_modules/sequelize/lib/dialects/postgres/query.js:437:14)\n        at null.<anonymous> (node_modules/sequelize/lib/dialects/postgres/query.js:112:19)\n        at emit (events.js:107:17)\n        at Query.handleError (node_modules/pg/lib/query.js:108:8)\n        at null.<anonymous> (node_modules/pg/lib/client.js:171:26)\n        at emit (events.js:107:17)\n        at Socket.<anonymous> (node_modules/pg/lib/connection.js:109:12)\n        at Socket.emit (events.js:107:17)\n        at readableAddChunk (_stream_readable.js:163:16)\n        at Socket.Readable.push (_stream_readable.js:126:10)\n        at TCP.onread (net.js:538:20)\n```\n\n```text\nALTER ROLE <username> SET search_path TO schema1,public;\n```\n\n```text\nnode_modules/sequelize-cli/bin/sequelize --url postgres://user:password@localhost:5432/database db:seed\n\n    Sequelize [Node: 0.12.6, CLI: 2.0.0, ORM: 3.11.0, pg: ^4.4.2]\n\n    Parsed url postgres://user:*****@localhost:5432/database\n    Using gulpfile node_modules/sequelize-cli/lib/gulpfile.js\n    Starting 'db:seed'...\n    Finished 'db:seed' after 558 ms\n    == 20151029161319-Countries: migrating =======\n    == 20151029161319-Countries: migrated (0.294s)\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n    up: function (queryInterface, Sequelize) {\n        return queryInterface.bulkInsert(\n            { tableName: 'account', schema: 'crm' },\n            {\n                name: 'Michael'\n            },\n            {}\n        );\n    },\n\n    down: function (queryInterface, Sequelize) {\n        return queryInterface.bulkDelete({ tableName: 'account', schema: 'crm' }, null, {});\n    }\n};\n```\n\n========================================\n\nComments:\n- What is the `search_path` for the DB user? Maybe it doesn't include `schema1`\n- Thanks for replying. Executed : show search_path The result is : \"$user\", public\n- Then of course an unqualified table name will not be resolved to `schema1`. You either need to change the user's search path to include `schema1`, teach your library to qualify the tables with a schema or teach your library on how to change the search path dynamically after a connect\n- thanks for the information about 'search_path'","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":227,"estimatedTokens":1509}}957{"id":"stack-37538014","source":"stackoverflow","questionId":37538014,"title":"How to disable a specific validation rule during a transaction?","tags":["transactions","sequelize.js"],"text":"Title: How to disable a specific validation rule during a transaction?\nTags: transactions, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two models: Files and Courses. Files belongs to Course and has a CourseId field. \n\nAt some point I needed to use transactions to validate both of them before inserting them, however, one of my validation rules for the File model verifies if the informed CourseId exists (it's useful in other cases where I don't use transactions) and this rule is flagged during the transaction because there's no CouseId during it, as we can all expect.\n\n```\nmodels.sequelize.transaction(function (t) {\n // if we want to insert a new course\n if (formData.courseId == 0) {\n return models.course.create({\n name: formData.courseName,\n fieldOfStudy: formData.fieldOfStudyId\n }, {transaction: t}).then(function(course) {\n return models.file.create({\n name: formData.name,\n universityId: formData.universityId,\n status: 1,\n type: formData.typeId,\n createdBy: userId,\n file_raw: files,\n courseId: course.id // here is the problem!\n }, {transaction: t});\n });\n // if we want to use a existing one \n } else { \n return models.file.create({\n name: formData.name,\n universityId: formData.universityId,\n courseId: formData.courseId,\n status: 1,\n type: formData.typeId,\n createdBy: userId,\n file_raw: files\n }, {transaction: t});\n }\n})\n```\n\nThis could be fixed if I could dinamically disable the validation rule for the CourseId field, but apparently this is not possible yet. Another approach would be virtual fields, but this one is not quite \"elegant\". \n\nAny ideas?\n\n========================================\n\nCode:\n```text\nmodels.sequelize.transaction(function (t) {\n    // if we want to insert a new course\n    if (formData.courseId == 0) {\n        return models.course.create({\n            name: formData.courseName,\n            fieldOfStudy: formData.fieldOfStudyId\n        }, {transaction: t}).then(function(course) {\n            return models.file.create({\n                name: formData.name,\n                universityId: formData.universityId,\n                status: 1,\n                type: formData.typeId,\n                createdBy: userId,\n                file_raw: files,\n                courseId: course.id // here is the problem!\n            }, {transaction: t});\n        });\n    // if we want to use a existing one                \n    } else { \n        return models.file.create({\n            name: formData.name,\n            universityId: formData.universityId,\n            courseId: formData.courseId,\n            status: 1,\n            type: formData.typeId,\n            createdBy: userId,\n            file_raw: files\n        }, {transaction: t});\n    }\n})\n```\n\n```text\nreturn models.file.create({\n    name: formData.name,\n    universityId: formData.universityId,\n    status: 1,\n    type: formData.typeId,\n    createdBy: userId,\n    file_raw: files,\n    courseId: course.id\n}, {skip: ['courseId'], transaction: t});\n```\n\n```text\nskip\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":97,"estimatedTokens":744}}958{"id":"stack-33887542","source":"stackoverflow","questionId":33887542,"title":"Get the data from related tables (models) sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: Get the data from related tables (models) sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet's say I have these tables:\n\n```\ncountries\n id - integer\n name - string\n\nusers\n id - integer\n countryId - integer\n name - string\n```\n\nWhat I want is to get all the users with their country names instead of the country ids... Sequelize docs are good, but confusing...\n\nI got the following func to get all the users:\n\n```\nfunction get( request, response ) {\n\n models.users.findAll( {\n\n order: [ [ request.query.orderBy, request.query.sort ] ]\n\n } ).then( function ( users ) {\n\n response.json( users );\n\n } );\n\n}\n```\n\nAnd here's my users.js model:\n\n```\n'use strict';\nmodule.exports = function ( sequelize, DataTypes ) {\n\n var users = sequelize.define( 'users', {\n name: DataTypes.STRING( 50 ),\n countryId: DataTypes.INTEGER,\n }, {\n classMethods: {\n associate: function ( models ) {\n // associations can be defined here\n }\n }\n } );\n\n return users;\n\n};\n```\n\nSo... what do I need to do in order to get the country name instead of the id when querying users model?\n\n========================================\n\nTop Answer:\n```\nUser.belongsTo(Country)\nUser.findAll({ include: [Country] })\n```\n\nEach user will have a `.country` property, where you can get the name - it's not possible to have the country name added directly to the same object, for that you'll have to use a raw query, or format the result afterwards\n\n========================================\n\nCode:\n```text\ncountries\n    id - integer\n    name - string\n\nusers\n    id - integer\n    countryId - integer\n    name - string\n```\n\n```text\nfunction get( request, response ) {\n\n    models.users.findAll( {\n\n        order: [ [ request.query.orderBy, request.query.sort ] ]\n\n    } ).then( function ( users ) {\n\n        response.json( users );\n\n    } );\n\n}\n```\n\n```text\n'use strict';\nmodule.exports = function ( sequelize, DataTypes ) {\n\n    var users = sequelize.define( 'users', {\n        name: DataTypes.STRING( 50 ),\n        countryId: DataTypes.INTEGER,\n    }, {\n        classMethods: {\n            associate: function ( models ) {\n                // associations can be defined here\n            }\n        }\n    } );\n\n    return users;\n\n};\n```\n\n```text\n'use strict';\nmodule.exports = function ( sequelize, DataTypes ) {\n\nvar users = sequelize.define( 'users', {\n    name: DataTypes.STRING( 50 ),\n    countryId: DataTypes.INTEGER,\n}, {\n    classMethods: {\n        associate: function ( models ) {\n            users.belongsTo(models.countries, {foreignKey: countryId})\n        }\n    }\n} );\n\nreturn users;\n\n};\n```\n\n```text\nmodels.users.findAll( {\n\n    order: [ [ request.query.orderBy, request.query.sort ] ],\n    include: [{\n        model: models.countries\n    }]\n} ).then( function ( users ) {\n\n    // do some formating on the output\n\n} );\n```\n\n```text\nUser.belongsTo(Country)\nUser.findAll({ include: [Country] })\n```\n\n```text\n.country\n```\n\n========================================\n\nComments:\n- Could you please explain a little bit about from where does that `User` and `Country` objects come?, I suppose they are the models, but... i would like to know the way to define assosiations at `classMethods: { associate: function ( models ) { &#47;&#47; associations can be defined here } }`","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":169,"estimatedTokens":817}}959{"id":"stack-8089957","source":"stackoverflow","questionId":8089957,"title":"do I need to worry about mysql connection pooling for node.js using sequelize?","tags":["mysql","node.js","connection-pooling","sequelize.js"],"text":"Title: do I need to worry about mysql connection pooling for node.js using sequelize?\nTags: mysql, node.js, connection-pooling, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm new to node.js and have heard of connection pooling and it makes sense to me as the connection is an expensive operation.\n\nI am looking at which node module to use for mysql and I like the look of Sequelize as it is an ORM.\n\nI'm not sure if I need to worry about connection pooling with Sequelize. Do I just instantiate it and reuse it for all clients?\n\n```\nvar sequelize = new Sequelize('database', 'username'[, 'password'])\n```\n\nAlso, do I need to worry about the number of parallel queries being executed?\n\nFor example, if I am looping through a table and executing a query per row. What happens if there are 1000 or more rows? \n\nDo those queries get executed all at once? \n\nIf so, is there a limit to the amount you can throw at it?\n\n========================================\n\nCode:\n```text\nvar sequelize = new Sequelize('database', 'username'[, 'password'])\n```\n\n========================================\n\nComments:\n- Thanks sdepold, what about the parallel queries, does it hammer the db?\n- Sequelize v3 does have connection pool: github.com/sequelize/sequelize/blob/v3/docs/docs/&hellip;\n- can you please explain how to use pool ? is it necessary ? i cant understand the ussage in docs","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":36,"estimatedTokens":343}}960{"id":"stack-67211877","source":"stackoverflow","questionId":67211877,"title":"How to set up Winston loggin with Sequelize properly?","tags":["javascript","node.js","sequelize.js","winston"],"text":"Title: How to set up Winston loggin with Sequelize properly?\nTags: javascript, node.js, sequelize.js, winston\nSource: Stack Overflow\n\nQuestion:\nI am configuring winston with Sequelize. I have the following:\n\n```\nconst logger = winston.createLogger({\n level: 'info',\n format: winston.format.json(),\n transports: [\n new winston.transports.File({ filename: path.join('logs', 'error.log'), level: 'error' }),\n new winston.transports.File({ filename: path.join('logs', 'info.log'), level: 'info' }),\n new winston.transports.File({ filename: path.join('logs', 'combined.log') }),\n ],\n});\n\nconst sequelize = new Sequelize(\n database.database,\n database.user,\n database.password,\n {\n host: database.host,\n dialect: 'mysql',\n logging: (msg) => logger.info(msg),\n }\n);\n```\n\nHowever, the logs files show the message before level:\n\n```\n{\"message\":\"Database connection has been established successfully.\",\"level\":\"info\"}\n```\n\nBesides, timestamp does not appear as shown here.\n\nAny fix?\n\n========================================\n\nCode:\n```text\nconst logger = winston.createLogger({\n    level: 'info',\n    format: winston.format.json(),\n    transports: [\n        new winston.transports.File({ filename: path.join('logs', 'error.log'), level: 'error' }),\n        new winston.transports.File({ filename: path.join('logs', 'info.log'), level: 'info' }),\n        new winston.transports.File({ filename: path.join('logs', 'combined.log') }),\n    ],\n});\n\nconst sequelize = new Sequelize(\n    database.database,\n    database.user,\n    database.password,\n    {\n        host: database.host,\n        dialect: 'mysql',\n        logging: (msg) => logger.info(msg),\n    }\n);\n```\n\n```text\n{\"message\":\"Database connection has been established successfully.\",\"level\":\"info\"}\n```\n\n```text\nconst logger = winston.createLogger({\n  level: 'info',\n  format: winston.format.combine(winston.format.timestamp(), winston.format.json()),\n  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  transports: [\n    new winston.transports.File({ filename: path.join('logs', 'error.log'), level: 'error', timestamp: true }),\n    new winston.transports.File({ filename: path.join('logs', 'info.log'), level: 'info', timestamp: true }),\n    new winston.transports.File({ filename: path.join('logs', 'combined.log'), timestamp: true }),\n  ],\n});\n```\n\n========================================\n\nComments:\n- can you please check my winston related question. stackoverflow.com/questions/67385636/&hellip; any help will be appreciated","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":87,"estimatedTokens":628}}961{"id":"stack-64554295","source":"stackoverflow","questionId":64554295,"title":"Send multiples params securely to IN clause with Sequelize for raw query","tags":["javascript","sql","security","sequelize.js"],"text":"Title: Send multiples params securely to IN clause with Sequelize for raw query\nTags: javascript, sql, security, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing Sequelize I can perform raw queries and send params securely (thanks to database bound params via parameters:\n\n```\nconst baz = 1;\n\nsequelize.query(\n 'select * from foo where bar=:baz',\n { replacements: { baz } },\n);\n```\n\nIs there a similar way to address the `IN` (with multiple values)?\n\n```\nconst baz = [1, 2, 3];\n\nsequelize.query(\n 'select * from foo where bar IN (:baz)',\n { replacements: { baz } },\n);\n```\n\n========================================\n\nCode:\n```js\nconst baz = 1;\n\nsequelize.query(\n  'select * from foo where bar=:baz',\n  { replacements: { baz } },\n);\n```\n\n```js\nconst baz = [1, 2, 3];\n\nsequelize.query(\n  'select * from foo where bar IN (:baz)',\n  { replacements: { baz } },\n);\n```\n\n```text\nIN\n```\n\n```js\nconst baz = [1, 2, 3];\n\nsequelize.query(\n  'select * from foo where bar IN (:baz)',\n  { replacements: { baz } },\n);\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":60,"estimatedTokens":252}}962{"id":"stack-56985226","source":"stackoverflow","questionId":56985226,"title":"Sequelize findAll() with where-parameter returns null while findByPk() returns correct data","tags":["node.js","graphql","sequelize.js"],"text":"Title: Sequelize findAll() with where-parameter returns null while findByPk() returns correct data\nTags: node.js, graphql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm setting up resolvers for a GraphQL API right now and running into some problems/questions regarding the findAll() function from sequelize.\n\nI have these 2 resolvers: \n\n```\nUser: async (parent, { id }, { models }) => {\n return await models.User.findAll({\n where: {\n ID_User: id\n }\n });\n}\n\nUserPK: async (parent, { id }, { models }) => {\n return await models.User.findByPk(id);\n}\n```\n\nModels:\n\n```\ntype Query {\n UserPK(id: ID): User\n User(id: ID): User\n}\ntype User {\n ID_User: ID,\n Username: String,\n}\n```\n\nIf I now run these queries\n\n```\n{\n UserPK(id: 1) {\n ID_User\n Username\n }\n User(id: 1) {\n ID_User\n Username\n }\n}\n```\n\nOnly the UserPK returns (correct) data, the User query returns null for every field which confuses me because the queries sequelize executes are exactly the same.\n\n```\nExecuting (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';\nExecuting (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';\n```\n\nI'm using apollo server btw if that makes any difference.\n\n========================================\n\nCode:\n```text\nUser: async (parent, { id }, { models }) => {\n  return await models.User.findAll({\n    where: {\n      ID_User: id\n    }\n  });\n}\n\nUserPK: async (parent, { id }, { models }) => {\n  return await models.User.findByPk(id);\n}\n```\n\n```text\ntype Query {\n  UserPK(id: ID): User\n  User(id: ID): User\n}\ntype User {\n  ID_User: ID,\n  Username: String,\n}\n```\n\n```text\n{\n UserPK(id: 1) {\n    ID_User\n    Username\n  }\n User(id: 1) {\n    ID_User\n    Username\n  }\n}\n```\n\n```text\nExecuting (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';\nExecuting (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';\n```\n\n```js\nreturn (await models.User.findAll({\n  where: {\n    ID_User: id\n  }\n}))[0];\n```\n\n```text\nfindByPk\n```\n\n```text\nfindAll\n```\n\n```text\nfindByPk\n```\n\n```text\nfindAll\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- Ah that makes so much sense now. Thanks for the quick answer, both return the same now!\n- Sometimes all the *implicit* resolvers are not helpful when it comes to errors :( Glad it works now!","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":139,"estimatedTokens":598}}963{"id":"stack-56183233","source":"stackoverflow","questionId":56183233,"title":"How to properly pass custom errors from Backend (Express) to Frontend (Vue)","tags":["node.js","express","vue.js","sequelize.js","axios"],"text":"Title: How to properly pass custom errors from Backend (Express) to Frontend (Vue)\nTags: node.js, express, vue.js, sequelize.js, axios\nSource: Stack Overflow\n\nQuestion:\nI am developing a basic **Node** app and I am facing a problem that I think is not new but I don't understand which is the proper way to solve. I need to handle those errors that are not generated by code, network or database but needed by the logic of the application. As an example I use the ***already registered user*** but the same handling will be needed in different case in the application.\n\nI start from the method in **login component**:\n\n```\nregister () {\n API\n .register(this.credentials)\n .then(\n data => {\n this.user = data;\n },\n error => {\n this.error = error;\n })\n .catch(error => {\n this.error = error;\n });\n},\n```\n\nThe **API** is:\n\n```\nregister (credentials) {\n return Axios\n .post('/auth/register',credentials)\n .then(response => {\n return response.data;\n })\n},\n```\n\nThe **Backend** is:\n\n```\nrouter.post('/auth/register',(req,res) => {\nUser.findOne({where:{username:req.body.username}})\n .then(user => {\n if (!user) {\n User\n .create(req.body)\n .then(user => {\n res.send(user);\n })\n } else {\n throw 'Username already exists';\n }\n });\n});\n```\n\nWhat I expect is that the error\n\n throw 'Username already exists';\n\n(but it can be ***No data found for your search***) is passed back to the component that catch it and show the error instead the registerd user.\nI try adding the `catch` after every `then` or using `res.send({error:...})` instead of throw but in this way the component shows the error message as user object.\n\n========================================\n\nCode:\n```text\nregister () {\n  API\n    .register(this.credentials)\n    .then(\n      data => {\n        this.user = data;\n      },\n      error => {\n        this.error = error;\n      })\n    .catch(error => {\n      this.error = error;\n    });\n},\n```\n\n```text\nregister (credentials) {\n return Axios\n  .post('/auth/register',credentials)\n  .then(response => {\n    return response.data;\n  })\n},\n```\n\n```text\nrouter.post('/auth/register',(req,res) => {\nUser.findOne({where:{username:req.body.username}})\n  .then(user => {\n    if (!user) {\n      User\n        .create(req.body)\n        .then(user => {\n          res.send(user);\n        })\n    } else {\n      throw 'Username already exists';\n    }\n  });\n});\n```\n\n```text\ncatch\n```\n\n```text\nthen\n```\n\n```text\nres.send({error:...})\n```\n\n```text\nrouter.post('/auth/register',(req,res) => {\nconsole.log('backend register 3',req.body);\nUser.findOne({where:{username:req.body.username}})\n  .then(user => {\n    if (!user) {\n      User\n        .create(req.body)\n        .then(user => {\n          console.log('backend register 4',req.body);\n          res.send(user);\n        })\n    } else {\n      res.status(409).send('User already exists')\n    }\n  });\n});\n```\n\n```text\nregister (credentials) {\n return Axios\n  .post('/auth/register',credentials)\n  .then(response => {\n    return response.data;\n  })\n  .catch(err => {\n    processError(err);\n  })\n},\n```\n\n========================================\n\nComments:\n- I try this way also but status(409) is received by Axios not in *then* section but in *catch* section resulting in the component as a standard error message with status code and without my custom message.\n- The best solution for this is to use axios response interceptor, as you are already using axios. And by using that you can handle all the errors from a single place.\n- The axios response interceptor logs the same error as .catch method. It just says \"Request failed with status code 409\" not the custom error passed from Express :(\n- Then you are correctly receiving a 409 error from your express. Watch out, error code and custom message often are two different fields. Look into your `err` object to find the message.","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":162,"estimatedTokens":954}}964{"id":"stack-67963977","source":"stackoverflow","questionId":67963977,"title":"Sequelize Op.iLike throwing Error with MySQL","tags":["mysql","database","sequelize.js"],"text":"Title: Sequelize Op.iLike throwing Error with MySQL\nTags: mysql, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n`Error: Invalid value { undefined: 'w%' }`\n\nThis is my query:\n\n```\nresults = await models.Record.findAll({\n where: {\n \n name: {\n [Op.iLike]: prefix + \"%\", //causing problems\n },\n },\n order: [[\"createdAt\", \"DESC\"]],\n limit: num,\n });\n```\n\nname is a String field in my MySQL table.\n\nYou have an error in your SQL syntax near `'ILIKE' 'james'`. It seems the ORM converts the query to ILIKE, which is not valid.\n\n========================================\n\nCode:\n```text\nresults = await models.Record.findAll({\n          where: {\n            \n            name: {\n              [Op.iLike]: prefix + \"%\", //causing problems\n            },\n          },\n          order: [[\"createdAt\", \"DESC\"]],\n          limit: num,\n        });\n```\n\n```text\nError: Invalid value { undefined: 'w%' }\n```\n\n```text\n'ILIKE' 'james'\n```\n\n```text\nresults = await models.Record.findAll({\n      where: {\n        \n        name: {\n          [Op.startsWith]: prefix, \n        },\n      },\n      order: [[\"createdAt\", \"DESC\"]],\n      limit: num,\n    });\n```\n\n```text\n[Op.like]: '%hat',                       // LIKE '%hat'\n  [Op.notLike]: '%hat',                    // NOT LIKE '%hat'\n  [Op.startsWith]: 'hat',                  // LIKE 'hat%'\n  [Op.endsWith]: 'hat',                    // LIKE '%hat'\n  [Op.substring]: 'hat',                   // LIKE '%hat%'\n  [Op.iLike]: '%hat',                      // ILIKE '%hat' (case insensitive) (PG only)\n  [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (PG only)\n  [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (MySQL/PG only)\n  [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)\n  [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (PG only)\n  [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (PG only)\n```\n\n```text\nOp.startsWith\n```\n\n========================================\n\nComments:\n- I suggest that you log the final SQL query. It's tough to debug generated code by staring at code that generates it. See stackoverflow.com/questions/21427501/&hellip;\n- ^ you can do that buy adding `log: true` to your query which will print the SQL to the console.\n- Sequelize ILIKE is for postgres only. MySQL doesn't support ILIKE. Instead, the regular LIKE in MySQL is case insensitive search by default. dev.mysql.com/doc/refman/8.0/en/case-sensitivity.html\n- Sequelize doesn't have LIKE.\n- They actually do. `[Op.like]: prefix + '%'` yet, if you are searching by `prefix`, you can use `Op.startsWith` as well. It internally translates into LIKE statement.\n- Thanks. Frustrating that the platform specific operations aren't detailed in the API docs.","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":90,"estimatedTokens":689}}965{"id":"stack-62826152","source":"stackoverflow","questionId":62826152,"title":"Sequelize migration doesnot read dotenv variable if I don't run it from root directory. why?","tags":["sequelize.js","sequelize-cli","dotenv"],"text":"Title: Sequelize migration doesnot read dotenv variable if I don't run it from root directory. why?\nTags: sequelize.js, sequelize-cli, dotenv\nSource: Stack Overflow\n\nQuestion:\nThis is what I did\n\n- require('dotenv').config() in the config file\n\n- set .sequelizerc in the root directory like below\n\n- set .sequelie file to point config, migrations, models, seeds directory from root directory\n\n- ran `npx seuqlie-cli db:migrate` form root directory. It work!\n\n- ran `npx seuqlie-cli db:migrate` form sequelize directory. It doesn't read dotenv variable and come with `connect ECONNREFUSED 127.0.0.1:3306`\n\nand I want to know what is differences between 4 and 5..?\n\nthis is my directory looks like\nhttps://i.sstatic.net/EgL2g.png\n\nmy .sequlizerc file\n\n```\nconst path = require('path')\n\nmodule.exports={\n config: path.resolve('src/sequelize/config','config.js'),\n 'migrations-path': path.resolve('src/sequelize/migrations'),\n 'seeders-path': path.resolve('src/sequelize/seeders'),\n 'models-path': path.resolve('src/sequelize/models')\n}\n```\n\nand my config file\n\n```\nrequire(\"dotenv\").config();\n\nmodule.exports = {\n development: {\n username: process.env.DEV_DATABASE_USER_NAME,\n password: process.env.DEV_DATABASE_PASSWORD,\n database: process.env.DEV_DATABASE_NAME,\n host: process.env.DEV_DATABASE_HOST,\n dialect: \"mysql\",\n charset: \"utf8\",\n collate: \"utf8_general_ci\",\n operatorsAliases: false,\n define: {\n underscored: true\n }\n },\n...\n}\n```\n\n========================================\n\nCode:\n```text\nconst path = require('path')\n\nmodule.exports={\n    config: path.resolve('src/sequelize/config','config.js'),\n    'migrations-path': path.resolve('src/sequelize/migrations'),\n    'seeders-path': path.resolve('src/sequelize/seeders'),\n    'models-path': path.resolve('src/sequelize/models')\n}\n```\n\n```text\nrequire(\"dotenv\").config();\n\nmodule.exports = {\n  development: {\n    username: process.env.DEV_DATABASE_USER_NAME,\n    password: process.env.DEV_DATABASE_PASSWORD,\n    database: process.env.DEV_DATABASE_NAME,\n    host: process.env.DEV_DATABASE_HOST,\n    dialect: \"mysql\",\n    charset: \"utf8\",\n    collate: \"utf8_general_ci\",\n    operatorsAliases: false,\n    define: {\n      underscored: true\n    }\n  },\n...\n}\n```\n\n```text\nnpx seuqlie-cli db:migrate\n```\n\n```text\nnpx seuqlie-cli db:migrate\n```\n\n```text\nconnect ECONNREFUSED 127.0.0.1:3306\n```\n\n```text\ndotenv.config({ path: `${process.cwd()}/.env`})\n```\n\n========================================\n\nComments:\n- That’s just how `dotenv` works it assume the .env file would be at the same level where you run the script.","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":113,"estimatedTokens":641}}966{"id":"stack-16128688","source":"stackoverflow","questionId":16128688,"title":"Saving object with Sequelize","tags":["javascript","sequelize.js"],"text":"Title: Saving object with Sequelize\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am struggling with step 1 of Sequelize. I have read through the tutorial and I must be missing on something basic, for I have already spent over a day trying to figure out what I am doing wrong.\n\nThe following is a unit test I have written using Mocha.\n\n```\nvar db = require(\"../../db.js\").sequelize;\nvar DataTypes = require(\"sequelize\");\n\nvar _table = db.define('users', {\n name: DataTypes.STRING,\n email: DataTypes.STRING\n }, { \n timestamps: false\n });\n\nvar assert = require(\"assert\")\ndescribe('Users', function(){\n describe('#save()', function(){\n it('should save a user', function(){\n _table\n .build({name: 'test', email: 'a@a.com'})\n .save()\n .success(function(o){\n console.log(\"saved\");\n console.log(o.values);\n }).error(function(error) {\n console.log(\"++++++++++\");\n console.log(error);\n });\n\n })\n })\n})\n```\n\nIt runs fine and I have removed the asserts for now. The problem is, I don't see either of the console logs, not success not error. Plus there's no row in the database.\n\nThe db.js is just a utility file that helps create an instance of Sequelize JS with the db configuration - I have already done a console.dir and looked through the instance and it looks as below:\n\n```\n{ options: \n { dialect: 'mysql',\n host: 'localhost',\n port: 3306,\n protocol: 'tcp',\n define: {},\n query: {},\n sync: {},\n logging: [Function],\n omitNull: false,\n queue: true,\n native: false,\n replication: false,\n pool: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 } },\n config: \n { database: 'beacon',\n username: 'beacon',\n password: 'beacon',\n host: 'localhost',\n port: 3306,\n pool: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 },\n protocol: 'tcp',\n queue: true,\n native: false,\n replication: false,\n maxConcurrentQueries: undefined },\n daoFactoryManager: { daos: [ [Object], [Object] ], sequelize: [Circular] },\n connectorManager: \n { sequelize: [Circular],\n client: null,\n config: \n { database: 'beacon',\n username: 'beacon',\n password: 'beacon',\n host: 'localhost',\n port: 3306,\n pool: [Object],\n protocol: 'tcp',\n queue: true,\n native: false,\n replication: false,\n maxConcurrentQueries: undefined },\n disconnectTimeoutId: null,\n queue: [],\n activeQueue: [ [Object] ],\n maxConcurrentQueries: 50,\n poolCfg: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 },\n pendingQueries: 0,\n useReplicaton: false,\n useQueue: true,\n pool: \n { destroy: [Function],\n acquire: [Function],\n borrow: [Function],\n release: [Function],\n returnToPool: [Function],\n drain: [Function],\n destroyAllNow: [Function],\n getPoolSize: [Function],\n getName: [Function],\n availableObjectsCount: [Function],\n waitingClientsCount: [Function] },\n isConnecting: false },\n importCache: {},\n queryInterface: \n { sequelize: [Circular],\n QueryGenerator: \n { createTableQuery: [Function],\n dropTableQuery: [Function],\n renameTableQuery: [Function],\n showTablesQuery: [Function],\n addColumnQuery: [Function],\n removeColumnQuery: [Function],\n changeColumnQuery: [Function],\n renameColumnQuery: [Function],\n selectQuery: [Function],\n insertQuery: [Function],\n updateQuery: [Function],\n deleteQuery: [Function],\n incrementQuery: [Function],\n addIndexQuery: [Function],\n showIndexQuery: [Function],\n removeIndexQuery: [Function],\n getWhereConditions: [Function],\n hashToWhereConditions: [Function],\n attributesToSQL: [Function],\n findAutoIncrementField: [Function],\n addQuotes: [Function],\n removeQuotes: [Function],\n options: [Object] } } }\n```\n\nNow I get the INSERT statement logged on the screen, but the instance never makes it to the db. what am I doing wrong?\n\n========================================\n\nCode:\n```text\nvar db = require(\"../../db.js\").sequelize;\nvar DataTypes = require(\"sequelize\");\n\nvar _table = db.define('users', {\n      name: DataTypes.STRING,\n      email: DataTypes.STRING\n    }, { \n      timestamps: false\n    });\n\nvar assert = require(\"assert\")\ndescribe('Users', function(){\n  describe('#save()', function(){\n    it('should save a user', function(){\n        _table\n        .build({name: 'test', email: 'a@a.com'})\n        .save()\n        .success(function(o){\n            console.log(\"saved\");\n            console.log(o.values);\n        }).error(function(error) {\n            console.log(\"++++++++++\");\n            console.log(error);\n        });\n\n    })\n  })\n})\n```\n\n```text\n{ options: \n   { dialect: 'mysql',\n     host: 'localhost',\n     port: 3306,\n     protocol: 'tcp',\n     define: {},\n     query: {},\n     sync: {},\n     logging: [Function],\n     omitNull: false,\n     queue: true,\n     native: false,\n     replication: false,\n     pool: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 } },\n  config: \n   { database: 'beacon',\n     username: 'beacon',\n     password: 'beacon',\n     host: 'localhost',\n     port: 3306,\n     pool: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 },\n     protocol: 'tcp',\n     queue: true,\n     native: false,\n     replication: false,\n     maxConcurrentQueries: undefined },\n  daoFactoryManager: { daos: [ [Object], [Object] ], sequelize: [Circular] },\n  connectorManager: \n   { sequelize: [Circular],\n     client: null,\n     config: \n      { database: 'beacon',\n        username: 'beacon',\n        password: 'beacon',\n        host: 'localhost',\n        port: 3306,\n        pool: [Object],\n        protocol: 'tcp',\n        queue: true,\n        native: false,\n        replication: false,\n        maxConcurrentQueries: undefined },\n     disconnectTimeoutId: null,\n     queue: [],\n     activeQueue: [ [Object] ],\n     maxConcurrentQueries: 50,\n     poolCfg: { maxConnections: 10, minConnections: 0, maxIdleTime: 1000 },\n     pendingQueries: 0,\n     useReplicaton: false,\n     useQueue: true,\n     pool: \n      { destroy: [Function],\n        acquire: [Function],\n        borrow: [Function],\n        release: [Function],\n        returnToPool: [Function],\n        drain: [Function],\n        destroyAllNow: [Function],\n        getPoolSize: [Function],\n        getName: [Function],\n        availableObjectsCount: [Function],\n        waitingClientsCount: [Function] },\n     isConnecting: false },\n  importCache: {},\n  queryInterface: \n   { sequelize: [Circular],\n     QueryGenerator: \n      { createTableQuery: [Function],\n        dropTableQuery: [Function],\n        renameTableQuery: [Function],\n        showTablesQuery: [Function],\n        addColumnQuery: [Function],\n        removeColumnQuery: [Function],\n        changeColumnQuery: [Function],\n        renameColumnQuery: [Function],\n        selectQuery: [Function],\n        insertQuery: [Function],\n        updateQuery: [Function],\n        deleteQuery: [Function],\n        incrementQuery: [Function],\n        addIndexQuery: [Function],\n        showIndexQuery: [Function],\n        removeIndexQuery: [Function],\n        getWhereConditions: [Function],\n        hashToWhereConditions: [Function],\n        attributesToSQL: [Function],\n        findAutoIncrementField: [Function],\n        addQuotes: [Function],\n        removeQuotes: [Function],\n        options: [Object] } } }\n```\n\n```text\nvar db = require(\"../../db.js\").sequelize;\nvar DataTypes = require(\"sequelize\");\n\nvar _table = db.define('users', {\n      name: DataTypes.STRING,\n      email: DataTypes.STRING\n    }, { \n      timestamps: false\n    });\n\nvar assert = require(\"assert\")\ndescribe('Users', function(){\n  describe('#save()', function(){\n    it('should save a user', function(done){\n        _table\n        .build({name: 'test', email: 'a@a.com'})\n        .save()\n        .success(function(o){\n            console.log(\"saved\");\n            console.log(o.values);\n            done();\n        }).error(function(error) {\n            console.log(\"++++++++++\");\n            console.log(error);\n            done();\n        });\n\n    })\n  })\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":298,"estimatedTokens":1954}}967{"id":"stack-46673940","source":"stackoverflow","questionId":46673940,"title":"Wait for queries with sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: Wait for queries with sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm currently using Node.js with Sequelize (MySQL) and have two models that have an association between them: `M.belongsTo(C)`. What I'm trying to do is to query all C and add all M that belongs to C to the returned JSON object. See code below that represents my latest attempt:\n\n```\nC.findAll({\n where: {\n parent_ids: ids\n }\n}).then(cs => {\n let fCs = [];\n for (let j = 0; j {\n let cMs = [];\n for (let k = 0; k {\n return res.json({\n success: false\n });\n});\n```\n\nThe problem is that the inner query on `M` model is made as an async query and I get the response before any query is performed. I tried also using `Promise.all()`, but I couldn't make it work properly because I'm iterating in the outer `C` query.\n\nHow can I make it work as expected?\n\n========================================\n\nCode:\n```text\nC.findAll({\n    where: {\n        parent_ids: ids\n    }\n}).then(cs => {\n    let fCs = [];\n    for (let j = 0; j < cs.length; j++) {\n        let c = cs[j].get({ plain: true });\n\n        M.findAll({\n            where: {\n                CId: c._id\n            }\n        }).then(ms => {\n            let cMs = [];\n            for (let k = 0; k < ms.length; k++) {\n                cMs.push(ms[k].get({ plain: true }));\n            }\n\n            c.ms = cMs;\n        });\n\n        fCs.push(c);\n    }\n\n    return res.json({\n        success: true,\n        cs: fCs\n    });\n}).catch(error => {\n    return res.json({\n        success: false\n    });\n});\n```\n\n```text\nM.belongsTo(C)\n```\n\n```text\nM\n```\n\n```text\nPromise.all()\n```\n\n```text\nC\n```\n\n```text\nvar fCs = [], cs,\nC.findAll({\n  where: {\n    parent_ids: ids\n  }\n}).then(data => {\n  cs = data;\n  var promises = [];\n  for (let j = 0; j < cs.length; j++) {\n    let c = cs[j].get({ plain: true });\n\n    promises.push(M.findAll({\n        where: {\n            CId: c._id\n        }\n    }).then(ms => {\n        let cMs = [];\n        for (let k = 0; k < ms.length; k++) {\n            cMs.push(ms[k].get({ plain: true }));\n        }\n\n        return cMs;\n    }));\n  }\n  return Promise.all(promises)\n}).then(result => {\n  fcs = cs.map((el, index) => {\n    let obj = el.get({plain:  true})\n    obj.ms = result[index]\n    return obj\n  })\n  return res.json({\n    success: true,\n    cs: fCs\n  });\n}).catch(error => {\n  return res.json({\n    success: false\n  });\n});\n```\n\n========================================\n\nComments:\n- Thanks! My mistake was that I was trying to use `Promise.all()` the wrong way.","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":130,"estimatedTokens":635}}968{"id":"stack-55332308","source":"stackoverflow","questionId":55332308,"title":"findByPrimary is not a function","tags":["javascript","sqlite","sequelize.js","discord","discord.js"],"text":"Title: findByPrimary is not a function\nTags: javascript, sqlite, sequelize.js, discord, discord.js\nSource: Stack Overflow\n\nQuestion:\n### TL;DR\n\n### I am getting an error saying that findByPrimary is not a function when using Sequelize.\n\nI have been following this tutorial on how to make a currency system for a Discord bot using Sequelize and SQLite 3. However, whenever I use `findByPrimary` on a model I get the following error:\n\n```\n(node:9182) UnhandledPromiseRejectionWarning: TypeError: Users.findByPrimary is not a function\n```\n\n`Users` is defined in `models/Users.js`:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n return sequelize.define('users', {\n userId: {\n type: DataTypes.STRING,\n primaryKey: true\n },\n balance: {\n type: DataTypes.INTEGER,\n defaultValue: 0,\n allowNull: false\n }\n }, {\n timestamps: false\n });\n};\n```\n\nwhich is referred to in `dbObjects.js`:\n\n```\n//modules\nconst Sequelize = require('sequelize');\n\n//sequelize connection info\nconst sequelize = new Sequelize('database', 'username', 'password', {\n host: 'localhost',\n dialect: 'sqlite',\n logging: false,\n storage: 'database.sqlite'\n});\n\n//models\nconst Users = sequelize.import('models/Users');\n\n//export\nmodule.exports = {Users};\n```\n\nwhich is imported in `server.js` and used as one of the arguments in `execute` in a command file:\n\n```\nconst {Users} = require('./dbObjects');\n\n//command is a file (in this case commands/inventory.js and commands/buy.js)\ncommand.execute(message, Users);\n```\n\nwhich is used in the commands that don't work:\n\n`commands/inventory.js`\n\n```\nmodule.exports = {\n execute: async (message, Users) => {\n const target = message.mentions.users.first() || message.author;\n const user = await Users.findByPrimary(target.id);\n }\n};\n```\n\n`commands/buy.js`\n\n```\nmodule.exports = {\n execute: async (message, Users) => {\n const user = await Users.findByPrimary(message.author.id);\n }\n};\n```\n\nI have tried using `findById` but that results in the same error message. I also have tried adding the following code to the execute function in the command files:\n\n```\nconst Sequelize = require('sequelize);\nconst SQLite = require('sqlite3');\n```\n\nThe only difference between my code and the aforementioned tutorial's is that I am using a command handler.\n\nAll other Sequelize functions such as `findAll` have been working.\n\n========================================\n\nCode:\n```text\n(node:9182) UnhandledPromiseRejectionWarning: TypeError: Users.findByPrimary is not a function\n```\n\n```js\nmodule.exports = (sequelize, DataTypes) => {\n    return sequelize.define('users', {\n        userId: {\n            type: DataTypes.STRING,\n            primaryKey: true\n        },\n        balance: {\n            type: DataTypes.INTEGER,\n            defaultValue: 0,\n            allowNull: false\n        }\n    }, {\n        timestamps: false\n    });\n};\n```\n\n```js\n//modules\nconst Sequelize = require('sequelize');\n\n//sequelize connection info\nconst sequelize = new Sequelize('database', 'username', 'password', {\n    host: 'localhost',\n    dialect: 'sqlite',\n    logging: false,\n    storage: 'database.sqlite'\n});\n\n//models\nconst Users = sequelize.import('models/Users');\n\n//export\nmodule.exports = {Users};\n```\n\n```js\nconst {Users} = require('./dbObjects');\n\n//command is a file (in this case commands/inventory.js and commands/buy.js)\ncommand.execute(message, Users);\n```\n\n```js\nmodule.exports = {\n    execute: async (message, Users) => {\n        const target = message.mentions.users.first() || message.author;\n        const user = await Users.findByPrimary(target.id);\n    }\n};\n```\n\n```js\nmodule.exports = {\n    execute: async (message, Users) => {\n        const user = await Users.findByPrimary(message.author.id);\n    }\n};\n```\n\n```js\nconst Sequelize = require('sequelize);\nconst SQLite = require('sqlite3');\n```\n\n```text\nfindByPrimary\n```\n\n```text\nUsers\n```\n\n```text\nmodels/Users.js\n```\n\n```text\ndbObjects.js\n```\n\n```text\nserver.js\n```\n\n```text\nexecute\n```\n\n```text\ncommands/inventory.js\n```\n\n```text\ncommands/buy.js\n```\n\n```text\nfindById\n```\n\n```text\nfindAll\n```\n\n```text\nUsers.findByPk(id)\n```\n\n========================================\n\nComments:\n- I believe it's `findByPk()`","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":220,"estimatedTokens":1040}}969{"id":"stack-54180518","source":"stackoverflow","questionId":54180518,"title":"Sequelize string is not a function error , why?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize string is not a function error , why?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nPlease need your help . \nWhy i got the strange error for String(150) in nickname object ? \n\n```\nconst Sequelize = require('sequelize');\nconst devOptions = require('./../config/config').connectionConf.development;\n\nconst sequelize = new Sequelize(\n devOptions.database,\n devOptions.username,\n devOptions.password,\n {\n host: devOptions.host,\n dialect: devOptions.dialect\n }\n);\n\nconst User = sequelize.define('user', {\n user_id: {\n primaryKey:true,\n type:sequelize.BIGINT,\n allowNull:false \n },\n nickname: {\n type:sequelize.STRING(150),\n unique:true,\n allowNull:false\n },\n email: {\n type:sequelize.STRING(150),\n unique:true,\n allowNull:false\n },\n user_password: {\n type:sequelize.STRING(150),\n unique:true,\n allowNull:false\n },\n created_at: {\n type:sequelize.Date,\n created_time:sequelize.NOW,\n allowNull:false\n },\n updated_at: {\n type:sequelize.Date,\n allowNull:false\n }\n }, {});\n```\n\n \n TypeError: sequelize.STRING is not a function\n at Object. (E:\\Projects\\JavaScript\\couponsystem\\src\\models\\schema.js:21:22)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n at Module.load (internal/modules/cjs/loader.js:598:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n at Module.require (internal/modules/cjs/loader.js:636:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at Object. (E:\\Projects\\JavaScript\\couponsystem\\src\\models\\generator.js:1:78)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n at Module.load (internal/modules/cjs/loader.js:598:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)\n at startup (internal/bootstrap/node.js:285:19)\n at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)\n\n========================================\n\nTop Answer:\nThis should work, for more info, read the docs below.\n\n```\nconst Sequelize = require('sequelize');\nconst devOptions = require('./../config/config').connectionConf.development;\n\nconst sequelize = new Sequelize(\n devOptions.database,\n devOptions.username,\n devOptions.password,\n {\n host: devOptions.host,\n dialect: devOptions.dialect\n }\n);\n\nconst User = sequelize.define('user', {\n user_id: {\n primaryKey:true,\n type:sequelize.BIGINT,\n allowNull:false \n },\n nickname: {\n type:sequelize.STRING,\n unique:true,\n allowNull:false\n },\n email: {\n type:sequelize.STRING,\n unique:true,\n allowNull:false\n },\n user_password: {\n type:sequelize.STRING,\n unique:true,\n allowNull:false\n },\n created_at: {\n type:sequelize.Date,\n created_time:sequelize.NOW,\n allowNull:false\n },\n updated_at: {\n type:sequelize.Date,\n allowNull:false\n }\n }, {});\n```\n\nDocs, Extra info\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\nconst devOptions = require('./../config/config').connectionConf.development;\n\nconst sequelize = new Sequelize(\n  devOptions.database,\n  devOptions.username,\n  devOptions.password,\n  {\n    host: devOptions.host,\n    dialect: devOptions.dialect\n  }\n);\n\nconst User = sequelize.define('user', {\n    user_id: {\n      primaryKey:true,\n      type:sequelize.BIGINT,\n      allowNull:false \n   },\n    nickname: {\n      type:sequelize.STRING(150),\n      unique:true,\n      allowNull:false\n    },\n    email: {\n      type:sequelize.STRING(150),\n      unique:true,\n      allowNull:false\n    },\n    user_password: {\n      type:sequelize.STRING(150),\n      unique:true,\n      allowNull:false\n    },\n    created_at: {\n      type:sequelize.Date,\n      created_time:sequelize.NOW,\n      allowNull:false\n    },\n    updated_at: {\n      type:sequelize.Date,\n      allowNull:false\n    }\n  }, {});\n```\n\n```text\nconst sequelize = new Sequelize(\n    devOptions.database,\n    devOptions.username,\n    devOptions.password,\n    {\n        host: devOptions.host,\n        dialect: devOptions.dialect\n    }\n);\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst devOptions = require('./../config/config').connectionConf.development;\n\nconst sequelize = new Sequelize(\n    devOptions.database,\n    devOptions.username,\n    devOptions.password,\n    {\n        host: devOptions.host,\n        dialect: devOptions.dialect\n    }\n);\n\nconst User = sequelize.define('user', {\n    user_id: {\n        primaryKey: true,\n        type: Sequelize.BIGINT,\n        allowNull: false\n    },\n    nickname: {\n        type: Sequelize.STRING(150),\n        unique: true,\n        allowNull: false\n    },\n    email: {\n        type: Sequelize.STRING(150),\n        unique: true,\n        allowNull: false\n    },\n    user_password: {\n        type: Sequelize.STRING(150),\n        unique: true,\n        allowNull: false\n    },\n    created_at: {\n        type: Sequelize.Date,\n        created_time: Sequelize.NOW,\n        allowNull: false\n    },\n    updated_at: {\n        type: Sequelize.Date,\n        allowNull: false\n    }\n}, {});\n```\n\n```text\nsequelize\n```\n\n```text\nconst Sequelize = require('sequelize');\n```\n\n```text\nsequelize\n```\n\n```text\nSequelize\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst devOptions = require('./../config/config').connectionConf.development;\n\nconst sequelize = new Sequelize(\n  devOptions.database,\n  devOptions.username,\n  devOptions.password,\n  {\n    host: devOptions.host,\n    dialect: devOptions.dialect\n  }\n);\n\nconst User = sequelize.define('user', {\n    user_id: {\n      primaryKey:true,\n      type:sequelize.BIGINT,\n      allowNull:false \n   },\n    nickname: {\n      type:sequelize.STRING,\n      unique:true,\n      allowNull:false\n    },\n    email: {\n      type:sequelize.STRING,\n      unique:true,\n      allowNull:false\n    },\n    user_password: {\n      type:sequelize.STRING,\n      unique:true,\n      allowNull:false\n    },\n    created_at: {\n      type:sequelize.Date,\n      created_time:sequelize.NOW,\n      allowNull:false\n    },\n    updated_at: {\n      type:sequelize.Date,\n      allowNull:false\n    }\n  }, {});\n```\n\n========================================\n\nComments:\n- What the problem with such syntax ??? type:sequelize.STRING(150) docs - docs.sequelizejs.com/manual/tutorial/&hellip;\n- Well, the error is very specific. STRING is not a function. so either a wrong \"Sequalize\" is being required. or the documentation is wrong. or the output is lying. OR, more probable. the \"sequalize\" const is initiated with irrelevant parameters.\n- @ArelSapir The doc: docs.sequelizejs.com/variable/&hellip;, clearly states that `sequalize.STRING` is a function.\n- So, as i said. It can be one of these cases: either a wrong \"Sequalize\" is being required. or the documentation is wrong. or the output is lying. or the \"sequalize\" const is initiated with the wrong parameters.\n- Any difference for sequelize.STRING and Sequelize.STRING ?\n- I explained the difference in my answer and the solution to your code also @Maks.Burkov","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":310,"estimatedTokens":1785}}970{"id":"stack-52738883","source":"stackoverflow","questionId":52738883,"title":"How to get access to accessor methods in sequelize","tags":["node.js","postgresql","express","orm","sequelize.js"],"text":"Title: How to get access to accessor methods in sequelize\nTags: node.js, postgresql, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a model called `user` and a model called `access_barrier` and a join table between a `user` and `access_barrier` called `barrier_users`.\n\nI have created the following associations for them\n\n```\nuser.belongsToMany(models.access_barrier, {\n as: \"access_barriers_accessible\",\n through: \"barrier_users\",\n foreignKey: \"userId\",\n onUpdate: \"CASCADE\",\n onDelete: \"CASCADE\"\n});\n\naccess_barrier.belongsToMany(models.user, {\n as: \"users_with_permission\",\n through: \"barrier_users\",\n foreignKey: \"barrierId\",\n onUpdate: \"CASCADE\",\n onDelete: \"CASCADE\"\n});\n```\n\nWhen querying users with the following code I can see all the data come in fine.\n\n```\nreturn models.user\n .findAll({\n include: [\n {\n model: models.access_barrier,\n as: \"access_barriers_accessible\"\n }\n ]\n })\n .then(function(result) {\n resolve(result);\n })\n .catch(models.Sequelize.DatabaseError, function() {\n reject(\"An error occurred in the database\");\n })\n .catch(function(err) {\n reject(err);\n });\n```\n\nThe documentation for sequelize mentions that accessor methods are created when using the above functionality as mentioned below\n\n`Project.belongsToMany(User, {through: 'UserProject'});`\n\n`User.belongsToMany(Project, {through: 'UserProject'});`\n\nThis will create a new model called UserProject with the equivalent foreign keys projectId and userId. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).\n\nDefining through is required. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups.\n\nThis will add methods getUsers, setUsers, addUser,addUsers to Project, and getProjects, setProjects, addProject, and addProjects to User.\n\nHow do I know the method names that are added for my models, where exactly can I view them? How do I get access to them?\n\nI used `Object.keys(models.user)` and got the data below\n\n```\n[ 'sequelize',\n 'options',\n 'associations',\n 'underscored',\n 'tableName',\n '_schema',\n '_schemaDelimiter',\n 'rawAttributes',\n 'primaryKeys',\n '_timestampAttributes',\n '_readOnlyAttributes',\n '_hasReadOnlyAttributes',\n '_isReadOnlyAttribute',\n '_dataTypeChanges',\n '_dataTypeSanitizers',\n '_booleanAttributes',\n '_dateAttributes',\n '_hstoreAttributes',\n '_rangeAttributes',\n '_jsonAttributes',\n '_geometryAttributes',\n '_virtualAttributes',\n '_defaultValues',\n 'fieldRawAttributesMap',\n 'fieldAttributeMap',\n 'uniqueKeys',\n '_hasBooleanAttributes',\n '_isBooleanAttribute',\n '_hasDateAttributes',\n '_isDateAttribute',\n '_hasHstoreAttributes',\n '_isHstoreAttribute',\n '_hasRangeAttributes',\n '_isRangeAttribute',\n '_hasJsonAttributes',\n '_isJsonAttribute',\n '_hasVirtualAttributes',\n '_isVirtualAttribute',\n '_hasGeometryAttributes',\n '_isGeometryAttribute',\n '_hasDefaultValues',\n 'attributes',\n 'tableAttributes',\n 'primaryKeyAttributes',\n 'primaryKeyAttribute',\n 'primaryKeyField',\n '_hasPrimaryKeys',\n '_isPrimaryKey',\n 'autoIncrementAttribute',\n '_scope',\n '_scopeNames',\n 'associate' ]\n```\n\nOn checking out what `associations` has it was\n\n```\n{ access_barriers_incharge: access_barriers_incharge,\n access_barriers_admin: access_barriers_admin,\n admin: admin,\n access_barriers_accessible: access_barriers_accessible,\n barriers_accessed: barriers_accessed }\n```\n\n========================================\n\nCode:\n```text\nuser.belongsToMany(models.access_barrier, {\n  as: \"access_barriers_accessible\",\n  through: \"barrier_users\",\n  foreignKey: \"userId\",\n  onUpdate: \"CASCADE\",\n  onDelete: \"CASCADE\"\n});\n\naccess_barrier.belongsToMany(models.user, {\n  as: \"users_with_permission\",\n  through: \"barrier_users\",\n  foreignKey: \"barrierId\",\n  onUpdate: \"CASCADE\",\n  onDelete: \"CASCADE\"\n});\n```\n\n```text\nreturn models.user\n    .findAll({\n        include: [\n          {\n            model: models.access_barrier,\n            as: \"access_barriers_accessible\"\n          }\n        ]\n    })\n    .then(function(result) {\n        resolve(result);\n    })\n    .catch(models.Sequelize.DatabaseError, function() {\n        reject(\"An error occurred in the database\");\n    })\n    .catch(function(err) {\n        reject(err);\n    });\n```\n\n```text\n[ 'sequelize',\n  'options',\n  'associations',\n  'underscored',\n  'tableName',\n  '_schema',\n  '_schemaDelimiter',\n  'rawAttributes',\n  'primaryKeys',\n  '_timestampAttributes',\n  '_readOnlyAttributes',\n  '_hasReadOnlyAttributes',\n  '_isReadOnlyAttribute',\n  '_dataTypeChanges',\n  '_dataTypeSanitizers',\n  '_booleanAttributes',\n  '_dateAttributes',\n  '_hstoreAttributes',\n  '_rangeAttributes',\n  '_jsonAttributes',\n  '_geometryAttributes',\n  '_virtualAttributes',\n  '_defaultValues',\n  'fieldRawAttributesMap',\n  'fieldAttributeMap',\n  'uniqueKeys',\n  '_hasBooleanAttributes',\n  '_isBooleanAttribute',\n  '_hasDateAttributes',\n  '_isDateAttribute',\n  '_hasHstoreAttributes',\n  '_isHstoreAttribute',\n  '_hasRangeAttributes',\n  '_isRangeAttribute',\n  '_hasJsonAttributes',\n  '_isJsonAttribute',\n  '_hasVirtualAttributes',\n  '_isVirtualAttribute',\n  '_hasGeometryAttributes',\n  '_isGeometryAttribute',\n  '_hasDefaultValues',\n  'attributes',\n  'tableAttributes',\n  'primaryKeyAttributes',\n  'primaryKeyAttribute',\n  'primaryKeyField',\n  '_hasPrimaryKeys',\n  '_isPrimaryKey',\n  'autoIncrementAttribute',\n  '_scope',\n  '_scopeNames',\n  'associate' ]\n```\n\n```text\n{ access_barriers_incharge: access_barriers_incharge,\n  access_barriers_admin: access_barriers_admin,\n  admin: admin,\n  access_barriers_accessible: access_barriers_accessible,\n  barriers_accessed: barriers_accessed }\n```\n\n```text\nuser\n```\n\n```text\naccess_barrier\n```\n\n```text\nuser\n```\n\n```text\naccess_barrier\n```\n\n```text\nbarrier_users\n```\n\n```text\nProject.belongsToMany(User, {through: 'UserProject'});\n```\n\n```text\nUser.belongsToMany(Project, {through: 'UserProject'});\n```\n\n```text\nObject.keys(models.user)\n```\n\n```text\nassociations\n```\n\n```text\nconsole.log(Object.keys(sequelizeObject.__proto__));\n```\n\n========================================\n\nComments:\n- Try using `Object.keys()` to get a list of property names.\n- @FranciscoMateo I updated the question with the result, I don't think there's much there.","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":281,"estimatedTokens":1560}}971{"id":"stack-47686358","source":"stackoverflow","questionId":47686358,"title":"error on sequelize raw query: query is not a function","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: error on sequelize raw query: query is not a function\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use raw queries from sequelize in an express app.\nMy folder structure is:\n\n```\n/\n/index.js\n/models/index.js\n/models/price.js\n/controllers/price.js\n```\n\nI want to use sequelize which I already define in /models/index.js from a controller.\n\nThis is /models/index.js:\n\n```\n\"use strict\";\n\nvar fs = require(\"fs\");\nvar path = require(\"path\");\nvar Sequelize = require('sequelize')\n , sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {\n dialect: \"mysql\", // or 'sqlite', 'postgres', 'mariadb'\n port: 3306, // or 5432 (for postgres)\n timezone:'America/Sao_Paulo',\n});\n\nsequelize\n .authenticate()\n .then(function(err) {\n console.log('Connection has been established successfully.');\n }, function (err) { \n console.log('Unable to connect to the database:', err);\n });\n\nvar db = {};\nfs\n .readdirSync(__dirname)\n .filter(function(file) {\n return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n })\n .forEach(function(file) {\n var model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n });\n\nObject.keys(db).forEach(function(modelName) {\n if (\"associate\" in db[modelName]) {\n db[modelName].associate(db);\n }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\nmodule.exports = db;\nmodule.exports.db = db;\n```\n\nI want to use a raw query in my price controller:\n\n```\nexports.index = function(req, res, next) {\n\n // var environment_hash = req.session.passport.user.environment_hash;\n\n var Price = require('../models/index').Price;\n var db = require('../models/index').db;\n\n console.log(db);\n\n db.query(`SELECT ... `).spread((results, metadata) => {\n // Results will be an empty array and metadata will contain the number of affected rows.\n console.log(results);\n });\n\n var values = { \n where: { symbol: 'xxx' }, \n };\n\n Price\n .findOne(values)\n .then(function(price) {\n console.log(\"found!!!!!\");\n console.log(price);\n res.render('home/home.ejs', {\n price: price\n });\n });\n};\n```\n\nBut I'm getting this error message:\n\n```\ndb: [Circular] }\nTypeError: db.query is not a function\n```\n\nHow can I fix this?\n\n========================================\n\nCode:\n```text\n/\n/index.js\n/models/index.js\n/models/price.js\n/controllers/price.js\n```\n\n```text\n\"use strict\";\n\nvar fs        = require(\"fs\");\nvar path      = require(\"path\");\nvar Sequelize = require('sequelize')\n  , sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {\n      dialect: \"mysql\", // or 'sqlite', 'postgres', 'mariadb'\n      port:    3306, // or 5432 (for postgres)\n      timezone:'America/Sao_Paulo',\n});\n\n\nsequelize\n  .authenticate()\n  .then(function(err) {\n    console.log('Connection has been established successfully.');\n  }, function (err) { \n    console.log('Unable to connect to the database:', err);\n  });\n\n\n\nvar db = {};\nfs\n  .readdirSync(__dirname)\n  .filter(function(file) {\n    return (file.indexOf(\".\") !== 0) && (file !== \"index.js\");\n  })\n  .forEach(function(file) {\n    var model = sequelize.import(path.join(__dirname, file));\n    db[model.name] = model;\n  });\n\nObject.keys(db).forEach(function(modelName) {\n  if (\"associate\" in db[modelName]) {\n    db[modelName].associate(db);\n  }\n});\n\ndb.sequelize = sequelize;\ndb.Sequelize = Sequelize;\n\n\n\nmodule.exports = db;\nmodule.exports.db = db;\n```\n\n```text\nexports.index = function(req, res, next) {\n\n    // var environment_hash = req.session.passport.user.environment_hash;\n\n    var Price  = require('../models/index').Price;\n    var db  = require('../models/index').db;\n\n    console.log(db);\n\n    db.query(`SELECT ... `).spread((results, metadata) => {\n        // Results will be an empty array and metadata will contain the number of affected rows.\n        console.log(results);\n    });\n\n\n    var values = { \n                    where: { symbol: 'xxx' },                    \n                };\n\n    Price\n        .findOne(values)\n        .then(function(price) {\n            console.log(\"found!!!!!\");\n            console.log(price);\n            res.render('home/home.ejs', {\n                    price: price\n                });\n      });\n};\n```\n\n```text\ndb: [Circular] }\nTypeError: db.query is not a function\n```\n\n```text\ndb.query\n```\n\n```text\ndb.sequelize.query\n```\n\n```text\ndb.query = db.sequelize.query\n```\n\n```text\ndb.query = { query } = db.sequelize\n```\n\n```text\ndb.query\n```\n\n========================================\n\nComments:\n- Your calling query as a function... and passing in a string `SELECT ...` it looks like db isn't being imported correctly or doesn't have the property 'query' attached.\n- In your index.js your db object needs a query function... otherwise what are you calling? If query is a function from sequelize then maybe you mean to say db.sequelize.query\n- You can fix it by making sure your `models&#47;index` file is exporting a function named `db`. `module.exports.db = function () {...}`\n- I'm using sequelize lib which contains the query function: docs.sequelizejs.com/manual/tutorial/raw-queries.html\n- use db.sequelize.query instead of db.query If you look at your current code your attaching the library to the property sequelize not assigning it.\n- @DanielTate it worked! thanks. Can you answer so I can accept?\n- @FilipeFerminiano updated.\n- I think you meant `db.sequelize.query`","metadata":{"transformedAt":"2026-08-18T18:33:34.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":234,"estimatedTokens":1353}}972{"id":"stack-55670688","source":"stackoverflow","questionId":55670688,"title":"Sequelize does not suport the MySQL 8 autentication protocol and I'm not getting how to change this protocol","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize does not suport the MySQL 8 autentication protocol and I'm not getting how to change this protocol\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to migrate a db with Sequelize working with MySQL 8.0.15, but I'm not able to do that. I keep receiving this error message.\n\n```\nSequelize CLI [Node: 10.15.0, CLI: 5.4.0, ORM: 5.3.5]\n\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\n\nERROR: Client does not support authentication protocol requested by server; consider upgrading MySQL client\n```\n\nI've tried every single solution for this problem. The thing is when i try to change the MySQL root password the message i get is this one: \n\n```\nERROR 1819 (HY000): Your password does not satisfy the current policy requirements\n```\n\nThen I did try to change the password validate policy following this procedure\n\nhttps://dev.mysql.com/doc/refman/5.6/en/validate-password-installation.html\n\nthen MySQL crashed cause it's deprecated. Then I tried this one\n\nhttps://dev.mysql.com/doc/refman/8.0/en/validate-password-installation.html\n\nThen I got this\n\n```\nmysql> INSTALL COMPONENT 'file://component_validate_password';\nERROR 3529 (HY000): Cannot load component from specified URN: \n'file://component_validate_password'.\n```\n\nThen I checked where the component is\n\n```\nls /usr/lib64/mysql/plugin/component_v*\n/usr/lib64/mysql/plugin/component_validate_password.so\n```\n\nAnyone can help? I'm realy out of options, now!\n\nThanks in advance\n\n========================================\n\nTop Answer:\nIf you are using MySQL 8.0 then https://dev.mysql.com/doc/refman/5.6/en/validate-password-installation.html then this shouldn't work.\n\nHave used mysql_secure_installation and installed the validate_password_component then?\n\nIf yes, in that case, the plugin must already be installed and all you need to do is set validate_password related parameters in the options file (default /etc/my.cnf) and some options require a server restart.\n\n========================================\n\nCode:\n```text\nSequelize CLI [Node: 10.15.0, CLI: 5.4.0, ORM: 5.3.5]\n\nLoaded configuration file \"config/config.json\".\nUsing environment \"development\".\n\nERROR: Client does not support authentication protocol requested by server; consider upgrading MySQL client\n```\n\n```text\nERROR 1819 (HY000): Your password does not satisfy the current policy requirements\n```\n\n```text\nmysql> INSTALL COMPONENT 'file://component_validate_password';\nERROR 3529 (HY000): Cannot load component from specified URN: \n'file://component_validate_password'.\n```\n\n```text\nls /usr/lib64/mysql/plugin/component_v*\n/usr/lib64/mysql/plugin/component_validate_password.so\n```\n\n```text\n[mysqld]\ndefault_authentication_plugin=mysql_native_password\n```\n\n```text\nmy.cnf\n```\n\n```text\nroot\n```\n\n```text\nALTER USER 'foo'@'bar' IDENTIFIED WITH mysql_native_password BY 'password';\nflush privileges;\n```\n\n```text\nDROP USER 'foo'@'bar';\nCREATE USER 'foo'@'bar' IDENTIFIED WITH mysql_native_password BY 'password';\nGRANT INSERT, SELECT, ... ON mydb.* TO 'foo'@'bar';\n```\n\n```text\nflush privileges;\n```\n\n========================================\n\nComments:\n- It worked!!!! but one more thing why's this \"Only use users for connecting via Sequelize, never root.\" @tadman?\n- What I mean is don't use \"root\" as your go-to account for access to the database. Use that only when adding or removing other users, as in for administration only. Sequelize should be connecting using an account specific to that project or application that's only got the necessary privileges, like it's constrained to the databases necessary for that application. `GRANT ALL PRIVILEGES ON app_db.*` for example.\n- turned out it is working for a user, and still not working for the root. I still don't get it, but for now it is exactly what I need. Thanks a lot\n- This only applies to new users, not existing ones.\n- Ooh this explains a lot. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":121,"estimatedTokens":980}}973{"id":"stack-50600858","source":"stackoverflow","questionId":50600858,"title":"How to dynamically connect mysql database according to each client?","tags":["javascript","mysql","node.js","sequelize.js","saas"],"text":"Title: How to dynamically connect mysql database according to each client?\nTags: javascript, mysql, node.js, sequelize.js, saas\nSource: Stack Overflow\n\nQuestion:\nI am building a SaaS product using MEAN stack here M = mysql\n\nI am using sequelize as ORM for mysql, my connection:\n\n```\nconst sequelize = new Sequelize('smallscale_superapp', 'root', 'root1', {\n host: '127.0.0.1',\n port: 3306,\n dialect: 'mysql',\n logging: false,\n});\n```\n\nFor example i have one admin super app so i create one business for example business code called\n\"001abcd\", this business code stores in my main admin db, then i told my all clients to go to one particular url called \"example.com\". \n\nSo if they enter the url, the home page will looks like slack.com there is one input box and after hardcoded value called example.com\n\nSo now my client in input box they put the business code which i created them and stored in my main db.\n\nAfter putting the business code in input box a new sub domain will open called \"001abcd.example.com\" (I am checking whether the business code matches in my main db if matches i am creating dynamic subdomains)\n\nSO if all good, after creation of subdomain client page will show as LOGIN screen where they needs to signup and the signup details needs to be there db dynamically\n\n**NOTE**: I am getting the client db, username, host, password in my main db table while creating business.\n\nHow to done this using sequelize mysql?\n\nHow to get sequelize connection to connect dynamically based on client login?\n\nAs i said before i have client dbname..etc in my db I am trying to create connection like this:\n\n```\nexports.dynamicDatabase = (req, res) => {\n const { code } = req.params;\n Business.find({\n where: { code },\n raw: true,\n })\n .then((data) => {\n const sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {\n host: data.dbhost,\n port: 3306,\n dialect: 'mysql',\n logging: false,\n });\n })\n .catch((err) => { res.status(400).send(err.message); });\n};\n```\n\nNow outside my this function i am trying to sync tables, like this:\n\n```\nsequelizeClient.authenticate().then((err) => {\n if (err) {\n console.log('There is connection in ERROR.');\n } else {\n console.log('Dynamic MYSQL Connection has been established successfully');\n }\n});\nsequelizeClient.sync().then(() => {\n console.log('Dynamic Missing Table Created');\n}, (err) => {\n console.log('An error occurred while creating the table:', err.message);\n});\n```\n\nThe variable **sequelizeClient** is inside the function, so i cant able to access? globally.\n\nSo i make the variable globally, but one problem \n\nI have sequelizeClient variable inside function, this will function execute after only entering my domain in url,\n\nBut the sequelizeClient.sync() is not inside function so when i start node server.js it throws me error:\n\n```\nsequelizeClient.authenticate().then((err) => {\n[0] ^\n[0]\n[0] TypeError: Cannot read property 'authenticate' of undefined\n```\n\n========================================\n\nTop Answer:\nFinally i tried this and make it work, but i dont know this is good approach or not, so tell me whether this is good approach or not?\n\nI am getting the exact data by user request params:\n\n```\nlet sequelizeClient;\nlet Login;\nexports.getDomain = (req, res) => {\n const { code } = req.params;\n Business.find({\n raw: true,\n where: { code },\n }).then((data) => {\n if (data === null) {\n res.status(400).send(data);\n } else {\n sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {\n host: data.dbhost,\n port: 3306,\n dialect: 'mysql',\n logging: false,\n });\n\n // end user connections\n sequelizeClient.authenticate().then((err) => {\n if (err) {\n console.log('There is connection in ERROR.');\n } else {\n console.log(`${data.code} MYSQL Connection has been established successfully`);\n }\n });\n\n sequelizeClient.sync().then(() => {\n console.log(`${data.code} Missing Table Created`);\n }, (err) => {\n console.log('An error occurred while creating the table:', err.message);\n });\n\n // mysql tables;\n Login = sequelizeClient.define('login', {\n username: Sequelize.STRING,\n firstName: Sequelize.STRING,\n lastName: Sequelize.STRING,\n });\n }\n });\n};\n```\n\nI am declaring table schema variable as global and i am using in my code:\n\n```\n// api\nexports.signUp = (req, res) => {\n const user = {\n username: req.body.username,\n firstName: req.body.firstName,\n lastName: req.body.lastName,\n\n };\n Login.create(user)\n .then(data => res.status(200).send(data))\n .catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))\n .catch(err => res.status(400).send(err.message));\n};\n```\n\n========================================\n\nCode:\n```text\nconst sequelize = new Sequelize('smallscale_superapp', 'root', 'root1', {\n  host: '127.0.0.1',\n  port: 3306,\n  dialect: 'mysql',\n  logging: false,\n});\n```\n\n```text\nexports.dynamicDatabase = (req, res) => {\n  const { code } = req.params;\n  Business.find({\n    where: { code },\n    raw: true,\n  })\n    .then((data) => {\n      const sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {\n        host: data.dbhost,\n        port: 3306,\n        dialect: 'mysql',\n        logging: false,\n      });\n    })\n    .catch((err) => { res.status(400).send(err.message); });\n};\n```\n\n```text\nsequelizeClient.authenticate().then((err) => {\n  if (err) {\n    console.log('There is connection in ERROR.');\n  } else {\n    console.log('Dynamic MYSQL Connection has been established successfully');\n  }\n});\nsequelizeClient.sync().then(() => {\n  console.log('Dynamic Missing Table Created');\n}, (err) => {\n  console.log('An error occurred while creating the table:', err.message);\n});\n```\n\n```text\nsequelizeClient.authenticate().then((err) => {\n[0]                 ^\n[0]\n[0] TypeError: Cannot read property 'authenticate' of undefined\n```\n\n```text\nconst postgresDB = new Sequelize('postgres://localhost:5432/test_enduser');\n\npostgresDB.authenticate().then((err) => {\n  if (err) {\n    console.log('There is connection in ERROR.');\n  } else {\n    console.log('Postgres Connection has been established successfully');\n  }\n});\n\npostgresDB.define('inventory', {\n  name: Sequelize.STRING,\n});\n\nconst createSchema = () => {\n  Business.findAll({\n    raw: true,\n  }).then((data) => {\n    data.forEach((client) => {\n      postgresDB.createSchema(client.code).then(() => {\n        Object.keys(postgresDB.models).forEach((currentItem) => {\n          postgresDB.models[currentItem].schema(client.code).sync();\n        });\n        // new schema is created\n        console.log('Postgres schema created');\n      }).catch((err) => {\n        console.log(err.message);\n      });\n    });\n  });\n};\ncreateSchema();\n\n\n// apis\nexports.getAllBusiness = (req, res) => {\n  postgresDB.models.inventory.schema(req.user.code).findAll()\n    .then((results) => {\n      res.send(results);\n    });\n};\n\nexports.postBusiness = (req, res) => {\n  const user = {\n    name: req.body.name,\n  };\n  postgresDB.models.inventory.schema(req.user.code).create(user)\n    .then(data => res.status(200).send(data))\n    .catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))\n    .catch(err => res.status(400).send(err.message));\n};\n```\n\n```text\nlet sequelizeClient;\nlet Login;\nexports.getDomain = (req, res) => {\n  const { code } = req.params;\n  Business.find({\n    raw: true,\n    where: { code },\n  }).then((data) => {\n    if (data === null) {\n      res.status(400).send(data);\n    } else {\n      sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {\n        host: data.dbhost,\n        port: 3306,\n        dialect: 'mysql',\n        logging: false,\n      });\n\n      // end user connections\n      sequelizeClient.authenticate().then((err) => {\n        if (err) {\n          console.log('There is connection in ERROR.');\n        } else {\n          console.log(`${data.code} MYSQL Connection has been established successfully`);\n        }\n      });\n\n      sequelizeClient.sync().then(() => {\n        console.log(`${data.code} Missing Table Created`);\n      }, (err) => {\n        console.log('An error occurred while creating the table:', err.message);\n      });\n\n      // mysql tables;\n      Login = sequelizeClient.define('login', {\n        username: Sequelize.STRING,\n        firstName: Sequelize.STRING,\n        lastName: Sequelize.STRING,\n      });\n    }\n  });\n};\n```\n\n```text\n// api\nexports.signUp = (req, res) => {\n  const user = {\n    username: req.body.username,\n    firstName: req.body.firstName,\n    lastName: req.body.lastName,\n\n  };\n  Login.create(user)\n    .then(data => res.status(200).send(data))\n    .catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))\n    .catch(err => res.status(400).send(err.message));\n};\n```\n\n========================================\n\nComments:\n- Instead of calling `const sequelize = new Sequelize(stuff);` at the start of your program, wait for `stuff`, *then* call it? I don't see/understand what your problem is, tbh.\n- I cant understand, any basic example?\n- @ChrisG I have multiple subdomains for each client, i want to connect multiple databases.\n- *After the login*, call `new Sequelize(...)` to create a 2nd connection. I still don't understand where you are stuck with this.\n- So i want to get dbname,host stuffs from req.user.session? am i right?\n- I guess? Depends on where you store them. You said those details are stored in the master DB, so read them from there, then create a 2nd connection.\n- Yes i did that, but there is drawback, i am getting and creating 2nd connection dynamically inside one function, so i want to write all of my client apis inside that one function, i think this is not good approach so?\n- Use a global variable then...\n- @ChrisG See my updated question, I tried the way you said, I posted my code which i tried!\n- Do you not know how to declare a global variable, outside any function? Was this entire question about this problem in the first place...? In other words, has **nothing** to do with sequelize, saas, etc...?\n- @ChrisG After your help only i am able to create second connection, So before posting this question i dont know about creating dynamic connection.\n- jsfiddle.net/zw093Leq\n- @ChrisG pastebin.com/u1pJu0Br\n- I have sequelizeClient variable inside function, this will function execute after only entering my domain in url, But the sequelizeClient.sync() is not inside function so when i start node server.js it throws me error: sequelizeClient.authenticate().then((err) => { [0] ^ [0] [0] TypeError: Cannot read property 'authenticate' of undefined\n- @ChrisG see my updated question\n- Your problems are too basic to get into here, sorry. You obviously need to 1) connect, *then* 2) authenticate, *then* 3) sync. You are trying to do 2 and 3 simultaneously, before 1. Telling you the solution will be worthless; if you want to succeed building this, you need to learn how to solve issues like that yourself. I'm not a JS beginner's tutor.\n- @ChrisG check my answer which i make it worked finally!, and tell whether this is good approach or not?\n- Seems good approach, but I am surprised to see this approach with more than 1000 clients. You would be creating more than 1000 schema for all 1000 clients. Isn't it creating performance issues?","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":347,"estimatedTokens":2807}}974{"id":"stack-55564036","source":"stackoverflow","questionId":55564036,"title":"Why my conditional WHERE inside the OR operator in the Sequelize query is converted to AND?","tags":["node.js","sequelize.js"],"text":"Title: Why my conditional WHERE inside the OR operator in the Sequelize query is converted to AND?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a query with Sequelize with a conditional WHERE like explained here (How to perform a search with conditional where parameters using Sequelize).\n\nThe relevant part of my code is like this\n\n```\nconst Op = Sequelize.Op;\n var search = {};\n if (typeof req.query.search !== 'undefined'){\n search.nome = {[Op.like]: '%' + req.query.search + '%'};\n search.username = {[Op.like]: '%' + req.query.search + '%'};\n }\n model.User.findAll({\n where:{\n [Op.or]: [\n search\n ]\n })\n```\n\nIt works, but the generated SQL adds an AND instead of an OR, like this:\n\n```\nSELECT 'id_', 'nome', 'username', 'id' FROM 'User' AS 'User' WHERE (('User'.'nome' LIKE '%test%' AND 'User'.'username' LIKE '%test%'))\n```\n\nAm I doing something wrong that I fail to see?\nI've already tried several combinations of this and none works.\n\n========================================\n\nTop Answer:\ntry to use spread\n\n```\nmodel.User.findAll({\n where: {\n [Op.or]: [\n {...search}\n ]\n }\n})\n```\n\nwhat about this?\n\n```\nconst where = {}\n if (typeof req.query.search !== 'undefined'){\n where[Op.or] = {\n nome : {\n [Op.like] : `%${req.query.search}%`\n },\n username : {\n [Op.like] : `%${req.query.search}%`\n },\n }\n }\n\n model.User.findAll({\n where\n })\n```\n\n========================================\n\nCode:\n```text\nconst Op = Sequelize.Op;\n    var search = {};\n     if (typeof req.query.search !== 'undefined'){\n         search.nome = {[Op.like]: '%' + req.query.search + '%'};\n         search.username = {[Op.like]: '%' + req.query.search + '%'};\n    }\n    model.User.findAll({\n        where:{\n         [Op.or]: [\n           search\n         ]\n      })\n```\n\n```text\nSELECT 'id_', 'nome', 'username', 'id' FROM 'User' AS 'User' WHERE (('User'.'nome' LIKE '%test%' AND 'User'.'username' LIKE '%test%'))\n```\n\n```text\nmodel.User.findAll({\n  where: {\n    [Op.or]: {\n      email: {\n        [Op.like]: 'abcd',\n      },\n      username: {\n        [Op.like]: 'cdf',\n      },\n    }\n  },\n  logging: console.log,\n});\n```\n\n```sql\nSELECT \"id\", \"name\", \"username\" FROM \"users\" AS \"User\" WHERE \"User\".\"deleted_at\" IS NULL AND (\"User\".\"email\" LIKE 'abcd' OR \"User\".\"username\" LIKE 'cdf');\n```\n\n```text\nsearch\n```\n\n```text\n[Op.or]\n```\n\n```text\nmodel.User.findAll({\n  where: {\n    [Op.or]: [\n      {...search}\n    ]\n  }\n})\n```\n\n```text\nconst where = {}\n     if (typeof req.query.search !== 'undefined'){\n       where[Op.or] = {\n         nome : {\n          [Op.like] : `%${req.query.search}%`\n         },\n         username : {\n          [Op.like] : `%${req.query.search}%`\n        },\n       }\n    }\n\n    model.User.findAll({\n      where\n    })\n```\n\n```text\nreturn Models.job.findAndCountAll({\n  raw: true,\n  where: {\n    isActive: 1,\n    ...((args.statusOfJob > 0) && {\n      status: args.statusOfJob\n    })\n  }\n})\n```\n\n```text\nstatusOfJob\n```\n\n========================================\n\nComments:\n- Yes I tried like this before and it works, but won't do for me because I want the `WHERE` clause dynamically constructed.\n- Spread search object inside the where key. I did mention it in the answer.\n- I see it now, thanks. I wasn't paying attention to the meaning of the brackets. Strangely, didn't have to spread the variable, just changed to `where: {[Op.or]: search }` and worked.\n- Yeah that will work since search is just an object constructed dynamically\n- That makes sense, but I get the same result. If I take out the curly brackets I get `search is not iterable`\n- This won't work. Or operator does not accept an array.\n- @anoop docs.sequelizejs.com/manual/querying.html#operators you can use array as you can see.\n- @kkangil yes you are right, it accepts. I was thinking combinations wasn't supported in arrays, but looks like it is. github.com/sequelize/sequelize/blob/v4/docs/&hellip;. Nice find.\n- @anoop yes that's what I said. I use it many times. but I wonder why the error, above code occurs.\n- @kkangil I think not using object spread plugins for transpiring\n- The edited code worked perfectly. As I commented on the other answer, the only problem with my code were the brackets.","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":176,"estimatedTokens":1050}}975{"id":"stack-45609316","source":"stackoverflow","questionId":45609316,"title":"Combine model's condition with its association's condition in Sequelize","tags":["javascript","orm","sequelize.js"],"text":"Title: Combine model's condition with its association's condition in Sequelize\nTags: javascript, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs there a way to find models by a condition that applies to its own field *or* to its association's field?\n\nGiven models `Model` and `Association`, where each `Model` has one `Association`.\n\n```\nconst Model = sequelize.define('model', {\n name: sequelize.STRING,\n});\n\nconst Association = sequelize.define('association', {\n name: sequelize.STRING,\n});\n\nAssociation.belongsTo(Model);\nModel.hasOne(Association);\n```\n\nI want to find all `Model`s, that either has a `name` equal to \"text\", *or* has an `Association` with a `name` equal to \"text\".\n\nSo far I come up with the solution with `Sequelize.literal`, that doesn't look robust enough.\n\n```\nModel.findAll({\n attributes: ['id', 'name'],\n include: [{\n model: Association,\n attributes: [],\n }],\n where: {\n $or: [\n { name: 'test' },\n Sequelize.literal('association.name = \\'test\\''),\n ],\n },\n});\n```\n\nIs there a better way?\n\n========================================\n\nCode:\n```text\nconst Model = sequelize.define('model', {\n    name: sequelize.STRING,\n});\n\nconst Association = sequelize.define('association', {\n    name: sequelize.STRING,\n});\n\nAssociation.belongsTo(Model);\nModel.hasOne(Association);\n```\n\n```text\nModel.findAll({\n    attributes: ['id', 'name'],\n    include: [{\n        model: Association,\n        attributes: [],\n    }],\n    where: {\n        $or: [\n            { name: 'test' },\n            Sequelize.literal('association.name = \\'test\\''),\n        ],\n    },\n});\n```\n\n```text\nModel\n```\n\n```text\nAssociation\n```\n\n```text\nModel\n```\n\n```text\nAssociation\n```\n\n```text\nModel\n```\n\n```text\nname\n```\n\n```text\nAssociation\n```\n\n```text\nname\n```\n\n```text\nSequelize.literal\n```\n\n```text\nModel.findAll({\n    attributes: ['id', 'name'],\n    include: [{\n        model: Association,\n        attributes: [],\n    }],\n    where: {\n        $or: [\n            { name: 'test' },\n            { '$association.name$':  'test' },\n        ],\n    },\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":127,"estimatedTokens":511}}976{"id":"stack-46113342","source":"stackoverflow","questionId":46113342,"title":"Sequelize create index on JSONB attribute","tags":["node.js","postgresql","sequelize.js","jsonb"],"text":"Title: Sequelize create index on JSONB attribute\nTags: node.js, postgresql, sequelize.js, jsonb\nSource: Stack Overflow\n\nQuestion:\nHow do I create an index using sequelize's syntax for a JSONB field in postgres?\n\nThe index I want to create in SQL would be:\n\n```\nCREATE INDEX people ON people (cast(people.data->>'id' AS bigint));\n```\n\nHow do achieve this with the sequelize syntax?\nI've searched the docs and googled for examples but come up blank.\n\n========================================\n\nTop Answer:\nI couldn't figure out a more elegant way to do this, ended up using an afterSync hook:\n\n```\nafterSync(options, done) {\n co(function* () {\n yield sequelize.query(\n 'CREATE INDEX people ON people (cast(people.data->>\\'id\\' AS bigint));'\n );\n })\n .then(() => done())\n .catch(err => done(err))\n }\n```\n\n========================================\n\nCode:\n```text\nCREATE INDEX people ON people (cast(people.data->>'id' AS bigint));\n```\n\n```js\nconst Test = sequelize.define(\n    'People',\n    {\n        data: {\n            type: DataTypes.JSONB,\n            allowNull: false,\n            field: 'data',\n        }\n    },\n    {\n        tableName: 'people',\n        timestamps: true,\n        paranoid: true,\n        indexes: [{\n            name: 'people_data_id',\n            fields: [Sequelize.literal(\"((\\\"data\\\"->>'id')::int)\")]\n        }]\n    }\n);\n```\n\n```text\nafterSync(options, done) {\n            co(function* () {\n                yield sequelize.query(\n                    'CREATE INDEX people ON people (cast(people.data->>\\'id\\' AS bigint));'\n                );\n            })\n            .then(() => done())\n            .catch(err => done(err))\n        }\n```\n\n========================================\n\nComments:\n- Instead of field name, you can provide `Sequelize.fn` in your index definition. Maybe you could use something like `Sequelize.fn(\"CAST\", Sequelize.col(\"data\"))`. I don't know its syntax so I just leave it as possible hint.","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":78,"estimatedTokens":484}}977{"id":"stack-42182951","source":"stackoverflow","questionId":42182951,"title":"Sequelize - Custom Create Method","tags":["node.js","express","sequelize.js"],"text":"Title: Sequelize - Custom Create Method\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIs it possible to create a custom `create` method in `Sequelize`. I would like it so that I could pass in a URL to download a thumbnail photo from, and then a method would be called with that data to download the photo, upload it to S3, and save that S3 URL as the thumbnailPhotoURL. \n\nHere is an example of the syntax I'm trying to do:\n\n```\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('database', 'username', 'password');\n\nvar User = sequelize.define('user', {\n username: Sequelize.STRING,\n birthday: Sequelize.DATE,\n thumbnailPhotoURL: Sequelize.STRING\n});\n\nsequelize.sync().then(function() {\n return User.create({\n username: 'janedoe',\n birthday: new Date(1980, 6, 20),\n // this will be used to download and upload the thumbnailPhoto to S3\n urlToDownloadThumbnailPhotoFrom: 'http://example.com/test.png'\n });\n}).then(function(jane) {\n console.log(jane.get({\n plain: true\n }));\n});\n```\n\nNotice how I'm calling `User.create` with a `urlToDownloadThumbnailPhotoFrom` parameter, rather than a `thumbnailPhotoURL` parameter\n\n========================================\n\nCode:\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('database', 'username', 'password');\n\nvar User = sequelize.define('user', {\n  username: Sequelize.STRING,\n  birthday: Sequelize.DATE,\n  thumbnailPhotoURL: Sequelize.STRING\n});\n\nsequelize.sync().then(function() {\n  return User.create({\n    username: 'janedoe',\n    birthday: new Date(1980, 6, 20),\n    // this will be used to download and upload the thumbnailPhoto to S3\n    urlToDownloadThumbnailPhotoFrom: 'http://example.com/test.png'\n  });\n}).then(function(jane) {\n  console.log(jane.get({\n    plain: true\n  }));\n});\n```\n\n```text\ncreate\n```\n\n```text\nSequelize\n```\n\n```text\nUser.create\n```\n\n```text\nurlToDownloadThumbnailPhotoFrom\n```\n\n```text\nthumbnailPhotoURL\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('database', 'username', 'password');\n\nvar User = sequelize.define('user', {\n  username: Sequelize.STRING,\n  birthday: Sequelize.DATE,\n  thumbnailPhotoURL: Sequelize.STRING\n});\n\n\nUser.beforeCreate(function(model, options, cb) { \n   var urlToDownloadThumbnailPhotoFrom = model.urlToDownloadThumbnailPhotoFrom;\n\n\n//.....Here you write the logic to get s3 url using urlToDownloadThumbnailPhotoFrom and then assign it to model and call the call back it will automatically get saved\n\n  model.thumbnailPhotoURL = thumbnailPhotoURL;\n  cb();\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":103,"estimatedTokens":642}}978{"id":"stack-44104860","source":"stackoverflow","questionId":44104860,"title":"Sequelize increment function returning error","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize increment function returning error\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nTrying to increment an integer field on a model instance in my DB. Here is the relevant code. \n\n```\nmodels.Options.findAll({\n where: { \n PollId: poll_id, \n name: option_to_update\n }\n }).then((option) => {\n option.increment('votes');\n res.json(option);\n });\n```\n\nWhen I console.log(option), it shows as an Instance so I know it inherits from the Instance class which has an increment function as can be seen here\n\nhttps://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L934\n\nHowever, when I try to run option.increment, I get this back \n\n Unhandled rejection TypeError: option.increment is not a function\n\nNot really sure what I'm doing wrong.\n\n========================================\n\nCode:\n```text\nmodels.Options.findAll({\n        where: { \n            PollId: poll_id, \n            name: option_to_update\n        }\n    }).then((option) => {\n        option.increment('votes');\n        res.json(option);\n    });\n```\n\n```text\nmodels.Options.findOne({\n  where: { \n    PollId: poll_id, \n    name: option_to_update\n  }\n}).then(option => {\n  return option.increment('votes'); // assumes `option` always exists\n}).then(option => {\n  return option.reload();\n}).then(option => {\n  res.json(option);\n});\n```\n\n```text\nfindAll()\n```\n\n```text\noption[0].increment('votes')\n```\n\n```text\nfindOne\n```\n\n```text\nfindAll\n```\n\n```text\nvotes\n```\n\n========================================\n\nComments:\n- What's the exact problem, though?\n- Sorry, I just re-read the question and realized I completely skipped over the error. The problem is that it returns option.increment is not a function.\n- Awesome! Thanks! I had another quick question, I'm not seeing the increment reflected when I res.json(option) right after incrementing it. Is that because the db needs to be synced to reflect the increment first?\n- Brilliant! Thanks a lot!","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":86,"estimatedTokens":496}}979{"id":"stack-42959073","source":"stackoverflow","questionId":42959073,"title":"Sequelize Find belongsToMany Association","tags":["javascript","mysql","node.js","associations","sequelize.js"],"text":"Title: Sequelize Find belongsToMany Association\nTags: javascript, mysql, node.js, associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an association m:n between two tables with sequelize like this:\n\n**Course**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\n var Course = sequelize.define('Course', {\n .....\n },\n {\n associate: function(models){\n Course.hasMany(models.Schedule);\n Course.belongsTo(models.Period);\n Course.belongsTo(models.Room);\n Course.belongsTo(models.Subject);\n Course.belongsTo(models.School);\n Course.belongsTo(models.Person, { as: 'Teacher' });\n }\n }\n );\n return Course;\n};\n```\n\n**Person**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\n var Person = sequelize.define('Person', {\n ....\n },\n {\n associate: function(models){\n Person.belongsTo(models.Role, { as: 'Role' });\n Person.belongsTo(models.School, { as: 'School' });\n Person.belongsTo(models.Person, { as: 'Tutor' });\n }\n }\n );\n\n return Person;\n};\n```\n\nAnd the association table **Enrollment**\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n\n var Enrollment = sequelize.define('Enrollment', {\n ....\n },\n {\n associate: function(models){\n Enrollment.belongsTo(models.Product, {as: 'Product'});\n Enrollment.belongsTo(models.School, { as: 'School' });\n\n models.Person.belongsToMany(models.Course, {through: {model: Enrollment},foreignKey: 'StudentEnrollId'});\n models.Course.belongsToMany(models.Person, {through: {model: Enrollment},foreignKey: 'CourseEnrollId'});\n\n }\n }\n\n );\n return Enrollment;\n};\n```\n\nI tried following this \"example\" but doesn't explain much rather than a simple query where include the parameter through.\n\nWhat I trying to archive is to get All the courses given a Student id (Person Model). As you can see the course model only saves the id of differents tables that together form a course. The Person Model also is associate to differents models so I give a custom id name with `foreignKey: 'StudentEnrollId'` but when I try to specify the id name in the include `model : db.Person, as: 'StundetEnroll'` the query show the following error: `Person (StudentEnroll) is not associated to Course`\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n  var Course = sequelize.define('Course', {\n     .....\n    },\n    {\n      associate: function(models){\n        Course.hasMany(models.Schedule);\n        Course.belongsTo(models.Period);\n        Course.belongsTo(models.Room);\n        Course.belongsTo(models.Subject);\n        Course.belongsTo(models.School);\n        Course.belongsTo(models.Person, { as: 'Teacher' });\n      }\n    }\n  );\n return Course;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n  var Person = sequelize.define('Person', {\n    ....\n    },\n    {\n      associate: function(models){\n        Person.belongsTo(models.Role, { as: 'Role' });\n        Person.belongsTo(models.School, { as: 'School' });\n        Person.belongsTo(models.Person, { as: 'Tutor' });\n      }\n    }\n  );\n\n  return Person;\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n\n  var Enrollment = sequelize.define('Enrollment', {\n      ....\n    },\n    {\n      associate: function(models){\n        Enrollment.belongsTo(models.Product, {as: 'Product'});\n        Enrollment.belongsTo(models.School, { as: 'School' });\n\n        models.Person.belongsToMany(models.Course, {through: {model: Enrollment},foreignKey: 'StudentEnrollId'});\n        models.Course.belongsToMany(models.Person, {through: {model: Enrollment},foreignKey: 'CourseEnrollId'});\n\n      }\n    }\n\n  );\n  return Enrollment;\n};\n```\n\n```text\nforeignKey: 'StudentEnrollId'\n```\n\n```text\nmodel : db.Person, as: 'StundetEnroll'\n```\n\n```text\nPerson (StudentEnroll) is not associated to Course\n```\n\n```text\nmodels.Person.belongsToMany(models.Course, { as: 'CourseEnrolls', through: { model: Enrollment }, foreignKey: 'StudentEnrollId'});\nmodels.Course.belongsToMany(models.Person, { as: 'StudentEnrolls', through: { model: Enrollment }, foreignKey: 'CourseEnrollId'});\n```\n\n```text\nmodels.Course.findByPrimary(1, {\n    include: [\n        {\n            model: models.Person,\n            as: 'StudentEnrolls'\n        }\n    ]\n}).then(course => {\n    // course.StudentEnrolls => array of Person instances (students of given course)\n});\n```\n\n```text\n// assuming that course is an instance of Course model\ncourse.getStudentEnrolls().then(students => {\n    // here you get all students of given course\n});\n```\n\n```text\nas\n```\n\n```text\nbelongsToMany\n```\n\n```text\nCourse\n```\n\n```text\nget/set Associations\n```\n\n========================================\n\nComments:\n- Thanks, That helped me a lot. Now I only have to play with the includes to get the other datas.","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":201,"estimatedTokens":1178}}980{"id":"stack-41070230","source":"stackoverflow","questionId":41070230,"title":"Sequelize: can you use hooks to add a comment to a query?","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize: can you use hooks to add a comment to a query?\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHeroku recently posted a list of some good tips for postgres. I was most intreged by the *Track the Source of Your Queries* section. I was curious if this was something that's possible to use with Sequelize. I know that sequelize has hooks, but wasn't sure if hooks could be used to make actual query string adjustments. \n\nI'm curious if it's possible to use a hook or another Sequelize method to append a comment to Sequelize query (without using `.raw`) to keep track of where the query was called from.\n\n(Appending and prepending to queries would also be helpful for implementing row-level security, specifically `set role` / `reset role`)\n\nEdit: Would it be possible to use `sequelize.fn()` for this?\n\n========================================\n\nTop Answer:\nThis overrides the `sequelize.query()` method that's internally used by Sequelize for all queries to add a comment showing the location of the query in the code. It also adds the stack trace to errors thrown.\n\n```\nconst excludeLineTexts = ['node_modules', 'internal/process', ' anonymous ', 'runMicrotasks', 'Promise.'];\n\n// overwrite the query() method that Sequelize uses internally for all queries so the error shows where in the code the query is from\nsequelize.query = function () {\n let stack;\n const getStack = () => {\n if (!stack) {\n const o = {};\n Error.captureStackTrace(o, sequelize.query);\n stack = o.stack;\n }\n return stack;\n };\n\n const lines = getStack().split(/\\n/g).slice(1);\n const line = lines.find((l) => !excludeLineTexts.some((t) => l.includes(t)));\n\n if (line) {\n const methodAndPath = line.replace(/(\\s+at (async )?|[^a-z0-9.:/\\\\\\-_ ]|:\\d+\\)?$)/gi, '');\n\n if (methodAndPath) {\n const comment = `/* ${methodAndPath} */`;\n if (arguments[0]?.query) {\n arguments[0].query = `${comment} ${arguments[0].query}`;\n } else {\n arguments[0] = `${comment} ${arguments[0]}`;\n }\n }\n }\n\n return Sequelize.prototype.query.apply(this, arguments).catch((err) => {\n err.fullStack = getStack();\n throw err;\n });\n};\n```\n\n========================================\n\nCode:\n```text\n.raw\n```\n\n```text\nset role\n```\n\n```text\nreset role\n```\n\n```text\nsequelize.fn()\n```\n\n```js\nModel.findById(id, {\n   attributes: {\n     include: [\n       [Sequelize.literal('/* your comment */ 1'), 'an_alias'],\n     ],\n   },\n });\n```\n\n```sql\nSELECT `model`.`id`, /* your comment */ 1 as `an_alias`\nFROM `model` as `model`\nWHERE `model`.`id` = ???\n```\n\n```js\n// alias findById() so we can call it once we fiddle with the input\n Sequelize.Model.prototype.findById_untagged = Sequelize.Model.prototype.findById;\n\n // override the findbyId() method so we can intercept the options.\n Sequelize.Model.prototype.findById = function findById(id, options) {\n   // get the caller somehow (I was having trouble accessing the call stack properly)\n   const caller = ???;\n\n   // you need to make sure it's defined and you aren't overriding settings, etc\n   options.attributes.include.push([Sequelize.literal('/* your comment */ 1'), 'an_alias']);\n\n   // pass it off to the aliased method to continue as normal\n   return this.findById_untagged(id, options);\n }\n\n // create the connection\n const connection = new Sequelize(...);\n```\n\n```text\nfunction Wrapper(model) {\n  return {\n    findById(id, options) {\n      // do your stuff\n      return model.findById(id, options);\n    },\n  };\n}\n\nWrapper(Model).findById(id, options);\n```\n\n```text\nSequelize.literal()\n```\n\n```text\noptions.attributes.include\n```\n\n```text\nSequelize.Model.prototype\n```\n\n```text\nnew Sequelize()\n```\n\n```text\nuse strict\n```\n\n```text\narguments.caller\n```\n\n```text\narguments.callee\n```\n\n```text\nSequelize.Model\n```\n\n```text\noptions.comment\n```\n\n```text\nconst excludeLineTexts = ['node_modules', 'internal/process', ' anonymous ', 'runMicrotasks', 'Promise.'];\n\n// overwrite the query() method that Sequelize uses internally for all queries so the error shows where in the code the query is from\nsequelize.query = function () {\n    let stack;\n    const getStack = () => {\n        if (!stack) {\n            const o = {};\n            Error.captureStackTrace(o, sequelize.query);\n            stack = o.stack;\n        }\n        return stack;\n    };\n\n    const lines = getStack().split(/\\n/g).slice(1);\n    const line = lines.find((l) => !excludeLineTexts.some((t) => l.includes(t)));\n\n    if (line) {\n        const methodAndPath = line.replace(/(\\s+at (async )?|[^a-z0-9.:/\\\\\\-_ ]|:\\d+\\)?$)/gi, '');\n\n        if (methodAndPath) {\n            const comment = `/* ${methodAndPath} */`;\n            if (arguments[0]?.query) {\n                arguments[0].query = `${comment} ${arguments[0].query}`;\n            } else {\n                arguments[0] = `${comment} ${arguments[0]}`;\n            }\n        }\n    }\n\n    return Sequelize.prototype.query.apply(this, arguments).catch((err) => {\n        err.fullStack = getStack();\n        throw err;\n    });\n};\n```\n\n```text\nsequelize.query()\n```\n\n========================================\n\nComments:\n- thank you for a thorough and well thought-out answer. I am very impressed. Maybe for caller some hack like `try { throw new Error(); } catch ( error ) { console.log( error.stack ); }` could work if it choose the correct line from the stack, but would be slow ;)","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":206,"estimatedTokens":1333}}981{"id":"stack-43056182","source":"stackoverflow","questionId":43056182,"title":"Can I dynamically import TypeScript modules in Node.js/Express?","tags":["javascript","node.js","express","typescript","sequelize.js"],"text":"Title: Can I dynamically import TypeScript modules in Node.js/Express?\nTags: javascript, node.js, express, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a Node.js server built with Express.js and coded in TypeScript. Here's a snippet of the get call for my server:\n\nserver.ts\n\n```\nprivate get(req: Request, res: Response, next: NextFunction, objectName: string) {\n var DatabaseObject = require(\"./models/\" + objectName + \".js\")(this.orm, Sequelize.DataTypes);\n var Transform = require(\"./routes/\" + objectName + \".js\");\n var transform = new Transform();\n\n // ...\n\n console.log(req.query[\"columns\"]);\n console.log(transform.columnWhitelist);\n console.log(transform);\n\n // ...\n\n if (transform.columnWhitelist) {\n console.log(\"Column Whitelist Exists.\");\n }\n // ...\n}\n```\n\nIt dynamically loads the Sequelize module for the database object being requested in the URL and then tries to load a TypeScript module with rules on what columns can be selected, which columns can be queried on, etc. Here's the beginning of my ruleset class:\n\naccount.ts\n\n```\nexport default class Transform {\n static columnWhitelist : Object = {\"id\": \"id\", \"name\": \"name\", \"parentAccountId\":\"parentAccountId\", \"masterAccountId\":\"masterAccountId\"};\n\n constructor() { }\n}\n```\n\nHowever, running my application, I get:\n\n```\nid,name,parentAccountId\nundefined\n{ default: \n { [Function: Transform]\n columnWhitelist: \n { id: 'id',\n name: 'name',\n parentAccountId: 'parentAccountId',\n masterAccountId: 'masterAccountId' } } }\n```\n\nMaking the call transform.columnWhitelist, I get undefined, despite seeing it in the generated JavaScript file as well. I've also tried just:\n\n```\nvar transform = require(\"./routes/\" + objectName + \".js\");\n```\n\nOr:\n\n```\nvar transform = require(\"./routes/\" + objectName + \".js\")();\n```\n\nBut neither of these work either.\n\n========================================\n\nTop Answer:\nIf you do not want to use \n\n```\nvar transform = require(\"./routes/\" + objectName + \".js\").default;\n```\n\nYou can export your class by doing\n\n```\nclass Transform {\n     static columnWhitelist: Object = {\"id\": \"id\", \"name\": \"name\", \"parentAccountId\": \"parentAccountId\", \"masterAccountId\": \"masterAccountId\"};\n\n     constructor () {}\n}\n\nexport = Transform;\n```\n\nAfter you can do again as before:\n\n```\nvar transform = require (\"./ routes /\" + objectName + \".js\");\n```\n\n========================================\n\nCode:\n```text\nprivate get(req: Request, res: Response, next: NextFunction, objectName: string) {\n    var DatabaseObject = require(\"./models/\" + objectName + \".js\")(this.orm, Sequelize.DataTypes);\n    var Transform = require(\"./routes/\" + objectName + \".js\");\n    var transform = new Transform();\n\n    // ...\n\n    console.log(req.query[\"columns\"]);\n    console.log(transform.columnWhitelist);\n    console.log(transform);\n\n    // ...\n\n    if (transform.columnWhitelist) {\n        console.log(\"Column Whitelist Exists.\");\n    }\n    // ...\n}\n```\n\n```text\nexport default class Transform {\n    static columnWhitelist : Object = {\"id\": \"id\", \"name\": \"name\", \"parentAccountId\":\"parentAccountId\", \"masterAccountId\":\"masterAccountId\"};\n\n    constructor() { }\n}\n```\n\n```text\nid,name,parentAccountId\nundefined\n{ default: \n   { [Function: Transform]\n     columnWhitelist: \n      { id: 'id',\n        name: 'name',\n        parentAccountId: 'parentAccountId',\n        masterAccountId: 'masterAccountId' } } }\n```\n\n```text\nvar transform = require(\"./routes/\" + objectName + \".js\");\n```\n\n```text\nvar transform = require(\"./routes/\" + objectName + \".js\")();\n```\n\n```text\nvar transform = require(\"./routes/\" + objectName + \".js\").default;\n```\n\n```text\nvar transform = require(\"./routes/\" + objectName + \".js\").default;\n```\n\n```text\nclass Transform {\n     static columnWhitelist: Object = {\"id\": \"id\", \"name\": \"name\", \"parentAccountId\": \"parentAccountId\", \"masterAccountId\": \"masterAccountId\"};\n\n     constructor () {}\n}\n\nexport = Transform;\n```\n\n```text\nvar transform = require (\"./ routes /\" + objectName + \".js\");\n```\n\n========================================\n\nComments:\n- I get it now. Thanks a lot! At one point I did try `var Transform = require(\".&#47;routes&#47;\" + objectName + \".js\"); var transform = Transform.Transform;` or something like that but I must've typed something wrong.\n- Is `export = Transform;` TypeScript-specific syntax versus the `module.exports = ...` of JavaScript, or another way of writing the latter?\n- **export =** is used to give typescript the **export default** behavior. In addition it works with interfaces, functions, enums etc ... You can find out more by reading the documentation https://www.typescriptlang.org/docs/handbook/modules.html (you can do a search with export =) if you want to keep typing, you can add: var transform: typeof Transform = require(\"./routes/\" +objectName+ \".js\");","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":177,"estimatedTokens":1202}}982{"id":"stack-34707102","source":"stackoverflow","questionId":34707102,"title":"How do I deal with SQL tablenames with hyphen (-) when writing raw queries? i.e project-users","tags":["sql","postgresql","sequelize.js"],"text":"Title: How do I deal with SQL tablenames with hyphen (-) when writing raw queries? i.e project-users\nTags: sql, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a table called `project-users` and want to write a SQL query like `SELECT * FROM project-users` I get this error `ERROR: syntax error at or near \"-\"`. \nI cannot change the table name at this point.\n\n========================================\n\nCode:\n```text\nproject-users\n```\n\n```text\nSELECT * FROM project-users\n```\n\n```text\nERROR: syntax error at or near \"-\"\n```\n\n```text\nSELECT * FROM \"project-users\";\n```\n\n========================================\n\nComments:\n- Possible duplicate of using (-) dash in mysql table name\n- You need to escape the name. Postgres uses double quotes. You can review the documentation on this: postgresql.org/docs/current/static/sql-syntax-lexical.html.\n- Double quoting invalid names is the Standard SQL approach, but this also results in case_sensitive object names, e.g. \"a\" and \"A\" are different tables. The basic recommendation is to avoid any names where quoting is needed, e.g. `project_users` instead of `\"project users\"` or `\"project-users\"`.","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":33,"estimatedTokens":289}}983{"id":"stack-28689944","source":"stackoverflow","questionId":28689944,"title":"How to use of between operator in Sequelize?","tags":["node.js","sequelize.js"],"text":"Title: How to use of between operator in Sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\nvar conditionalData = {\n id: {\n $Between: [11, 15]\n },\n technician_id: technicianId\n};\nvar attributes = ['id', 'service_start_time', 'service_end_time'];\nuserServiceAppointmentModel.findAll({\n where: conditionalData,\n attributes: attributes\n}).complete(function (err, serviceAppointmentResponse) {\n if (err) {\n var response = constants.responseErrors.FETCHING_DATA;\n return callback(err, null);\n } else {\n if (serviceAppointmentResponse.length > 0) {\n var response = constants.responseErrors.NO_AVAILABLE_SLOTS_IN_YOUR_CALENDAR;\n return callback(response, null);\n }\n }\n);\n```\n\nWhen I run the above query it gives me error as\n\n \"message\": \"ER_SP_DOES_NOT_EXIST: FUNCTION user_service_appointment.id\n does not exist\"\n\n========================================\n\nCode:\n```text\nvar conditionalData = {\n    id: {\n        $Between: [11, 15]\n    },\n    technician_id: technicianId\n};\nvar attributes = ['id', 'service_start_time', 'service_end_time'];\nuserServiceAppointmentModel.findAll({\n    where: conditionalData,\n    attributes: attributes\n}).complete(function (err, serviceAppointmentResponse) {\n    if (err) {\n        var response = constants.responseErrors.FETCHING_DATA;\n        return callback(err, null);\n    } else {\n        if (serviceAppointmentResponse.length > 0) {\n            var response = constants.responseErrors.NO_AVAILABLE_SLOTS_IN_YOUR_CALENDAR;\n            return callback(response, null);\n        }\n    }\n);\n```\n\n```text\n$Between\n```\n\n```text\n$between\n```\n\n```text\n$\n```\n\n========================================\n\nComments:\n- Thanks . I used 2.0.3 version of sequelize","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":426}}984{"id":"stack-32363697","source":"stackoverflow","questionId":32363697,"title":"How to set sequelize.sync option force to false?","tags":["mysql","node.js","heroku","sequelize.js"],"text":"Title: How to set sequelize.sync option force to false?\nTags: mysql, node.js, heroku, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am deploying a node.js app using a mysql database and using sequelize ORM on heroku. When I deploy, sequelize re-creates the database. The application does not work because it expects data in the database.\n\nI believe sequelize.sync option is the culprit. On my local development env, I have set force: false by hand. But on heroku, sequelize is being reinstalled (package.json) and I am guessing sync is defaulting to force:true. \n\nHow do I set an option to stop this behavior? I went through the doc and tried this:\n\n```\nvar sequelizeOptions = {\n host: \"blah.blah.us-east-1.rds.amazonaws.com\",\n dialect: 'mysql',\n port: 3306,\n sync: {force:false}\n};\n```\n\nThis is being passed to the sequelizeManager that in turn is handling the creation of DB. This approach is is not working. Any help is much appreciated.\n\n========================================\n\nCode:\n```text\nvar sequelizeOptions = {\n    host: \"blah.blah.us-east-1.rds.amazonaws.com\",\n    dialect: 'mysql',\n    port: 3306,\n    sync: {force:false}\n};\n```\n\n```text\nsequelize.sync\n```\n\n```text\nforce\n```\n\n```text\nfalse\n```\n\n```text\nsequelize.sync()\n```\n\n```text\nsync()\n```\n\n========================================\n\nComments:\n- Thanks. Spot on. I tracked down where sync() was being invoked. No more sync and no more re-creation issue.\n- I call sequelize.sync({force: false}), but still the tables are re-created. Why is this?","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":59,"estimatedTokens":379}}985{"id":"stack-35808979","source":"stackoverflow","questionId":35808979,"title":"Pulling Sequelize Info from multiple tables","tags":["mysql","node.js","express","sequelize.js"],"text":"Title: Pulling Sequelize Info from multiple tables\nTags: mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm pretty new to new sequelize but I'm trying to figure out how I can pull sequelize information from multiple tables (Place and Review tables) and render them on the same page. The Review table has a User Id and a Place Id. I've tried raw queries and different variations of the code below to no avail. What sort of syntax should I use in this case?\n\n```\nUser.hasMany(Review);\nReview.belongsTo(User);\n\nUser.hasMany(Place);\nPlace.belongsTo(User);\n\nPlace.hasMany(Review);\nReview.belongsTo(Place);\n\napp.get('/place/:category/:id', function(req, res){\n var id = req.params.id;\n Place.findAll({\n where : {id : id},\n include: [{\n model: [Review]\n }]\n }).then(function(reviews){\n res.render('singular', {reviews});\n });\n\n});\n```\n\n========================================\n\nCode:\n```text\nUser.hasMany(Review);\nReview.belongsTo(User);\n\nUser.hasMany(Place);\nPlace.belongsTo(User);\n\nPlace.hasMany(Review);\nReview.belongsTo(Place);\n\n\n\napp.get('/place/:category/:id', function(req, res){\n  var id = req.params.id;\n  Place.findAll({\n    where : {id : id},\n    include: [{\n      model: [Review]\n    }]\n  }).then(function(reviews){\n    res.render('singular', {reviews});\n  });\n\n});\n```\n\n```text\nPlaces.hasMany(Reviews);\nUsers.hasMany(Reviews);\n\nReview.belongsTo(Places);\nReview.belongsTo(Users);\n```\n\n```text\nPlaces.findById(req.params.id, {\n    include: [{\n        model: Reviews,\n        required: false,\n        include: [{\n            model: Users,\n            required: false\n        }]\n    }]\n}).then(function(place) {\n    // The rest of your logic here...\n});\n```\n\n========================================\n\nComments:\n- Thanks this is a great solution to a problem that I had.","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":87,"estimatedTokens":449}}986{"id":"stack-34974302","source":"stackoverflow","questionId":34974302,"title":"Sequelize join table through foreign keys not created","tags":["join","express","many-to-many","sequelize.js"],"text":"Title: Sequelize join table through foreign keys not created\nTags: join, express, many-to-many, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a user > friend relationship in sequelize. Therefore, I created a user model and a belongsToMany relationship through a join-table called friends. It created the table but the foreignKeys userId and friendId are not created. I would be happy if someone could help me out.\n\nUser model:\n\n```\nvar User = sequelize.define('user', {\n id: {\n type: Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n emailaddress: {\n type: Sequelize.STRING\n },\n firstname: {\n type: Sequelize.STRING\n },\n lastname: {\n type: Sequelize.STRING\n },\n description: {\n type: Sequelize.STRING\n },\n password: {\n type: Sequelize.STRING\n }\n }, {\n freezeTableName: true, \n classMethods: {\n associate: function (models) {\n User.belongsToMany(models.user, {\n as: \"user\",\n through: \"friend\"\n });\n User.belongsToMany(models.user, {\n as: \"friend\",\n through: \"friend\"\n });\n User.sync({\n force: true\n })\n }\n }\n });\n```\n\nfriend model\n\n```\nvar Friend = sequelize.define('friend', {\n // userId: DataTypes.INTEGER,\n // friendId: DataTypes.INTEGER,\n status: {\n type: DataTypes.BOOLEAN,\n defaultValue: 0\n }\n }, {\n freezeTableName: true,\n classMethods: {\n associate: function (models) {\n Friend.sync()\n }\n }\n });\n```\n\nThis generates the following field in the friend table:\n\n id status createdAt updatedAt\n\nI would like the following fields:\n\n id status userId friendId createdAt updatedAt\n\npackage.json > \"sequelize\": \"^3.17.1\",\n\n========================================\n\nTop Answer:\nYou can set `otherKey` and `foreignKey` to a sequelize associations. I think you should try this:\n\n```\nUser.belongsToMany(models.user, {\n as: \"friends\",\n through: \"friend\",\n otherKey: 'userId',\n foreignKey: 'friendId'\n});\n```\n\nSorry I can't try it right now, but I hope, it helps you.\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('user', {\n    id: {\n      type: Sequelize.INTEGER,\n      autoIncrement: true,\n      primaryKey: true\n    },\n    emailaddress: {\n      type: Sequelize.STRING\n    },\n    firstname: {\n      type: Sequelize.STRING\n    },\n    lastname: {\n      type: Sequelize.STRING\n    },\n    description: {\n      type: Sequelize.STRING\n    },\n    password: {\n      type: Sequelize.STRING\n    }\n  }, {\n    freezeTableName: true, \n    classMethods: {\n      associate: function (models) {\n        User.belongsToMany(models.user, {\n          as: \"user\",\n          through: \"friend\"\n        });\n        User.belongsToMany(models.user, {\n          as: \"friend\",\n          through: \"friend\"\n        });\n        User.sync({\n            force: true\n          })\n      }\n    }\n  });\n```\n\n```text\nvar Friend = sequelize.define('friend', {\n    // userId: DataTypes.INTEGER,\n    // friendId: DataTypes.INTEGER,\n    status: {\n      type: DataTypes.BOOLEAN,\n      defaultValue: 0\n    }\n  }, {\n    freezeTableName: true,\n    classMethods: {\n      associate: function (models) {\n        Friend.sync()\n      }\n    }\n  });\n```\n\n```text\nUser.belongsToMany(models.user, {\n    as: \"friends\",\n    through: \"friend\",\n    otherKey: 'userId',\n    foreignKey: 'friendId'\n});\n```\n\n```text\notherKey\n```\n\n```text\nforeignKey\n```\n\n========================================\n\nComments:\n- I tried it out and I came to the conclusion that it did not solve my problem, although it is a nice way to achieve the same result. My problem was the fact that I call User.sync directly when initializing every table, when I removed the sync from every table and only did one sync, using the sequelize express example code (I am using express) it worked.\n- I would still like to assign to you the 100 bounty because your answer pointed me in the right direction. update: will be dealt with in 2 hours. I am not allowed to award it yet ;)","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":182,"estimatedTokens":964}}987{"id":"stack-29249133","source":"stackoverflow","questionId":29249133,"title":"Dependency Chain: category -> shop => category in model sequelizejs while defining foreign key","tags":["node.js","sequelize.js"],"text":"Title: Dependency Chain: category -> shop => category in model sequelizejs while defining foreign key\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nList of Error:\n\n \\Possibly unhandled Error: Cyclic dependency found. 'category' is\n dependent of itself. Dependency Chain: category -> shop => category\n\n at visit\n (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:74:27)\n\n at /home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:96:25\n\n at Array.forEach (native)\n\n at visit (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:95:20)\n\n at /home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:96:25\n\n at Array.forEach (native)\n\n at visit (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:95:20)\n\n at Toposort.self.sort (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:104:21)\n\n at module.exports.ModelManager.forEachDAO (/home/rashmi/nodejs/node_modules/sequelize/lib/model-manager.js:88:21)\n\n at /home/rashmi/nodejs/node_modules/sequelize/lib/sequelize.js:894:25\n\nWhile running this file Model.js \n\n```\nvar Category=sequelize.define(\"category\",{\n categoryname :{\n type: Sequelize.STRING,\n validate:{isAlpha:true}\n }},\n {\n paranoid: true,\n freezeTableName: true, //modeltable name will be the same as model name\n comment: \"I'm Category table!\"\n });\n\nvar shop=sequelize.define(\"shop\",{\n shopID:{\n type: Sequelize.INTEGER,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n title: {\n type: Sequelize.STRING(100),\n allowNull: false,\n validate:{isAlpha: true} \n },\n shopKeeperName:{\n type: Sequelize.STRING(100),\n allowNull: false,\n validate:{isAlpha: true} \n },\n mobile :{\n type: Sequelize.CHAR(10),\n allowNull: false\n },\n city :{\n type: Sequelize.INTEGER,\n allowNull: false,\n references: \"City\",\n referencesKey: \"cityId\"\n },\n scategory :{\n type: Sequelize.STRING,\n allowNull: false,\n references: \"category\",\n referencesKey: \"Id\"\n },\n address :{\n type: Sequelize.TEXT,\n allowNull: false,\n validate:{ isAlphanumeric:true}\n },\n stock :{\n type: Sequelize.INTEGER,\n validate: {isInt: true}\n }\n },\n {\n paranoid: true,\n freezeTableName: true, //modeltable name will be the same as model name\n underscored: true,\n comment: \"I'm Shop table!\"\n });\n\nstate.hasMany(city);\ncity.belongsTo(state,{foreignKey: 'stateID'});\n\nAgent.hasOne(city);\ncity.belongsTo(Agent);\n\nAgent.hasOne(state);\nstate.belongsTo(Agent);\n\nshop.hasOne(Category);\nCategory.belongsTo(shop);\nsequelize.sync();\n```\n\nWhile defining shop model, I got the above errors. foreign key categoryid in shop, I'm not getting the exact reason, what it means by Shop is dependent on itself, dependency cycle.\n\n========================================\n\nTop Answer:\nHowever, the code above will result in the following error: Cyclic dependency found. 'Document' is dependent of itself. Dependency Chain: Document -> Version => Document. In order to alleviate that, we can pass constraints: false to one of the associations:\n `Document.hasMany(Version)\n Document.belongsTo(Version, { as: 'Current', foreignKey: 'current_version_id', constraints: false})`\n\nhttp://docs.sequelizejs.com/en/latest/docs/associations/\n\n========================================\n\nCode:\n```text\nvar Category=sequelize.define(\"category\",{\n    categoryname :{\n        type: Sequelize.STRING,\n        validate:{isAlpha:true}\n    }},\n    {\n        paranoid: true,\n        freezeTableName: true, //modeltable name will be the same as model name\n        comment: \"I'm Category table!\"\n    });\n\nvar shop=sequelize.define(\"shop\",{\n    shopID:{\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    title: {\n        type: Sequelize.STRING(100),\n         allowNull: false,\n        validate:{isAlpha: true} \n    },\n    shopKeeperName:{\n        type: Sequelize.STRING(100),\n         allowNull: false,\n        validate:{isAlpha: true} \n    },\n    mobile :{\n        type: Sequelize.CHAR(10),\n         allowNull: false\n    },\n    city :{\n        type: Sequelize.INTEGER,\n         allowNull: false,\n         references: \"City\",\n         referencesKey: \"cityId\"\n    },\n    scategory :{\n        type: Sequelize.STRING,\n        allowNull: false,\n        references: \"category\",\n        referencesKey: \"Id\"\n    },\n    address :{\n        type: Sequelize.TEXT,\n        allowNull: false,\n        validate:{ isAlphanumeric:true}\n    },\n    stock :{\n        type: Sequelize.INTEGER,\n        validate: {isInt: true}\n    }\n    },\n    {\n        paranoid: true,\n        freezeTableName: true, //modeltable name will be the same as model name\n        underscored: true,\n        comment: \"I'm Shop table!\"\n    });\n\nstate.hasMany(city);\ncity.belongsTo(state,{foreignKey: 'stateID'});\n\nAgent.hasOne(city);\ncity.belongsTo(Agent);\n\nAgent.hasOne(state);\nstate.belongsTo(Agent);\n\nshop.hasOne(Category);\nCategory.belongsTo(shop);\nsequelize.sync();\n```\n\n```text\nshop.hasOne(Category);\nCategory.belongsTo(shop);\n```\n\n```text\nshop.belongsTo(Category);\nCategory.hasOne(shop);\n```\n\n```text\nshop.belongsTo(Category, { foreignKey: 'scategory' });\n```\n\n```text\nShop.belongsTo(Category, { \n  foreignKey: { \n    allowNull: false, \n    name: 'scategory'\n  }\n});\n```\n\n```text\nscategory\n```\n\n```text\nCategory.hasMany(shop);\n```\n\n```text\nscategory\n```\n\n```text\nscategory\n```\n\n```text\nDocument.hasMany(Version)\n  Document.belongsTo(Version, { as: 'Current', foreignKey: 'current_version_id', constraints: false})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":242,"estimatedTokens":1392}}988{"id":"stack-28354810","source":"stackoverflow","questionId":28354810,"title":"Sequelize, Raw Query by daterange","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize, Raw Query by daterange\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI use \"sequelize\": \"^2.0.0-rc3\" with pg (postgresql), in this moment i am trying to do a **raw query** with date range but sequelize don't return data.\n\nWhen I run the same query in postgresql db get correct results. Please Help Me.\n\nIn sequilize:\n\n```\n// Init main query\n var query = \"SELECT * FROM\" + '\"Calls\"' +\n \" WHERE \" + '\"EquipmentId\"' + \" = 1\" +\n \" AND \" + '\"initDate\"' + \" >= \" + \"'2015-02-05 14:40' \" +\n \" AND \" + '\"endDate\"' + \" In console of node server I get.\n\n```\nExecuting (default): SELECT * FROM \"Calls\" WHERE \"EquipmentId\" = 1 AND \"initDate\" >= '2015-02-05 14:40' AND \"endDate\" But empty array calls...\n\n========================================\n\nTop Answer:\nYou can also use sequelize function like `findAll`\n\n```\nModel.findAll(\n where : { \n gte:sequelize.fn('date_format', initDate, '%Y-%m-%dT%H:%i:%s'),\n lte:sequelize.fn('date_format', endDate, '%Y-%m-%dT%H:%i:%s')\n }\n)\n```\n\n========================================\n\nCode:\n```text\n// Init main query\n  var query = \"SELECT * FROM\" + '\"Calls\"' +\n              \" WHERE \"  + '\"EquipmentId\"' + \" = 1\" +\n              \" AND \" + '\"initDate\"' + \" >= \" + \"'2015-02-05 14:40' \" +\n              \" AND \" + '\"endDate\"' + \" <= \" + \" '2015-02-05 15:00' \";\n\n  global.db.sequelize.query(query)\n  .then(function(calls) {\n    console.log(calls);\n  })\n  .error(function (err) {\n    console.log(err);\n  });\n```\n\n```text\nExecuting (default): SELECT * FROM \"Calls\" WHERE \"EquipmentId\" = 1 AND \"initDate\" >= '2015-02-05 14:40'  AND \"endDate\" <=  '2015-02-05 15:00'\n```\n\n```text\nvar query = ' \\\n  SELECT * FROM \"Calls\" \\\n  WHERE \"EquipmentId\" = :EquipmentId \\\n  AND \"initDate\" >= :initDate \\\n  AND \"endDate\" <= :endDate; \\\n';\n\nglobal.db.sequelize.query(query, null, {raw: true}, { \n  EquipmentId: 1, \n  initDate: new Date('2015-02-05 14:40'), \n  endDate: new Date('2015-02-05 15:00')\n})\n.then(function(calls) {\n  console.log(calls);\n})\n.error(function (err) {\n  console.log(err);\n});\n```\n\n```text\nModel.findAll(\n  where : {    \n     gte:sequelize.fn('date_format', initDate, '%Y-%m-%dT%H:%i:%s'),\n     lte:sequelize.fn('date_format', endDate, '%Y-%m-%dT%H:%i:%s')\n  }\n)\n```\n\n```text\nfindAll\n```\n\n```text\nlet whereClause = { \n  where: {  $and: [  \n           { time: { [ Op.gte ]: req.query.start_time } },\n           { time: { [ Op.lte ]: req.query.end_time } } \n           ] \n       }\n };\n\n await model_name.findAll(whereClause);\n```\n\n========================================\n\nComments:\n- What happens if you use `psql` to run that exact query?\n- The problem is that sequelize doesn't have the time part. How to add time part to sequelize.\n- `bash Executing (default): SELECT * FROM \"Calls\" WHERE \"EquipmentId\" = :EquipmentId AND \"initDate\" >= :initDate AND \"endDate\" <= :endDate; Possibly unhandled TypeError: Cannot read property '1' of null`\n- I've updated my answer, try adding null as the second parameter, eg. db.sequelize.query(query, null, {raw: true},\n- It is so perfect, I get the calls yeah, mmm in `bash console.log(calls)`\n- Only one more question, Why? Now I get **node console** `bash Executing (default): SELECT * FROM \"Calls\" WHERE \"EquipmentId\" = 1 AND \"initDate\" >= '2015-02-05 19:40:00.000 +00:00' AND \"endDate\" <= '2015-02-05 20:00:00.000 +00:00';` And this is perfect...\n- Yeah it is perfect, but i want to understand really well.\n- If it works, then please mark my answer is correct. Instead of doing string concatenation, I used a parameterized query, and let Sequelize convert the JavaScript Date object to proper PostgresSQL format.\n- say... Votes up requires 15 reputation","metadata":{"transformedAt":"2026-08-18T18:33:34.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":116,"estimatedTokens":916}}989{"id":"stack-26682851","source":"stackoverflow","questionId":26682851,"title":"Create/update with Sequelize on an array of items","tags":["node.js","promise","bluebird","sequelize.js"],"text":"Title: Create/update with Sequelize on an array of items\nTags: node.js, promise, bluebird, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI created a function to:\n\n- take an array of 'labels' and look for whether they have a record in the db already\n\n- create those which don't exist,\n\n- and update those which do exist\n\n- return a json array reporting on each item, whether they were updated/created, or resulted in an error\n\nI managed to make it work but I feel like I just made some ugly dogs' dinner!\n\n```\nvar models = require(\"../models\");\nvar Promise = models.Sequelize.Promise;\n\nmodule.exports = {\n\n addBeans: function (req, callback) {\n\n Promise.map(req.body.beansArr, function (bean) {\n return models.Portfolio.findOrCreate({where: {label: bean}}, {label: bean});\n\n }).then(function (results) { // Array of 'instance' and 'created' for each bean \"findOrCreate(where, [defaults], [options]) -> Promise\"\n var promisesArr = [];\n results.forEach(function (result) {\n if (result[1]) { // result[1] = wasCreated\n promisesArr.push(Promise.resolve([result[0].dataValues.label, \"created\"])); \n } else {\n promisesArr.push(\n models.Portfolio.update({label: result[0].dataValues.label},\n {where: {label: result[0].dataValues.label}}).then(function () {\n return Promise.resolve([result[0].dataValues.label, \"updated\"])\n })\n );\n }\n }); \n return promisesArr;\n\n // When it's all done create a JSON response\n }).then(function (results) {\n var resultObj = {items: []}; // JSON to return at the end\n Promise.settle(results).then(function (promiseinstances) {\n\n for (var i = 0; i Question:\n\n- Is there an easier or more obvious way to create/update values with Sequelize?\n\n- Is my use of `Promise.settle()` appropriate for this case? I have the feeling I made this more complicated than it needs to be.\n\nI am new to Sequelize and using Promises, I'd appreciate if someone could advise on this.\n\n========================================\n\nTop Answer:\nI use Promise.settle for sequelize.update, and can get affect rows number by _settledValueField .\n\n```\npromise.push(...update...)\n\ndb.sequelize.Promise.settle(promise).then(function (allresult) {\n var affectcnt = 0\n allresult.forEach(function (singlecnt) {\n if (undefined !== singlecnt._settledValueField[1]) {\n affectcnt += parseInt(singlecnt._settledValueField[1])\n }\n })\n```\n\nunfortunately, it's only work for update.\n\n========================================\n\nCode:\n```text\nvar models = require(\"../models\");\nvar Promise = models.Sequelize.Promise;\n\nmodule.exports = {\n\n    addBeans: function (req, callback) {\n\n        Promise.map(req.body.beansArr, function (bean) {\n            return models.Portfolio.findOrCreate({where: {label: bean}}, {label: bean});\n\n        }).then(function (results) {   // Array of 'instance' and 'created' for each bean \"findOrCreate(where, [defaults], [options]) -> Promise<Instance>\"\n            var promisesArr = [];\n            results.forEach(function (result) {\n                if (result[1]) {   // result[1] = wasCreated\n                    promisesArr.push(Promise.resolve([result[0].dataValues.label, \"created\"]));   \n                } else {\n                    promisesArr.push(\n                        models.Portfolio.update({label: result[0].dataValues.label},\n                            {where: {label: result[0].dataValues.label}}).then(function () {\n                                return Promise.resolve([result[0].dataValues.label, \"updated\"])\n                            })\n                    );\n                }\n            }); \n            return promisesArr;\n\n        // When it's all done create a JSON response\n        }).then(function (results) {\n            var resultObj = {items: []};  // JSON to return at the end\n            Promise.settle(results).then(function (promiseinstances) {\n\n                for (var i = 0; i < promiseInstances.length; i++) {\n                    if (promiseInstances[i].isFulfilled()) {\n                        resultObj.items.push({\n                            item: {\n                                label: promiseInstances[i].value()[0],\n                                result: promiseInstances[i].value()[1],\n                                error: ''\n                            }\n                        });\n                    }\n                    else if (promiseInstances[i].isRejected()){\n                        resultObj.items.push({\n                            label: promiseInstances[i].value()[0],\n                            result: 'error',\n                            error: promiseInstances[i].reason()\n                        });\n                    }\n                }\n\n            // Send the response back to caller\n            }).then(function () {\n                return callback(null, resultObj);\n            }, function (e) {\n                return callback(e, resultObj);\n            });\n\n        });\n    }\n\n};\n```\n\n```text\nPromise.settle()\n```\n\n```text\n.then(function(array){\n   var newArr = [];\n   array.forEach(function(elem){\n       newArr.push(fn(elem);\n   }\n   return newArr;\n});\n```\n\n```text\n.map(fn)\n```\n\n```text\n).then(function (results) {   // Array of 'instance' and 'created' for each bean \"findOrCreate(where, [defaults], [options]) -> Promise<Instance>\"\n    var promisesArr = [];\n    results.forEach(function (result) {\n        if (result[1]) {   // result[1] = wasCreated\n            promisesArr.push(Promise.resolve([result[0].dataValues.label, \"created\"]));   \n        } else {\n            promisesArr.push(\n                models.Portfolio.update({label: result[0].dataValues.label},\n                    {where: {label: result[0].dataValues.label}}).then(function () {\n                        return Promise.resolve([result[0].dataValues.label, \"updated\"])\n                    })\n            );\n        }\n    }); \n    return promisesArr;\n})\n```\n\n```text\n.map(function(result){\n     if(result[1]) return [result[0].dataValues.label, \"created\"];\n     return  models.Portfolio.update({label: result[0].dataValues.label},\n                    {where: {label: result[0].dataValues.label}}).\n                    return([result[0].dataValues.label, \"updated\"]);\n });\n```\n\n```text\n.then(function(results){\n     return results.map(function(result){\n     if(result[1]) return [result[0].dataValues.label, \"created\"];\n     return  models.Portfolio.update({label: result[0].dataValues.label},\n                    {where: {label: result[0].dataValues.label}}).\n                    return([result[0].dataValues.label, \"updated\"]);\n });\n });\n```\n\n```text\n.settle().then(function(results){\n     // your settle logic here\n});\n```\n\n```text\n}).then(function () {\n    return callback(null, resultObj);\n}, function (e) {\n    return callback(e, resultObj);\n});\n```\n\n```text\n.nodeify(callback);\n```\n\n```text\nreturn val;\n```\n\n```text\n.then\n```\n\n```text\nreturn Promise.resolve(val);\n```\n\n```text\n.settle()\n```\n\n```text\npromise.push(...update...)\n\ndb.sequelize.Promise.settle(promise).then(function (allresult) {\n    var affectcnt = 0\n    allresult.forEach(function (singlecnt) {\n      if (undefined !== singlecnt._settledValueField[1]) {\n        affectcnt += parseInt(singlecnt._settledValueField[1])\n      }\n    })\n```\n\n```text\nlanguage: { type: DataTypes.STRING, \n          allowNull: false,\n          get() \n         { \n         return this.getDataValue('language').split(';') \n         }, \n        set(val)\n        {\n        this.setDataValue('language',Array.isArray(val) ? val.join(','):val);\n\n      }\n  }\n```\n\n========================================\n\nComments:\n- Thanks a million! One question: What do you mean 'promises assimilate'? I though with 'return val;' I pass 'val' as an argument to the function unwrapped with 'then' (e.g.: .then(function(val){}); ), and with 'Promise.resolve(val)' I pass the promise?\n- Promise.resolve will be called implicitly on everything you return in `then`.\n- It looks like partial answer. Please try to consolidate it into complete answer","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":267,"estimatedTokens":1985}}990{"id":"stack-25932144","source":"stackoverflow","questionId":25932144,"title":"Using built-in SQL functions with SequelizeJS","tags":["sql","node.js","sequelize.js"],"text":"Title: Using built-in SQL functions with SequelizeJS\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nCan I make Sequelize JS to include combined field to the result set, to get results like for following query?\n\n```\nSELECT id, NOW()-timestamp as recordAge FROM myTable\n```\n\nI wouldn't use raw query for this task, prefer to resolve it with model paradigm.\n\n========================================\n\nCode:\n```text\nSELECT id, NOW()-timestamp as recordAge FROM myTable\n```\n\n```text\noptions = {};\noptions.attributes = ['id', sequelize.literal('(NOW() - timestamp) as recordAge')];\nMyTable.find(options).success(success);\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":25,"estimatedTokens":160}}991{"id":"stack-25870760","source":"stackoverflow","questionId":25870760,"title":"Many-to-Many: sequelize doesn't create methods","tags":["mysql","database","node.js","sequelize.js"],"text":"Title: Many-to-Many: sequelize doesn't create methods\nTags: mysql, database, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nConsider two models `User` and `Project` with the relation Many-To-Many.\n\nWhen I try this: `db.User.getProjects()` I get an error \n\n TypeError: Object [object Object] has no method 'getProjects()'\n\nI've read in the docs this method should be generated automatically\n\nSo why I get this error?\n\n### Source Code:\n\nproject.js\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var Project = sequelize.define('Project', {\n name: DataTypes.STRING\n }, {\n classMethods: {\n associate: function(models) {\n Project.hasMany(models.User);\n }\n }\n })\n\n return Project\n}\n```\n\nuser.js \n\n```\nmodule.exports = function(sequelize, DataTypes) {\n var User = sequelize.define('User', {}, {\n classMethods: {\n associate: function(models) {\n User.hasMany(models.Project),\n User.belongsTo(models.Boss, {\n foreignKey: 'user_id'\n })\n }\n }\n })\n\n return User\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var Project = sequelize.define('Project', {\n        name: DataTypes.STRING\n    }, {\n        classMethods: {\n            associate: function(models) {\n                Project.hasMany(models.User);\n            }\n        }\n    })\n\n    return Project\n}\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n    var User = sequelize.define('User', {}, {\n        classMethods: {\n            associate: function(models) {\n                User.hasMany(models.Project),\n                User.belongsTo(models.Boss, {\n                    foreignKey: 'user_id'\n                })\n            }\n        }\n    })\n\n    return User\n}\n```\n\n```text\nUser\n```\n\n```text\nProject\n```\n\n```text\ndb.User.getProjects()\n```\n\n```text\ndb.User\n    .find( {where: {user_id: user_id}} )\n    .then(function(user) {\n        return user.getProjects();\n    })\n    .then(function(projects) {\n        //do something with your projects DAO\n    })\n    .catch(function(err) {});\n```\n\n```text\ndb.User.find\n```\n\n========================================\n\nComments:\n- Can you add your model code?","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":122,"estimatedTokens":536}}992{"id":"stack-74302443","source":"stackoverflow","questionId":74302443,"title":"How to add sequelize getter to model object?","tags":["typescript","sequelize.js","sequelize-typescript"],"text":"Title: How to add sequelize getter to model object?\nTags: typescript, sequelize.js, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI would like to add getter to **name** field of the Company model object.\ntried several things but no luck.\nUnable to find a proper example as well.\nSequelize version is 5.21.\nWould it be inside decorator or somewhere else?\nTrimmed code for clarity.\nAny help is appreciated\n\n```\nexport default class Company extends Model {\n @PrimaryKey\n @Default(DataType.UUIDV4)\n @Column(DataType.UUID)\n id: string;\n \n @Default(DataType.NOW)\n @Column\n created_at: Date;\n \n @Default(0)\n @Column\n deleted_at: Date;\n \n @AllowNull(false)\n @Column(DataType.STRING(25))\n name: string;\n \n @Default(true)\n @Column\n active: boolean;\n \n \n }\n```\n\n========================================\n\nCode:\n```text\nexport default class Company extends Model<Company> {\n      @PrimaryKey\n      @Default(DataType.UUIDV4)\n      @Column(DataType.UUID)\n      id: string;\n    \n      @Default(DataType.NOW)\n      @Column\n      created_at: Date;\n    \n      @Default(0)\n      @Column\n      deleted_at: Date;\n    \n      @AllowNull(false)\n      @Column(DataType.STRING(25))\n      name: string;\n    \n      @Default(true)\n      @Column\n      active: boolean;\n    \n      \n    }\n```\n\n```js\n@Table({ modelName: 'application' })\nexport class Application extends Model<Application> {\n\n  @Column(DataType.VIRTUAL(DataType.STRING))\n  get clientSecret(): string {\n    return this.getDataValue('clientSecret')\n  }\n\n  set clientSecret(value: string) {\n    this.setDataValue('clientSecret', value)\n  }\n}\n```\n\n```text\nVIRTUAL\n```\n\n========================================\n\nComments:\n- Look at github.com/sequelize/sequelize-typescript/issues/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":93,"estimatedTokens":432}}993{"id":"stack-70444388","source":"stackoverflow","questionId":70444388,"title":"How to create this tsvector generated always as column with sequelize?","tags":["postgresql","sequelize.js","full-text-search","tsvector"],"text":"Title: How to create this tsvector generated always as column with sequelize?\nTags: postgresql, sequelize.js, full-text-search, tsvector\nSource: Stack Overflow\n\nQuestion:\nI see that sequelize has DataTypes.TSVECTOR for postgres dialect.\nI have a column whose definition in raw SQL is as follows\n\n```\ntsvector GENERATED ALWAYS AS (((\nsetweight(to_tsvector('english'::regconfig, (COALESCE(title, ''::character varying))::text), 'A'::\"char\") || \nsetweight(to_tsvector('english'::regconfig, COALESCE(summary, ''::text)), 'B'::\"char\")) || \nsetweight(to_tsvector('english'::regconfig, (COALESCE(content, ''::character varying))::text), 'C'::\"char\"))) \nSTORED\n```\n\nHow can I define this in my sequelize model\n\n```\nconst FeedItem = sequelize.define(\n 'FeedItem', {\n feedItemId: {\n type: DataTypes.UUID,\n primaryKey: true,\n allowNull: false,\n defaultValue: DataTypes.UUIDV4,\n },\n pubdate: {\n type: DataTypes.DATE,\n allowNull: false,\n defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),\n validate: {\n isDate: true,\n },\n },\n link: {\n type: DataTypes.STRING,\n allowNull: false,\n validate: {\n len: [0, 2047],\n },\n },\n guid: {\n type: DataTypes.STRING,\n validate: {\n len: [0, 2047],\n },\n },\n title: {\n type: DataTypes.TEXT,\n allowNull: false,\n validate: {\n len: [0, 65535],\n },\n },\n summary: {\n type: DataTypes.TEXT,\n validate: {\n len: [0, 65535],\n },\n },\n content: {\n type: DataTypes.TEXT,\n validate: {\n len: [0, 1048575],\n },\n },\n author: {\n type: DataTypes.STRING,\n validate: {\n len: [0, 63],\n },\n },\n tags: {\n type: DataTypes.ARRAY(DataTypes.STRING),\n defaultValue: [],\n },\n // How to do that generated always part here???\n searchable: {\n type: DataTypes.TSVECTOR\n },\n }, {\n timestamps: false,\n underscored: true,\n indexes: [\n {\n name: 'idx_feed_items_searchable',\n fields: ['searchable'],\n using: 'gin',\n },\n ],\n }\n );\n```\n\n========================================\n\nCode:\n```text\ntsvector GENERATED ALWAYS AS (((\nsetweight(to_tsvector('english'::regconfig, (COALESCE(title, ''::character varying))::text), 'A'::\"char\") || \nsetweight(to_tsvector('english'::regconfig, COALESCE(summary, ''::text)), 'B'::\"char\")) || \nsetweight(to_tsvector('english'::regconfig, (COALESCE(content, ''::character varying))::text), 'C'::\"char\"))) \nSTORED\n```\n\n```text\nconst FeedItem = sequelize.define(\n    'FeedItem', {\n        feedItemId: {\n            type: DataTypes.UUID,\n            primaryKey: true,\n            allowNull: false,\n            defaultValue: DataTypes.UUIDV4,\n        },\n        pubdate: {\n            type: DataTypes.DATE,\n            allowNull: false,\n            defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),\n            validate: {\n                isDate: true,\n            },\n        },\n        link: {\n            type: DataTypes.STRING,\n            allowNull: false,\n            validate: {\n                len: [0, 2047],\n            },\n        },\n        guid: {\n            type: DataTypes.STRING,\n            validate: {\n                len: [0, 2047],\n            },\n        },\n        title: {\n            type: DataTypes.TEXT,\n            allowNull: false,\n            validate: {\n                len: [0, 65535],\n            },\n        },\n        summary: {\n            type: DataTypes.TEXT,\n            validate: {\n                len: [0, 65535],\n            },\n        },\n        content: {\n            type: DataTypes.TEXT,\n            validate: {\n                len: [0, 1048575],\n            },\n        },\n        author: {\n            type: DataTypes.STRING,\n            validate: {\n                len: [0, 63],\n            },\n        },\n        tags: {\n            type: DataTypes.ARRAY(DataTypes.STRING),\n            defaultValue: [],\n        },\n        // How to do that generated always part here???\n        searchable: {\n            type: DataTypes.TSVECTOR\n        },\n    }, {\n        timestamps: false,\n        underscored: true,\n        indexes: [\n            {\n                name: 'idx_feed_items_searchable',\n                fields: ['searchable'],\n                using: 'gin',\n            },\n        ],\n    }\n  );\n```\n\n```text\nconst FeedItem = sequelize.define(\n    'FeedItem',\n    {\n      feedItemId: {\n        type: DataTypes.UUID,\n        primaryKey: true,\n        allowNull: false,\n        defaultValue: DataTypes.UUIDV4,\n      },\n      pubdate: {\n        type: DataTypes.DATE,\n        allowNull: false,\n        defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),\n        validate: {\n          isDate: true,\n        },\n      },\n      link: {\n        type: DataTypes.STRING,\n        allowNull: false,\n        validate: {\n          len: [0, 2047],\n        },\n      },\n      guid: {\n        type: DataTypes.STRING,\n        validate: {\n          len: [0, 2047],\n        },\n      },\n      title: {\n        type: DataTypes.TEXT,\n        allowNull: false,\n        validate: {\n          len: [0, 65535],\n        },\n      },\n      summary: {\n        type: DataTypes.TEXT,\n        validate: {\n          len: [0, 65535],\n        },\n      },\n      content: {\n        type: DataTypes.TEXT,\n        validate: {\n          len: [0, 1048575],\n        },\n      },\n      author: {\n        type: DataTypes.STRING,\n        validate: {\n          len: [0, 63],\n        },\n      },\n      tags: {\n        type: DataTypes.ARRAY(DataTypes.STRING),\n        defaultValue: [],\n      },\n      // https://stackoverflow.com/questions/67051281/use-postgres-generated-columns-in-sequelize-model\n      searchable: {\n        type: `tsvector GENERATED ALWAYS AS (((setweight(to_tsvector('english'::regconfig, (COALESCE(title, ''::character varying))::text), 'A'::\"char\") || setweight(to_tsvector('english'::regconfig, COALESCE(summary, ''::text)), 'B'::\"char\")) || setweight(to_tsvector('english'::regconfig, (COALESCE(content, ''::character varying))::text), 'C'::\"char\"))) STORED`,\n        set() {\n          throw new Error('generatedValue is read-only');\n        },\n      },\n    },\n    {\n      timestamps: false,\n      underscored: true,\n      indexes: [\n        {\n          name: 'idx_feed_items_pubdate_feed_item_id_desc',\n          fields: [\n            { attribute: 'pubdate', order: 'DESC' },\n            { attribute: 'feed_item_id', order: 'DESC' },\n          ],\n        },\n        {\n          name: 'idx_feed_items_tags',\n          fields: ['tags'],\n          using: 'gin',\n        },\n        {\n          name: 'idx_feed_items_searchable',\n          fields: ['searchable'],\n          using: 'gin',\n        },\n      ],\n    }\n  );\n```\n\n========================================\n\nComments:\n- thanks for sharing your solution. This is very useful, as many people are looking to use FTS with Sequelize and NodeJS. I was wondering if you would also be OK to the resolver (or some source code) ? This is to understand how you do the research. This would be very appreciated. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":281,"estimatedTokens":1697}}994{"id":"stack-66698322","source":"stackoverflow","questionId":66698322,"title":"Mock sequelize with Jest and sequelize-mock","tags":["javascript","node.js","unit-testing","sequelize.js","supertest"],"text":"Title: Mock sequelize with Jest and sequelize-mock\nTags: javascript, node.js, unit-testing, sequelize.js, supertest\nSource: Stack Overflow\n\nQuestion:\nI'm building a new project and I'm trying to use TDD as my default methodology and trying to apply it with integration test.\n\nThe thing is easy I want to retrieve all the users from my DB.\n\n```\n//controller.js\nconst UserService = require('../services/user');\n\nmodule.exports = {\n // corresponds to /users\n getAllUsers: async (req, res, next) => {\n const users = await UserService.fetchAllUsers();\n res.send(users);\n },\n};\n```\n\n```\nconst models = require('../database/models/index'); // I tried also with destructuring\n\nmodule.exports = {\n fetchAllUsers: async () => models.user.findAll(),\n};\n```\n\nand my actual test file looks like\n\n```\nconst request = require('supertest');\n\nconst SequelizeMock = require('sequelize-mock');\nconst app = require('..');\n\nconst dbMock = new SequelizeMock();\nconst models = require('../src/database/models/index');\n\njest.mock('../src/database/models/index', () => ({\n user: jest.fn(),\n}));\n\nmodels.user.mockImplementation(() => {\n const UserMock = dbMock.define('user', {});\n UserMock.$queueResult(UserMock.build({\n username: 'username',\n mail: 'myMail@myMail.com',\n }));\n return UserMock;\n});\n\ndescribe('Demo test', () => {\n it('should respond to users route', (done) => {\n request(app)\n .get('/users')\n .end((err, res) => {\n expect(err).toBeNull();\n expect(res.status).toBe(200);\n expect(res.json).toBe('object');\n done();\n });\n });\n});\n```\n\nAll of this is actually working but when I'm trying to mock the user I `TypeError: models.user.findAll is not a function`\n\nI need to replace the model.user with the UserMock's value.\n\nIs there anyway to do this? or I should just mock findAll like\n\n```\njest.mock('../src/database/models/index', () => ({\n user: () => ({ findAll: jest.fn() }),\n}));\n\n``\n```\n\n========================================\n\nCode:\n```text\n//controller.js\nconst UserService = require('../services/user');\n\nmodule.exports = {\n  // corresponds to /users\n  getAllUsers: async (req, res, next) => {\n    const users = await UserService.fetchAllUsers();\n    res.send(users);\n  },\n};\n```\n\n```text\nconst models = require('../database/models/index'); // I tried also with destructuring\n\nmodule.exports = {\n  fetchAllUsers: async () => models.user.findAll(),\n};\n```\n\n```js\nconst request = require('supertest');\n\nconst SequelizeMock = require('sequelize-mock');\nconst app = require('..');\n\nconst dbMock = new SequelizeMock();\nconst models = require('../src/database/models/index');\n\njest.mock('../src/database/models/index', () => ({\n  user: jest.fn(),\n}));\n\nmodels.user.mockImplementation(() => {\n  const UserMock = dbMock.define('user', {});\n  UserMock.$queueResult(UserMock.build({\n    username: 'username',\n    mail: 'myMail@myMail.com',\n  }));\n  return UserMock;\n});\n\ndescribe('Demo test', () => {\n  it('should respond to users route', (done) => {\n    request(app)\n      .get('/users')\n      .end((err, res) => {\n        expect(err).toBeNull();\n        expect(res.status).toBe(200);\n        expect(res.json).toBe('object');\n        done();\n      });\n  });\n});\n```\n\n```text\njest.mock('../src/database/models/index', () => ({\n  user: () => ({ findAll: jest.fn() }),\n}));\n\n``\n```\n\n```text\nTypeError: models.user.findAll is not a function\n```\n\n```text\nconst { sequelize, Report, User } = require('../../database/models/index');\n\n\ndescribe(\"my test\", () => {\n    it(\"should just mock\", () => {\n        jest.SpyOn(Report, \"count\").mockResolvedOnce(6);\n    })\n})\n```\n\n```text\nconst BaseService = require('../BaseService');\nconst mockFecthOne = jest.fn();\n```\n\n```text\njest.mock('../BaseService',\n  () => jest.fn().mockImplementation(\n    () => ({\n      fetchOne: mockFetchOne,\n    }),\n  ));\n\n// inside your test just\n\nBaseService().fetchOne.mockResolvedOnce({....})\n```\n\n```text\nSpyOn\n```\n\n========================================\n\nComments:\n- Were you able to find a solution for this? I am running into the same issue.\n- Yes, let me write the solution for you.\n- So grateful that you posted your solution, thanks a lot!","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":193,"estimatedTokens":1026}}995{"id":"stack-77741037","source":"stackoverflow","questionId":77741037,"title":"Can't connect AWS RDS using sequelize","tags":["node.js","postgresql","amazon-web-services","sequelize.js"],"text":"Title: Can't connect AWS RDS using sequelize\nTags: node.js, postgresql, amazon-web-services, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen I use this code, I can connect successfully to my AWS RDS postgre\n\n```\nimport pg from \"pg\";\nimport dotenv from \"dotenv\";\n\ndotenv.config();\n\n(async () => {\n try {\n const client = new pg.Client({\n host: process.env.PG_HOST,\n port: process.env.PG_PORT,\n user: process.env.PG_USER,\n password: process.env.PG_PASSWORD,\n database: process.env.PG_DATABASE,\n ssl: true,\n });\n\n await client.connect();\n const res = await client.query(\"SELECT $1::text as connected\", [\n \"Connection to postgres successful!\",\n ]);\n console.log(res.rows[0].connected);\n await client.end();\n } catch (error) {\n console.error(\"Error occurred:\", error);\n }\n})();\n```\n\nBut now I want to use sequelize and I try this code\n\n```\nimport \"dotenv/config.js\";\nimport Sequelize from \"sequelize\";\n\nconst dbConfig = {\n HOST: process.env.PG_HOST,\n USER: process.env.PG_USER,\n PASSWORD: process.env.PG_PASSWORD + \"\",\n DB: process.env.PG_DATABASE,\n PORT: process.env.PG_PORT, \n dialect: \"postgres\",\n // ssl: true,\n ssl: {\n rejectUnauthorized: false,\n },\n};\n\nconsole.log(dbConfig.USER);\n\nconst sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {\n host: dbConfig.HOST,\n port: dbConfig.PORT, \n dialect: dbConfig.dialect,\n});\n\nconst db = {};\n\ndb.Sequelize = Sequelize;\ndb.sequelize = sequelize;\n\nexport default db;\n```\n\nI got errors:\n\n```\nCannot connect to the database! ConnectionError [SequelizeConnectionError]: no pg_hba.conf entry for host \"118.70.42.38\", user \"postgres\", database \"My_first\", no encryption\n```\n\nand\n\noriginal: error:\n\n```\nno pg_hba.conf entry for host \"118.70.42.38\", user \"postgres\", database \"My_first\", no encryption\n```\n\n.\n\nI'm not sure why this happens. Maybe there is a problem with Sequelize? Any support would be appreciated.\n\n========================================\n\nTop Answer:\nThis is not a conclusive answer, but i will add for other people in the future, i've been experiencing the same error, but a comment was given that helps tremendously.\n\ndialect options are found here in the sequelize docs, but they are not a complete list:\n\nhttps://sequelize.org/docs/v6/other-topics/dialect-specific-things/#postgresql\n\nsequelize depends on an underlying library PG for postgres, which has these options:\nhttps://node-postgres.com/features/ssl\n\nthe dialect options belong to a node library found here, with more dialect options: https://nodejs.org/api/tls.html#tls_class_tls_tlssocket\n\nthe ones most commonly seen in examples found online are found here:\nhttps://nodejs.org/api/tls.html#tlscreatesecurecontextoptions\n\nthese 4 links provide 100% of the context for dialect options\n\n========================================\n\nCode:\n```text\nimport pg from \"pg\";\nimport dotenv from \"dotenv\";\n\ndotenv.config();\n\n(async () => {\n  try {\n    const client = new pg.Client({\n      host: process.env.PG_HOST,\n      port: process.env.PG_PORT,\n      user: process.env.PG_USER,\n      password: process.env.PG_PASSWORD,\n      database: process.env.PG_DATABASE,\n      ssl: true,\n    });\n\n    await client.connect();\n    const res = await client.query(\"SELECT $1::text as connected\", [\n      \"Connection to postgres successful!\",\n    ]);\n    console.log(res.rows[0].connected);\n    await client.end();\n  } catch (error) {\n    console.error(\"Error occurred:\", error);\n  }\n})();\n```\n\n```text\nimport \"dotenv/config.js\";\nimport Sequelize from \"sequelize\";\n\nconst dbConfig = {\n  HOST: process.env.PG_HOST,\n  USER: process.env.PG_USER,\n  PASSWORD: process.env.PG_PASSWORD + \"\",\n  DB: process.env.PG_DATABASE,\n  PORT: process.env.PG_PORT, \n  dialect: \"postgres\",\n  // ssl: true,\n  ssl: {\n    rejectUnauthorized: false,\n  },\n};\n\nconsole.log(dbConfig.USER);\n\nconst sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {\n  host: dbConfig.HOST,\n  port: dbConfig.PORT, \n  dialect: dbConfig.dialect,\n});\n\nconst db = {};\n\ndb.Sequelize = Sequelize;\ndb.sequelize = sequelize;\n\nexport default db;\n```\n\n```text\nCannot connect to the database! ConnectionError [SequelizeConnectionError]: no pg_hba.conf entry for host \"118.70.42.38\", user \"postgres\", database \"My_first\", no encryption\n```\n\n```text\nno pg_hba.conf entry for host \"118.70.42.38\", user \"postgres\", database \"My_first\", no encryption\n```\n\n```js\nconst sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {\n  host: dbConfig.HOST,\n  port: dbConfig.PORT, \n  dialect: dbConfig.dialect,\n  dialectOptions: { //< Add this\n     ssl: {\n        require: true,\n        rejectUnauthorized: false\n     }\n  }\n});\n```\n\n```text\ndialectOptions\n```\n\n```text\ndbConfig\n```\n\n========================================\n\nComments:\n- The error is saying that, for some reason, SSL is turned off -- even though you appear to have requested that it be turned on. I frequently see this error when SSL is False. So, your mission is to figure out how to get it to set SSL to True. This *might* help: How to connect via SSL to sequelize DB or even: How to configure sequalize & node mysql to use new aws rds root cert rds-ca-2019","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":207,"estimatedTokens":1278}}996{"id":"stack-39151050","source":"stackoverflow","questionId":39151050,"title":"Sequelize and Feathers: When Relationships Fall Apart","tags":["node.js","postgresql","sequelize.js","feathersjs","vorpal.js"],"text":"Title: Sequelize and Feathers: When Relationships Fall Apart\nTags: node.js, postgresql, sequelize.js, feathersjs, vorpal.js\nSource: Stack Overflow\n\nQuestion:\nAfter two days of trying to figure out why my Sequelize models aren't committed to their relationships, I've decided it was time to ask y'all for advice.\n\nHere's the story.\n\nI'm writing a Feathers JS app using a Postgres (9.4) database with Sequelize as the driver. I ran through the setup in the Feathers Docs, and with some coaxing, I got my migrations to run.\n\nFrom what I understand, special consideration must be taken to get two-way relations working with Sequelize because if `ModelA` references `ModelB`, `ModelB` must be defined already, but if `ModelB` references `ModelA`...well, we run into a dependency loop.\n\nIt's because of that dependency loop that the docs say to \"define your models using the method described here.\" (Okay, technically it just \"assumes\" such a structure is used. Also, I can only post 2 links, otherwise I'd link that sucker. Sorry about that.) I've found the same structure in a Feathers demo.\n\nNaturally, I mirrored all of that (unless I'm missing a small-but-important detail, of course), but...still no dice.\n\nHere's what I'm looking at:\n\n### Migrations\n\n### migrations/create-accounts.js\n\n```\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n // Make the accounts table if it doesn't already exist.\n // \"If it doesn't already exist\" because we have the previous migrations\n // from Laravel.\n return queryInterface.showAllTables().then(function(tableNames) {\n if (tableNames.accounts === undefined) {\n queryInterface.createTable('accounts', {\n // Field definitions here\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n name: Sequelize.STRING,\n url_name: Sequelize.STRING,\n createdAt: {\n type: Sequelize.DATE,\n allowNull: false\n },\n updatedAt: {\n type: Sequelize.DATE,\n allowNull: false\n },\n deletedAt: Sequelize.DATE\n });\n }\n });\n\n // See the create-user migration for an explanation of why I\n // commented out the above code.\n },\n\n down: function (queryInterface, Sequelize) {\n return queryInterface.dropTable('accounts');\n }\n};\n```\n\n### migrations/create-users.js\n\n```\n'use strict';\n\nmodule.exports = {\n up: function (queryInterface, Sequelize) {\n return queryInterface.showAllTables().then(function(tableNames) {\n if (tableNames.users === undefined) {\n queryInterface.createTable('users', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n accountId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'accounts',\n key: 'id'\n },\n allowNull: false\n },\n email: {\n type: Sequelize.STRING,\n allowNull: false\n },\n [...]\n });\n }\n });\n },\n\n down: function (queryInterface, Sequelize) {\n return queryInterface.dropTable('users');\n }\n};\n```\n\n### psql\n\nI then fired up psql to see if the references were right:\n\n`databaseName=# \\d accounts`:\n\n```\nReferenced by:\n TABLE \"users\" CONSTRAINT \"users_accountId_fkey\" FOREIGN KEY (\"accountId\") REFERENCES accounts(id)\n```\n\n`databaseName=# \\d users`:\n\n```\nForeign-key constraints:\n \"users_accountId_fkey\" FOREIGN KEY (\"accountId\") REFERENCES accounts(id)\n```\n\nSo far so good, right?\n\nLet's look at the models segment of this program!\n\n### Models\n\n### src/models/account.js\n\n```\n'use strict';\n\n// account-model.js - A sequelize model\n//\n// See http://docs.sequelizejs.com/en/latest/docs/models-definition/\n// for more of what you can do here.\n\nconst Sequelize = require('sequelize');\n\nmodule.exports = function(app) {\n // We assume we're being called from app.configure();\n // If we're not, though, we need to be passed the app instance.\n // Fair warning: I added this bit myself, so it's suspect.\n if (app === undefined)\n app = this;\n const sequelize = app.get('sequelize');\n\n // The rest of this is taken pretty much verbatim from the examples\n const account = sequelize.define('account', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n name: Sequelize.STRING,\n url_name: Sequelize.STRING,\n }, {\n paranoid: true,\n timestamps: true,\n\n classMethods: {\n associate() {\n const models = app.get('models');\n this.hasMany(models['user'], {});\n }\n }\n });\n\n return account;\n};\n```\n\n### src/models/user.js\n\n```\n'use strict';\n\n// user-model.js - A sequelize model\n//\n// See http://docs.sequelizejs.com/en/latest/docs/models-definition/\n// for more of what you can do here.\n\nconst Sequelize = require('sequelize');\n\nmodule.exports = function(app) {\n // We assume we're being called from app.configure();\n // If we're not, though, we need to be passed the app instance\n if (app === undefined)\n app = this;\n const sequelize = app.get('sequelize');\n\n const user = sequelize.define('user', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n accountId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'accounts', // Table name...is that right? Made the migration work...\n key: 'id'\n }\n },\n email: Sequelize.STRING,\n [... curtailed for brevity ...]\n }, {\n // Are these necessary here, or just when defining the model to make a\n // psuedo-migration?\n paranoid: true, // soft deletes\n timestamps: true,\n\n classMethods: {\n associate() {\n const models = app.get('models');\n // This outputs like I'd expect:\n // Just to be sure...From the user model, models[\"account\"]: account\n console.log('Just to be sure...From the user model, models[\"account\"]:', models['account']);\n this.belongsTo(models['account'], {});\n }\n }\n });\n\n return user;\n};\n```\n\n### src/models/index.js\n\n```\n// I blatantly ripped this from both the following:\n// https://github.com/feathersjs/generator-feathers/issues/94#issuecomment-204165134\n// https://github.com/feathersjs/feathers-demos/blob/master/examples/migrations/sequelize/src/models/index.js\n\nconst Sequelize = require('sequelize');\nconst _ = require('lodash');\n\n// Import the models\nconst account = require('./account');\nconst user = require('./user');\n\nmodule.exports = function () {\n const app = this;\n\n // Note: 'postgres' is found in config/default.json as the db url\n const sequelize = new Sequelize(app.get('postgres'), {\n dialect: app.get('db_dialect'),\n logging: console.log\n });\n app.set('sequelize', sequelize);\n\n // Configure the models\n app.configure(account);\n app.configure(user);\n\n app.set('models', sequelize.models);\n\n // Set associations\n Object.keys(sequelize.models).forEach(modelName => {\n if ('associate' in sequelize.models[modelName]) {\n sequelize.models[modelName].associate();\n }\n });\n\n sequelize.sync();\n\n // Extra credit: Check to make sure the two instances of sequelize.models are the same...\n // Outputs: sequelize.models after sync === app.get(\"models\")\n // I've also run this comparison on sequelize and app.get('sequelize'); _.eq() said they also were identical\n if (_.eq(sequelize.models, app.get('models')))\n console.log('sequelize.models after sync === app.get(\"models\")');\n else\n console.log('sequelize.models after sync !== app.get(\"models\")');\n};\n```\n\n### Pulling it Together\n\n### src/app.js\n\nCutting a lot out of it for brevity, I load the models in `app` like so:\n\n```\nconst models = require('./models')\napp.use(compress())\n // Lots of other statements\n .configure(models);\n```\n\n### Testing\n\nI've been trying to make a command line utility for changing passwords, modifying user permissions and other utility tasks, so I've taken up Vorpal (again, only 2 links, so you'll have to look it up yourself if you're not familiar--sorry). The following is the relevant snippet of my Vorpal program:\n\n### cli.js\n\n```\nconst vorpal = require('vorpal')();\nconst _ = require('lodash');\n\n// Initialize app\n// This seems a bit overkill since we don't need the server bit for this, but...\nconst app = require('./src/app');\nconst models = app.get('models');\n\n// Get the models for easy access...\nconst User = models['user'];\nconst Account = models['account'];\n\n// Run by issuing the command: node cli test\n// Outputs to terminal\nvorpal.command('test', 'A playground for testing the Vorpal environment.')\n .action(function(args, callback) {\n // User.belongsTo(Account); // {\n console.log(\"user.account.name:\", user.account.name);\n });\n });\n\nvorpal.show().parse(process.argv);\n```\n\n### The Problem\n\nSorry it's taken so long to get here, but I don't know which part of this is the relevant part, so I had to vomit it all up.\n\nRunning `node cli test` gives me an error\n\n```\nJust to be sure...From the user model, models[\"account\"]: account\nsequelize.models after sync === app.get(\"models\")\nconnect: \nUnhandled rejection Error: account is not associated to user!\n at validateIncludedElement (/vagrant/node_modules/sequelize/lib/model.js:550:11)\n at /vagrant/node_modules/sequelize/lib/model.js:432:29\n at Array.map (native)\n at validateIncludedElements (/vagrant/node_modules/sequelize/lib/model.js:428:37)\n at . (/vagrant/node_modules/sequelize/lib/model.js:1364:32)\n at tryCatcher (/vagrant/node_modules/bluebird/js/release/util.js:16:23)\n at Promise._settlePromiseFromHandler (/vagrant/node_modules/bluebird/js/release/promise.js:504:31)\n at Promise._settlePromise (/vagrant/node_modules/bluebird/js/release/promise.js:561:18)\n at Promise._settlePromise0 (/vagrant/node_modules/bluebird/js/release/promise.js:606:10)\n at Promise._settlePromises (/vagrant/node_modules/bluebird/js/release/promise.js:685:18)\n at Async._drainQueue (/vagrant/node_modules/bluebird/js/release/async.js:138:16)\n at Async._drainQueues (/vagrant/node_modules/bluebird/js/release/async.js:148:10)\n at Immediate.Async.drainQueues (/vagrant/node_modules/bluebird/js/release/async.js:17:14)\n at runCallback (timers.js:574:20)\n at tryOnImmediate (timers.js:554:5)\n at processImmediate [as _immediateCallback] (timers.js:533:5)\n```\n\n*Agh!*\n\nIf, however, I uncomment the line right above the `User.findOne()`, it works like a charm.\n\nWhy do I have to explicitly set the relation **immediately** before querying for the relation? Why is the relation (presumably) established in the user model's associate() method not sticking? It's being called--and on the proper model, as far as I can tell. Is it somehow being overridden? Is `app`, for some bizarre reason, not the same in the user model when it's making the association as it is in `cli.js`?\n\nI'm really quite baffled. Any help y'all can give is much, much appreciated.\n\n========================================\n\nCode:\n```text\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    // Make the accounts table if it doesn't already exist.\n    // \"If it doesn't already exist\" because we have the previous migrations\n    //  from Laravel.\n    return queryInterface.showAllTables().then(function(tableNames) {\n      if (tableNames.accounts === undefined) {\n        queryInterface.createTable('accounts', {\n          // Field definitions here\n          id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n          },\n          name: Sequelize.STRING,\n          url_name: Sequelize.STRING,\n          createdAt: {\n            type: Sequelize.DATE,\n            allowNull: false\n          },\n          updatedAt: {\n            type: Sequelize.DATE,\n            allowNull: false\n          },\n          deletedAt: Sequelize.DATE\n        });\n      }\n    });\n\n    // See the create-user migration for an explanation of why I\n    //  commented out the above code.\n  },\n\n  down: function (queryInterface, Sequelize) {\n    return queryInterface.dropTable('accounts');\n  }\n};\n```\n\n```text\n'use strict';\n\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return queryInterface.showAllTables().then(function(tableNames) {\n      if (tableNames.users === undefined) {\n        queryInterface.createTable('users', {\n          id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n          },\n          accountId: {\n            type: Sequelize.INTEGER,\n            references: {\n              model: 'accounts',\n              key: 'id'\n            },\n            allowNull: false\n          },\n          email: {\n            type: Sequelize.STRING,\n            allowNull: false\n          },\n          [...]\n        });\n      }\n    });\n  },\n\n  down: function (queryInterface, Sequelize) {\n    return queryInterface.dropTable('users');\n  }\n};\n```\n\n```text\nReferenced by:\n    TABLE \"users\" CONSTRAINT \"users_accountId_fkey\" FOREIGN KEY (\"accountId\") REFERENCES accounts(id)\n```\n\n```text\nForeign-key constraints:\n    \"users_accountId_fkey\" FOREIGN KEY (\"accountId\") REFERENCES accounts(id)\n```\n\n```text\n'use strict';\n\n// account-model.js - A sequelize model\n//\n// See http://docs.sequelizejs.com/en/latest/docs/models-definition/\n// for more of what you can do here.\n\nconst Sequelize = require('sequelize');\n\nmodule.exports = function(app) {\n  // We assume we're being called from app.configure();\n  // If we're not, though, we need to be passed the app instance.\n  // Fair warning: I added this bit myself, so it's suspect.\n  if (app === undefined)\n    app = this;\n  const sequelize = app.get('sequelize');\n\n  // The rest of this is taken pretty much verbatim from the examples\n  const account = sequelize.define('account', {\n    id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: Sequelize.STRING,\n    url_name: Sequelize.STRING,\n  }, {\n    paranoid: true,\n    timestamps: true,\n\n    classMethods: {\n      associate() {\n        const models = app.get('models');\n        this.hasMany(models['user'], {});\n      }\n    }\n  });\n\n  return account;\n};\n```\n\n```text\n'use strict';\n\n// user-model.js - A sequelize model\n//\n// See http://docs.sequelizejs.com/en/latest/docs/models-definition/\n// for more of what you can do here.\n\nconst Sequelize = require('sequelize');\n\nmodule.exports = function(app) {\n  // We assume we're being called from app.configure();\n  // If we're not, though, we need to be passed the app instance\n  if (app === undefined)\n    app = this;\n  const sequelize = app.get('sequelize');\n\n  const user = sequelize.define('user', {\n    id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    accountId: {\n      type: Sequelize.INTEGER,\n      references: {\n        model: 'accounts', // Table name...is that right? Made the migration work...\n        key: 'id'\n      }\n    },\n    email: Sequelize.STRING,\n    [... curtailed for brevity ...]\n  }, {\n    // Are these necessary here, or just when defining the model to make a\n    //  psuedo-migration?\n    paranoid: true, // soft deletes\n    timestamps: true,\n\n    classMethods: {\n      associate() {\n        const models = app.get('models');\n        // This outputs like I'd expect:\n        // Just to be sure...From the user model, models[\"account\"]: account\n        console.log('Just to be sure...From the user model, models[\"account\"]:', models['account']);\n        this.belongsTo(models['account'], {});\n      }\n    }\n  });\n\n  return user;\n};\n```\n\n```text\n// I blatantly ripped this from both the following:\n// https://github.com/feathersjs/generator-feathers/issues/94#issuecomment-204165134\n// https://github.com/feathersjs/feathers-demos/blob/master/examples/migrations/sequelize/src/models/index.js\n\nconst Sequelize = require('sequelize');\nconst _ = require('lodash');\n\n// Import the models\nconst account = require('./account');\nconst user = require('./user');\n\nmodule.exports = function () {\n  const app = this;\n\n  // Note: 'postgres' is found in config/default.json as the db url\n  const sequelize = new Sequelize(app.get('postgres'), {\n    dialect: app.get('db_dialect'),\n    logging: console.log\n  });\n  app.set('sequelize', sequelize);\n\n  // Configure the models\n  app.configure(account);\n  app.configure(user);\n\n  app.set('models', sequelize.models);\n\n  // Set associations\n  Object.keys(sequelize.models).forEach(modelName => {\n    if ('associate' in sequelize.models[modelName]) {\n      sequelize.models[modelName].associate();\n    }\n  });\n\n  sequelize.sync();\n\n  // Extra credit: Check to make sure the two instances of sequelize.models are the same...\n  // Outputs: sequelize.models after sync === app.get(\"models\")\n  // I've also run this comparison on sequelize and app.get('sequelize'); _.eq() said they also were identical\n  if (_.eq(sequelize.models, app.get('models')))\n    console.log('sequelize.models after sync === app.get(\"models\")');\n  else\n    console.log('sequelize.models after sync !== app.get(\"models\")');\n};\n```\n\n```text\nconst models = require('./models')\napp.use(compress())\n  // Lots of other statements\n  .configure(models);\n```\n\n```text\nconst vorpal = require('vorpal')();\nconst _ = require('lodash');\n\n// Initialize app\n// This seems a bit overkill since we don't need the server bit for this, but...\nconst app = require('./src/app');\nconst models = app.get('models');\n\n// Get the models for easy access...\nconst User = models['user'];\nconst Account = models['account'];\n\n// Run by issuing the command: node cli test\n// Outputs to terminal\nvorpal.command('test', 'A playground for testing the Vorpal environment.')\n  .action(function(args, callback) {\n    // User.belongsTo(Account); // <-- uncomment this and it works\n    User.findOne({ include: [{ model: Account }]}).then((user) => {\n      console.log(\"user.account.name:\", user.account.name);\n    });\n  });\n\nvorpal.show().parse(process.argv);\n```\n\n```text\nJust to be sure...From the user model, models[\"account\"]: account\nsequelize.models after sync === app.get(\"models\")\nconnect: \nUnhandled rejection Error: account is not associated to user!\n    at validateIncludedElement (/vagrant/node_modules/sequelize/lib/model.js:550:11)\n    at /vagrant/node_modules/sequelize/lib/model.js:432:29\n    at Array.map (native)\n    at validateIncludedElements (/vagrant/node_modules/sequelize/lib/model.js:428:37)\n    at .<anonymous> (/vagrant/node_modules/sequelize/lib/model.js:1364:32)\n    at tryCatcher (/vagrant/node_modules/bluebird/js/release/util.js:16:23)\n    at Promise._settlePromiseFromHandler (/vagrant/node_modules/bluebird/js/release/promise.js:504:31)\n    at Promise._settlePromise (/vagrant/node_modules/bluebird/js/release/promise.js:561:18)\n    at Promise._settlePromise0 (/vagrant/node_modules/bluebird/js/release/promise.js:606:10)\n    at Promise._settlePromises (/vagrant/node_modules/bluebird/js/release/promise.js:685:18)\n    at Async._drainQueue (/vagrant/node_modules/bluebird/js/release/async.js:138:16)\n    at Async._drainQueues (/vagrant/node_modules/bluebird/js/release/async.js:148:10)\n    at Immediate.Async.drainQueues (/vagrant/node_modules/bluebird/js/release/async.js:17:14)\n    at runCallback (timers.js:574:20)\n    at tryOnImmediate (timers.js:554:5)\n    at processImmediate [as _immediateCallback] (timers.js:533:5)\n```\n\n```text\nModelA\n```\n\n```text\nModelB\n```\n\n```text\nModelB\n```\n\n```text\nModelB\n```\n\n```text\nModelA\n```\n\n```text\ndatabaseName=# \\d accounts\n```\n\n```text\ndatabaseName=# \\d users\n```\n\n```text\napp\n```\n\n```text\nnode cli test\n```\n\n```text\nUser.findOne()\n```\n\n```text\napp\n```\n\n```text\ncli.js\n```\n\n```text\nObject.keys(sequelize.models).forEach(modelName => {\n  if ('associate' in sequelize.models[modelName]) {\n    sequelize.models[modelName].associate();\n  }\n});\n```\n\n```text\n/**\n * This is workaround for relating models.\n * I don't know why it works, but it does.\n *\n * @param app  The initialized app\n */\nmodule.exports = function(app) {\n  const sequelize = app.get('sequelize');\n\n  // Copied this from src/models/index.js\n  Object.keys(sequelize.models).forEach(modelName => {\n    if ('associate' in sequelize.models[modelName]) {\n      sequelize.models[modelName].associate();\n    }\n  });\n}\n```\n\n```text\nconst models = require('./models')\napp.use(compress())\n  // Lots of other statements\n  .configure(models);\n\nrequire('./relate-models')(app);\n```\n\n```text\nsrc/relate-models.js\n```\n\n```text\nsrc/app.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":740,"estimatedTokens":4964}}997{"id":"stack-33911452","source":"stackoverflow","questionId":33911452,"title":"Sequelize get request data in hooks?","tags":["javascript","node.js","express","sequelize.js"],"text":"Title: Sequelize get request data in hooks?\nTags: javascript, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to store some log data for my models on create, update, delete calls. I want to store some data from the request along with some user data also in the request (using express.js).\n\nIn the hooks I have some modules for logging.\n\n```\nhooks: {\n afterCreate: function (order, options, done) {\n // How to get user data stored in express request.\n\n return app.log.set('event', [{message: 'created', data: order, userId: 1}, done]);\n }\n}\n...\n```\n\nThe module just makes a record in a table. However it's the `userId` part I'm having trouble with. I'm using the `passport` module and it's stored in the request, so how can I get a user object (or any external object for that matter) into the model hooks?\n\nI would like to avoid doing it in a controller or anywhere else as there could be some scripts or other commands that may also enter data.\n\n========================================\n\nCode:\n```text\nhooks: {\n    afterCreate: function (order, options, done) {\n        // How to get user data stored in express request.\n\n        return app.log.set('event', [{message: 'created', data: order, userId: 1}, done]);\n    }\n}\n...\n```\n\n```text\nuserId\n```\n\n```text\npassport\n```\n\n```text\nmodule.exports = sequelize.addHook('beforeCreate',\n  function(model, options, done) {//hook 2\n    //handle what you want\n    //return app.log.set('event', [{message: 'created', data: order,      userId: 1}, done]);\n});\n```\n\n```text\nmodule.exports = {\n  CreateUser: function(req, res) {\n    User.beforeCreate(function(model, options, done) {//hook1\n        model.request = req;\n    });\n    User.create({\n            id: 1,\n            username: 'thanh9999',\n            password: '31231233123'\n                //ex.....\n        })\n        .then(function(success) {\n            //response success\n        }, function(err) {\n            //response error\n        });\n   }\n};\n```\n\n```text\nbeforeCreate\n```\n\n```text\nbeforeBulkUpdate\n```\n\n```text\nhook declaration in model\n```\n\n========================================\n\nComments:\n- While the passing `req` around is a working and transparent solution, I find it weird and annoying to do it just for logging. You may want to check out continuation-local-storage (npmjs.com/package/continuation-local-storage) to store data, so that every `logger.log` function would have access to wherever it is called. In theory it should work, in practice - never tried.","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":91,"estimatedTokens":627}}998{"id":"stack-66067124","source":"stackoverflow","questionId":66067124,"title":"Sequelize + postgres, how to calculate Connection Pool size?","tags":["node.js","postgresql","sequelize.js","database-performance"],"text":"Title: Sequelize + postgres, how to calculate Connection Pool size?\nTags: node.js, postgresql, sequelize.js, database-performance\nSource: Stack Overflow\n\nQuestion:\nIn our nodejs app, we started to have `SequelizeConnectionAcquireTimeoutError` errors. Currently we are using default sequelize connection settings:\n\n```\n{\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000\n}\n```\n\nHow to choose the best value of max pool?\n\nI search lots of similar questions ant websites but I could not find a specific answer to this question. I use sequelize in connection with postgres, The only, most sensible information I found on the Pg wiki:\nhttps://wiki.postgresql.org/wiki/Number_Of_Database_Connections\n\nWhere is the paragraph \"**How to Find the Optimal Database Connection Pool Size**\", and answer (in short):\n\n*A formula which has held up pretty well across a lot of benchmarks for years is that for optimal throughput the number of active connections should be somewhere near **((core_count * 2) + effective_spindle_count)**.*\n\nI have found very similar topic on stack overflow which can help provide context of my problem - but without answer.\nNodejs, Optimal parameters for sequelize connection pool?\n\n========================================\n\nCode:\n```text\n{\n    max: 5,\n    min: 0,\n    acquire: 30000,\n    idle: 10000\n}\n```\n\n```text\nSequelizeConnectionAcquireTimeoutError\n```\n\n========================================\n\nComments:\n- Did you ever get a grasp on this? Been down the exact same rabbit hole(s) myself, ha. :)","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":48,"estimatedTokens":379}}999{"id":"stack-66247076","source":"stackoverflow","questionId":66247076,"title":"Sequelize: Problem with dobule $ in JSON_EXTRACT","tags":["mysql","typescript","sequelize.js"],"text":"Title: Sequelize: Problem with dobule $ in JSON_EXTRACT\nTags: mysql, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm having a problem with the double dollar in query with JSON_EXTRACT.\n\nMy query:\n\n```\nconst user = await UserModel.findOne({\n where: where(fn('JSON_EXTRACT', col('config'), '$.type'), type),\n attributes: ['id'],\n})\n```\n\nthe result looks like this:\n\n```\nSELECT `id` FROM `users` WHERE JSON_EXTRACT(`config`, '$$.type') = 'admin' LIMIT 1;\n```\n\nThe problem is in double **$$**. Is this a problem specific or am I doing something wrong?\n\n========================================\n\nCode:\n```text\nconst user = await UserModel.findOne({\n    where: where(fn('JSON_EXTRACT', col('config'), '$.type'), type),\n    attributes: ['id'],\n})\n```\n\n```text\nSELECT `id` FROM `users` WHERE JSON_EXTRACT(`config`, '$$.type') = 'admin' LIMIT 1;\n```\n\n```text\nsequelize.where(\n  sequelize.fn('JSON_EXTRACT', \n    sequelize.col('config'), \n    sequelize.literal(`'$.type'`)\n  ),\n  type\n)\n```\n\n========================================\n\nComments:\n- could you describe a bit more explicitly what is the specific problem? I don't quite .\n- Also, if you are inspecting a json stored in a field to filter results, you may find it better to extract that element to its own column. It will also help with performance because it allows you to add indexes.\n- Add youor error log\n- Please add some explanation to your answer such that others can learn from it","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":55,"estimatedTokens":363}}1000{"id":"stack-35435314","source":"stackoverflow","questionId":35435314,"title":"how to set model validation with sequelize in nodejs?","tags":["javascript","node.js","sequelize.js"],"text":"Title: how to set model validation with sequelize in nodejs?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI’m new at nodejs. I have used sequelize for nodejs orm. But I can not set validate to an attribute;\n\nmodels/farmer.js\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var Farmer = sequelize.define('Farmer', {\n username:{\n type: DataTypes.STRING,\n allowNull: false,\n },\n address: DataTypes.STRING,\n email: {\n type: DataTypes.STRING,\n validate: {\n isEmail: true\n }\n },\n phone:{\n type: DataTypes.STRING,\n allowNull: false,\n },\n }, {\n classMethods: {\n associate: function(models) {\n Farmer.hasMany(models.Task);\n // associations can be defined here\n }\n }\n });\n return Farmer;\n};\n```\n\nError:\n\n Possibly unhandled SequelizeValidationError: Validation error\n at /Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/lib/instance-validator.js:149:14\n at tryCatch1 (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/util.js:43:21)\n at Promise$_callHandler [as _callHandler] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:639:13)\n at Promise$_settlePromiseFromHandler [as _settlePromiseFromHandler] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:653:18)\n at Promise$_settlePromiseAt [as _settlePromiseAt] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:817:14)\n at Promise$_settlePromises [as _settlePromises] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:951:14)\n at Async$_consumeFunctionBuffer [as _consumeFunctionBuffer] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/async.js:75:12)\n at Async$consumeFunctionBuffer (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/async.js:38:14)\n at doNTCallback0 (node.js:419:9)\n at process._tickCallback (node.js:348:13)\n\nHow can i set validate model?\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var Farmer = sequelize.define('Farmer', {\n    username:{\n            type: DataTypes.STRING,\n            allowNull: false,\n    },\n    address: DataTypes.STRING,\n    email: {\n        type: DataTypes.STRING,\n        validate: {\n           isEmail: true\n        }\n    },\n    phone:{\n            type: DataTypes.STRING,\n            allowNull: false,\n    },\n  }, {\n    classMethods: {\n      associate: function(models) {\n          Farmer.hasMany(models.Task);\n        // associations can be defined here\n      }\n    }\n  });\n  return Farmer;\n};\n```\n\n```text\nFarmer.create({\n  //your data\n}).then(function(){\n  //do something when Farmer is created\n}).catch(function(err){\n  //do something when you get error\n  //you could check if this is validation error or other error\n});\n```\n\n```text\nSequelizeValidationError\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":104,"estimatedTokens":806}}1001{"id":"stack-70321171","source":"stackoverflow","questionId":70321171,"title":"Express + Sequelize: hanging the app on connection","tags":["node.js","postgresql","docker","sequelize.js"],"text":"Title: Express + Sequelize: hanging the app on connection\nTags: node.js, postgresql, docker, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an app with postgres as db, sequelize, and express, and whenever it receives a db query, it just stays there forever, no logging or anything\nI run postgres in a container which I can connect to through GUI normally\nWhen I swapped it for sqlite, it worked perfectly the application\n\nhere is the relevant piece of code\n\n```\nconst databaseURL =\n process.env.DATABASE_URL ||\n \"postgres://postgres:postgres@0.0.0.0:5432/postgres\";\nconsole.log(databaseURL)\nconst db = new Sequelize(databaseURL, { logging: console.log });\n```\n\non docker compose\n\n```\ndc ps \n Name Command State Ports \n-----------------------------------------------------------------------------------------------------\nbaity-backend_db_1 docker-entrypoint.sh postgres Up 0.0.0.0:5432->5432/tcp,:::5432->5432/tcp\n```\n\nlogs\n\n```\n> DEBUG=express:* node index.js\n\n express:application set \"x-powered-by\" to true +0ms\n express:application set \"etag\" to 'weak' +1ms\n express:application set \"etag fn\" to [Function: generateETag] +1ms\n express:application set \"env\" to 'development' +0ms\n express:application set \"query parser\" to 'extended' +1ms\n express:application set \"query parser fn\" to [Function: parseExtendedQueryString] +0ms\n express:application set \"subdomain offset\" to 2 +0ms\n express:application set \"trust proxy\" to false +0ms\n express:application set \"trust proxy fn\" to [Function: trustNone] +0ms\n express:application booting in development mode +0ms\n express:application set \"view\" to [Function: View] +0ms\n express:application set \"views\" to '/home/omar/workspace/js/baity-backend/views' +0ms\n express:application set \"jsonp callback name\" to 'callback' +0ms\npostgres://postgres:postgres@0.0.0.0:5432/postgres\n```\n\n**Update 1:**\n\n```\nversion: \"3.9\"\n\nservices:\n web:\n build:\n dockerfile: Dockerfile\n context: ./frontend\n env_file:\n - ./frontend/.env\n ports:\n - \"8080:8080\"\n - \"3000:3000\"\n stdin_open: true\n volumes:\n - ./frontend:/opt/web\n app:\n build: .\n ports:\n - \"4000:4000\"\n volumes:\n - .:/code\n - /code/node_modules\n restart: always\n command: npm start\n env_file:\n - .env\n links:\n - db\n db:\n image: postgres:11.14-bullseye\n ports:\n - \"5432:5432\"\n env_file:\n - .env\n volumes:\n - ./.data/db:/var/lib/postgresql/data\n```\n\n```\nFROM node:14.18.2-bullseye\n\nWORKDIR /code\n\nCOPY package*.json ./\nRUN npm install -g nodemon\nRUN npm install\n\nCOPY . .\n```\n\nPackage.json\n\n```\n{\n \"name\": \"server\",\n \"version\": \"1.0.0\",\n \"description\": \"Node based server for real eastate website\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"start\": \"node index.js\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"xxx \",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"axios\": \"^0.19.2\",\n \"bcrypt\": \"^4.0.1\",\n \"cloudinary\": \"^1.20.0\",\n \"cors\": \"^2.8.5\",\n \"dotenv\": \"^8.2.0\",\n \"express\": \"^4.17.1\",\n \"express-form-data\": \"^2.0.12\",\n \"express-formidable\": \"^1.2.0\",\n \"jsonwebtoken\": \"^8.5.1\",\n \"multer\": \"^1.4.4\",\n \"node-cron\": \"^2.0.3\",\n \"pg\": \"^7.18.2\",\n \"sequelize\": \"^5.21.5\",\n \"sequelize-auto-migrations\": \"^1.0.3\",\n \"sqlite3\": \"^5.0.2\",\n \"stripe\": \"^8.35.0\"\n }\n}\n```\n\n**node:** 14.18.2\n\n```\nDATABASE_URL=postgres://postgres:postgres@db:5432/postgres\n```\n\n========================================\n\nTop Answer:\nI think it is your \"0.0.0.0:5432\".\n\nIf local, it should be just \"localhost:5432\".\nIf deployed server is remote, it should be a certain IP address XXX.XXX.XXX.XXX:5432.\nIf deployed server is home network, it should be \"192.168.0.XXX:5432\".\n\nCheck your postgres network configuration\nhttps://youtu.be/Erqp4C3Y3Ds\n\n========================================\n\nCode:\n```js\nconst databaseURL =\n  process.env.DATABASE_URL ||\n  \"postgres://postgres:postgres@0.0.0.0:5432/postgres\";\nconsole.log(databaseURL)\nconst db = new Sequelize(databaseURL, { logging: console.log });\n```\n\n```text\ndc ps            \n       Name                     Command              State                    Ports                  \n-----------------------------------------------------------------------------------------------------\nbaity-backend_db_1   docker-entrypoint.sh postgres   Up      0.0.0.0:5432->5432/tcp,:::5432->5432/tcp\n```\n\n```text\n> DEBUG=express:* node index.js\n\n  express:application set \"x-powered-by\" to true +0ms\n  express:application set \"etag\" to 'weak' +1ms\n  express:application set \"etag fn\" to [Function: generateETag] +1ms\n  express:application set \"env\" to 'development' +0ms\n  express:application set \"query parser\" to 'extended' +1ms\n  express:application set \"query parser fn\" to [Function: parseExtendedQueryString] +0ms\n  express:application set \"subdomain offset\" to 2 +0ms\n  express:application set \"trust proxy\" to false +0ms\n  express:application set \"trust proxy fn\" to [Function: trustNone] +0ms\n  express:application booting in development mode +0ms\n  express:application set \"view\" to [Function: View] +0ms\n  express:application set \"views\" to '/home/omar/workspace/js/baity-backend/views' +0ms\n  express:application set \"jsonp callback name\" to 'callback' +0ms\npostgres://postgres:postgres@0.0.0.0:5432/postgres\n```\n\n```yaml\nversion: \"3.9\"\n\nservices:\n  web:\n    build:\n      dockerfile: Dockerfile\n      context: ./frontend\n    env_file:\n      - ./frontend/.env\n    ports:\n      - \"8080:8080\"\n      - \"3000:3000\"\n    stdin_open: true\n    volumes:\n      - ./frontend:/opt/web\n  app:\n    build: .\n    ports:\n      - \"4000:4000\"\n    volumes:\n        - .:/code\n        - /code/node_modules\n    restart: always\n    command: npm start\n    env_file:\n      - .env\n    links:\n      - db\n  db:\n    image: postgres:11.14-bullseye\n    ports:\n      - \"5432:5432\"\n    env_file:\n      - .env\n    volumes:\n      - ./.data/db:/var/lib/postgresql/data\n```\n\n```text\nFROM node:14.18.2-bullseye\n\nWORKDIR /code\n\nCOPY package*.json ./\nRUN npm install -g nodemon\nRUN npm install\n\nCOPY . .\n```\n\n```json\n{\n  \"name\": \"server\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Node based server for real eastate website\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"start\": \"node index.js\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"xxx <xxx@gmail.com>\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"axios\": \"^0.19.2\",\n    \"bcrypt\": \"^4.0.1\",\n    \"cloudinary\": \"^1.20.0\",\n    \"cors\": \"^2.8.5\",\n    \"dotenv\": \"^8.2.0\",\n    \"express\": \"^4.17.1\",\n    \"express-form-data\": \"^2.0.12\",\n    \"express-formidable\": \"^1.2.0\",\n    \"jsonwebtoken\": \"^8.5.1\",\n    \"multer\": \"^1.4.4\",\n    \"node-cron\": \"^2.0.3\",\n    \"pg\": \"^7.18.2\",\n    \"sequelize\": \"^5.21.5\",\n    \"sequelize-auto-migrations\": \"^1.0.3\",\n    \"sqlite3\": \"^5.0.2\",\n    \"stripe\": \"^8.35.0\"\n  }\n}\n```\n\n```text\nDATABASE_URL=postgres://postgres:postgres@db:5432/postgres\n```\n\n```text\nyarn add pg@\"8.7.1\"\n```\n\n```text\npackage.json\n```\n\n```text\npg\n```\n\n```text\npg\n```\n\n```text\nDockerfile\n```\n\n```text\nservices:\n  postgres:\n    container_name: app-database\n    network: postgres\n    image: postgres\n    ...\n\n  express:\n    container_name: app-backend\n    network: postgres\n    environment:\n      DATABASE_URL: \"postgresql://postgres:postgres@app-database:5432/postgres\"\n\n  networks:\n    postgres:\n      driver: bridge\n\n    ...\n```\n\n```text\n\"0.0.0.0:5432\"\n```\n\n```text\ndocker-name\n```\n\n```text\npostgresql://postgres:postgres@your_machine_ip:5432/postgres\n```\n\n========================================\n\nComments:\n- All these inside one container , or different containers, attach your Dockerfile or docker-compose.\n- post your package.json file and Node.JS Version\n- @madflow done @ yassine done\n- I'm on local, and I can connect with DBeaver with the same credentials, host, pass I also made a new container and tested the connection with hostname db (container name) instead, and still fails\n- done that with host db, still nothing new\n- @OmarS. check if you are using the correct network driver. I've included that in the update answer.\n- also tried that but no joy","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":343,"estimatedTokens":1982}}1002{"id":"stack-64750785","source":"stackoverflow","questionId":64750785,"title":"Sequelize NodeJS server throwing \"ERR_UNKNOWN_ENCODING\" error","tags":["node.js","socket.io","mariadb","sequelize.js"],"text":"Title: Sequelize NodeJS server throwing \"ERR_UNKNOWN_ENCODING\" error\nTags: node.js, socket.io, mariadb, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ncould anyone help me locate the problem. I'm getting this error:\n\n```\nnode:internal/streams/writable:296\n throw new ERR_UNKNOWN_ENCODING(encoding);\n ^\n\n TypeError [ERR_UNKNOWN_ENCODING]: Unknown encoding: Handshake {\n _events: [Object: null prototype],\n _eventsCount: 1,\n _maxListeners: undefined,\n sequenceNo: 1,\n compressSequenceNo: -1,\n resolve: [Function: bound _authSucceedHandler],\n reject: [Function: bound _authFailHandler],\n sending: false,\n _createSecureContext: [Function: bound _createSecureContext],\n _addCommand: [Function: bound _addCommandEnable],\n getSocket: [Function: _getSocket],\n onPacketReceive: [Function: parseHandshakeInit],\n plugin: [Circular *1],\n [Symbol(kCapture)]: false\n }\n at new NodeError (node:internal/errors:259:15)\n at Socket.Writable.write (node:internal/streams/writable:296:13)\n at PacketOutputStream.flushBufferBasic (/var/www/app/node_modules/mariadb/lib/io/packet-output-stream.js:444:17)\n at Object.send (/var/www/app/node_modules/mariadb/lib/cmd/handshake/client-handshake-response.js:118:7)\n at Handshake.parseHandshakeInit (/var/www/app/node_modules/mariadb/lib/cmd/handshake/handshake.js:82:31)\n at PacketInputStream.receivePacketBasic (/var/www/app/node_modules/mariadb/lib/io/packet-input-stream.js:104:9)\n at PacketInputStream.onData (/var/www/app/node_modules/mariadb/lib/io/packet-input-stream.js:169:20)\n at Socket.emit (node:events:327:20)\n at addChunk (node:internal/streams/readable:304:12)\n at readableAddChunk (node:internal/streams/readable:279:9) {\n code: 'ERR_UNKNOWN_ENCODING'\n }\n```\n\nI currently have no idea what's wrong. Figured out, that the problem lies here:\n\n```\nconst sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {\n host: process.env.DB_HOST,\n port: process.env.DB_PORT,\n dialect: 'mariadb',\n});\n\nsequelize.authenticate()\n .then(() => {\n logger.log('info', 'Connected to database')\n })\n .catch((error) => {\n logger.log('error', 'Failed to connect to database!');\n logger.log('error', JSON.stringify(error));\n })\n```\n\nin the `authenticate` function. Database: mariadb:10.5.7-focal (docker)\n\n========================================\n\nCode:\n```none\nnode:internal/streams/writable:296\n       throw new ERR_UNKNOWN_ENCODING(encoding);\n       ^\n\n TypeError [ERR_UNKNOWN_ENCODING]: Unknown encoding: <ref *1> Handshake {\n   _events: [Object: null prototype],\n   _eventsCount: 1,\n   _maxListeners: undefined,\n   sequenceNo: 1,\n   compressSequenceNo: -1,\n   resolve: [Function: bound _authSucceedHandler],\n   reject: [Function: bound _authFailHandler],\n   sending: false,\n   _createSecureContext: [Function: bound _createSecureContext],\n   _addCommand: [Function: bound _addCommandEnable],\n   getSocket: [Function: _getSocket],\n   onPacketReceive: [Function: parseHandshakeInit],\n   plugin: [Circular *1],\n   [Symbol(kCapture)]: false\n }\n     at new NodeError (node:internal/errors:259:15)\n     at Socket.Writable.write (node:internal/streams/writable:296:13)\n     at PacketOutputStream.flushBufferBasic (/var/www/app/node_modules/mariadb/lib/io/packet-output-stream.js:444:17)\n     at Object.send (/var/www/app/node_modules/mariadb/lib/cmd/handshake/client-handshake-response.js:118:7)\n     at Handshake.parseHandshakeInit (/var/www/app/node_modules/mariadb/lib/cmd/handshake/handshake.js:82:31)\n     at PacketInputStream.receivePacketBasic (/var/www/app/node_modules/mariadb/lib/io/packet-input-stream.js:104:9)\n     at PacketInputStream.onData (/var/www/app/node_modules/mariadb/lib/io/packet-input-stream.js:169:20)\n     at Socket.emit (node:events:327:20)\n     at addChunk (node:internal/streams/readable:304:12)\n     at readableAddChunk (node:internal/streams/readable:279:9) {\n   code: 'ERR_UNKNOWN_ENCODING'\n }\n```\n\n```js\nconst sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {\n    host: process.env.DB_HOST,\n    port: process.env.DB_PORT,\n    dialect: 'mariadb',\n});\n\nsequelize.authenticate()\n    .then(() => {\n        logger.log('info', 'Connected to database')\n    })\n    .catch((error) => {\n        logger.log('error', 'Failed to connect to database!');\n        logger.log('error', JSON.stringify(error));\n    })\n```\n\n```text\nauthenticate\n```\n\n```text\nnpm update\n```\n\n========================================\n\nComments:\n- Hi I am using mariadb as dialect. How can I set the timezone please? Using timezone in dialect options is not making an effect. The created_at and updated_at are still according to the timezone of the server.\n- @LukeGalea would love to answer your question, but I am not able to fix this issue myself and currently do not have the time to read the documentation.","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":131,"estimatedTokens":1203}}1003{"id":"stack-23833337","source":"stackoverflow","questionId":23833337,"title":"Squelize - geolocation in where clauses using MariaDB","tags":["node.js","orm","mariadb","sequelize.js"],"text":"Title: Squelize - geolocation in where clauses using MariaDB\nTags: node.js, orm, mariadb, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've got a node.js app , using MariaDB.\nSo far all my SQL is in Stored Procedures.\n\nI'm considering Sequelize, the only thing I haven't found in there - that I need - is using functions in where clauses. \n\nI've got something like this in my current query :\n\n```\nSelect * from places p\nwhere ST_WITHIN(p.geolocation, ST_BUFFER(GeomFromText(in_geolocation), radius)) = 1\n```\n\n(in_gelocation and radius are SP parameters).\n\nIs there anyway to do this in Sequelize, or another ORM ?\n\nThanks\n\n========================================\n\nTop Answer:\nHere's a Sequelize geolocation example for you to reference. It utilizes SQL functions and illustrates the inclusion of the where attribute.\n\n```\nif(!query.includes(',') && lat && lng) {\n attributes.push([\n DataTypes.fn('concat',\n DataTypes.col('city'),\n DataTypes.col('state')\n ),'city_state'])\n attributes.push([\n DataTypes.fn('ST_Distance',\n DataTypes.col('location'),\n DataTypes.literal(`ST_GeomFromText('POINT(${lat} ${lng})', 4326)`)\n ), 'distance'])\n}\nif(!query.includes(',')) {\n attributes.push([DataTypes.literal(`CASE\n WHEN\n name = '` + query + `' THEN 4\n WHEN\n city LIKE '%` + query + `%' THEN 3\n WHEN\n name LIKE '%` + query + `%' THEN 2\n WHEN\n name LIKE '` + query + `%' THEN 1\n END`), 'exact_like_match'])\n}\nvar whereAnd = []\nwhereAnd.push(\n DataTypes.literal('MATCH(name, city, state, zip) AGAINST(:search_query)')\n)\nwhereAnd.push({\n menu_enabled: 'Y'\n})\nvar search_params = { \n where: whereAnd,\n replacements: {\n search_query: '+' + query + '*',\n type: DataTypes.QueryTypes.SELECT\n },\n attributes: attributes,\n offset: parseInt(req.query.start),\n limit: req.query.limit ? parseInt(req.query.limit) : 12\n}\nsearch_params['order'] = [\n DataTypes.literal('exact_like_match DESC')\n]\nif(!query.includes(',')) {\n // console.log('comma detected!')\n search_params['order'] = [\n DataTypes.literal('exact_like_match DESC, distance ASC')\n ]\n}\ndispensary.findAndCountAll(search_params).then(disp_rx => {\n\n})\n```\n\n========================================\n\nCode:\n```text\nSelect * from places p\nwhere ST_WITHIN(p.geolocation, ST_BUFFER(GeomFromText(in_geolocation), radius)) = 1\n```\n\n```text\nSequelize.fn\n```\n\n```text\nif(!query.includes(',') && lat && lng) {\n    attributes.push([\n        DataTypes.fn('concat',\n        DataTypes.col('city'),\n        DataTypes.col('state')\n    ),'city_state'])\n    attributes.push([\n        DataTypes.fn('ST_Distance',\n        DataTypes.col('location'),\n        DataTypes.literal(`ST_GeomFromText('POINT(${lat} ${lng})', 4326)`)\n    ), 'distance'])\n}\nif(!query.includes(',')) {\n    attributes.push([DataTypes.literal(`CASE\n        WHEN\n            name = '` + query + `' THEN 4\n        WHEN\n            city LIKE '%` + query + `%' THEN 3\n        WHEN\n            name LIKE '%` + query + `%' THEN 2\n        WHEN\n            name LIKE '` + query + `%' THEN 1\n    END`), 'exact_like_match'])\n}\nvar whereAnd = []\nwhereAnd.push(\n    DataTypes.literal('MATCH(name, city, state, zip) AGAINST(:search_query)')\n)\nwhereAnd.push({\n    menu_enabled: 'Y'\n})\nvar search_params = {   \n    where: whereAnd,\n    replacements: {\n        search_query: '+' + query + '*',\n        type: DataTypes.QueryTypes.SELECT\n    },\n    attributes: attributes,\n    offset: parseInt(req.query.start),\n    limit: req.query.limit ? parseInt(req.query.limit) : 12\n}\nsearch_params['order'] = [\n    DataTypes.literal('exact_like_match DESC')\n]\nif(!query.includes(',')) {\n    // console.log('comma detected!')\n    search_params['order'] = [\n        DataTypes.literal('exact_like_match DESC, distance ASC')\n    ]\n}\ndispensary.findAndCountAll(search_params).then(disp_rx => {\n\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":151,"estimatedTokens":939}}1004{"id":"stack-66523624","source":"stackoverflow","questionId":66523624,"title":"Sequelize where condition for nested models","tags":["javascript","node.js","database","postgresql","sequelize.js"],"text":"Title: Sequelize where condition for nested models\nTags: javascript, node.js, database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a database with notes and users.Now i want to get all notes where note content = something or users.name = something.I can write this query easily with SQL but couldn't get it working with sequlizer.\n\n```\nNote.findAll({\n include: [\n { model: Users, where: { name: 'something' }}\n ]\n})\n```\n\nexpected query is\n\n```\nselect * from users,notes where notes.content='something' or users.name='something'\n```\n\nThe issue is Note is not inside include so I cannot use\n\n```\nwhere: {\n '$or':{\n```\n\nMy question is how to have where with or condition on nested table using sequelize\n\n========================================\n\nCode:\n```text\nNote.findAll({\n   include: [\n             { model: Users, where: { name: 'something' }}\n    ]\n})\n```\n\n```text\nselect * from users,notes where notes.content='something' or users.name='something'\n```\n\n```text\nwhere: {\n     '$or':{\n```\n\n```text\nNote.findAll({\n    where: {\n        [Op.or]: [\n            { content: { [Op.like]: 'something' } },\n            { '$users.name$': { [Op.like]: 'john' } },\n        ]\n    },\n    include: [\n        { model: Users, as: 'users', required: true }\n    ]\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":63,"estimatedTokens":319}}1005{"id":"stack-66399694","source":"stackoverflow","questionId":66399694,"title":"Sequelize MySQL Migration - unique to false","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize MySQL Migration - unique to false\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to write a migration in Sequelize and MySQL, which sets the unique attribute to false. This is my approach so far:\n\n```\nmodule.exports = {\n up: async (queryInterface, Sequelize) => {\n await queryInterface.changeColumn(\"users\", \"name\", {\n type: Sequelize.STRING,\n allowNull: false,\n unique: true,\n });\n await queryInterface.changeColumn(\"users\", \"email\", {\n type: Sequelize.STRING,\n allowNull: false,\n unique: true,\n });\n },\n\n down: async (queryInterface, Sequelize) => {\n await queryInterface.changeColumn(\"users\", \"name\", {\n type: Sequelize.STRING,\n allowNull: true,\n unique: false,\n });\n await queryInterface.changeColumn(\"users\", \"email\", {\n type: Sequelize.STRING,\n allowNull: true,\n unique: false,\n });\n },\n};\n```\n\nThe up migration works like charme, the down migration works for allowNull, but not for unique attribute. I am new to Sequelize so I am wondering, what is going wrong here. Can someone help me out?\n\nThank you very much in advance.\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n          await queryInterface.changeColumn(\"users\", \"name\", {\n              type: Sequelize.STRING,\n              allowNull: false,\n              unique: true,\n          });\n          await queryInterface.changeColumn(\"users\", \"email\", {\n              type: Sequelize.STRING,\n              allowNull: false,\n              unique: true,\n         });\n    },\n\n down: async (queryInterface, Sequelize) => {\n          await queryInterface.changeColumn(\"users\", \"name\", {\n            type: Sequelize.STRING,\n            allowNull: true,\n            unique: false,\n      });\n          await queryInterface.changeColumn(\"users\", \"email\", {\n            type: Sequelize.STRING,\n            allowNull: true,\n            unique: false,\n   });\n  },\n};\n```\n\n```text\npublic removeConstraint(tableName: string, constraintName: string, options: Object): Promise\n```\n\n```text\nmodule.exports = {\n  up: async (queryInterface, Sequelize) => {\n    await queryInterface.changeColumn(\"users\", \"name\", {\n      type: Sequelize.STRING,\n      allowNull: false,\n      unique: true,\n    });\n    await queryInterface.changeColumn(\"users\", \"email\", {\n      type: Sequelize.STRING,\n      allowNull: false,\n      unique: true,\n    });\n  },\n\n  down: async (queryInterface, Sequelize) => {\n    await queryInterface.changeColumn(\"users\", \"name\", {\n      type: Sequelize.STRING,\n      allowNull: true,\n    });\n    await queryInterface.removeConstraint(\"users\", \"name_unique_key\");\n    await queryInterface.changeColumn(\"users\", \"email\", {\n      type: Sequelize.STRING,\n      allowNull: true,\n    });\n    await queryInterface.removeConstraint(\"users\", \"email_unique_key\");\n  },\n};\n```\n\n========================================\n\nComments:\n- Hi Sir. Thanks a bunch. I realy struggle with the docs. Unfortunately your approach leads to an error: name_unique_key on table users does not exist. I might have to specify a constraintName, but I dont know how I could do it with sequelize.\n- Can you please try to change \"name_unique_key\" -> \"name\" and \"email_unique_key\" -> \"email\"\n- If you got the same issue please try to change \"name_unique_key\" -> \"name_UNIQUE\" and \"email_unique_key\" -> \"email_UNIQUE\"\n- Hi, thanks once again for helping me out. Indeed the version without _unique_key worked. Thanks a million.","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":115,"estimatedTokens":869}}1006{"id":"stack-63816145","source":"stackoverflow","questionId":63816145,"title":"Sequelize query - Return all items, if one item matches query","tags":["sequelize.js"],"text":"Title: Sequelize query - Return all items, if one item matches query\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 2 models, Recipe and Ingredient.\n\nBasically I have a search function, where ideally when you search for an ingredient, it will return the recipes that uses said ingredient.\n\nI manage to get the query working with the below. The only problem is, it only returns the ingredients that matches the query. I'd like for it to return all ingredients in the Recipe, if one of the ingredients matches the query. How would I adapt the below to do that?\n\nFor example if I search for tomato, I will get recipes with tomatoes win them, but the returned ingredients only includes tomatoes, but not the rest of the ingredients.\n\n```\nconst recipes = await Recipe.findAll({\n include: {\n model: Ingredient,\n where: {\n name: {\n [Op.iLike]: `%${ingredients}%`,\n },\n },\n },\n});\n```\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nI had to use the same trick as the one provided by @Anatoly and it works perfectly!\n\nThe thing is, it also returns a field `FilteringIngredients` with the matched element inside. To those who want to remove this field from the returned object, it is possible to add a `attributes: []` as follows :\n\n```\nawait Recipe.findAll({\n include: [{\n model: Ingredient,\n as: \"FilteringIngredients\",\n where: { /* my where clause */ },\n attributes: [],\n },\n {\n model: Ingredient,\n as: \"Ingredients\",\n separate: true,\n }]\n})\n```\n\n========================================\n\nCode:\n```text\nconst recipes = await Recipe.findAll({\n      include: {\n        model: Ingredient,\n        where: {\n          name: {\n            [Op.iLike]: `%${ingredients}%`,\n          },\n        },\n      },\n});\n```\n\n```text\nRecipe.hasMany(Ingredient, { foreignKey: 'recipeId', as: 'Ingredients' })\nRecipe.hasMany(Ingredient, { foreignKey: 'recipeId', as: 'FilteringIngredients' })\n...\nconst recipes = await Recipe.findAll({\n      include: [{\n        model: Ingredient,\n        as: 'FilteringIngredients',\n        where: {\n          name: {\n            [Op.iLike]: `%${ingredients}%`,\n          },\n        },\n      }, {\n        model: Ingredient,\n        as: 'Ingredients',\n        separate: true\n      }],\n});\n```\n\n```js\nawait Recipe.findAll({\n  include: [{\n    model: Ingredient,\n    as: \"FilteringIngredients\",\n    where: { /* my where clause */ },\n    attributes: [],\n  },\n  {\n    model: Ingredient,\n    as: \"Ingredients\",\n    separate: true,\n  }]\n})\n```\n\n```text\nFilteringIngredients\n```\n\n```text\nattributes: []\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":111,"estimatedTokens":636}}1007{"id":"stack-60921950","source":"stackoverflow","questionId":60921950,"title":"How to define Table name using `sequelize-typescript`?","tags":["typescript","sequelize.js","typescript-typings"],"text":"Title: How to define Table name using `sequelize-typescript`?\nTags: typescript, sequelize.js, typescript-typings\nSource: Stack Overflow\n\nQuestion:\nit used to be possible to define `tableName` parameter in the Table decorator from `sequelize-typescript` like the below:\n\n```\n@Table({\n tableName: 'my-custom-tablename'\n})\nexport class Tenants extends Model {\n @IsUUID(4)\n @Default(uuid())\n @PrimaryKey\n @Column\n uuid!: string;\n\n @CreatedAt\n @Column\n created_at!: Date;\n\n @UpdatedAt\n @Column\n updated_at!: Date;\n}\n```\n\nWith the latest version it doesn't seem possible to do this, only two options remain available:\n`modelName` and `version`, so now, TableName is automatically mapped to the ModelName (className)\n\nHow to pass the real table name associated to the model?\n\n========================================\n\nCode:\n```text\n@Table({\n  tableName: 'my-custom-tablename'\n})\nexport class Tenants extends Model<Tenants> {\n  @IsUUID(4)\n  @Default(uuid())\n  @PrimaryKey\n  @Column\n  uuid!: string;\n\n  @CreatedAt\n  @Column\n  created_at!: Date;\n\n  @UpdatedAt\n  @Column\n  updated_at!: Date;\n}\n```\n\n```text\ntableName\n```\n\n```text\nsequelize-typescript\n```\n\n```text\nmodelName\n```\n\n```text\nversion\n```\n\n```text\n@Table({\n  tableName: 'user'\n})\nexport class User extends Model<User> {\n  @Column\n  firstName!: string;\n\n  @CreatedAt\n  @Column\n  createdAt!: Date;\n\n  @UpdatedAt\n  @Column\n  updatedAt!: Date;\n\n}\n```\n\n========================================\n\nComments:\n- It works with `@ts-ignore` but I suppose this's not what you're looking for","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":96,"estimatedTokens":382}}1008{"id":"stack-63102705","source":"stackoverflow","questionId":63102705,"title":"Error with migration postgress, i have two columns over, why?","tags":["postgresql","express","sequelize.js"],"text":"Title: Error with migration postgress, i have two columns over, why?\nTags: postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni have a migration, i only have four colums, id, name, last_name and email but when i do a query from postman it show me other colums over `SELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\"` what is the wrong?\n\n```\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('User', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false,\n },\n last_name: {\n type: Sequelize.STRING,\n allowNull: false,\n },\n email: {\n type: Sequelize.STRING,\n allowNull: false,\n },\n });\n },\n down: (queryInterface) => {\n return queryInterface.dropTable('User');\n }\n};\n```\n\nand when i used my service\n\n```\nstatic async getAllUsers() {\n try {\n const users = await database.User.findAll();\n console.log('COnsOLE ', users)\n return users\n } catch (error) {\n throw error;\n }\n }\n```\n\ni get this error from postman:\n\n```\n{\n \"status\": \"error\",\n \"message\": {\n \"name\": \"SequelizeDatabaseError\",\n \"parent\": {\n \"length\": 104,\n \"name\": \"error\",\n \"severity\": \"ERROR\",\n \"code\": \"42P01\",\n \"position\": \"73\",\n \"file\": \"parse_relation.c\",\n \"line\": \"1180\",\n \"routine\": \"parserOpenTable\",\n \"sql\": \"SELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\";\"\n },\n \"original\": {\n \"length\": 104,\n \"name\": \"error\",\n \"severity\": \"ERROR\",\n \"code\": \"42P01\",\n \"position\": \"73\",\n \"file\": \"parse_relation.c\",\n \"line\": \"1180\",\n \"routine\": \"parserOpenTable\",\n \"sql\": \"SELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\";\"\n },\n \"sql\": \"SELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\";\"\n }\n}\n```\n\ni before used this commands many times: `sequelize db:migrate` and `sequelize db:migrate:undo`\n\nthis is my git repository: https://github.com/x-rw/basePostgresExpressjs\n\nyou should situate in server directory and write `npm run dev`\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable('User', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER\n      },\n      name: {\n        type: Sequelize.STRING,\n        allowNull: false,\n      },\n      last_name: {\n        type: Sequelize.STRING,\n        allowNull: false,\n      },\n      email: {\n        type: Sequelize.STRING,\n        allowNull: false,\n      },\n    });\n  },\n  down: (queryInterface) => {\n    return queryInterface.dropTable('User');\n  }\n};\n```\n\n```text\nstatic async getAllUsers() {\n    try {\n      const users = await database.User.findAll();\n      console.log('COnsOLE ', users)\n      return users\n    } catch (error) {\n      throw error;\n    }\n  }\n```\n\n```text\n{\n    \"status\": \"error\",\n    \"message\": {\n        \"name\": \"SequelizeDatabaseError\",\n        \"parent\": {\n            \"length\": 104,\n            \"name\": \"error\",\n            \"severity\": \"ERROR\",\n            \"code\": \"42P01\",\n            \"position\": \"73\",\n            \"file\": \"parse_relation.c\",\n            \"line\": \"1180\",\n            \"routine\": \"parserOpenTable\",\n            \"sql\": \"SELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\";\"\n        },\n        \"original\": {\n            \"length\": 104,\n            \"name\": \"error\",\n            \"severity\": \"ERROR\",\n            \"code\": \"42P01\",\n            \"position\": \"73\",\n            \"file\": \"parse_relation.c\",\n            \"line\": \"1180\",\n            \"routine\": \"parserOpenTable\",\n            \"sql\": \"SELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\";\"\n        },\n        \"sql\": \"SELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\";\"\n    }\n}\n```\n\n```text\nSELECT \\\"id\\\", \\\"name\\\", \\\"lastName\\\", \\\"email\\\", \\\"createdAt\\\", \\\"updatedAt\\\" FROM \\\"Users\\\" AS \\\"User\\\"\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nsequelize db:migrate:undo\n```\n\n```text\nnpm run dev\n```\n\n```text\nclass YourModel extends Sequelize.Model { }\nYourModel.init(\n    {\n        name: {\n            type: Sequelize.DataTypes.STRING(100),\n            allowNull: false,\n            validate: {\n                notNull: true,\n                notEmpty: true,\n                len: [2, 100]\n            }\n        },\n    },\n    {\n        sequelize: sequelizeInstance,\n        timestamps: false // This is what you need.\n    }\n);\n```\n\n========================================\n\nComments:\n- how can i put false?\n- Check the answer. I have added an example.\n- i have this problem ReferenceError: sequelizeInstance is not defined\n- but this worrked for me { freezeTableName: true, // Model tableName will be the same as the model name timestamps: false, underscored: true }","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":212,"estimatedTokens":1266}}1009{"id":"stack-62272169","source":"stackoverflow","questionId":62272169,"title":"Sequelize Error: Include unexpected. Element has to be either a Model, an Association or an object","tags":["mysql","node.js","typescript","sequelize.js"],"text":"Title: Sequelize Error: Include unexpected. Element has to be either a Model, an Association or an object\nTags: mysql, node.js, typescript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am receiving the error when I make a call to my API with a get request:\n\n```\nInclude unexpected. Element has to be either a Model, an Association or an object.\n```\n\nMy Models look like this:\n\n```\nmodule.exports = (sequelize, Sequelize) => {\n const Productions = sequelize.define(\"productions\", {\n id: {\n type: Sequelize.SMALLINT,\n autoIncrement: true,\n primaryKey: true\n },\n setupTime: {\n type: Sequelize.DECIMAL(6, 3)\n },\n notes: {\n type: Sequelize.TEXT\n }\n }, { timestamps: false });\n\n return Productions;\n};\n```\n\n```\nmodule.exports = (sequelize, Sequelize) => {\n const ProductionPrints = sequelize.define(\"productionPrints\", {\n id: {\n type: Sequelize.SMALLINT,\n autoIncrement: true,\n primaryKey: true\n },\n compDate: {\n type: Sequelize.DATE\n }\n }, { timestamps: false });\n\n return ProductionPrints;\n};\n```\n\nThe relationship between the models is defined here:\n\n```\ndb.productions = require(\"./productions.model.js\")(sequelize, Sequelize);\ndb.productionprints = require(\"./production-prints.model.js\")(sequelize, Sequelize);\n\ndb.productions.hasOne(db.productionprints, {\n foreignKey: {\n name: 'productionId',\n allowNull: false\n }\n});\ndb.productionprints.belongsTo(db.productions, { foreignKey: 'productionId' });\n```\n\nAnd the sequelize query looks as so:\n\n```\nconst db = require(\"../models\");\nconst Productions = db.productions;\nconst ProductionPrints = db.productionPrints;\n\nexports.findAll = (req, res) => {\n Productions.findAll({\n include: [ { model: ProductionPrints, as: 'prints' } ]\n })\n .then(data => {\n res.send(data);\n })\n .catch(err => {\n res.status(500).send({\n message:\n err.message || \"An error occurred while finding the productions.\"\n });\n });\n};\n```\n\nI have checked around for others with the issue but have had no avail with any solutions posted on those problems. Generally it was caused by typos, or error in the require paths. I have checked those and all my other includes work, just not on any of the models I include on the productions model.\n\nAny feedback is greatly appreciated.\n\n========================================\n\nTop Answer:\nI had the same issue , this is usually caused by naming issue , to track the issue you can check one of the following places to resolve it\n\n- check if you are calling the correct model class name\n\n- when importing models becarefull not to call the file name instead of model name => the one exported\n\n3.check if you got your association correctly by calling the exported model not the file name\n\n- check if your cases e.g users vs Users.\n\na bonus tip is to use same name for model and file name to avoid these issues because the moment you make them different you likely to make these mistakes\n\n========================================\n\nCode:\n```text\nInclude unexpected. Element has to be either a Model, an Association or an object.\n```\n\n```text\nmodule.exports = (sequelize, Sequelize) => {\n    const Productions = sequelize.define(\"productions\", {\n        id: {\n            type: Sequelize.SMALLINT,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        setupTime: {\n            type: Sequelize.DECIMAL(6, 3)\n        },\n        notes: {\n            type: Sequelize.TEXT\n        }\n    }, { timestamps: false });\n\n    return Productions;\n};\n```\n\n```text\nmodule.exports = (sequelize, Sequelize) => {\n    const ProductionPrints = sequelize.define(\"productionPrints\", {\n        id: {\n            type: Sequelize.SMALLINT,\n            autoIncrement: true,\n            primaryKey: true\n        },\n        compDate: {\n            type: Sequelize.DATE\n        }\n    }, { timestamps: false });\n\n    return ProductionPrints;\n};\n```\n\n```text\ndb.productions = require(\"./productions.model.js\")(sequelize, Sequelize);\ndb.productionprints = require(\"./production-prints.model.js\")(sequelize, Sequelize);\n\ndb.productions.hasOne(db.productionprints, {\n    foreignKey: {\n        name: 'productionId',\n        allowNull: false\n    }\n});\ndb.productionprints.belongsTo(db.productions, { foreignKey: 'productionId' });\n```\n\n```text\nconst db = require(\"../models\");\nconst Productions = db.productions;\nconst ProductionPrints = db.productionPrints;\n\nexports.findAll = (req, res) => {\n    Productions.findAll({\n        include: [ { model: ProductionPrints, as: 'prints' } ]\n    })\n        .then(data => {\n            res.send(data);\n        })\n        .catch(err => {\n            res.status(500).send({\n                message:\n                    err.message || \"An error occurred while finding the productions.\"\n            });\n        });\n};\n```\n\n```text\ndb.productions = require(\"./productions.model.js\")(sequelize, Sequelize);\ndb.productionprints = require(\"./production-prints.model.js\")(sequelize, Sequelize);\n```\n\n```text\nconst Productions = db.productions;\nconst ProductionPrints = db.productionPrints;\n```\n\n```text\ndb.productionprints != db.productionPrints\n```\n\n```text\ninclude: [ { } ]\n```\n\n```text\n[{model: Model, as: 'assciationName'}]\n```\n\n========================================\n\nComments:\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":211,"estimatedTokens":1351}}1010{"id":"stack-63398544","source":"stackoverflow","questionId":63398544,"title":"Transaction cannot be rolled back because it has been finished","tags":["javascript","node.js","sequelize.js"],"text":"Title: Transaction cannot be rolled back because it has been finished\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create an order and associate the order with products and quantities :\n\n```\nconst t = await sequelize.transaction();\n try {\n const local_orderInstance = await LocalOrder.create({\n user: req.body.client,\n timestamp: Date.now(),\n }, {transaction: t})\n for(let order_item of req.body.items) {\n const order_itemInstance = await LocalOrderItem.create({\n quantity: order_item.quantity,\n ProductReference: order_item.reference,\n LocalOrderId: local_orderInstance.id\n }, {transaction: t})\n await t.commit()\n res.json({message: `successfully saved order`})\n }\n } catch(error) {\n await t.rollback()\n res.status(503).json(error)\n }\n```\n\nhttps://i.sstatic.net/R9F5W.png\n\nAs you can see, it's very similar to the example in the sequelize documentation but a weird thing is happening, even when there is no error with all the inserts in the database, (t.commit() is called), apparently it still goes in the catch section and tries to rollback. And after that I get the error \"Transaction cannot be rolled back because it has been finished with state: commit\"\nWhy does it try to execute the catch section even though there is no exception thrown ?\nI am also getting this \"[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\" It really wants me to try catch the rollback ? Well I tried and I am getting \" Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client\"\nIs nodejs broken ?\n\n========================================\n\nCode:\n```text\nconst t = await sequelize.transaction();\n  try {\n    const local_orderInstance = await LocalOrder.create({\n      user: req.body.client,\n      timestamp: Date.now(),\n    }, {transaction: t})\n    for(let order_item of req.body.items) {\n      const order_itemInstance = await LocalOrderItem.create({\n        quantity: order_item.quantity,\n        ProductReference: order_item.reference,\n        LocalOrderId: local_orderInstance.id\n      }, {transaction: t})\n      await t.commit()\n      res.json({message: `successfully saved order`})\n    }\n  } catch(error) {\n    await t.rollback()\n    res.status(503).json(error)\n  }\n```\n\n```text\nconst t = await sequelize.transaction();\n  try {\n    const local_orderInstance = await LocalOrder.create({\n      user: req.body.client,\n      timestamp: Date.now(),\n    }, {transaction: t})\n    for(let order_item of req.body.items) {\n      const order_itemInstance = await LocalOrderItem.create({\n        quantity: order_item.quantity,\n        ProductReference: order_item.reference,\n        LocalOrderId: local_orderInstance.id\n      }, {transaction: t})  \n    }\n    await t.commit() // <--- move outside of loop\n    res.json({message: `successfully saved order`})\n  } catch(error) {\n    await t.rollback()\n    res.status(503).json(error)\n  }\n```\n\n========================================\n\nComments:\n- probably you call commit in one iteration but failed at somewhere next\n- you should commit after the loop. or create new transaction object each iteration.\n- Oh I didn't realize I committed in the loop damn\n- Well it solved thanks, I think I need some rest :D\n- glad it helps :)","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":91,"estimatedTokens":840}}1011{"id":"stack-62431589","source":"stackoverflow","questionId":62431589,"title":"sequelize/sequelize-typescript - findAll with HasMany returns an object instead of an array","tags":["node.js","typescript","sequelize.js","sequelize-typescript"],"text":"Title: sequelize/sequelize-typescript - findAll with HasMany returns an object instead of an array\nTags: node.js, typescript, sequelize.js, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a one-to-many relationship using sequelize-typescript.\nBut when I try to get the data, the relationship for many, returns me an object instead of an array\n\nI have two tables. Team and Players.\n\nTeam can has many players, and a player belongs to a team.\n\nMy models:\n\n```\n@Table\nexport class Team extends Model {\n @Column\n name: string\n\n @HasMany(() => Player)\n players: Player[]\n}\n\n@Table\nexport class Player extends Model {\n @Column\n name: string\n\n @Column\n num: number\n\n @ForeignKey(() => Team)\n @Column\n teamId: number\n\n @BelongsTo(() => Team)\n team: Team\n}\n```\n\nWhen I run:\n\n```\nTeam.findAll({ include: [Player] })\n```\n\nI get this:\n\n```\n[\n {\n \"id\": 1,\n \"name\": \"My Team\",\n \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n \"updatedAt\": \"2020-06-17T14:23:03.000Z\",\n \"players\": {\n \"id\": 1,\n \"name\": \"Player One\",\n \"num\": 10,\n \"teamId\": 1,\n \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n }\n },\n {\n \"id\": 1,\n \"name\": \"My Team\",\n \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n \"updatedAt\": \"2020-06-17T14:23:03.000Z\",\n \"players\": {\n \"id\": 2,\n \"name\": \"Player Two\",\n \"num\": 99,\n \"teamId\": 1,\n \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n }\n }\n]\n```\n\nbut I need get this:\n\n```\n[\n {\n \"id\": 1,\n \"name\": \"My Team\",\n \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n \"updatedAt\": \"2020-06-17T14:23:03.000Z\",\n \"players\": [\n {\n \"id\": 1,\n \"name\": \"Player One\",\n \"num\": 10,\n \"teamId\": 1,\n \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n },\n {\n \"id\": 2,\n \"name\": \"Player Two\",\n \"num\": 99,\n \"teamId\": 1,\n \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n }\n ]\n }\n]\n```\n\nI don't know if I'm doing something wrong, or if it's a problem with sequelize-typescript, or if it's a problem with sequelize.\n\ncan anybody help me?\n\n========================================\n\nCode:\n```text\n@Table\nexport class Team extends Model<Team> {\n  @Column\n  name: string\n\n  @HasMany(() => Player)\n  players: Player[]\n}\n\n@Table\nexport class Player extends Model<Player> {\n  @Column\n  name: string\n\n  @Column\n  num: number\n\n  @ForeignKey(() => Team)\n  @Column\n  teamId: number\n\n  @BelongsTo(() => Team)\n  team: Team\n}\n```\n\n```text\nTeam.findAll({ include: [Player] })\n```\n\n```text\n[\n  {\n    \"id\": 1,\n    \"name\": \"My Team\",\n    \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n    \"updatedAt\": \"2020-06-17T14:23:03.000Z\",\n    \"players\": {\n      \"id\": 1,\n      \"name\": \"Player One\",\n      \"num\": 10,\n      \"teamId\": 1,\n      \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n      \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n    }\n  },\n  {\n    \"id\": 1,\n    \"name\": \"My Team\",\n    \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n    \"updatedAt\": \"2020-06-17T14:23:03.000Z\",\n    \"players\": {\n      \"id\": 2,\n      \"name\": \"Player Two\",\n      \"num\": 99,\n      \"teamId\": 1,\n      \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n      \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n    }\n  }\n]\n```\n\n```text\n[\n  {\n    \"id\": 1,\n    \"name\": \"My Team\",\n    \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n    \"updatedAt\": \"2020-06-17T14:23:03.000Z\",\n    \"players\": [\n      {\n        \"id\": 1,\n        \"name\": \"Player One\",\n        \"num\": 10,\n        \"teamId\": 1,\n        \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n        \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n      },\n      {\n        \"id\": 2,\n        \"name\": \"Player Two\",\n        \"num\": 99,\n        \"teamId\": 1,\n        \"createdAt\": \"2020-06-17T14:23:03.000Z\",\n        \"updatedAt\": \"2020-06-17T14:23:03.000Z\"\n      }\n    ]\n  }\n]\n```\n\n```text\nTeam.findAll({\n        include: [\n            Player\n        ],\n        raw: true // <-- problem\n    }\n)\n```\n\n```text\n[\n  {\n    \"id\": 1,\n    \"name\": \"Team 1\",\n    \"players.id\": 1,\n    \"players.name\": \"Player 1\",\n    \"players.num\": 1,\n    \"players.teamId\": 1\n  },\n  {\n    \"id\": 1,\n    \"name\": \"Team 1\",\n    \"players.id\": 2,\n    \"players.name\": \"Player 2\",\n    \"players.num\": 2,\n    \"players.teamId\": 1\n  }\n]\n```\n\n```text\nTeam.findAll({\n        include: [\n            Player\n        ]\n    }\n)\n```\n\n```text\n[\n   {\n      \"id\":1,\n      \"name\":\"Team 1\",\n      \"players\":[\n         {\n            \"id\":1,\n            \"name\":\"Player 1\",\n            \"num\":1,\n            \"teamId\":1\n         },\n         {\n            \"id\":2,\n            \"name\":\"Player 2\",\n            \"num\":2,\n            \"teamId\":1\n         }\n      ]\n   }\n]\n```\n\n```text\nraw: true\n```\n\n========================================\n\nComments:\n- Thank you very much, that was the problem. I was using `raw: true` and `nest: true` as a hook beforeFind. I didn't know that these options caused this problem.","metadata":{"transformedAt":"2026-08-18T18:33:34.495Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":284,"estimatedTokens":1197}}1012{"id":"stack-60536763","source":"stackoverflow","questionId":60536763,"title":"Sequilize query is returning only one row while using include","tags":["mysql","node.js","express","select","sequelize.js"],"text":"Title: Sequilize query is returning only one row while using include\nTags: mysql, node.js, express, select, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**Context :** I am having this problem were I am doing a query using sequilize an it only return's me an array with one position even though I have more than one field that correspond to the query.\n\n**This are my two involved models**\n\nThis is my **group.js** model\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Group = sequelize.define('Group', {\n name: DataTypes.STRING,\n limit: DataTypes.STRING,\n user_id: DataTypes.INTEGER\n });\n\n Group.associate = models => {\n Group.belongsTo(models.User, { foreignKey: 'user_id' });\n };\n\n Group.associate = models => {\n Group.hasMany(models.Movement, { foreignKey: 'group_id' });\n };\n\n return Group;\n}\n```\n\nThis is my **movement.js** model\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const Mov = sequelize.define('Movement', {\n description: DataTypes.STRING,\n value: DataTypes.INTEGER,\n group_id: DataTypes.INTEGER\n });\n\n Mov.associate = models => {\n Mov.hasOne(models.Group, { foreignKey: 'group_id' });\n };\n\n return Mov;\n}\n```\n\nThis is my **query** (where you will see that I am doing an `INNER JOIN` to `SUM` the fields of the **Movement** table)\n\n```\nrouter.get('/', verify, async (req, res) => {\n try {\n const group = await Group.findAll({\n attributes: [\n 'id',\n 'name',\n 'limit',\n [sequelize.fn('SUM', sequelize.col('Movements.value')), 'total_spent'],\n ],\n include: [{\n attributes: [], // this is empty because I want to hide the Movement object in this query (if I want to show the object just remove this)\n model: Movement,\n required: true\n }],\n where: {\n user_id: req.userId\n }\n });\n if (group.length === 0) return res.status(400).json({ error: \"This user has no groups\" })\n res.status(200).json({ groups: group }) //TODO see why this is onyl return one row\n } catch (error) {\n console.log(error)\n res.status(400).json({ Error: \"Error while fetching the groups\" });\n }\n});\n```\n\n**Problem** is that it only return's one position of the expected array :\n\n```\n{\n \"groups\": [\n {\n \"id\": 9,\n \"name\": \"rgrgrg\",\n \"limit\": 3454354,\n \"total_spent\": \"2533\"\n }\n ]\n}\n```\n\nIt **should** return 2 positions\n\n```\n{\n \"groups\": [\n {\n \"id\": 9,\n \"name\": \"rgrgrg\",\n \"limit\": 3454354,\n \"total_spent\": \"2533\"\n },\n {\n \"id\": 9,\n \"name\": \"rgrgrg\",\n \"limit\": 3454354,\n \"total_spent\": \"2533\"\n }\n ]\n}\n```\n\nThis is the query sequilize is giving me:\n\n```\nSELECT `Group`.`id`, `Group`.`name`, `Group`.`limit`, SUM(`Movements`.`value`) AS `total_spent` FROM `Groups` AS `Group` INNER JOIN `Movements` AS `Movements` ON `Group`.`id` = `Movements`.`group_id` WHERE `Group`.`user_id` = 1;\n```\n\n========================================\n\nTop Answer:\nMany-to-many \"through\" table with multiple rows of identical foreign key pairs only returns one result?\n\nI just ran into this bug and added this options to the main query:\n\n```\n{\n raw: true,\n plain: false, \n nest: true\n}\n```\n\nThen you just merge the query.\n\nIt's a workaround, but might help someone.\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Group = sequelize.define('Group', {\n        name: DataTypes.STRING,\n        limit: DataTypes.STRING,\n        user_id: DataTypes.INTEGER\n    });\n\n    Group.associate = models => {\n        Group.belongsTo(models.User, { foreignKey: 'user_id' });\n    };\n\n    Group.associate = models => {\n        Group.hasMany(models.Movement, { foreignKey: 'group_id' });\n    };\n\n    return Group;\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const Mov = sequelize.define('Movement', {\n        description: DataTypes.STRING,\n        value: DataTypes.INTEGER,\n        group_id: DataTypes.INTEGER\n    });\n\n    Mov.associate = models => {\n        Mov.hasOne(models.Group, { foreignKey: 'group_id' });\n    };\n\n    return Mov;\n}\n```\n\n```text\nrouter.get('/', verify, async (req, res) => {\n    try {\n        const group = await Group.findAll({\n            attributes: [\n                'id',\n                'name',\n                'limit',\n                [sequelize.fn('SUM', sequelize.col('Movements.value')), 'total_spent'],\n            ],\n            include: [{\n                attributes: [], // this is empty because I want to hide the Movement object in this query (if I want to show the object just remove this)\n                model: Movement,\n                required: true\n            }],\n            where: {\n                user_id: req.userId\n            }\n        });\n        if (group.length === 0) return res.status(400).json({ error: \"This user has no groups\" })\n        res.status(200).json({ groups: group }) //TODO see why this is onyl return one row\n    } catch (error) {\n        console.log(error)\n        res.status(400).json({ Error: \"Error while fetching the groups\" });\n    }\n});\n```\n\n```text\n{\n    \"groups\": [\n        {\n            \"id\": 9,\n            \"name\": \"rgrgrg\",\n            \"limit\": 3454354,\n            \"total_spent\": \"2533\"\n        }\n    ]\n}\n```\n\n```text\n{\n    \"groups\": [\n        {\n            \"id\": 9,\n            \"name\": \"rgrgrg\",\n            \"limit\": 3454354,\n            \"total_spent\": \"2533\"\n        },\n    {\n            \"id\": 9,\n            \"name\": \"rgrgrg\",\n            \"limit\": 3454354,\n            \"total_spent\": \"2533\"\n        }\n    ]\n}\n```\n\n```text\nSELECT `Group`.`id`, `Group`.`name`, `Group`.`limit`, SUM(`Movements`.`value`) AS `total_spent` FROM `Groups` AS `Group` INNER JOIN `Movements` AS `Movements` ON `Group`.`id` = `Movements`.`group_id` WHERE `Group`.`user_id` = 1;\n```\n\n```text\nINNER JOIN\n```\n\n```text\nSUM\n```\n\n```text\nconst group = await Group.findAll({\n    attributes: [\n        'id',\n        'name',\n        'limit',\n        [sequelize.fn('SUM', sequelize.col('Movements.value')), 'total_spent'],\n    ],\n    include: [{\n        attributes: [], // this is empty because I want to hide the Movement object in this query (if I want to show the object just remove this)\n        model: Movement,\n        required: true\n    }],\n    where: {\n        user_id: req.userId\n    },\n    group: '`Movements`.`group_id`'\n});\n```\n\n```text\n{\n  raw: true,\n  plain: false, \n  nest: true\n}\n```\n\n```sql\nSELECT super_long_column_name AS super_long_table_name.super_long_column_name\nFROM super_long_table_name;\n\n-- # super_long_table_name.super_long_column_name will be truncated to something like super_long_table_name.supe\n-- # Not sure about the exact char limit.\n```\n\n```js\nconst nestedObject = await Table1.findAll({\n  include: [\n    {\n      model: SuperLongTableName,\n      as: \"super_long_table_name\"\n    },\n    // ...\n  ]\n});\n```\n\n```js\nconst nestedObject = await Table1.findAll({\n  include: [\n    {\n      model: SuperLongTableName,\n      as: \"sltn\"\n    },\n    // ...\n  ]\n});\n```\n\n```text\nraw: true\n```\n\n```text\nJOIN\n```\n\n```text\nawait Ride.findAll({`enter code here`\n  where: { id: 1 },\n  include: [\n    {\n      model: RidesSampleRequestsMapper,\n      include: [\n        {\n          model: SampleRequest,\n          include: [\n            {\n              model: SamplerequestParameterMappers,\n              separate: true,  // Fetch in a separate sub-query\n            },\n          ],\n        },\n      ],\n    },\n  ],\n  distinct: true, // Ensures unique results across the associations\n});\n```\n\n========================================\n\nComments:\n- Are you sure, do you have multiple datas in the group table?\n- it did not worked. At some point I did this : SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); because I had an error. Can this be the cause of the problem?\n- I think you have not posted your Sequelize statement correctly. In the Sequelize statement mentioned in the question, there is no group by clause. Can you please check and post the sequelize statement with group by clause?\n- Yes there is not, and I still have this error on the database? That's the strange part, I had to put this in order to query the database\n- Can you please the query that you want to generate and the query that Sequelize is generating?\n- just updated the question with the query sequilize is giving me, it's the query I want, The problem is that is only returning one row and it should return more\n- I guess you need to add an appropriate group by clause and I guess in your case it is `group: '`Movements`.`group_id`'`\n- yes that worked. Please put that in your answer(and remove the raw:true) and I will approve it. Thanks\n- @Jos&#233;Nobre, Welcome, Glad to know that your issue is fixed. As you suggested I have updated my answer.\n- It did not work for me. Unsetting these properties fixed the issue though. I was expecting an array, even if it had just one object.","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":355,"estimatedTokens":2171}}1013{"id":"stack-59695989","source":"stackoverflow","questionId":59695989,"title":"How to get data with just inserted data with Sequelize in PostgreSql?","tags":["javascript","node.js","postgresql","express","sequelize.js"],"text":"Title: How to get data with just inserted data with Sequelize in PostgreSql?\nTags: javascript, node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to get updated table values after I add user to my \"WOD\" table. For instance, I have 2 users in my WOD table and after I add third user , I want to return a response to client with I have just inserted data (third guy). But now , I can only return first 2 users because I can not take updated values. Of course I can make another query to get updated table values after I insert, but is there any better solution ? Here is my codes;\n\n```\nconst addUser = async (req, res) => {\n try {\nconst { userId, wodId } = req.body;\n\nif (!userId || !wodId) {\n res.status(400).send({ status: false, message: 'need userId and wodId' });\n}\n\nconst wod = await Wod.findByPk(wodId, {\n include: [\n {\n model: User,\n as: 'Participants',\n through: { attributes: [] }\n }\n ]\n});\n//check capacity if full.\nif (wod.Participants.length >= wod.capacity) {\n res\n .status(403)\n .send({ status: false, message: 'Capacity of this class is full!' });\n}\nconst result = await wod.addParticipants(userId);\n\nres.status(201).json({ status: !!result, wod });\n} catch (error) {\nres.status(500).send({ status: result, message: error.message });\nconsole.log(error.message);\n }\n};\n```\n\n========================================\n\nCode:\n```text\nconst addUser = async (req, res) => {\n try {\nconst { userId, wodId } = req.body;\n\nif (!userId || !wodId) {\n  res.status(400).send({ status: false, message: 'need userId and wodId' });\n}\n\nconst wod = await Wod.findByPk(wodId, {\n  include: [\n    {\n      model: User,\n      as: 'Participants',\n      through: { attributes: [] }\n    }\n  ]\n});\n//check capacity if full.\nif (wod.Participants.length >= wod.capacity) {\n  res\n    .status(403)\n    .send({ status: false, message: 'Capacity of this class is full!' });\n}\nconst result = await wod.addParticipants(userId);\n\nres.status(201).json({ status: !!result, wod });\n} catch (error) {\nres.status(500).send({ status: result, message: error.message });\nconsole.log(error.message);\n  }\n};\n```\n\n```text\nawait wod.reload()\n```\n\n```text\nINSERT INTO 'user_wods' ('user_id''wod_id') VALUES (2,1)\n```\n\n```text\nSELECT * FROM 'user' WHERE 'id'=2\n```\n\n========================================\n\nComments:\n- Thanks a lot buddy. I have not known reload method. It works (update object without creating another one.)","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":94,"estimatedTokens":605}}1014{"id":"stack-54883499","source":"stackoverflow","questionId":54883499,"title":"Sequelize createdAt and updatedAt","tags":["node.js","sql-server","express","sequelize.js"],"text":"Title: Sequelize createdAt and updatedAt\nTags: node.js, sql-server, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using node, express, mssql and seqelize orm, but when I am fired a query it gives error column cratedAt not declared at save the query\n\n========================================\n\nCode:\n```text\nsequelize.define('modelName', {\n// props\n},{\n    timestamps: false\n})\n```\n\n========================================\n\nComments:\n- it got resolved if we create column createdAt and updatedAt and also declare it in Model, But I don't want to use this two column so how can I suppress it","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":22,"estimatedTokens":151}}1015{"id":"stack-50837222","source":"stackoverflow","questionId":50837222,"title":"Identify Sequelize model in global hook","tags":["sequelize.js"],"text":"Title: Identify Sequelize model in global hook\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm looking to add some low level logging to all of my Sequelize operations via global hooks. Something like this:\n\n`db.addHook('beforeUpdate', (instance, options) => {\n log.info({ instance, options }, `Updating ${modelName} ${instance.get('id')}`);\n});`\n\nWhat I haven't figured out is how to populate `modelName` or even whether it's possible (although the lack of information I've found is indicative that it may not be possible). Any chance this *is* possible and I just haven't found the key?\n\nAs logged, here's the instance value:\n\n`instance: {\n \"id\": null,\n \"nonIncarcerationAgreementIndicator\": true,\n \"insuranceApplicationId\": 22,\n \"updatedAt\": \"2018-06-13T13:55:10.978Z\",\n \"createdAt\": \"2018-06-13T13:55:10.978Z\"\n}`\n\nThe `options` are too long to list, but nowhere do they mention the model name.\n\n========================================\n\nCode:\n```text\ndb.addHook('beforeUpdate', (instance, options) => {\n  log.info({ instance, options }, `Updating ${modelName} ${instance.get('id')}`);\n});\n```\n\n```text\nmodelName\n```\n\n```text\ninstance: {\n  \"id\": null,\n  \"nonIncarcerationAgreementIndicator\": true,\n  \"insuranceApplicationId\": 22,\n  \"updatedAt\": \"2018-06-13T13:55:10.978Z\",\n  \"createdAt\": \"2018-06-13T13:55:10.978Z\"\n}\n```\n\n```text\noptions\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = new Sequelize('test_db', 'postgres', 'postgres', {\n  host: '127.0.0.1',\n  dialect: 'postgres',\n  define: {\n    hooks: {\n      beforeCreate: (model, options) => {\n        console.log(model.constructor.name);\n      }\n    }\n  }\n});\nconst User = sequelize.define('user', {\n  username: Sequelize.STRING,\n});\n\nUser.create({\n  username: 'UserOne',\n  projects: {\n    projectName: 'projectOne'\n  }\n}).then((user) => {\n  console.log(user);\n})\n```\n\n========================================\n\nComments:\n- Will you please the output of `instance` and `options` ?\n- Added the `instance` output and referenced `options` which is longer than would be useful since it doesn't mention the model name.","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":84,"estimatedTokens":526}}1016{"id":"stack-53831372","source":"stackoverflow","questionId":53831372,"title":"Subtract value from previous row value if it is greater than the max value","tags":["postgresql","sequelize.js"],"text":"Title: Subtract value from previous row value if it is greater than the max value\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIm using Postgresql & Sequelize. I have to find the consumption from the reading table. Currently, I have the query to subtract the value from the previous row. But the problem was If the value is less than the previous value means I have to ignore the row and need to wait for the greater value to make the calculation. \n\nCurrent Query\n\n```\nselect \"readingValue\",\n \"readingValue\" - coalesce(lag(\"readingValue\") over (order by \"id\")) as consumption\nfrom public.\"EnergyReadingTbl\";\n```\n\nExample Record & Current Output\n\n```\nid readingValue consumption\n\n65479 \"35.8706703186035\" \"3.1444168090820\"\n65480 \"39.0491638183594\" \"3.1784934997559\"\n65481 \"42.1287002563477\" \"3.0795364379883\"\n65482 \"2.38636064529419\" \"-39.74233961105351\"\n65483 \"5.91744041442871\" \"3.53107976913452\"\n65484 \"9.59204387664795\" \"3.67460346221924\"\n65485 \"14.3925561904907\" \"4.80051231384275\"\n65486 \"19.4217891693115\" \"5.0292329788208\"\n65487 \"24.2393398284912\" \"4.8175506591797\"\n65488 \"29.2515335083008\" \"5.0121936798096\"\n65489 \"34.2519302368164\" \"5.0003967285156\"\n65490 \"38.6513633728027\" \"4.3994331359863\"\n65491 \"43.7513643778087\" \"5.1000010050060\"\n```\n\nIn this picture, the last max value was 42.1287002563477. I have to wait until to get the greater value than 42.1287002563477 to make the calculation like the next greater value - 42.1287002563477. In this, 43.7513643778087 - 42.1287002563477.\n\nExpected Output\n\n```\nid readingValue consumption\n\n65479 \"35.8706703186035\" \"3.1444168090820\"\n65480 \"39.0491638183594\" \"3.1784934997559\"\n65481 \"42.1287002563477\" \"3.0795364379883\"\n65482 \"2.38636064529419\" \"0\"\n65483 \"5.91744041442871\" \"0\"\n65484 \"9.59204387664795\" \"0\"\n65485 \"14.3925561904907\" \"0\"\n65486 \"19.4217891693115\" \"0\"\n65487 \"24.2393398284912\" \"0\"\n65488 \"29.2515335083008\" \"0\"\n65489 \"34.2519302368164\" \"0\"\n65490 \"38.6513633728027\" \"0\"\n65491 \"43.7513643778087\" \"1.1226641214710\"\n```\n\nIs there any chance to resolve this issue in the query?\n\n========================================\n\nCode:\n```text\nselect \"readingValue\",\n       \"readingValue\" - coalesce(lag(\"readingValue\") over (order by \"id\")) as consumption\nfrom public.\"EnergyReadingTbl\";\n```\n\n```text\nid      readingValue        consumption\n\n65479   \"35.8706703186035\"  \"3.1444168090820\"\n65480   \"39.0491638183594\"  \"3.1784934997559\"\n65481   \"42.1287002563477\"  \"3.0795364379883\"\n65482   \"2.38636064529419\"  \"-39.74233961105351\"\n65483   \"5.91744041442871\"  \"3.53107976913452\"\n65484   \"9.59204387664795\"  \"3.67460346221924\"\n65485   \"14.3925561904907\"  \"4.80051231384275\"\n65486   \"19.4217891693115\"  \"5.0292329788208\"\n65487   \"24.2393398284912\"  \"4.8175506591797\"\n65488   \"29.2515335083008\"  \"5.0121936798096\"\n65489   \"34.2519302368164\"  \"5.0003967285156\"\n65490   \"38.6513633728027\"  \"4.3994331359863\"\n65491   \"43.7513643778087\"  \"5.1000010050060\"\n```\n\n```text\nid      readingValue        consumption\n\n65479   \"35.8706703186035\"  \"3.1444168090820\"\n65480   \"39.0491638183594\"  \"3.1784934997559\"\n65481   \"42.1287002563477\"  \"3.0795364379883\"\n65482   \"2.38636064529419\"  \"0\"\n65483   \"5.91744041442871\"  \"0\"\n65484   \"9.59204387664795\"  \"0\"\n65485   \"14.3925561904907\"  \"0\"\n65486   \"19.4217891693115\"  \"0\"\n65487   \"24.2393398284912\"  \"0\"\n65488   \"29.2515335083008\"  \"0\"\n65489   \"34.2519302368164\"  \"0\"\n65490   \"38.6513633728027\"  \"0\"\n65491   \"43.7513643778087\"  \"1.1226641214710\"\n```\n\n```text\nSELECT readingValue,\n       MAX(readingValue) OVER (ORDER BY id) - MAX(readingValue) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\nFROM e;\n\n┌──────────────────┬─────────────────┐\n│   readingvalue   │    ?column?     │\n├──────────────────┼─────────────────┤\n│ 35.8706703186035 │          (null) │\n│ 39.0491638183594 │ 3.1784934997559 │\n│ 42.1287002563477 │ 3.0795364379883 │\n│ 2.38636064529419 │               0 │\n│ 5.91744041442871 │               0 │\n│ 9.59204387664795 │               0 │\n│ 14.3925561904907 │               0 │\n│ 19.4217891693115 │               0 │\n│ 24.2393398284912 │               0 │\n│ 29.2515335083008 │               0 │\n│ 34.2519302368164 │               0 │\n│ 38.6513633728027 │               0 │\n│ 43.7513643778087 │  1.622664121461 │\n└──────────────────┴─────────────────┘\n(13 rows)\n\nTime: 0,430 ms\n```\n\n```text\nROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING\n```\n\n```text\nMAX\n```\n\n```text\nMAX\n```\n\n========================================\n\nComments:\n- Please add some sample data (as text not as image) and expected output\n- @S-Man - Updated\n- Thanks a lot. Got the Solution as expected\n- This is a really great one!","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":150,"estimatedTokens":1157}}1017{"id":"stack-57893394","source":"stackoverflow","questionId":57893394,"title":"Sequelize associations / models suddenly not recognized when nothing was changed, Vague Error Cannot Read Property 'field' of undefined","tags":["node.js","reactjs","express","redux","sequelize.js"],"text":"Title: Sequelize associations / models suddenly not recognized when nothing was changed, Vague Error Cannot Read Property 'field' of undefined\nTags: node.js, reactjs, express, redux, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've been working on this project using React, node, sequelize, Redux for a while and everything has been running great. The other day I decided to update some of my node packages as I try to do every so often, but Sequelize suddenly broke right after I ran `npm update --save/--save-dev`.\n\nAll of a sudden, when I try to run the app, my initial fetches to sql fail, and my sequelize models are throwing an error:\n\n```\n/node_modules/sequelize/lib/associations/belongs-to-many.js:130\n this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;\n ^\n\nTypeError: Cannot read property 'field' of undefined\n at new BelongsToMany (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/node_modules/sequelize/lib/associations/belongs-to-many.js:130:69)\n at Function.belongsToMany (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/node_modules/sequelize/lib/associations/mixin.js:64:25)\n at Object. (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/authenticationBI.js:63:12)\n at Module._compile (internal/modules/cjs/loader.js:776:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at Module.load (internal/modules/cjs/loader.js:643:32)\n at Function.Module._load (internal/modules/cjs/loader.js:556:12)\n at Module.require (internal/modules/cjs/loader.js:683:19)\n at require (internal/modules/cjs/helpers.js:16:16)\n at Object. (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/api/routes/backgroundInstrumentalsRoutes.js:6:36)\n at Module._compile (internal/modules/cjs/loader.js:776:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at Module.load (internal/modules/cjs/loader.js:643:32)\n at Function.Module._load (internal/modules/cjs/loader.js:556:12)\n at Module.require (internal/modules/cjs/loader.js:683:19)\n at require (internal/modules/cjs/helpers.js:16:16)\n at Object. (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/server.js:4:39)\n at Module._compile (internal/modules/cjs/loader.js:776:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at Module.load (internal/modules/cjs/loader.js:643:32)\n at Function.Module._load (internal/modules/cjs/loader.js:556:12)\n at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)\n```\n\nThat's weird. I've only been working on the front-end recently. I haven't even touched any of the sequelize models, associations, or controllers in over a month, not to mention the associations have been working without error for over three months, yet all of a sudden it's saying its not valid. \n\nOkay. Fine. Not a big deal. Sequelize just didn't like one of those modules, so I'll reset my git head, trash my modules folder, and figure out which module it doesn't like.\n\nI reset git head, delete my modules folder, and run `npm i`.\n\nTHE SAME ERROR IS STILL COMING UP WHEN I WAS NEVER GETTING THIS ERROR BEFORE.\n\nThis is preventing the sequelize association tables from being created, thus my app can't even start. \n\nI comment out the sequelize associations causing the error and now the sequelize is running fine, but I need those associations in order for certain features of my application to work. \n\nI'm about ready to pull my hair out this shit is frustrating the hell out of me. I don't even know what to do anymore. I tried messing with my associations by changing the methods but literally nothing works.\n\nHere are the sequelize associations it apparently has an issue with. To clarify, there can be multiple styles per category, but each style only has one category. \n\n```\nCategoryBI.belongsToMany(StyleBI,\n { constraints: false,\n timestamps: false,\n foreignKey: \"cat_id\",\n sourceKey: \"style_id\",\n through: \"cat_styles\"\n });\n\nStyleBI.belongsTo(CategoryBI,\n { constraints: false,\n timestamps: false,\n foreignKey: \"cat_id\",\n targetKey: \"cat_id\",\n through: \"cat_styles\"\n });\n```\n\nAND the models:\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define(\"categories\", {\n cat_id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n cat_name: {\n type: DataTypes.STRING(50),\n allowNull: true\n }\n }, {\n tableName: \"categories\",\n underscored: true,\n timestamps: false\n });\n};\n```\n\n```\nmodule.exports = function(sequelize, DataTypes) {\n return sequelize.define(\"styles\", {\n style_id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true\n },\n cat_id: {\n type: DataTypes.INTEGER(8),\n allowNull: false,\n defaultValue: \"0\"\n },\n style_name: {\n type: DataTypes.STRING(50),\n allowNull: true\n },\n style_img: {\n type: DataTypes.STRING(55),\n allowNull: true\n }\n }, {\n tableName: \"styles\",\n underscored: true,\n timestamps: false\n });\n};\n```\n\n========================================\n\nCode:\n```text\n/node_modules/sequelize/lib/associations/belongs-to-many.js:130\n    this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;\n                                                                    ^\n\nTypeError: Cannot read property 'field' of undefined\n    at new BelongsToMany (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/node_modules/sequelize/lib/associations/belongs-to-many.js:130:69)\n    at Function.belongsToMany (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/node_modules/sequelize/lib/associations/mixin.js:64:25)\n    at Object.<anonymous> (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/authenticationBI.js:63:12)\n    at Module._compile (internal/modules/cjs/loader.js:776:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n    at Module.load (internal/modules/cjs/loader.js:643:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:556:12)\n    at Module.require (internal/modules/cjs/loader.js:683:19)\n    at require (internal/modules/cjs/helpers.js:16:16)\n    at Object.<anonymous> (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/api/routes/backgroundInstrumentalsRoutes.js:6:36)\n    at Module._compile (internal/modules/cjs/loader.js:776:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n    at Module.load (internal/modules/cjs/loader.js:643:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:556:12)\n    at Module.require (internal/modules/cjs/loader.js:683:19)\n    at require (internal/modules/cjs/helpers.js:16:16)\n    at Object.<anonymous> (/Users/dlmusic/Desktop/Cullan - Site/Metadata-Tagging-With-Redux/server.js:4:39)\n    at Module._compile (internal/modules/cjs/loader.js:776:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n    at Module.load (internal/modules/cjs/loader.js:643:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:556:12)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)\n```\n\n```text\nCategoryBI.belongsToMany(StyleBI,\n  { constraints: false,\n    timestamps: false,\n    foreignKey: \"cat_id\",\n    sourceKey: \"style_id\",\n    through: \"cat_styles\"\n  });\n\nStyleBI.belongsTo(CategoryBI,\n  { constraints: false,\n    timestamps: false,\n    foreignKey: \"cat_id\",\n    targetKey: \"cat_id\",\n    through: \"cat_styles\"\n  });\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define(\"categories\", {\n    cat_id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    cat_name: {\n      type: DataTypes.STRING(50),\n      allowNull: true\n    }\n  }, {\n    tableName: \"categories\",\n    underscored: true,\n    timestamps: false\n  });\n};\n```\n\n```text\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define(\"styles\", {\n    style_id: {\n      type: DataTypes.INTEGER(11),\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    cat_id: {\n      type: DataTypes.INTEGER(8),\n      allowNull: false,\n      defaultValue: \"0\"\n    },\n    style_name: {\n      type: DataTypes.STRING(50),\n      allowNull: true\n    },\n    style_img: {\n      type: DataTypes.STRING(55),\n      allowNull: true\n    }\n  }, {\n    tableName: \"styles\",\n    underscored: true,\n    timestamps: false\n  });\n};\n```\n\n```text\nnpm update --save/--save-dev\n```\n\n```text\nnpm i\n```\n\n```text\nCategoryBI.hasMany(StyleBI,\n  { constraints: false,\n    timestamps: false,\n    foreignKey: \"style_id\",\n    sourceKey: \"cat_id\"\n  });\n\nStyleBI.belongsTo(CategoryBI,\n  { constraints: false,\n    timestamps: false,\n    foreignKey: \"style_id\",\n    targetKey: \"cat_id\"\n  });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":251,"estimatedTokens":2197}}1018{"id":"stack-48736603","source":"stackoverflow","questionId":48736603,"title":"Using both \"AND\" and \"OR\" in a scope in Sequelize js","tags":["javascript","express","orm","sequelize.js"],"text":"Title: Using both \"AND\" and \"OR\" in a scope in Sequelize js\nTags: javascript, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nEncountering more trouble with the lovely Sequelize JS.\n\nI'm trying to put the following query into a Sequelize scope. \n\n```\nSELECT *\nFROM Projects\nWHERE isDeleted IS NOT true\nAND ( \n ( importSource IS NOT null ) AND ( createdAt BETWEEN '2018-01-19' AND '2018-01-29') \n OR \n ( importSource IS null ) AND ( createdAt > '2018-01-19' )\n)\n```\n\nTrying this at the moment to no avail in my model.\n\n```\nscopes: {\n active: {\n where: {\n isDeleted: {\n [Op.not]: true\n },\n [Op.or]: [\n {\n importSource: { [Op.ne]: null },\n createdAt: {\n [Op.between]: [\n new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),\n new Date(new Date() - 4 * (24 * 60 * 60 * 1000))\n ],\n }\n },\n {\n importSource: { [Op.eq]: null },\n createdAt: {\n [Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),\n }\n }\n ]\n }\n }\n}\n```\n\nThere is no error. Just this the following MySQL that's being run.\n\n```\nExecuting (default): SELECT `id`, `url`, `title`, `company`, `importSource`, `importSourceId`, `publishedAt`, `createdAt`, `updatedAt` FROM `Projects` AS `Project` WHERE `Project`.`isDeleted` IS NOT true ORDER BY `Project`.`id` DESC LIMIT 5;\n```\n\nAnd here is the controller method calling the model and scope.\n\n```\nexports.index = (req, res) => {\n const MAX = 50;\n var numberProjects = ((req.query.number) ? req.query.number : MAX);\n numberProjects = ((numberProjects > MAX) ? MAX : numberProjects);\n\n Project.scope('active').findAll({\n order: [\n ['id', 'DESC']\n ],\n limit: +numberProjects\n })\n .then( projects => {\n res.send( projects );\n })\n};\n```\n\nAny help appreciated.\n\n========================================\n\nCode:\n```text\nSELECT *\nFROM Projects\nWHERE isDeleted IS NOT true\nAND ( \n    ( importSource IS NOT null ) AND ( createdAt BETWEEN '2018-01-19' AND '2018-01-29') \n    OR \n    ( importSource IS null ) AND ( createdAt > '2018-01-19' )\n)\n```\n\n```text\nscopes: {\n  active: {\n    where: {\n      isDeleted: {\n        [Op.not]: true\n      },\n      [Op.or]: [\n        {\n          importSource: { [Op.ne]: null },\n          createdAt: {\n            [Op.between]: [\n              new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),\n              new Date(new Date() - 4 * (24 * 60 * 60 * 1000))\n            ],\n          }\n        },\n        {\n          importSource: { [Op.eq]: null },\n          createdAt: {\n            [Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),\n          }\n        }\n      ]\n    }\n  }\n}\n```\n\n```text\nExecuting (default): SELECT `id`, `url`, `title`, `company`, `importSource`, `importSourceId`, `publishedAt`, `createdAt`, `updatedAt` FROM `Projects` AS `Project` WHERE `Project`.`isDeleted` IS NOT true ORDER BY `Project`.`id` DESC LIMIT 5;\n```\n\n```text\nexports.index = (req, res) => {\n  const MAX = 50;\n  var numberProjects = ((req.query.number) ? req.query.number : MAX);\n  numberProjects = ((numberProjects > MAX) ? MAX : numberProjects);\n\n  Project.scope('active').findAll({\n    order: [\n      ['id', 'DESC']\n    ],\n    limit: +numberProjects\n  })\n  .then( projects => {\n    res.send( projects );\n  })\n};\n```\n\n```text\nscopes: {\n  active: {\n    where: {\n      isDeleted: { [Op.not]: true },\n      $or: [\n        {\n          importSource: { [Op.ne]: null },\n          createdAt: {\n            [Op.between]: [\n              new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),\n              new Date(new Date() - 4 * (24 * 60 * 60 * 1000))\n            ],\n          }\n        },\n        {\n          importSource: { [Op.eq]: null },\n          createdAt: {\n            [Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),\n          }\n        }\n      ]\n    }\n  }\n}\n```\n\n```text\n[Op.or]\n```\n\n```text\n$or\n```\n\n========================================\n\nComments:\n- Wow - i had the same issue, and changing the top level to $or worked for me too. Do you know why this is?","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":183,"estimatedTokens":979}}1019{"id":"stack-52578029","source":"stackoverflow","questionId":52578029,"title":"nodejs bulk update without compromising the performance","tags":["node.js","sequelize.js"],"text":"Title: nodejs bulk update without compromising the performance\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a node application with MySQL as DB. I on my way to making an endpoint that will update multiple rows with different data for each. Also, I am using sequelize as ORM.\n\nNow I know I can update a row like\n\n```\nmodel.update(data).then(()=>{res.end('Row Updated')});\n```\n\nNow my question is where should I call update method for second model. ie in the cb function passed to `then()` or after the `update.model` method\n\nI mean which of the following would be a best practice.\n\n```\nmodels1.update(data1).then(()=>{console.log('Row 1 Updated')});\nmodel2.update(data2).then(()=>{console.log('Row 2 Updated')});\n\n **OR**\n\nmodel1.update(data1).then(()=>{\n model2.update(data2).then(()=>{console.log('All the rows have been updated')})\n});\n```\n\n========================================\n\nCode:\n```text\nmodel.update(data).then(()=>{res.end('Row Updated')});\n```\n\n```text\nmodels1.update(data1).then(()=>{console.log('Row 1 Updated')});\nmodel2.update(data2).then(()=>{console.log('Row 2 Updated')});\n\n                      **OR**\n\nmodel1.update(data1).then(()=>{\n    model2.update(data2).then(()=>{console.log('All the rows have been updated')})\n});\n```\n\n```text\nthen()\n```\n\n```text\nupdate.model\n```\n\n```text\nPromise.all([\n  model1.update(data1),\n  model2.update(data2)\n])\n.then(() => {\n  console.log('All the rows have been updated');\n});\n```\n\n========================================\n\nComments:\n- Promise.all is another option I guess.\n- @FazalRasel have you used it with sequelize\n- It doesn't matter if it's Sequelize or anything else. Promises are promises.","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":70,"estimatedTokens":420}}1020{"id":"stack-51532000","source":"stackoverflow","questionId":51532000,"title":"How to use 'select if' function with sequelize in nodejs","tags":["node.js","postgresql","sequelize.js"],"text":"Title: How to use 'select if' function with sequelize in nodejs\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am developing a rest api in nodejs. I am using the sequelize library with\na postgresql database.\n\nWith sequelize in nodejs I want to get a temporary column to manage some values. I have two column `vip_start` and `vip_end`. These columns are `DataTypes.DATEONLY` format. \n\nWhen I select all the columns, I want to compare two dates, and finally create a new column with the answer. If true then `1`, else `0`. And then I want to order the selected rows by `VIP_ANSWER (1 or 0)`.\n\nIn mysql it solves that like this:\n\n```\n( SELECT IF (CURDATE( ) >= DATE( vip_start ) AND CURDATE( ) How can I make it in sequelize? :\n\n```\nconst datetime = new Date();\nreturn Phones\n .findAll({\n attributes: ['id', 'description', 'vip_start', 'vip_end','user_id' ],//I want to there new column like vip_answer [1,0] and order by this values\n where: {\n enabled: 1,\n vip_start: { $lte: datetime }, // in there i am stopped (((\n },\n })\n .then(phone => res.status(200).send(phone));\n```\n\nAny help will be appreciated.\n\n========================================\n\nCode:\n```text\n( SELECT IF (CURDATE( ) >= DATE( vip_start ) AND CURDATE( ) <= DATE( vip_end ), 1, 0 ) ) as vip\n```\n\n```text\nconst datetime = new Date();\nreturn Phones\n    .findAll({\n        attributes: ['id', 'description',  'vip_start', 'vip_end','user_id' ],//I want to there new column like vip_answer [1,0] and order by this values\n         where: {\n             enabled: 1,\n             vip_start: { $lte: datetime }, // in there i am stopped (((\n         },\n       })\n    .then(phone => res.status(200).send(phone));\n```\n\n```text\nvip_start\n```\n\n```text\nvip_end\n```\n\n```text\nDataTypes.DATEONLY\n```\n\n```text\n1\n```\n\n```text\n0\n```\n\n```text\nVIP_ANSWER (1 or 0)\n```\n\n```text\n[ sequelize.literal('( SELECT IF (CURDATE( ) >= DATE( vip_start ) AND CURDATE( ) <= DATE( vip_end ), 1, 0 ) )'),'vip']\n```\n\n```text\nattributes: ['id', 'description',  'vip_start', 'vip_end','user_id' , [ sequelize.literal('( SELECT IF (CURDATE( ) >= DATE( vip_start ) AND CURDATE( ) <= DATE( vip_end ), 1, 0 ) )'),'vip'] ]\n```\n\n========================================\n\nComments:\n- @Benfactor , then please create query in Postgres and then you can use that like above.\n- Please check : postgresql.org/docs/9.4/static/functions-conditional.html\n- Thank you very much. I change syntax and it works. [sequelize.literal('( CASE WHEN (vip_start = CURRENT_DATE) THEN 1 ELSE 0 END )'), 'vip']\n- sequelize.literal this is a nice feature that I learn just now\n- Sorry i have little problem, I want to order rows by vip, it gives databaseError syntax near vip\n- @Benfactor, Yeah , Great that you made it , Happy Coding BTW :) , Yes coz you can't access such field in order by.","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":93,"estimatedTokens":705}}1021{"id":"stack-48680590","source":"stackoverflow","questionId":48680590,"title":"How to add new attributes to schema after the migration?","tags":["mysql","node.js","migration","sequelize.js","sequelize-cli"],"text":"Title: How to add new attributes to schema after the migration?\nTags: mysql, node.js, migration, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\ncurrently I am working on a node.js project, and I found a problem while I was building the schema, usually, I use command line provided by http://docs.sequelizejs.com/manual/tutorial/migrations.html to define my schema, which is `$ node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string` , and after the `$ node_modules/.bin/sequelize db:migrate`, I can write these attributes into database. However, I am wondering how to add new attribute to schema after the migration, I searched and found this https://github.com/sequelize/cli/issues/133 is discussing this problem, but after I tried the solution and run `$ node_modules/.bin/sequelize db:migrate` again, it did not write the new attributes to the original schema, I don't understand where's the problem, below is my code, I am trying to add two attributes 'address'& 'height' into the user schema, can you guys give me some advice? Thank you!\n\n```\n'use strict';\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n let migration = [];\n migrations.push(queryInterface.addColumn(\n 'address',\n 'height',\n {\n type: Sequelize.STRING,\n }\n ));\n\n return Promise.all(migrations);\n return queryInterface.createTable('Users', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER,\n },\n firstName: {\n type: Sequelize.STRING,\n },\n lastName: {\n type: Sequelize.STRING,\n },\n email: {\n type: Sequelize.STRING,\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE,\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE,\n },\n });\n },\n\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Users');\n }\n};\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    let migration = [];\n    migrations.push(queryInterface.addColumn(\n            'address',\n            'height',\n            {\n                type: Sequelize.STRING,\n              }\n        ));\n\n    return Promise.all(migrations);\n    return queryInterface.createTable('Users', {\n      id: {\n        allowNull: false,\n        autoIncrement: true,\n        primaryKey: true,\n        type: Sequelize.INTEGER,\n      },\n      firstName: {\n        type: Sequelize.STRING,\n      },\n      lastName: {\n        type: Sequelize.STRING,\n      },\n      email: {\n        type: Sequelize.STRING,\n      },\n      createdAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n      },\n      updatedAt: {\n        allowNull: false,\n        type: Sequelize.DATE,\n      },\n    });\n  },\n\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.dropTable('Users');\n  }\n};\n```\n\n```text\n$ node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string\n```\n\n```text\n$ node_modules/.bin/sequelize db:migrate\n```\n\n```text\n$ node_modules/.bin/sequelize db:migrate\n```\n\n```text\nmodule.exports = {\n  up: function (queryInterface, Sequelize) {\n    return [\n      queryInterface.addColumn(\n        'users',\n        'height',\n        {\n          type: Sequelize.STRING,\n        }\n      ),\n      queryInterface.addColumn(\n        'users',\n        'address',\n        {\n          type: Sequelize.STRING,\n        }\n      )\n    ];\n  },\n\n  down: function (queryInterface, Sequelize) {\n    return [\n      queryInterface.removeColumn('users', 'height'),\n      queryInterface.removeColumn('users', 'address')\n    ];\n  }\n};\n```\n\n```text\nsequelize migration:create --name add-height-and-address-to-user\nsequelize db:migrate\n```\n\n========================================\n\nComments:\n- Hi, this issue has been solved, you can use below link stackoverflow.com/questions/46357533/&hellip; to solve that issue, also you can check the query part of sequelize to see the documents docs.sequelizejs.com/class/lib/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":155,"estimatedTokens":1002}}1022{"id":"stack-53167370","source":"stackoverflow","questionId":53167370,"title":"How to update if key exists - sequelize","tags":["javascript","node.js","postgresql","sequelize.js"],"text":"Title: How to update if key exists - sequelize\nTags: javascript, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to update my database if the key of the request exists.\n\nthis is my update action:\n\n```\nshopsModel.Shop.update({\n name: req.body.name,\n province: req.body.province,\n city: req.body.city,\n address: req.body.address,\n username: req.body.username,\n type: req.body.type,\n ...\n```\n\nFor example, I want to update the `name` column if `req.body.name` is not empty. \nWhat is the shortest way to do this?\n\n========================================\n\nTop Answer:\nTry below with use of `nullish coalescing`:\n\n```\nshopsModel.Shop.update({\n name: req.body.name ?? undefined,\n province: req.body.province ?? undefined,\n city: req.body.city ?? undefined,\n address: req.body.address ?? undefined,\n username: req.body.username ?? undefined,\n type: req.body.type ?? undefined\n })\n```\n\nIt provides **returning only keys you want to update** and as a result **changing only those columns** in DB.\n\nYou can create a helper function for it:\n\n```\nconst returnIfNotNil = key => key ?? undefined\n```\n\nand use as above\n\n```\nshopsModel.Shop.update({\n name: returnIfNotNil(req.body.name),\n province: returnIfNotNil(req.body.province),\n city: returnIfNotNil(req.body.city),\n address: returnIfNotNil(req.body.address),\n username: returnIfNotNil(req.body.username),\n type: returnIfNotNil(req.body.type)\n })\n```\n\nor make even more consistent (assuming you use all body to update):\n\n```\n// get only defined fields\nconst getOnlyDefinedFields = (body: Body) = Object.entries(body)\n .reduce((acc, [key, value]) => ({\n ...acc,\n [key]: returnIfNotNil(value) \n }), {})\nconst data = getOnlyDefinedFields(req.body)\n\nawait shopsModel.Shop.update(data)\n```\n\n========================================\n\nCode:\n```text\nshopsModel.Shop.update({\n        name: req.body.name,\n        province: req.body.province,\n        city: req.body.city,\n        address: req.body.address,\n        username: req.body.username,\n        type: req.body.type,\n        ...\n```\n\n```text\nname\n```\n\n```text\nreq.body.name\n```\n\n```text\nlet request = {\n        name: req.body.name,\n        province: req.body.province,\n        city: req.body.city,\n        address: req.body.address,\n        username: req.body.username,\n        type: req.body.type,\n        ...\n}\n\n// With the help of Lodash\nrequest = _.pickBy(request, _.identity); // <--- Will remove empty | null | undefined\n```\n\n```text\nshopsModel.Shop.update(request,...);\n```\n\n```text\nlet request = req.body;\n```\n\n```text\nreq.body\n```\n\n```text\nif(req.body.name) {\n    client.query('UPDATE table SET name=($1)', [name]);\n}\n```\n\n```js\nshopsModel.Shop.update({\n       name: req.body.name ?? undefined,\n       province: req.body.province ?? undefined,\n       city: req.body.city ?? undefined,\n       address: req.body.address ?? undefined,\n       username: req.body.username ?? undefined,\n       type: req.body.type ?? undefined\n    })\n```\n\n```text\nconst  returnIfNotNil = key => key ?? undefined\n```\n\n```js\nshopsModel.Shop.update({\n       name: returnIfNotNil(req.body.name),\n       province: returnIfNotNil(req.body.province),\n       city: returnIfNotNil(req.body.city),\n       address: returnIfNotNil(req.body.address),\n       username: returnIfNotNil(req.body.username),\n       type: returnIfNotNil(req.body.type)\n    })\n```\n\n```js\n// get only defined fields\nconst getOnlyDefinedFields = (body: Body) = Object.entries(body)\n   .reduce((acc, [key, value]) => ({\n      ...acc,\n      [key]: returnIfNotNil(value) \n   }), {})\nconst data = getOnlyDefinedFields(req.body)\n\nawait shopsModel.Shop.update(data)\n```\n\n```text\nnullish coalescing\n```\n\n========================================\n\nComments:\n- What is your database?\n- my database is `postgres`\n- Do you have something started already? like the connection to the database?","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":177,"estimatedTokens":960}}1023{"id":"stack-50654515","source":"stackoverflow","questionId":50654515,"title":"Sequelize BelongsToMany self reference inverse SQL QUERY","tags":["node.js","express","orm","sequelize.js","has-and-belongs-to-many"],"text":"Title: Sequelize BelongsToMany self reference inverse SQL QUERY\nTags: node.js, express, orm, sequelize.js, has-and-belongs-to-many\nSource: Stack Overflow\n\nQuestion:\nHello everyone hope you day is being great. I have searched all through the internet and here is my last line of hope. Hopefully some beautiful soul will explain to me why is that happening because I could not grasp from the documentations or other Q&A here on stack overflow the light on this situation.\n\nThe case is kind of simple:\nIn short I am getting the inverse SQL query.\n\nI have this self reference association:\n\n```\nUser.belongsToMany(User, {as: 'parents', through: 'kids_parents',foreignKey: 'parent', otherKey: 'kid'}); \nUser.belongsToMany(User, {as: 'kids', through: 'kids_parents', foreignKey: 'kid',otherKey: 'parent'});\n```\n\nthen in my controller I have this:\n\n```\nUser.findById(2).then((parent) => {\n parent.getKids().then((kids)=> {\n console.log(kids);\n });\n```\n\nI would be expecting to get ALL kids from the parent instance. Is that right ? Instead I am getting the opposite ALL parents from the specific KID id.\n\n```\nSELECT `user`.`id`, `user`.`name`, `user`.`surname`, `user`.`username`, `kids_parents`.`id` AS `kids_parents.id`, `kids_parents`.`kid` AS `kids_parents.kid`, `kids_parents`.`parent` AS `kids_parents.parent` FROM `users` AS `user` INNER JOIN `kids_parents` AS `kids_parents` ON **`user`.`id` = `kids_parents`.`parent`** AND **`kids_parents`.`kid` = 2;**\n```\n\nand note this line: \n\n**`user`.`id` = `kids_parents`.`parent`** AND **`kids_parents`.`kid` = 2;**\n\nCan someone explain why is that happening ? What am I missing here ? Thanks for the attention.\n\n========================================\n\nCode:\n```text\nUser.belongsToMany(User, {as: 'parents', through: 'kids_parents',foreignKey: 'parent', otherKey: 'kid'}); \nUser.belongsToMany(User, {as: 'kids', through: 'kids_parents', foreignKey: 'kid',otherKey: 'parent'});\n```\n\n```text\nUser.findById(2).then((parent) => {\n      parent.getKids().then((kids)=> {\n          console.log(kids);\n      });\n```\n\n```text\nSELECT `user`.`id`, `user`.`name`, `user`.`surname`, `user`.`username`,  `kids_parents`.`id` AS `kids_parents.id`, `kids_parents`.`kid` AS `kids_parents.kid`, `kids_parents`.`parent` AS `kids_parents.parent` FROM `users` AS `user` INNER JOIN `kids_parents` AS `kids_parents` ON **`user`.`id` = `kids_parents`.`parent`** AND **`kids_parents`.`kid` = 2;**\n```\n\n```text\nuser\n```\n\n```text\nid\n```\n\n```text\nkids_parents\n```\n\n```text\nparent\n```\n\n```text\nkids_parents\n```\n\n```text\nkid\n```\n\n```text\nUser(Kid).belongsToMany(User(Parents), {as:(target) 'parents', through: 'kids_parents',foreignKey(source): 'parent' (wrong!!!), otherKey: 'kid'});\n```\n\n```text\nUser.belongsToMany(User, {as: 'parents', through: 'kids_parents',foreignKey: 'kid' , otherKey: 'parent'});\n```\n\n```text\nUser.belongsToMany(User, {as: 'kids', through: 'kids_parents', foreignKey: 'parent',otherKey: 'kid'});\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":92,"estimatedTokens":734}}1024{"id":"stack-49015012","source":"stackoverflow","questionId":49015012,"title":"How Can I set the default Sort order in FeathersJs","tags":["sequelize.js","feathersjs"],"text":"Title: How Can I set the default Sort order in FeathersJs\nTags: sequelize.js, feathersjs\nSource: Stack Overflow\n\nQuestion:\nI have an issue with Feathersjs , integrating with sequalize. If I set the default pagination like below, and there is no sort specified it will generate an error because the SQL statement generated is invalid.\n\nService Created with default of 5:\n\n```\napp.use('/manifests', service({\n paginate: {\n default: 5,\n max: 25\n }\n}));\n```\n\nSQL Statement Generated ( setting a limit of 20 ) \n\n```\nSELECT [id], ...etc\nFROM [Manifest] AS [Manifest] OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY\n```\n\nIt Makes sense to set a default order , but I am not sure how to do that in the service.\n\nThe SQL Statement I want to achieve in this case is \n\n```\nSELECT [id], ...etc\nFROM [Manifest] AS [Manifest] ORDER BY Date desc OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY\n```\n\nI would like to somehow set the default for this..?\n\n```\napp.use('/manifests', service({\n paginate: {\n default: 5,\n max: 25\n }\n sort:{\n default: date -1 ( or something ) \n }\n}));\n```\n\n========================================\n\nTop Answer:\nHaving default sorting works well for me. E.g. you have a field **sort_order** in some models.\n\nserver/app.hooks.js\n\n```\nmodule.exports = {\n before: {\n find: [() => {\n const { query = {} } = context.params;\n\n if (context.service.options.Model.attributes.sort_order && !query.$sort) {\n Object.assign(query, { $sort: { sort_order: 1 } });\n }\n\n return context;\n }],\n }\n };\n```\n\n========================================\n\nCode:\n```text\napp.use('/manifests', service({\n  paginate: {\n    default: 5,\n    max: 25\n  }\n}));\n```\n\n```text\nSELECT [id], ...etc\nFROM [Manifest] AS [Manifest] OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY\n```\n\n```text\nSELECT [id], ...etc\nFROM [Manifest] AS [Manifest] ORDER BY Date desc OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY\n```\n\n```text\napp.use('/manifests', service({\n  paginate: {\n    default: 5,\n    max: 25\n  }\n  sort:{\n    default: date -1  ( or something ) \n  }\n}));\n```\n\n```text\napp.service('/manifests').hooks({\n  before(context) {\n    const { query = {} } = context.params;\n\n    if(!query.$sort) {\n      query.$sort = {\n        date: -1\n      }\n    }\n\n    context.params.query = query;\n  }\n});\n```\n\n```text\n$sort\n```\n\n```text\nmodule.exports = {\n  before: {\n    find: [() => {\n      const { query = {} } = context.params;\n\n      if (context.service.options.Model.attributes.sort_order && !query.$sort) {\n         Object.assign(query, { $sort: { sort_order: 1 } });\n      }\n\n      return context;\n    }],\n   }\n };\n```\n\n========================================\n\nComments:\n- Perfect , thanks. One thing I had to do was set the service to a variable and then execute hooks off that otherwise I got the \"app.use requires a middleware function\" . Probably goes without saying but I am quite new to nodejs. Cheers.\n- Oh sorry, `app.use` was supposed to be `app.service`. I updated the answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":146,"estimatedTokens":727}}1025{"id":"stack-60542346","source":"stackoverflow","questionId":60542346,"title":"Sequelize hooks not triggering when updating records manually","tags":["javascript","node.js","postgresql","sequelize.js","sequelize-hooks"],"text":"Title: Sequelize hooks not triggering when updating records manually\nTags: javascript, node.js, postgresql, sequelize.js, sequelize-hooks\nSource: Stack Overflow\n\nQuestion:\nI am new to sequelize and RDBMS,\nI have added sequelize hook as follows\n\n```\nbills.afterBulkUpdate((instance, options) => {\n console.log(instance);\n});\n```\n\nI have questions here If I update any record in bills table manually(using DB script or query or triggers)\nDo this update will trigger `bills.afterBulkUpdate` hook declared?\n\n========================================\n\nCode:\n```text\nbills.afterBulkUpdate((instance, options) => {\n  console.log(instance);\n});\n```\n\n```text\nbills.afterBulkUpdate\n```\n\n```text\nafterBulkCreate(name, fn)\n```\n\n========================================\n\nComments:\n- My question is does this hook would be triggered if same table record updated/created with DB level triggers or script outside application.\n- It will trigger but as your full code is not available there so I have mentioned that It depends on how you have declared and used in your code. If you are following documentation so it will work","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":39,"estimatedTokens":277}}1026{"id":"stack-64817756","source":"stackoverflow","questionId":64817756,"title":"Use AND operation with many to many relationship in Sequelize","tags":["javascript","sql","node.js","postgresql","sequelize.js"],"text":"Title: Use AND operation with many to many relationship in Sequelize\nTags: javascript, sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nMy problem in nutshell: I want to use the AND operation in a joined table. I think it is a very general use-case in the real life, but I didn't find any related article, blog, or issue yet. (My bad I think :D)\n\nLet me describe an example of what I mean:\nI would like to create a webshop and I have a Mobile and a Feature model and there is many-to-many relation between them. There is a multi-select filter for the feature (on my website) and I want to list those mobiles which have selected features. (eg.: A **and** B **and** C ...)\nI think I cannot create it one query because a column cannot be A and B at the same time, but I'm not sure.\nExample:\n\n```\nconst mobiles = await models.mobile.findAll({\n where: '???',\n attributes: ['id', 'name'],\n include: [\n {\n model: models.feature,\n where: '???',\n attributes: ['id', 'name],\n through: {\n attributes: [],\n },\n },\n ],\n });\n```\n\nI'm interested in the Sequelize and also the SQL solution too.\n\nExample models and expected result:\n\n```\nconst Mobile = sequelize.define('Mobile', {\n id: {\n autoIncrement: true,\n primaryKey: true,\n type: DataTypes.INTEGER,\n },\n name: {\n type: DataTypes.STRING\n }\n}, {});\n\nconst Feature = sequelize.define('Feature', {\n id: {\n autoIncrement: true,\n primaryKey: true,\n type: DataTypes.INTEGER,\n },\n name: {\n type: DataTypes.STRING\n }\n}, {});\n\nMobile.belongsToMany(Feature, { through: 'MobileFeature' });\nFeature.belongsToMany(Mobile, { through: 'MobileFeature' });\n\n// Example Data in DB (from mobile context)\nconst exampleData = [\n{\n \"id\": 1,\n \"name\": \"Mobile1\",\n \"features\": [\n {\n \"id\": 1,\n \"name\": \"A\",\n },\n {\n \"id\": 2,\n \"name\": \"B\",\n },\n {\n \"id\": 3,\n \"name\": \"C\",\n },\n ],\n},\n{\n \"id\": 2,\n \"name\": \"Mobile2\",\n \"features\": [],\n},\n{\n \"id\": 3,\n \"name\": \"Mobile3\",\n \"features\": [\n {\n \"id\": 1,\n \"name\": \"A\",\n },\n ]\n}\n];\n\n// Expected result\n// Scenario: I want to list those mobiles which have A and C feature\nconst result = [\n{\n \"id\": 1,\n \"name\": \"Mobile1\",\n \"features\": [\n {\n \"id\": 1,\n \"name\": \"A\",\n },\n {\n \"id\": 2,\n \"name\": \"B\",\n },\n {\n \"id\": 3,\n \"name\": \"C\",\n },\n ]\n},\n];\n```\n\n========================================\n\nCode:\n```js\nconst mobiles = await models.mobile.findAll({\n      where: '???',\n      attributes: ['id', 'name'],\n      include: [\n        {\n          model: models.feature,\n          where: '???',\n          attributes: ['id', 'name],\n          through: {\n            attributes: [],\n          },\n        },\n      ],\n    });\n```\n\n```js\nconst Mobile = sequelize.define('Mobile', {\n  id: {\n     autoIncrement: true,\n     primaryKey: true,\n     type: DataTypes.INTEGER,\n  },\n  name: {\n    type: DataTypes.STRING\n  }\n}, {});\n\nconst Feature = sequelize.define('Feature', {\n  id: {\n     autoIncrement: true,\n     primaryKey: true,\n     type: DataTypes.INTEGER,\n  },\n  name: {\n    type: DataTypes.STRING\n  }\n}, {});\n\nMobile.belongsToMany(Feature, { through: 'MobileFeature' });\nFeature.belongsToMany(Mobile, { through: 'MobileFeature' });\n\n// Example Data in DB (from mobile context)\nconst exampleData = [\n{\n  \"id\": 1,\n  \"name\": \"Mobile1\",\n  \"features\": [\n    {\n      \"id\": 1,\n      \"name\": \"A\",\n    },\n    {\n      \"id\": 2,\n      \"name\": \"B\",\n    },\n    {\n      \"id\": 3,\n      \"name\": \"C\",\n    },\n  ],\n},\n{\n  \"id\": 2,\n  \"name\": \"Mobile2\",\n  \"features\": [],\n},\n{\n  \"id\": 3,\n  \"name\": \"Mobile3\",\n  \"features\": [\n    {\n      \"id\": 1,\n      \"name\": \"A\",\n    },\n  ]\n}\n];\n\n// Expected result\n// Scenario: I want to list those mobiles which have A and C feature\nconst result = [\n{\n  \"id\": 1,\n  \"name\": \"Mobile1\",\n  \"features\": [\n    {\n      \"id\": 1,\n      \"name\": \"A\",\n    },\n    {\n      \"id\": 2,\n      \"name\": \"B\",\n    },\n    {\n      \"id\": 3,\n      \"name\": \"C\",\n    },\n  ]\n},\n];\n```\n\n```js\nWHERE: {\n name: { [Op.or]: [A,B,C] } // here we pass array of selected feature names to where. It returns mobiles only with this features. But we are looking for mobile with ALL features passed in array)\n}\n```\n\n```js\nattributes: ['id', 'name', [sequelize.fn('COUNT', 'table.fieldToCount'), 'CountedFeatures']],\n```\n\n```js\ngroup: [\"table.name, table.id\"]\n```\n\n```js\nhaving: sequelize.where(sequelize.fn('COUNT', 'countedFeatures'), '=', searchedFeaturesArray.length)\n```\n\n```js\n(...).findAll({\n  attributes: [...],\n  include : [\n    (...)\n  ],\n  group: [...],\n  having: [...]\n})\n```\n\n```text\nwhere\n```\n\n```text\nwhere\n```\n\n```text\nCOUNT\n```\n\n```text\nCountedFeatures\n```\n\n```text\ngroup\n```\n\n```text\nenter code here\n```\n\n```text\nhaving\n```\n\n```text\ncountedFeatures\n```\n\n```text\nlogging: console.log\n```\n\n```text\nfindAll\n```\n\n========================================\n\nComments:\n- Can you provide simple Sequelize model example for both `mobile` and `feature` and their association, data example, and the expected result?\n- I've added some example, I hope it helps.\n- Sounds reasonable. I have two questions: 1. Must I use 'sequelize literal' in 'having'? 2. How can I collect the 'features' if I add group by?","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":302,"estimatedTokens":1259}}1027{"id":"stack-51509748","source":"stackoverflow","questionId":51509748,"title":"sequelize.js belongsTo not null doesn't work","tags":["node.js","sequelize.js"],"text":"Title: sequelize.js belongsTo not null doesn't work\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI made some API system with Node.js\n\nAlso use sequelize.js(version 4) for communicate with MySQL.\n\nIn my model, I defined two model.\n\n[model.js]\n\n// User model\n\n```\nexport const User = sequelize.define('user', {\n id: {\n type: Sequelize.INTEGER,\n autoIncrement: true,\n primaryKey: true\n },\n username: {\n type: Sequelize.STRING(30),\n unique: true,\n allowNull: false\n },\n email: {\n type: Sequelize.STRING(50),\n unique: true,\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(30),\n allowNull: false\n },\n profile_image: {\n type: Sequelize.BLOB\n },\n phone: {\n type: Sequelize.STRING(14),\n allowNull: true,\n unique: true\n },\n gender: {\n type: Sequelize.STRING(5),\n allowNull: false,\n },\n is_admin: {\n type: Sequelize.BOOLEAN,\n defaultValue: false\n }\n}, {\n freezeTableName: true,\n timestamps: true,\n underscored: true\n})\n\n// Image model\nexport const Image = sequelize.define('image', {\n file: {\n type: Sequelize.BLOB\n },\n location: {\n type: Sequelize.STRING(100)\n },\n caption: {\n type: Sequelize.STRING(100)\n },\n}, {\n freezeTableName: true,\n underscored: true,\n timestamps: true\n})\n```\n\nAnd defined association for connect model to each other.\n\n```\nImage.belongsTo(User, {foreignKey: 'creator', targetKey: 'username', onDelete: 'CASCADE', allowNull: false});\nUser.hasMany(Image, {foreignKey: 'creator', allowNull: false});\n```\n\nIn above code, I defined `allowNull: false` to prevent null.\n\nBut when I desc image, it allow null.\n\n```\nmysql> desc image;\n+------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+--------------+------+-----+---------+----------------+\n| id | int(11) | NO | PRI | NULL | auto_increment |\n| file | blob | YES | | NULL | |\n| location | varchar(100) | YES | | NULL | |\n| caption | varchar(100) | YES | | NULL | |\n| created_at | datetime | NO | | NULL | |\n| updated_at | datetime | NO | | NULL | |\n| creator | varchar(30) | YES | MUL | NULL | |\n+------------+--------------+------+-----+---------+----------------+\n```\n\nHow can I set `not null` to `creator(FK)`?\n\n========================================\n\nTop Answer:\n`allowNull` has to be nested in a `foreignKey` object on both models for this to work.\n\n```\nImage.belongsTo(User, {onDelete: 'CASCADE', foreignKey: {allowNull: false}});\nUser.hasMany(Image, {foreignKey: {allowNull: false}});\n```\n\n========================================\n\nCode:\n```text\nexport const User = sequelize.define('user', {\n    id: {\n        type: Sequelize.INTEGER,\n        autoIncrement: true,\n        primaryKey: true\n    },\n    username: {\n        type: Sequelize.STRING(30),\n        unique: true,\n        allowNull: false\n    },\n    email: {\n        type: Sequelize.STRING(50),\n        unique: true,\n        allowNull: false\n    },\n    password: {\n        type: Sequelize.STRING(30),\n        allowNull: false\n    },\n    profile_image: {\n        type: Sequelize.BLOB\n    },\n    phone: {\n        type: Sequelize.STRING(14),\n        allowNull: true,\n        unique: true\n    },\n    gender: {\n        type: Sequelize.STRING(5),\n        allowNull: false,\n    },\n    is_admin: {\n        type: Sequelize.BOOLEAN,\n        defaultValue: false\n    }\n}, {\n    freezeTableName: true,\n    timestamps: true,\n    underscored: true\n})\n\n// Image model\nexport const Image = sequelize.define('image', {\n    file: {\n        type: Sequelize.BLOB\n    },\n    location: {\n        type: Sequelize.STRING(100)\n    },\n    caption: {\n        type: Sequelize.STRING(100)\n    },\n}, {\n    freezeTableName: true,\n    underscored: true,\n    timestamps: true\n})\n```\n\n```text\nImage.belongsTo(User, {foreignKey: 'creator', targetKey: 'username', onDelete: 'CASCADE', allowNull: false});\nUser.hasMany(Image, {foreignKey: 'creator', allowNull: false});\n```\n\n```text\nmysql> desc image;\n+------------+--------------+------+-----+---------+----------------+\n| Field      | Type         | Null | Key | Default | Extra          |\n+------------+--------------+------+-----+---------+----------------+\n| id         | int(11)      | NO   | PRI | NULL    | auto_increment |\n| file       | blob         | YES  |     | NULL    |                |\n| location   | varchar(100) | YES  |     | NULL    |                |\n| caption    | varchar(100) | YES  |     | NULL    |                |\n| created_at | datetime     | NO   |     | NULL    |                |\n| updated_at | datetime     | NO   |     | NULL    |                |\n| creator    | varchar(30)  | YES  | MUL | NULL    |                |\n+------------+--------------+------+-----+---------+----------------+\n```\n\n```text\nallowNull: false\n```\n\n```text\nnot null\n```\n\n```text\ncreator(FK)\n```\n\n```text\ncreator: {\n    type: Sequelize.STRING(30),\n    allowNull: false,\n}\n```\n\n```text\ncreator\n```\n\n```text\nallowNull: false\n```\n\n```text\nImage.belongsTo(User, {onDelete: 'CASCADE', foreignKey: {allowNull: false}});\nUser.hasMany(Image, {foreignKey: {allowNull: false}});\n```\n\n```text\nallowNull\n```\n\n```text\nforeignKey\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":237,"estimatedTokens":1267}}1028{"id":"stack-61819904","source":"stackoverflow","questionId":61819904,"title":"Sequelize and module.exports","tags":["node.js","sequelize.js"],"text":"Title: Sequelize and module.exports\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am new to nodejs and Sequelize and have been having an issue that I cannot figure out how to get over. I want to use a connection I created and exported it to a module.\n\nLike this:\n\n```\nconst dotEnv = require('dotenv');\nconst Sequelize = require('sequelize');\n\ndotEnv.config();\n\nmodule.exports.connection = async () => {\n try{\n const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {\n host: process.env.DB_HOST,\n port: process.env.DB_PORT,\n dialect: 'mysql',\n logging: false,\n define: {\n charset: 'utf8',\n collate: 'utf8_general_ci',\n },\n });\n await sequelize\n .authenticate()\n .then(() => {\n console.log('Connection has been established successfully.');\n })\n .catch(error => {\n throw error;\n });\n }catch(error){\n throw error;\n }\n}\n```\n\nI then have another file where I want to use it that looks like this\n\n```\nconst Sequelize = require('sequelize');\nconst { connection }= require('../database');\n\nconst accountModel = connection.define('accounts', {\n // attributes\n id: {\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4,\n primaryKey: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false\n },\n email: {\n type: Sequelize.STRING,\n unique: true\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n //is: /^[0-9a-f]{64}$/i\n },\n permission: {\n type: Sequelize.STRING,\n allowNull: false\n },\n discount: {\n type: Sequelize.INTEGER,\n allowNull: false\n }\n}, {\n freezeTableName: true\n});\nmodule.exports = connection.model('accounts', accountModel);\n```\n\nThe problem is that I get told that: TypeError: connection.define is not a function,\n\nThe connection works, the database is running, everything else works\nAnd last if I do it like this, it works too:\n\n```\nconst dotEnv = require('dotenv');\nconst Sequelize = require('sequelize');\n\ndotEnv.config();\n\nconst sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {\n host: process.env.DB_HOST,\n port: process.env.DB_PORT,\n dialect: 'mysql',\n logging: false,\n define: {\n charset: 'utf8',\n collate: 'utf8_general_ci',\n },\n});\n\nconst accountModel = sequelize.define('accounts', {\n // attributes\n id: {\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4,\n primaryKey: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false\n },\n email: {\n type: Sequelize.STRING,\n unique: true\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n //is: /^[0-9a-f]{64}$/i\n },\n permission: {\n type: Sequelize.STRING,\n allowNull: false\n },\n discount: {\n type: Sequelize.INTEGER,\n allowNull: false\n }\n}, {\n freezeTableName: true\n});\nmodule.exports = sequelize.model('accounts', accountModel);\n```\n\nI am really not sure why the module one does not work but the direct method does. I have tried to search Google and Stack Overflow for a solution.\n\n========================================\n\nTop Answer:\nI would do something like this. In the connections file you export the function then in the accountModel file you import and invoke the function.\n\nconnection.js: \n\n```\nexports.connection= async function() { // Stuff here }\n```\n\naccountModel.js: \n\n```\nconst { connection }= require('../database');\nlet connection = await connection.connection();\n```\n\n========================================\n\nCode:\n```text\nconst dotEnv        = require('dotenv');\nconst Sequelize     = require('sequelize');\n\ndotEnv.config();\n\nmodule.exports.connection = async () => {\n    try{\n        const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {\n            host: process.env.DB_HOST,\n            port: process.env.DB_PORT,\n            dialect: 'mysql',\n            logging: false,\n            define: {\n                charset: 'utf8',\n                collate: 'utf8_general_ci',\n            },\n        });\n        await sequelize\n        .authenticate()\n        .then(() => {\n            console.log('Connection has been established successfully.');\n        })\n        .catch(error => {\n            throw error;\n        });\n    }catch(error){\n        throw error;\n    }\n}\n```\n\n```text\nconst Sequelize     = require('sequelize');\nconst { connection }= require('../database');\n\nconst accountModel = connection.define('accounts', {\n  // attributes\n  id: {\n      type: Sequelize.UUID,\n      defaultValue: Sequelize.UUIDV4,\n      primaryKey: true\n  },\n  name: {\n    type: Sequelize.STRING,\n    allowNull: false\n  },\n  email: {\n      type: Sequelize.STRING,\n      unique: true\n  },\n  password: {\n      type: Sequelize.STRING,\n      allowNull: false,\n      //is: /^[0-9a-f]{64}$/i\n  },\n  permission: {\n      type: Sequelize.STRING,\n      allowNull: false\n  },\n  discount: {\n      type: Sequelize.INTEGER,\n      allowNull: false\n  }\n}, {\n  freezeTableName: true\n});\nmodule.exports = connection.model('accounts', accountModel);\n```\n\n```text\nconst dotEnv        = require('dotenv');\nconst Sequelize     = require('sequelize');\n\ndotEnv.config();\n\nconst sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {\n    host: process.env.DB_HOST,\n    port: process.env.DB_PORT,\n    dialect: 'mysql',\n    logging: false,\n    define: {\n        charset: 'utf8',\n        collate: 'utf8_general_ci',\n    },\n});\n\nconst accountModel = sequelize.define('accounts', {\n  // attributes\n  id: {\n      type: Sequelize.UUID,\n      defaultValue: Sequelize.UUIDV4,\n      primaryKey: true\n  },\n  name: {\n    type: Sequelize.STRING,\n    allowNull: false\n  },\n  email: {\n      type: Sequelize.STRING,\n      unique: true\n  },\n  password: {\n      type: Sequelize.STRING,\n      allowNull: false,\n      //is: /^[0-9a-f]{64}$/i\n  },\n  permission: {\n      type: Sequelize.STRING,\n      allowNull: false\n  },\n  discount: {\n      type: Sequelize.INTEGER,\n      allowNull: false\n  }\n}, {\n  freezeTableName: true\n});\nmodule.exports = sequelize.model('accounts', accountModel);\n```\n\n```text\nmodule.exports.connection = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {\n            host: process.env.DB_HOST,\n            port: process.env.DB_PORT,\n            dialect: 'mysql',\n            logging: false,\n            define: {\n                charset: 'utf8',\n                collate: 'utf8_general_ci',\n            },\n        });\n```\n\n```text\nasync function\n```\n\n```text\nSequelize instance\n```\n\n```text\nconnection.define()\n```\n\n```text\ndatabase.js\n```\n\n```text\nauthenticate()\n```\n\n```text\ntry {} catch (error) {}\n```\n\n```text\njs\n```\n\n```text\ndatabase.js\n```\n\n```text\nnew Sequelize()\n```\n\n```text\ndefine()\n```\n\n```text\nexports.connection= async function() { // Stuff here }\n```\n\n```text\nconst { connection }= require('../database');\nlet connection = await connection.connection();\n```\n\n========================================\n\nComments:\n- @DenisTsoi: we should try to avoid asking for repos if we can help it. The point of Stack Overflow is to produce answerable problems within the question post itself, so that if a repo/link dies, the question will still be understandable for future readers.","metadata":{"transformedAt":"2026-08-18T18:33:34.496Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":347,"estimatedTokens":1776}}1029{"id":"stack-49080058","source":"stackoverflow","questionId":49080058,"title":"Sequelize include objects with scope 1:m constraint = false","tags":["javascript","node.js","orm","sequelize.js"],"text":"Title: Sequelize include objects with scope 1:m constraint = false\nTags: javascript, node.js, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to use same table `Photo` for other tables.\nI read Sequelize doc here\nthey use scope and set constraint = false like this\n\n\r\n\r\n\n```\nconst Comment = this.sequelize.define('comment', {\r\n title: Sequelize.STRING,\r\n commentable: Sequelize.STRING,\r\n commentable_id: Sequelize.INTEGER\r\n});\r\n\r\nComment.prototype.getItem = function(options) {\r\n return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)](options);\r\n};\r\n\r\nPost.hasMany(this.Comment, {\r\n foreignKey: 'commentable_id',\r\n constraints: false,\r\n scope: {\r\n commentable: 'post'\r\n }\r\n});\r\nComment.belongsTo(this.Post, {\r\n foreignKey: 'commentable_id',\r\n constraints: false,\r\n as: 'post'\r\n});\n```\n\n\r\n\r\n\r\n\nmy question is: HOW I can query list of Post that include list comments for each post (with limit if it's avaiable).\nThank you.\n\n========================================\n\nCode:\n```html\nconst Comment = this.sequelize.define('comment', {\n  title: Sequelize.STRING,\n  commentable: Sequelize.STRING,\n  commentable_id: Sequelize.INTEGER\n});\n\nComment.prototype.getItem = function(options) {\n  return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)](options);\n};\n\nPost.hasMany(this.Comment, {\n  foreignKey: 'commentable_id',\n  constraints: false,\n  scope: {\n    commentable: 'post'\n  }\n});\nComment.belongsTo(this.Post, {\n  foreignKey: 'commentable_id',\n  constraints: false,\n  as: 'post'\n});\n```\n\n```text\nPhoto\n```\n\n```text\nPost\n  .find({\n    where: { /* include where condition if you have or remove this */ },\n    include: [{\n      model: Comment,\n      as: 'comments',\n    }],\n  })\n  .then(function(result) {\n    // check result.dataValues. it should contain `comments` array\n  });\n```\n\n========================================\n\nComments:\n- can you try again @RobertPham? I updated with `promise` use\n- Do we need this: Comment.prototype.getItem = function(options) { return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)](options); };\n- I think I missed this instance function when doing query, modify this function make it work. Thanks\n- ok glad it worked. also, does this work? `Post.hasMany(this.Comment, {` you might want to remove `this.` as well so it looks like this `Post.hasMany(Comment`","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":97,"estimatedTokens":614}}1030{"id":"stack-51106589","source":"stackoverflow","questionId":51106589,"title":"Dynamically add attributes to sequelize.js query","tags":["javascript","node.js","sequelize.js"],"text":"Title: Dynamically add attributes to sequelize.js query\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a query with multiple attributes that look like this. \n\n```\nconst queryPvCompletedByMonth = {\n attributes: [\n [\n Sequelize.literal(\n `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${getFirstAndLastDayInMonth(0).startDate}' AND '${\n getFirstAndLastDayInMonth(0).endDate\n }' THEN 1 ELSE NULL END)`\n ),\n 'Jan',\n ],\n [\n Sequelize.literal(\n `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${getFirstAndLastDayInMonth(1).startDate}' AND '${\n getFirstAndLastDayInMonth(1).endDate\n }' THEN 1 ELSE NULL END)`\n ),\n 'Feb',\n ],\n [\n Sequelize.literal(\n `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${getFirstAndLastDayInMonth(2).startDate}' AND '${\n getFirstAndLastDayInMonth(2).endDate\n }' THEN 1 ELSE NULL END)`\n ),\n 'Mar',\n ],\n ],\n where: {\n Field2: 2,\n },\n raw: false,\n };\n```\n\nAnd so on for all the months. This works, and I am getting the expected result from the query.\n\nThe query generated by sequelize looks like this.\n\n SELECT COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '2018-01-01' AND '2018-01-31' THEN 1 ELSE NULL END) AS [Jan],\n COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '2018-02-01' AND '2018-02-28' THEN 1 ELSE NULL END) AS [Feb],\n COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '2018-03-01' AND '2018-03-31' THEN 1 ELSE NULL END) AS [Mar]\n FROM [dbo].[Table1] AS [table1] WHERE [table1].[field2] = 2;\n\nInstead of having 12 hardcoded attributes I would like to insert them dynamically. So I put all the months in an array like this. \n\n```\nconst months = [\n { index: 0, name: 'Jan' },\n { index: 1, name: 'Feb' },\n { index: 2, name: 'Mar' },\n { index: 3, name: 'Apr' },\n { index: 4, name: 'May' },\n { index: 5, name: 'Jun' },\n { index: 6, name: 'Jul' },\n { index: 7, name: 'Aug' },\n { index: 8, name: 'Sep' },\n { index: 9, name: 'Oct' },\n { index: 10, name: 'Nov' },\n { index: 11, name: 'Dec' },\n];\n```\n\nAnd tried to map through the list to return the attributes like this.\n\n```\nconst queryPvCompletedByMonth = {\n attributes: [\n months.map(m => [\n Sequelize.literal(\n `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${\n getFirstAndLastDayInMonth(m.index).startDate\n }' AND '${getFirstAndLastDayInMonth(m.index).endDate}' THEN 1 ELSE NULL END)`\n ),\n m.name,\n ]),\n ],\n where: {\n AOTyp: 2,\n },\n raw: false,\n };\n```\n\nThis gives me an error from sequelize\n\n [[{\\\"val\\\":\\\"COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '2018-01-01' AND '2018-01-31' THEN 1 ELSE NULL END)\\\"},\\\"Jan\\\"],[{\\\"val\\\":\\\"COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '2018-02-01' AND '2018-02-28' THEN 1 ELSE NULL END)\\\"},\\\"Feb\\\"],[{\\\"val\\\":\\\"COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '2018-03-01' AND '2018-03-31' THEN 1 ELSE NULL END)\\\"},\\\"Mar\\\"]] is not a valid attribute definition. Please use the following format: ['attribute definition', 'alias']\n\nSo it kind of creates the right query but with alot of axtra symbols.\n\nSo my question is, is there a way to achieve this?\n\n========================================\n\nCode:\n```text\nconst queryPvCompletedByMonth = {\n    attributes: [\n      [\n        Sequelize.literal(\n          `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${getFirstAndLastDayInMonth(0).startDate}' AND '${\n            getFirstAndLastDayInMonth(0).endDate\n          }' THEN 1 ELSE NULL END)`\n        ),\n        'Jan',\n      ],\n      [\n        Sequelize.literal(\n          `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${getFirstAndLastDayInMonth(1).startDate}' AND '${\n            getFirstAndLastDayInMonth(1).endDate\n          }' THEN 1 ELSE NULL END)`\n        ),\n        'Feb',\n      ],\n      [\n        Sequelize.literal(\n          `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${getFirstAndLastDayInMonth(2).startDate}' AND '${\n            getFirstAndLastDayInMonth(2).endDate\n          }' THEN 1 ELSE NULL END)`\n        ),\n        'Mar',\n      ],\n    ],\n    where: {\n      Field2: 2,\n    },\n    raw: false,\n  };\n```\n\n```text\nconst months = [\n  { index: 0, name: 'Jan' },\n  { index: 1, name: 'Feb' },\n  { index: 2, name: 'Mar' },\n  { index: 3, name: 'Apr' },\n  { index: 4, name: 'May' },\n  { index: 5, name: 'Jun' },\n  { index: 6, name: 'Jul' },\n  { index: 7, name: 'Aug' },\n  { index: 8, name: 'Sep' },\n  { index: 9, name: 'Oct' },\n  { index: 10, name: 'Nov' },\n  { index: 11, name: 'Dec' },\n];\n```\n\n```text\nconst queryPvCompletedByMonth = {\n    attributes: [\n      months.map(m => [\n        Sequelize.literal(\n          `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${\n            getFirstAndLastDayInMonth(m.index).startDate\n          }' AND '${getFirstAndLastDayInMonth(m.index).endDate}' THEN 1 ELSE NULL END)`\n        ),\n        m.name,\n      ]),\n    ],\n    where: {\n      AOTyp: 2,\n    },\n    raw: false,\n  };\n```\n\n```text\nconst attributesPvCompletedByMonth = [];\n```\n\n```text\nconst generateAttributesForPvCompletedMyMonths = () => {\n  months.map(m => {\n    const attribute = [\n      Sequelize.literal(\n        `COUNT(CASE WHEN CONVERT(date,[Field1]) BETWEEN '${\n          getFirstAndLastDayInMonth(m.index).startDate\n        }' AND '${getFirstAndLastDayInMonth(m.index).endDate}' THEN 1 ELSE NULL END)`\n      ),\n      m.name,\n    ];\n    return attributesPvCompletedByMonth.push(attribute);\n  });\n};\n```\n\n```text\nconst queryPvCompletedByMonth = {\n  attributes: attributesPvCompletedByMonth,\n  where: {\n    Field2: 2,\n  },\n  raw: true,\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":202,"estimatedTokens":1354}}1031{"id":"stack-49836363","source":"stackoverflow","questionId":49836363,"title":"Build and save with associations","tags":["node.js","sequelize.js"],"text":"Title: Build and save with associations\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a user, create a location (I'm using google geocode API) and save all, but the association isn't created in the database. Everything is working fine. The response is exactly what I want but when I go into the database, the association isn't created. The only way I made it work was to create and save the location entity separately and directly set the foreign key \"locationId\" to the newly generated ID. It's been almost a week and I still can't figure out how to make it work. If it can help, I'm also using PostgreSQL. Here is the doc for creation with associations.\n\nHere are my associations:\n\n```\nUser.belongsTo(models.Location, { as: 'location', foreignKey: 'locationId' });\nLocation.hasMany(models.User, { as: 'users', foreignKey: 'locationId' });\n```\n\nHere is my controller code:\n\n```\nconst createRandomToken = crypto\n .randomBytesAsync(16)\n .then(buf => buf.toString('hex'));\n\nconst createUser = token => User.build({\n firstName: req.body.firstName,\n lastName: req.body.lastName,\n email: req.body.email,\n passwordResetToken: token,\n passwordResetExpires: moment().add(1, 'days'),\n role: req.body.roleId,\n active: true\n}, {\n include: [{ model: Location, as: 'location' }]\n});\n\nconst createLocation = (user) => {\n if (!user) return;\n if (!req.body.placeId) return user;\n return googleMapsHelper.getLocationByPlaceId(req.body.placeId).then((location) => {\n user.location = location;\n return user;\n });\n};\n\nconst saveUser = (user) => {\n if (!user) return;\n return user.save()\n .then(user => res.json(user.getPublicInfo()));\n};\n\ncreateRandomToken\n .then(createUser)\n .then(createLocation)\n .then(saveUser)\n .catch(Sequelize.ValidationError, (err) => {\n for (let i = 0; i next(createError.InternalServerError(err)));\n```\n\nHere's the response:\n\n```\n{\n \"id\": 18,\n \"firstName\": \"FirstName\",\n \"lastName\": \"LastName\",\n \"email\": \"test@test.com\",\n \"lastLogin\": null,\n \"passwordResetExpires\": \"2018-04-15T21:02:34.624Z\",\n \"location\": {\n \"id\": 5,\n \"placeId\": \"ChIJs0-pQ_FzhlQRi_OBm-qWkbs\",\n \"streetNumber\": null,\n \"route\": null,\n \"city\": \"Vancouver\",\n \"postalCode\": null,\n \"country\": \"Canada\",\n \"region\": \"British Columbia\",\n \"formatted\": \"Vancouver, BC, Canada\",\n \"createdAt\": \"2018-04-14T20:57:54.196Z\",\n \"updatedAt\": \"2018-04-14T20:57:54.196Z\"\n}\n```\n\n========================================\n\nCode:\n```text\nUser.belongsTo(models.Location, { as: 'location', foreignKey: 'locationId' });\nLocation.hasMany(models.User, { as: 'users', foreignKey: 'locationId' });\n```\n\n```text\nconst createRandomToken = crypto\n  .randomBytesAsync(16)\n  .then(buf => buf.toString('hex'));\n\nconst createUser = token => User.build({\n  firstName: req.body.firstName,\n  lastName: req.body.lastName,\n  email: req.body.email,\n  passwordResetToken: token,\n  passwordResetExpires: moment().add(1, 'days'),\n  role: req.body.roleId,\n  active: true\n}, {\n  include: [{ model: Location, as: 'location' }]\n});\n\nconst createLocation = (user) => {\n  if (!user) return;\n  if (!req.body.placeId) return user;\n  return googleMapsHelper.getLocationByPlaceId(req.body.placeId).then((location) => {\n    user.location = location;\n    return user;\n  });\n};\n\nconst saveUser = (user) => {\n  if (!user) return;\n  return user.save()\n    .then(user => res.json(user.getPublicInfo()));\n};\n\ncreateRandomToken\n  .then(createUser)\n  .then(createLocation)\n  .then(saveUser)\n  .catch(Sequelize.ValidationError, (err) => {\n    for (let i = 0; i < err.errors.length; i++) {\n      if (err.errors[i].type === 'unique violation') {\n        return next(createError.Conflict(err.errors[i]));\n      }\n    }\n  })\n  .catch(err => next(createError.InternalServerError(err)));\n```\n\n```text\n{\n  \"id\": 18,\n  \"firstName\": \"FirstName\",\n  \"lastName\": \"LastName\",\n  \"email\": \"test@test.com\",\n  \"lastLogin\": null,\n  \"passwordResetExpires\": \"2018-04-15T21:02:34.624Z\",\n  \"location\": {\n    \"id\": 5,\n    \"placeId\": \"ChIJs0-pQ_FzhlQRi_OBm-qWkbs\",\n    \"streetNumber\": null,\n    \"route\": null,\n    \"city\": \"Vancouver\",\n    \"postalCode\": null,\n    \"country\": \"Canada\",\n    \"region\": \"British Columbia\",\n    \"formatted\": \"Vancouver, BC, Canada\",\n    \"createdAt\": \"2018-04-14T20:57:54.196Z\",\n    \"updatedAt\": \"2018-04-14T20:57:54.196Z\"\n}\n```\n\n```text\nconst createLocation = new Promise((resolve, reject) => {\n  if (!req.body.placeId) return resolve();\n  googleMapsHelper\n    .getLocationByPlaceId(req.body.placeId)\n    .then(location => resolve(location))\n    .catch(() => reject(createError.BadRequest('PlaceId invalide')));\n});\n\nconst createUser = () => sequelize.transaction((t) => {\n  const user = User.build({\n    firstName: req.body.firstName,\n    lastName: req.body.lastName,\n    email: req.body.email,\n    passwordResetToken: crypto.randomBytes(16).toString('hex'),\n    passwordResetExpires: moment().add(1, 'days'),\n    active: true\n  });\n  return user.save({ transaction: t })\n    .then(user => createLocation\n      .then(location => user.setLocation(location, { transaction: t })));\n});\n\ncreateUser\n  .then(user => res.json(user))\n  .catch(err => httpErrorHandler(err, next));\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":185,"estimatedTokens":1282}}1032{"id":"stack-50571647","source":"stackoverflow","questionId":50571647,"title":"Why does Sequelize pluralize / singularize names of anything all? And how to stop that completely?","tags":["node.js","sequelize.js"],"text":"Title: Why does Sequelize pluralize / singularize names of anything all? And how to stop that completely?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe names of my tables in the .create() method function and model definitions are swinging from singular to plural and vice-versa. **Why does Sequelize have this functionality at all?** And why is disabling it so unstable?\n\nThe table names in my database are (as in the code) \"user\", \"email\", \"settings\". But when doing the INSERT and SELECT SQL statements Sequelize singularizes the names as if I there was need for a library to choose the best name for my database tables! Because of that, some INSERTs fail.\n\nHere is my code:\n\n```\n// DEPENDENCIES\nconst Sequelize = require('sequelize');\n\n// Connection set up:\nconst sequelize = new Sequelize(\n 'sql_database_1',\n 'sqlusername1',\n 'dbpassw0rd',\n { // Sequelize options:\n host: 'localhost',\n port: 3306,\n dialect: 'mysql',\n operatorsAliases: false,\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000\n },\n logging: console.log,\n define: {\n freezeTableName: true, // Do not change my table names.\n timestamps: false // I will do this individually, thanks.\n },\n });\n\n// Set up models:\nconst User = sequelize.define('user',\n { // Database columns:\n user_id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n column1: Sequelize.STRING,\n });\n\nconst Settings = sequelize.define('settings',\n { // Database columns:\n entry_id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n owner_id: Sequelize.INTEGER,\n column1: Sequelize.STRING\n });\n\nconst Email = sequelize.define('email',\n { // Database columns:\n entry_id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n owner_id: Sequelize.INTEGER,\n column1: Sequelize.STRING\n });\n\n// Set up associations:\nUser.hasOne(Settings,\n { // Options:\n foreignKey: 'owner_id'\n });\n\nUser.hasMany(Email,\n { // Options:\n foreignKey: 'owner_id'\n });\n\n// Actions:\nsequelize\n .sync({\n force: true\n })\n .then(function() {\n User\n .create({\n column1: 'test123',\n settings: { // STACK OVERFLOW: Not working because of Sequelize singularizing the name.\n column1: 'This is dummy address'\n },\n emails: [ // STACK OVERFLOW: I need to write this table name in plural to work because Sequelize is changing MY names...\n { column1: 'Some data here' },\n { column1: 'Other data there' }\n ],\n },\n {\n include: [Settings, Email]\n })\n })\n .then(function() {\n User\n .findOne({\n include: [Settings, Email],\n })\n .then(function(result) {\n console.log('FindAll results:\\n', JSON.stringify(result));\n });\n });\n```\n\nAs you can see, I am using \"define: { freezeTableName: true }\" in the object dedicated to set up Sequelize options. It is only working when creating the new table names: it does not pluralize them. The INSERT and SELECT statements still have a similar same problem: they are being singularized.\n\n**Can this be a bug?**\n\n========================================\n\nCode:\n```text\n// DEPENDENCIES\nconst Sequelize = require('sequelize');\n\n\n\n// Connection set up:\nconst sequelize = new Sequelize(\n    'sql_database_1',\n    'sqlusername1',\n    'dbpassw0rd',\n    { // Sequelize options:\n        host: 'localhost',\n        port: 3306,\n        dialect: 'mysql',\n        operatorsAliases: false,\n        pool: {\n            max: 5,\n            min: 0,\n            acquire: 30000,\n            idle: 10000\n        },\n        logging: console.log,\n        define: {\n            freezeTableName: true, // Do not change my table names.\n            timestamps: false // I will do this individually, thanks.\n        },\n    });\n\n\n\n// Set up models:\nconst User = sequelize.define('user',\n    { // Database columns:\n        user_id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        column1: Sequelize.STRING,\n    });\n\nconst Settings = sequelize.define('settings',\n    { // Database columns:\n        entry_id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        owner_id: Sequelize.INTEGER,\n        column1: Sequelize.STRING\n    });\n\nconst Email = sequelize.define('email',\n    { // Database columns:\n        entry_id: {\n            type: Sequelize.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        owner_id: Sequelize.INTEGER,\n        column1: Sequelize.STRING\n    });\n\n\n\n// Set up associations:\nUser.hasOne(Settings,\n    { // Options:\n        foreignKey: 'owner_id'\n    });\n\nUser.hasMany(Email,\n    { // Options:\n        foreignKey: 'owner_id'\n    });\n\n\n\n// Actions:\nsequelize\n    .sync({\n        force: true\n    })\n    .then(function() {\n        User\n            .create({\n                    column1: 'test123',\n                    settings: { // STACK OVERFLOW: Not working because of Sequelize singularizing the name.\n                        column1: 'This is dummy address'\n                    },\n                    emails: [ // STACK OVERFLOW: I need to write this table name in plural to work because Sequelize is changing MY names...\n                        { column1: 'Some data here' },\n                        { column1: 'Other data there' }\n                    ],\n                },\n                {\n                    include: [Settings, Email]\n                })\n    })\n    .then(function() {\n        User\n            .findOne({\n                include: [Settings, Email],\n            })\n            .then(function(result) {\n                console.log('FindAll results:\\n', JSON.stringify(result));\n            });\n    });\n```\n\n```js\nconst User = sequelize.define('user', {\n  username: Sequelize.STRING,\n});\n\nconst Email = sequelize.define('emails', {\n  text: Sequelize.STRING,\n});\n\nUser.hasMany(Email);\n\nsequelize.sync({ force: true })\n  .then(() => User.create({\n    username: 'test1234',\n    emails: {\n      text: 'this is dummy Email123'\n    },\n  }, { include: [Email] }))\n  .then(user => {\n    console.log(user.dataValues);\n  });\n```\n\n```js\nconst User = sequelize.define('user', {\n  username: Sequelize.STRING,\n});\n\nconst Email = sequelize.define('emails', {\n  text: Sequelize.STRING,\n});\n\n\nUser.hasOne(Email);\n\nsequelize.sync({ force: true })\n  .then(() => User.create({\n    username: 'test1234',\n    email: {\n      text: 'this is dummy Email123'\n    },\n  }, { include: [Email] }))\n  .then(user => {\n    console.log(user.dataValues);\n  });\n```\n\n```text\nhasOne\n```\n\n```text\nhasMany\n```\n\n```text\nemails\n```\n\n```text\nUser\n```\n\n```text\nhasMany\n```\n\n```text\nEmail\n```\n\n```text\nhasOne\n```\n\n========================================\n\nComments:\n- Thank you for your explanation! I understand. But how is that functionality useful at all? And how can I get rid of it? Because of it I cannot insert entries to the \"settings\" table because Sequelize makes it singular.\n- I am not sure what do you mean by you cannot insert. You can just use singular name when you are inserting.\n- It works! Thank you :) I still think that this feature needs to be taken down, though.\n- Glad that it helped.","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":314,"estimatedTokens":1767}}1033{"id":"stack-49677774","source":"stackoverflow","questionId":49677774,"title":"Support for `{where: 'raw query'}` has been removed","tags":["javascript","lambda","sequelize.js","graphql","serverless-framework"],"text":"Title: Support for `{where: 'raw query'}` has been removed\nTags: javascript, lambda, sequelize.js, graphql, serverless-framework\nSource: Stack Overflow\n\nQuestion:\nI'm running a GraphQL server using the serverless framework on AWS Lambda.\nI'm fetching the data in the UI using `apollo-link-batch-http`.\n\nIf I run it locally using `serverless-offline`, it works fine. But if I run it on AWS Lambda, it successfully resolves the `fooResolver` but not the `barResolver` as it throws the above error message.\n\nThe `Model.cached(300)` is a tiny cache wrapper I made. You can see it here:\nhttps://gist.github.com/lookapanda/4676083186849bb6c5ae6f6230ad7d8f\nIt basically just makes me able to use my own `findById` function and so on.\n\nThe weird thing is, this error only appears, if I use `apollo-link-batch-http` but not if I use `apollo-link-http`. So if the request is batched into a single GraphQL request, there is no such errors (although, then I get this error: https://github.com/sequelize/sequelize/issues/9242)\n\nI really don't know what is going on there, there is no raw where query in any of those resolvers. And it gets even weirder: It only happens with the cached result. The first request is totally valid and successful, but then every consecutive request fails with the above error message.\n\nI really hope someone can help me, I'm getting insane :D\n\n```\nexport const fooResolver = async () => {\n const Model = db.getDB().sequelize.models.fooModel;\n const data = await Model.cached(300).findAll({\n where: {\n time: {\n [Op.gt]: Model.sequelize.literal('CURRENT_TIMESTAMP()'),\n },\n enabled: true,\n state: 'PLANNED',\n },\n order: [['time', 'DESC']],\n limit: 5,\n });\n return data.value;\n};\n\nexport const barResolver = async () => {\n const models = db.getDB().sequelize.models;\n const Model = models.fooModel;\n const data = await Model.findById(data.id, {\n include: [\n {\n model: models.barModel,\n include: [\n {\n association: 'fooAssociation',\n include: [{ association: 'barAssociation' }],\n order: ['showOrder', 'ASC'],\n },\n ],\n },\n ],\n });\n\n return {\n data,\n };\n};\n```\n\n========================================\n\nTop Answer:\nI faced similar situation, except in my case using the code below works well:\n\n```\n.findAll({\n where: {\n title: req.params.title \n } \n})\n```\n\n========================================\n\nCode:\n```js\nexport const fooResolver = async () => {\n  const Model = db.getDB().sequelize.models.fooModel;\n  const data = await Model.cached(300).findAll({\n      where: {\n          time: {\n              [Op.gt]: Model.sequelize.literal('CURRENT_TIMESTAMP()'),\n          },\n          enabled: true,\n          state: 'PLANNED',\n      },\n      order: [['time', 'DESC']],\n      limit: 5,\n  });\n  return data.value;\n};\n\nexport const barResolver = async () => {\n  const models = db.getDB().sequelize.models;\n  const Model = models.fooModel;\n  const data = await Model.findById(data.id, {\n    include: [\n      {\n        model: models.barModel,\n        include: [\n          {\n            association: 'fooAssociation',\n            include: [{ association: 'barAssociation' }],\n            order: ['showOrder', 'ASC'],\n          },\n        ],\n      },\n    ],\n  });\n\n  return {\n    data,\n  };\n};\n```\n\n```text\napollo-link-batch-http\n```\n\n```text\nserverless-offline\n```\n\n```text\nfooResolver\n```\n\n```text\nbarResolver\n```\n\n```text\nModel.cached(300)\n```\n\n```text\nfindById\n```\n\n```text\napollo-link-batch-http\n```\n\n```text\napollo-link-http\n```\n\n```js\nexport const getSqlFromSelect = (Model, method, args) => {\n  if (!SUPPORTED_SELECT_METHODS.includes(method)) {\n    throw new Error('Unsupported method.');\n  }\n\n  const id = generateRandomHash(10);\n\n  return new Promise((resolve, reject) => {\n    Model.addHook('beforeFindAfterOptions', id, options, => {\n      Model.removeHook('beforeFindAfterOptions', id);\n\n      resolve(\n        Model.sequelize.dialect.QueryGenerator.selectQuery(\n          Model.getTableName(),\n          options,\n          Model\n        ).slice(0, -1)\n      );\n    });\n\n    return Model[method](...args).catch(reject);\n  });\n};\n```\n\n```js\nexport const getSqlFromSelect = (Model, identifier, options) => {\n  if (typeof identifier === 'number' || typeof identifier === 'string' || Buffer.isBuffer(identifier) {\n    options.where = {\n      [Model.primaryKeyAttribute]: identifier,\n    };\n  };\n\n  return Model.sequelize.dialect.QueryGenerator.selectQuery(\n    Model.getTableName(),\n    options,\n    Model\n  ).slice(0, -1);\n};\n```\n\n```text\nselectQuery()\n```\n\n```text\nModel.addHook\n```\n\n```text\n.findAll({\n    where: {\n        title: req.params.title \n    } \n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":207,"estimatedTokens":1145}}1034{"id":"stack-59118628","source":"stackoverflow","questionId":59118628,"title":"sequelize handling rejection in the create statement - catch not firing","tags":["node.js","sequelize.js"],"text":"Title: sequelize handling rejection in the create statement - catch not firing\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe sequelize create statement has an error and I would like to handle that error. Since the create statement has the error I need to handle promise rejection. How do I do that in code? Tried to look at the sequelize documents but unable to work it out. \n\n```\ndb.Employee.create(empData, \n{\n include:[\n {\n model: db.EmployeeDetails\n }\n ]\n}).then(function(newEmployee){\n res.json(newEmployee);\n}).catch(function(err){\n return next(err);\n});\n```\n\nThe error is on the create and so the webpage just gives an internal server error. I was under the impression that the catch was something that handled the promise rejection and failure. In this case, how can I handle the promise rejection in code. An example would be greatly appreciated.\n\n========================================\n\nTop Answer:\nYour webpage showing a 500 error means the issue was caught / working as intended. What you need to do is figure out how to handle displaying that error in a pretty format - this being a UI task. If you want a 'patch' for hiding the issue, change your return to a res. This will trick your browser with a 200 status and hide the error.\n\nI do want to add, I recommend trying async/await for sequelize. There's a good amount of usage examples with it.\n\n**Promise**\n\n```\ndb.Employee.create(empData, \n{\n include:[\n {\n model: db.EmployeeDetails\n }\n ]\n}).then(function(newEmployee){\n res.json(newEmployee);\n}).catch(function(err){\n // Temporary patch\n res.json(\"pretty error message\");\n});\n```\n\n**Async/Await version**\n\n```\nasync function createEmployee(empData) {\n try {\n return await db.Employee.create(empData, {\n include:[ { model: db.EmployeeDetails } ]\n });\n } catch (err) {\n // Handle error here\n return err;\n }\n}\n```\n\n========================================\n\nCode:\n```text\ndb.Employee.create(empData, \n{\n    include:[\n        {\n            model: db.EmployeeDetails\n        }\n    ]\n}).then(function(newEmployee){\n    res.json(newEmployee);\n}).catch(function(err){\n    return next(err);\n});\n```\n\n```text\nconst err = new Error(\"my custom error\")\nerr.statusCode = 400\nnext(err)\n```\n\n```text\ndb.Employee.create(empData, {\n    include:[\n        {\n            model: db.EmployeeDetails\n        }\n    ]\n}).then(function(newEmployee){\n    res.json(newEmployee);\n}).catch(function(err){\n    err.statusCode = 400\n    next(err);\n});\n```\n\n```text\n// Error Handler\napp.use(function(err, req, res, next) {\n  console.error(err)\n  if (!err.statusCode) err.statusCode = 500;\n  let msg = err.message\n  // Do not expose 500 error messages in production, to the client\n  if (process.env.NODE_ENV === \"production\" && err.statusCode === 500) {\n     msg = \"Internal Server Error\"\n  }\n  res.status(err.statusCode).send(msg)\n})\n```\n\n```text\nnext(err)\n```\n\n```text\n500 Internal Server Error\n```\n\n```text\n5xx\n```\n\n```text\ndb.Employee.create(empData, \n{\n    include:[\n        {\n            model: db.EmployeeDetails\n        }\n    ]\n}).then(function(newEmployee){\n    res.json(newEmployee);\n}).catch(function(err){\n    // Temporary patch\n    res.json(\"pretty error message\");\n});\n```\n\n```text\nasync function createEmployee(empData) {\n  try {\n    return await db.Employee.create(empData, {\n      include:[ { model: db.EmployeeDetails } ]\n    });\n  } catch (err) {\n    // Handle error here\n    return err;\n  }\n}\n```\n\n========================================\n\nComments:\n- If you get promise as reulst of this function then catch should be enough to get all erros happen in it. But it could be that error happens in separate context, then catch will not help.\n- in express you can use their error-handing expressjs.com/en/guide/error-handling.html\n- Can you please give details about the error? stack trace?","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":164,"estimatedTokens":952}}1035{"id":"stack-27715290","source":"stackoverflow","questionId":27715290,"title":"Transaction with Sequelize doesn't work","tags":["sql","node.js","transactions","promise","sequelize.js"],"text":"Title: Transaction with Sequelize doesn't work\nTags: sql, node.js, transactions, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to build a simple webform where you can enter a persons firstname, lastname and select multiple groups for this person (but one for now)\n\nI'm using node.js and sequelize to store the person in a MariaDB -Database.\n\nSequelize created the tables *Persons*, *Groups* and *GroupsPersons* according to the defined models.\n\n```\nvar Sequelize = require(\"sequelize\");\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\n\nvar Group = sequelize.define(\"Group\", {\n name: {\n type: DataTypes.STRING,\n allowNull: false\n }\n}\n\nvar Person = sequelize.define(\"Person\", {\n firstName: {\n type: DataTypes.STRING,\n allowNull: false\n },\n lastName: {\n type: DataTypes.STRING,\n allowNull: false\n }\n}\n\nPerson.belongsToMany(Group, {as: 'Groups'});\nGroup.belongsToMany(Person, {as: 'Persons'});\n```\n\nBecause creating the person and assigning it into a group should be handled atomically in one step I decided to use a transaction, shown in the docs here:\nhttp://sequelize.readthedocs.org/en/latest/docs/transactions/#using-transactions-with-other-sequelize-methods\n\n```\nvar newPerson = {\n firstName: 'Hans',\n lastName: 'Fischer'\n}\nvar id = 3 // group\n\nsequelize.transaction(function (t) {\n return Person.create(newPerson, {transaction: t}).then(function (person) {\n return Group.find(id, {transction: t}).then(function(group){\n if (!group) throw Error(\"Group not found for id: \" + id);\n return person.setGroups( [group], {transction: t});\n }) \n\n });\n}).then(function (result) {\n // Transaction has been committed\n // result is whatever the result of the promise chain returned to the transaction callback is\n console.log(result);\n}).catch(function (err) {\n // Transaction has been rolled back\n // err is whatever rejected the promise chain returned to the transaction callback is\n console.error(err);\n});`\n```\n\nBut for some reason neither `function (result) {..` for success nor the function in catch gets called. However, the complete SQL queries of the transaction were generated except COMMIT, so nothing was inserted into the db.\n\nIf I put it like this \n `return person.setGroups( [], {transction: t});`\nthe transactions succeeds, but with no inserts into *GroupsPersons* of course.\n\nAny ideas or suggestions?\n\nThanks for help!\n\n========================================\n\nCode:\n```text\nvar Sequelize = require(\"sequelize\");\nvar sequelize = new Sequelize(config.database, config.username, config.password, config);\n\nvar Group = sequelize.define(\"Group\", {\n    name: {\n        type: DataTypes.STRING,\n        allowNull: false\n    }\n}\n\nvar Person = sequelize.define(\"Person\", {\n    firstName: {\n        type: DataTypes.STRING,\n        allowNull: false\n    },\n    lastName: {\n      type: DataTypes.STRING,\n      allowNull: false\n    }\n}\n\n\nPerson.belongsToMany(Group, {as: 'Groups'});\nGroup.belongsToMany(Person, {as: 'Persons'});\n```\n\n```text\nvar newPerson = {\n    firstName: 'Hans',\n    lastName: 'Fischer'\n}\nvar id = 3    // group\n\nsequelize.transaction(function (t) {\n    return Person.create(newPerson, {transaction: t}).then(function (person) {\n        return Group.find(id, {transction: t}).then(function(group){\n            if (!group) throw Error(\"Group not found for id: \" + id);\n            return person.setGroups( [group], {transction: t});\n        })              \n\n    });\n}).then(function (result) {\n    // Transaction has been committed\n    // result is whatever the result of the promise chain returned to the transaction callback is\n    console.log(result);\n}).catch(function (err) {\n    // Transaction has been rolled back\n    // err is whatever rejected the promise chain returned to the transaction callback is\n    console.error(err);\n});`\n```\n\n```text\nfunction (result) {..\n```\n\n```text\nreturn person.setGroups( [], {transction: t});\n```\n\n========================================\n\nComments:\n- Shouldn't your Group model use `hasMany` instead of `belongsToMany`?\n- what would be the benefit?\n- You should consider opening an issue at the issue tracker of sequelize - from first looks your code looks like it should work.","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":146,"estimatedTokens":1049}}1036{"id":"stack-32322667","source":"stackoverflow","questionId":32322667,"title":"sequelize incrementing id on validation error","tags":["javascript","postgresql","sequelize.js"],"text":"Title: sequelize incrementing id on validation error\nTags: javascript, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSequelize is incrementing the id, even though it's not adding it into the DB.\n\nFor example for my user mode:\n\n```\nvar User = sequelize.define(\"User\", {\n email: {\n type: DataTypes.STRING,\n unique: true,\n allowNull: false,\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false,\n },\n},\n```\n\nIf I run \n\n```\nvar newUser = User.create({\n email: \"a\",\n password: \"a\"\n })\n```\n\nI get id 1, but if I run it again I get a validation error\n\nnext if I run it with a different email\n\n```\nvar newUser = User.create({\n email: \"b\",\n password: \"a\"\n })\n```\n\nThe id is 3, even though the db only has 2 enteries (id 1 and 3)\n\nI don't quite understand why the id keeps increasing even though its not being added to the db. Is there anyway to get around this?\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define(\"User\", {\n    email: {\n        type: DataTypes.STRING,\n        unique: true,\n        allowNull: false,\n    },\n    password: {\n        type: DataTypes.STRING,\n        allowNull: false,\n    },\n},\n```\n\n```text\nvar newUser = User.create({\n        email: \"a\",\n        password: \"a\"\n    })\n```\n\n```text\nvar newUser = User.create({\n        email: \"b\",\n        password: \"a\"\n    })\n```\n\n```text\nid\n```\n\n```text\nserial\n```\n\n```text\nid\n```\n\n```text\nsmallserial\n```\n\n```text\nserial\n```\n\n```text\nbigserial\n```\n\n```text\nnextval()\n```\n\n```text\nid\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":109,"estimatedTokens":374}}1037{"id":"stack-30121186","source":"stackoverflow","questionId":30121186,"title":"Set column order in sequelize.js","tags":["mysql","node.js","sequelize.js"],"text":"Title: Set column order in sequelize.js\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI would like to put `user_id` column before the timestamps, how can i tell this to `sequelize.define`?\n\n```\nsequelize.define('UserPassport', {\n method: DataType.STRING,\n token: DataType.STRING,\n social_id: DataType.STRING\n }, {\n classMethods: {\n associate: function(models) {\n UserPassport.belongsTo(models.User);\n }\n },\n tableName: 'user_passports',\n underscored: true\n });\n```\n\nschema of the table:\n\n```\nCREATE TABLE `user_passports` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `method` varchar(255) DEFAULT NULL,\n `token` varchar(255) DEFAULT NULL,\n `social_id` varchar(255) DEFAULT NULL,\n `created_at` datetime NOT NULL,\n `updated_at` datetime NOT NULL,\n `user_id` int(11) DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `user_id` (`user_id`),\n CONSTRAINT `user_passports_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE\n ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;\n```\n\nP.S: is it possible to make a composite key out of `method` and `social_id` so they both would compose the PK instead of the id field.\n\n========================================\n\nCode:\n```text\nsequelize.define('UserPassport', {\n    method: DataType.STRING,\n    token:  DataType.STRING,\n    social_id: DataType.STRING\n  }, {\n    classMethods: {\n      associate: function(models) {\n        UserPassport.belongsTo(models.User);\n      }\n    },\n    tableName:   'user_passports',\n    underscored: true\n  });\n```\n\n```text\nCREATE TABLE `user_passports` (\n      `id` int(11) NOT NULL AUTO_INCREMENT,\n      `method` varchar(255) DEFAULT NULL,\n      `token` varchar(255) DEFAULT NULL,\n      `social_id` varchar(255) DEFAULT NULL,\n      `created_at` datetime NOT NULL,\n      `updated_at` datetime NOT NULL,\n      `user_id` int(11) DEFAULT NULL,\n      PRIMARY KEY (`id`),\n      KEY `user_id` (`user_id`),\n      CONSTRAINT `user_passports_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE\n    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;\n```\n\n```text\nuser_id\n```\n\n```text\nsequelize.define\n```\n\n```text\nmethod\n```\n\n```text\nsocial_id\n```\n\n```js\nvar user_passport = sequelize.define('user_passport', {\n    method: DataTypes.STRING,\n    token: DataTypes.STRING,\n    social_id: DataTypes.STRING,\n    user_id: DataTypes.INTEGER\n}, {\n    classMethods: {\n        associate: function(models) {\n            user_passport.belongsTo(models.User, { foreignKey: 'user_id' });\n        }\n    },\n    tableName: 'user_passports',\n    underscored: true\n});\n```\n\n```js\nuser_passport.belongsTo(models.settings, { foreignKey: 'user_id' });\n```\n\n```text\ndefine\n```\n\n```text\nassociate\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":120,"estimatedTokens":684}}1038{"id":"stack-28578745","source":"stackoverflow","questionId":28578745,"title":"Sequelize many-to-many relationship table gets unneeded extra column","tags":["javascript","node.js","entity-relationship","sequelize.js"],"text":"Title: Sequelize many-to-many relationship table gets unneeded extra column\nTags: javascript, node.js, entity-relationship, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to define a M:N relationship between models `Survey` and `Question`. The name of the relationship is `SurveyHasQuestions` which also has a definition (see further down how it's used in the associations definitions):\n\n```\nvar SurveyHasQuestions = sequelize.define('survey_has_questions', {\n shq_id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n }\n}, {\n tableName: 'survey_has_questions'\n});\n```\n\nTables for `Survey` and `Question` are generated correctly in the DB (which btw is Postgres):\n\n```\nsurvey_id: integer (pkey)\nsurvey_url: string\ndate: timestamp\n```\n\nand\n\n```\nquestion_id: integer (pkey)\nquestion_text: string\n```\n\nNow, the following associations:\n\n```\nSurvey.hasMany(SurveyQuestion, {through: SurveyHasQuestions, foreignKey: 'survey_id'});\nSurveyQuestion.hasMany(Survey, {through: SurveyHasQuestions, foreignKey: 'question_id'});\nSurveyHasQuestions.belongsTo(Survey, {foreignKey: 'survey_id'});\nSurveyHasQuestions.belongsTo(SurveyQuestion, {foreignKey: 'question_id'});\n```\n\nwork correctly i.e. they generate a `survey_has_questions` table for the M:N relationship with the desired structure:\n\n```\nshq_id: integer (pkey)\nquestion_id: integer (fkey references survey_question.question_id)\nsurvey_id: integer (fkey references survey.survey_id)\n```\n\nbut sequelize complains with the warning: `Using 2 x hasMany to represent N:M relations has been deprecated. Please use belongsToMany instead`\n\nSo in an effort to do things correctly, I've tried using only `belongsToMany()`. But these associations:\n\n```\nSurveyQuestion.belongsToMany(Survey, {\n through: SurveyHasQuestions,\n foreignKey: 'question_id'\n});\nSurvey.belongsToMany(SurveyQuestion, {\n through: SurveyHasQuestions,\n foreignKey: 'survey_id'\n});\n```\n\ngenerate for `survey_has_questions` the incorrect table:\n\n```\nshq_id: integer (pkey)\nquestion_id: integer (fkey references survey_question.question_id)\nsurvey_survey_id: integer (fkey references survey.survey_id) The problem is the extra column `survey_survey_id` which serves absolutely nothing as it's a duplicate of the other column `survey_id`.\n\nThe interesting part is that if I reverse the order of the `.belongsToMany()` statements, I get an extra field `survey_question_question_id` in place of the `survey_survey_id`.\n\nNow I know that I can `fix` this situation if in the definition of `SurveyHasQuestions` I remove my own primary key `shq_id` and let the combination of the fkeys serve as the pkey. But even though technically the serial pkey may not offer anything in the relationship (it might even be an overhead), still as far as I know it's not illegal to define one.\n\nAnyone else come across this kind of behavior? Is there a way to work around it i.e. define associations using only `belongsToMany()` and still get the correct table structure for `survey_has_questions`?\n\n========================================\n\nCode:\n```text\nvar SurveyHasQuestions = sequelize.define('survey_has_questions', {\n    shq_id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    }\n}, {\n    tableName: 'survey_has_questions'\n});\n```\n\n```text\nsurvey_id: integer (pkey)\nsurvey_url: string\ndate: timestamp\n```\n\n```text\nquestion_id: integer (pkey)\nquestion_text: string\n```\n\n```text\nSurvey.hasMany(SurveyQuestion, {through: SurveyHasQuestions, foreignKey: 'survey_id'});\nSurveyQuestion.hasMany(Survey, {through: SurveyHasQuestions, foreignKey: 'question_id'});\nSurveyHasQuestions.belongsTo(Survey, {foreignKey: 'survey_id'});\nSurveyHasQuestions.belongsTo(SurveyQuestion, {foreignKey: 'question_id'});\n```\n\n```text\nshq_id: integer (pkey)\nquestion_id: integer (fkey references survey_question.question_id)\nsurvey_id: integer (fkey references survey.survey_id)\n```\n\n```text\nSurveyQuestion.belongsToMany(Survey, {\n    through: SurveyHasQuestions,\n    foreignKey: 'question_id'\n});\nSurvey.belongsToMany(SurveyQuestion, {\n    through: SurveyHasQuestions,\n    foreignKey: 'survey_id'\n});\n```\n\n```text\nshq_id: integer (pkey)\nquestion_id: integer (fkey references survey_question.question_id)\nsurvey_survey_id: integer (fkey references survey.survey_id) <---??? UNWANTED\nsurvey_id: integer (fkey references survey.survey_id)\n```\n\n```text\nSurvey\n```\n\n```text\nQuestion\n```\n\n```text\nSurveyHasQuestions\n```\n\n```text\nSurvey\n```\n\n```text\nQuestion\n```\n\n```text\nsurvey_has_questions\n```\n\n```text\nUsing 2 x hasMany to represent N:M relations has been deprecated. Please use belongsToMany instead\n```\n\n```text\nbelongsToMany()\n```\n\n```text\nsurvey_has_questions\n```\n\n```text\nsurvey_survey_id\n```\n\n```text\nsurvey_id\n```\n\n```text\n.belongsToMany()\n```\n\n```text\nsurvey_question_question_id\n```\n\n```text\nsurvey_survey_id\n```\n\n```text\nfix\n```\n\n```text\nSurveyHasQuestions\n```\n\n```text\nshq_id\n```\n\n```text\nbelongsToMany()\n```\n\n```text\nsurvey_has_questions\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":211,"estimatedTokens":1246}}1039{"id":"stack-31704458","source":"stackoverflow","questionId":31704458,"title":"Breeze-Sequelize with autoGeneratedKeyType Identity","tags":["javascript","node.js","breeze","sequelize.js"],"text":"Title: Breeze-Sequelize with autoGeneratedKeyType Identity\nTags: javascript, node.js, breeze, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create an MS SQL db with breeze-breeze sequelize and i like to generate the ids on the db server. My solution is oriented on the tempHire example from the breeze samples repo \n\nMy Metadata.json looks like this:\n\n```\n{\n \"metadataVersion\": \"1.0.5\",\n \"namingConvetion\": \"camelCase\",\n \"localQueryComparisonOptions\": \"caseInsensitiveSQL\",\n \"dataServices\": [{\n \"serviceName\": \"breeze/\",\n \"hasServerMetadata\": true,\n \"useJsonp\": false\n }],\n \"structuralTypes\": [{\n\n \"shortName\": \"User\",\n \"namespace\": \"Model\",\n \"autoGeneratedKeyType\": \"Identity\",\n \"defaultResourceName\": \"Users\",\n \"dataProperties\": [{\n \"nameOnServer\": \"id\",\n \"dataType\": \"Int32\",\n \"isPartOfKey\": true,\n \"isNullable\": false\n }, {\n \"name\": \"firstName\",\n \"dataType\": \"String\"\n }, {\n \"name\": \"lastName\",\n \"dataType\": \"String\"\n }, {\n \"name\": \"userName\",\n \"dataType\": \"String\",\n \"isNullable\": false,\n \"maxLength\": 64,\n \"validators\": [{\n \"name\": \"required\"\n }, {\n \"maxLength\": 64,\n \"name\": \"maxLength\"\n }]\n }, {\n \"name\": \"email\",\n \"dataType\": \"String\"\n }]\n }],\n \"resourceEntityTypeMap\": {\n \"Users\": \"User:#Model\"\n }\n}\n```\n\nthough this will not create an identity id column.\nthe created table looks like the following create script:\n\n```\nCREATE TABLE [User] (\n [id] INTEGER NOT NULL , \n [firstName] NVARCHAR(255) DEFAULT NULL, \n [lastName] NVARCHAR(255) DEFAULT NULL, \n [userName] NVARCHAR(64) NOT NULL DEFAULT '', \n [email] NVARCHAR(255) DEFAULT NULL, \n PRIMARY KEY ([id])\n)\n```\n\nIn addition here are some breeze server side implementations:\n\n```\nvar dbConfig = {\n user: 'user',\n password: 'secret',\n dbName: 'dbname'\n};\n\nvar sequelizeOptions = {\n host: 'hostname',\n dialect: 'mssql',\n port: 1433\n};\n\nfunction createSequelizeManager() {\n var metadata = readMetadata();\n var sm = new SequelizeManager(dbConfig, sequelizeOptions);\n sm.importMetadata(metadata);\n\n return sm;\n}\n\nvar _sequelizeManager = createSequelizeManager();\n\n_sequelizeManager.authenticate();\n\n_sequelizeManager.sync(false /* createDb */)\n .then(seed)\n .then(function () {\n console.log('db init successful');\n });\n```\n\nDo i have a wrong configuration? Is the Identity not available with the mssql dialect? Am i doing something wrong?\n\n========================================\n\nCode:\n```text\n{\n    \"metadataVersion\": \"1.0.5\",\n    \"namingConvetion\": \"camelCase\",\n    \"localQueryComparisonOptions\": \"caseInsensitiveSQL\",\n    \"dataServices\": [{\n        \"serviceName\": \"breeze/\",\n        \"hasServerMetadata\": true,\n        \"useJsonp\": false\n    }],\n    \"structuralTypes\": [{\n\n        \"shortName\": \"User\",\n        \"namespace\": \"Model\",\n        \"autoGeneratedKeyType\": \"Identity\",\n        \"defaultResourceName\": \"Users\",\n        \"dataProperties\": [{\n            \"nameOnServer\": \"id\",\n            \"dataType\": \"Int32\",\n            \"isPartOfKey\": true,\n            \"isNullable\": false\n        }, {\n            \"name\": \"firstName\",\n            \"dataType\": \"String\"\n        }, {\n            \"name\": \"lastName\",\n            \"dataType\": \"String\"\n        }, {\n            \"name\": \"userName\",\n            \"dataType\": \"String\",\n            \"isNullable\": false,\n            \"maxLength\": 64,\n            \"validators\": [{\n                \"name\": \"required\"\n            }, {\n                \"maxLength\": 64,\n                \"name\": \"maxLength\"\n            }]\n        }, {\n            \"name\": \"email\",\n            \"dataType\": \"String\"\n        }]\n    }],\n    \"resourceEntityTypeMap\": {\n        \"Users\": \"User:#Model\"\n    }\n}\n```\n\n```text\nCREATE TABLE [User] (\n    [id] INTEGER NOT NULL , \n    [firstName] NVARCHAR(255) DEFAULT NULL, \n    [lastName] NVARCHAR(255) DEFAULT NULL, \n    [userName] NVARCHAR(64) NOT NULL DEFAULT '', \n    [email] NVARCHAR(255) DEFAULT NULL, \n    PRIMARY KEY ([id])\n)\n```\n\n```text\nvar dbConfig = {\n    user: 'user',\n    password: 'secret',\n    dbName: 'dbname'\n};\n\nvar sequelizeOptions = {\n    host: 'hostname',\n    dialect: 'mssql',\n    port: 1433\n};\n\nfunction createSequelizeManager() {\n    var metadata = readMetadata();\n    var sm = new SequelizeManager(dbConfig, sequelizeOptions);\n    sm.importMetadata(metadata);\n\n    return sm;\n}\n\nvar _sequelizeManager = createSequelizeManager();\n\n_sequelizeManager.authenticate();\n\n_sequelizeManager.sync(false /* createDb */)\n    .then(seed)\n    .then(function () {\n        console.log('db init successful');\n    });\n```\n\n```text\nif (attributes.type.key == \"INTEGER\" || attributes.type.key ==\"BIGINT\") {\n    attributes.autoIncrement = true;\n  }\n```\n\n```text\nMetadataMapper\n```\n\n```text\nMetadataMapper.js\n```\n\n```text\n134\n```\n\n```text\nattributes.type== \"INTEGER\" || attributes.type==\"BIGINT\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":224,"estimatedTokens":1179}}1040{"id":"stack-29561436","source":"stackoverflow","questionId":29561436,"title":"How to correctly implement Sequelize.js in a MEAN-stack based app?","tags":["node.js","sequelize.js","mean-stack"],"text":"Title: How to correctly implement Sequelize.js in a MEAN-stack based app?\nTags: node.js, sequelize.js, mean-stack\nSource: Stack Overflow\n\nQuestion:\ni have a MEAN.js based app, and now i need (at the behest of the cleint)to use MySQL instead of MongoDB. i understand that Sequelize is the way to go.\n\nbut searching around for some easy to implement solution didnt bare much fruit, im new to node.js and server side programming.\n\ni need a step by step instruction on how to implement Sequelize in an existing MEAN.js stack that would fit to the existing architecture\n\n========================================\n\nTop Answer:\nQuite late to join this conversation but thinking my reply could help new google crawlers/ solution seekers. You can try SEANjs, it could help, nearly perfect but needs contribution for Yeoman's auto generators of sub-modules.\n\nSEANjs allows you to use Sequelize for your MySQL or Postgre database. While mean-stack-relational (mentioned in previous comment) provides MVC app architecture, SEANjs follows Modules architecture which resembles the latest MEAN stack 4.2, at time of this writing.\n\n========================================\n\nComments:\n- I don't think there's an \"easy\" solution. You'll need to recreate the schemas/models, import the data from MongoDB to MySQL. Sequelize has a basic express tutorial in their old docs which could be useful. Else there's the current Getting Started guide.\n- i ended up merging between mean stack relational and the regular mean-stack, simply copied the sequelize part over the mongoose.. not the most proffesional way but hey, it worked! so thanks","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":23,"estimatedTokens":404}}1041{"id":"stack-39187525","source":"stackoverflow","questionId":39187525,"title":"When defining a Model, should I use Sequelize or DataType?","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: When defining a Model, should I use Sequelize or DataType?\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize to handle a MySQL database in a Node-Express app. I'm trying to define a Teacher model following the docs, but I've found two possible options to do so. The first one means doing\n\n```\nvar Teacher = sequelize.define('Teacher', {\n firstname: Sequelize.STRING,\n lastname: Sequelize.STRING})\n```\n\nThe other option was\n\n```\nexport default function(sequelize, DataTypes) {\n var Teacher = sequelize.define('Teacher', {\n firstname: DataTypes.STRING,\n lastname: DataTypes.STRING})\n```\n\nI don't see if there's actually a difference between those two (Sequelize and DataTypes), or why should I export the second one.\n\n========================================\n\nCode:\n```text\nvar Teacher = sequelize.define('Teacher', {\n  firstname: Sequelize.STRING,\n  lastname: Sequelize.STRING})\n```\n\n```text\nexport default function(sequelize, DataTypes) {\n  var Teacher = sequelize.define('Teacher', {\n  firstname: DataTypes.STRING,\n  lastname: DataTypes.STRING})\n```\n\n```text\nconst DataTypes = require('./data-types');\n\n…\n\nfor (const dataType in DataTypes) {\n   Sequelize[dataType] = DataTypes[dataType];\n}\n\n…\n\nmodule.exports = Promise.Sequelize = Sequelize;\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":53,"estimatedTokens":329}}1042{"id":"stack-38080111","source":"stackoverflow","questionId":38080111,"title":"ExpressJS: Promises and Error Handling middleware","tags":["javascript","node.js","express","promise","sequelize.js"],"text":"Title: ExpressJS: Promises and Error Handling middleware\nTags: javascript, node.js, express, promise, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have some error handling middleware defined and a route returning a promise. But when that promise gives an error, I have to manually append `.catch(err => next(err))` after every promise. While its not a problem, isn't it sensible for ExpressJs to see if a route returns a promise and if so call the error handling middleware automatically.\n\nMy current shortened code:\n\n```\n// errorHandlers.js\nfunction sequelizeValidationError (err, req, res, next) {\n if (err.name && err.name == 'SequelizeValidationError')\n res.status(400).send(err.errors)\n else next(err)\n}\n\n// auth.js\nrouter.post ('/register', middleware.isNotAuthenticated, (req, res, next) => {\n const { email, password, name } = req.body;\n\n return models.User.find({where : { email }}).then(user => {\n if (user) {\n if (user.password == password) sendToken(user.id, res);\n else res.sendStatus(401);\n } else {\n return models.User.create({\n email, password, name\n }).then(user => {\n sendToken(user.id, res);\n })\n }\n }).catch(next)\n})\n\n// index.js\nrouter.use('/auth', require('./auth'))\n\nrouter.use(errorHandlers.sequelizeValidationError)\n```\n\nFor example, currently I could have forgot to write `catch` at one place and the server would have failed.\n\nAm I missing out on something? How can I avoid having to type the `catch` every time?\n\n========================================\n\nCode:\n```text\n// errorHandlers.js\nfunction sequelizeValidationError (err, req, res, next) {\n  if (err.name && err.name == 'SequelizeValidationError')\n    res.status(400).send(err.errors)\n  else next(err)\n}\n\n// auth.js\nrouter.post ('/register',  middleware.isNotAuthenticated, (req, res, next) => {\n  const { email, password, name } = req.body;\n\n  return models.User.find({where : { email }}).then(user => {\n    if (user) {\n      if (user.password == password) sendToken(user.id, res);\n      else res.sendStatus(401);\n    } else {\n      return models.User.create({\n        email, password, name\n      }).then(user => {\n        sendToken(user.id, res);\n      })\n    }\n  }).catch(next)\n})\n\n// index.js\nrouter.use('/auth', require('./auth'))\n\nrouter.use(errorHandlers.sequelizeValidationError)\n```\n\n```text\n.catch(err => next(err))\n```\n\n```text\ncatch\n```\n\n```text\ncatch\n```\n\n```text\npromise-express-router\n```\n\n```text\nroute-params\n```\n\n```text\nexpress-co\n```\n\n========================================\n\nComments:\n- Not sure if switching the framework is an option for you, but koajs.com works with promises natively. Writing a catching middleware is trivial in koa.js\n- @Herku , I cannot for this project, but will look at koa for the next project definitely. Took a look at it, looks quite easy to use with koa-router\n- There are various modules that provide promise support for Express, for example `promise-express-router` and `express-ko` (which also happens to implement some Koa-goodness for Express). Perhaps it's of use.\n- @robertklep promise-express-router is good but lacks route-params and maybe some other features. IMHO its better to use a simple wrap function like the one in the answer instead . `express-ko` looks like a wrap function + generators . Thanks anyways\n- The modules mentioned above are hardly if at all used by any significant number of people in production and therefore are questionable at best to adopt moving forward. Check the stars/watch count of each repository to identify this.\n- Coming in Express v5 github.com/expressjs/express/issues/2259#issuecomment-433586&zwnj;&#8203;394","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":113,"estimatedTokens":900}}1043{"id":"stack-36700473","source":"stackoverflow","questionId":36700473,"title":"Is it possible in sequelize to query based on an association?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Is it possible in sequelize to query based on an association?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI modelled a data structure where I have a n:m relation between \"Rooms\" and \"Users\".\n\nNow I want to delete / destroy a room.\nTherefore I want to check if the deleting user is in the room.\n\nI have the username and the roomid.\n\nHow can I accomplisch that in **one** Query.\nBasically my question is of it possible to do something like that in a query:\n\n```\nRoom.destroy({\n where: {\n //username in users\n users: {$contains: { username: \"some username\" }}\n }\n})\n```\n\nHere users is an \"Association\" to my users.\n\n========================================\n\nCode:\n```text\nRoom.destroy({\n   where: {\n       //username in users\n       users: {$contains: { username: \"some username\" }}\n   }\n})\n```\n\n```js\nRoom.destroy({\n  include: [{\n    model: User,\n      through: {\n        where: {username: \"some username\"}\n      }\n  }]\n});\n```\n\n```text\nUser.findAll({\n  include: [{\n    model: Project,\n      through: {\n        attributes: ['createdAt', 'startedAt', 'finishedAt']\n          where: {completed: true}\n      }\n  }]\n});\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- How is it declared your models associations?","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":69,"estimatedTokens":318}}1044{"id":"stack-35697295","source":"stackoverflow","questionId":35697295,"title":"lodash merge and combine objects","tags":["javascript","sequelize.js","lodash"],"text":"Title: lodash merge and combine objects\nTags: javascript, sequelize.js, lodash\nSource: Stack Overflow\n\nQuestion:\nI have an array of objects as below that I read from my database using sequelize ORM: \nI want to have all my videos from a section, but the better I can return using sequelize is : \n\n```\n[{\n \"id\": 2,\n \"name\": \"Ru\",\n \"subsection\": 1,\n \"Video\": {\n \"id\": 11,\n \"source\": \"sourrrccrsss22222\",\n \"videoSubSection\": 2\n }\n },\n {\n \"id\": 2,\n \"name\": \"Ru\",\n \"subsection\": 1,\n \"Video\": {\n \"id\": 12,\n \"source\": \"sourrrccrsss111\",\n \"videoSubSection\": 2\n }\n },\n {\n \"id\": 1,\n \"name\": \"Oc\",\n \"subsection\": 1,\n \"Video\": {\n \"id\": 13,\n \"source\": \"sourrrcc\",\n \"videoSubSection\": 1\n }\n },\n {\n \"id\": 1,\n \"name\": \"Oc\",\n \"subsection\": 1,\n \"Video\": {\n \"id\": 14,\n \"source\": \"sourrrcc\",\n \"videoSubSection\": 1\n }\n }]\n```\n\nIs there a way to merge and combine the objects in my array to obtain something like this : \n\n```\n[{\n \"id\": 2,\n \"name\": \"Ru\",\n \"subsection\": 1,\n \"Video\": [{\n \"id\": 11,\n \"source\": \"sourrrccrsss22222\",\n \"videoSubSection\": 2\n },{\n \"id\": 12,\n \"source\": \"sourrrccrsss111\",\n \"videoSubSection\": 2\n }]\n },\n {\n \"id\": 1,\n \"name\": \"Oc\",\n \"subsection\": 1,\n \"Video\": [{\n \"id\": 13,\n \"source\": \"sourrrcc\",\n \"videoSubSection\": 1\n },{\n \"id\": 14,\n \"source\": \"sourrrcc\",\n \"videoSubSection\": 1\n }]\n }\n```\n\nThe function that approach the most is _.mergeWith(object, sources, customizer) but the main problem I have is that I have on object and need to merge this object.\n\n========================================\n\nTop Answer:\nMaybe try transform():\n\n```\n_.transform(data, (result, item) => {\n let found;\n\n if ((found = _.find(result, { id: item.id }))) { \n found.Video.push(item.Video);\n } else {\n result.push(_.defaults({ Video: [ item.Video ] }, item));\n }\n}, []);\n```\n\nUsing reduce() would work here as well, but `transform()` is less verbose.\n\n========================================\n\nCode:\n```text\n[{\n    \"id\": 2,\n    \"name\": \"Ru\",\n    \"subsection\": 1,\n    \"Video\": {\n      \"id\": 11,\n      \"source\": \"sourrrccrsss22222\",\n      \"videoSubSection\": 2\n    }\n  },\n  {\n    \"id\": 2,\n    \"name\": \"Ru\",\n    \"subsection\": 1,\n    \"Video\": {\n      \"id\": 12,\n      \"source\": \"sourrrccrsss111\",\n      \"videoSubSection\": 2\n    }\n  },\n  {\n    \"id\": 1,\n    \"name\": \"Oc\",\n    \"subsection\": 1,\n    \"Video\": {\n      \"id\": 13,\n      \"source\": \"sourrrcc\",\n      \"videoSubSection\": 1\n    }\n  },\n  {\n    \"id\": 1,\n    \"name\": \"Oc\",\n    \"subsection\": 1,\n    \"Video\": {\n      \"id\": 14,\n      \"source\": \"sourrrcc\",\n      \"videoSubSection\": 1\n    }\n  }]\n```\n\n```text\n[{\n    \"id\": 2,\n    \"name\": \"Ru\",\n    \"subsection\": 1,\n    \"Video\": [{\n      \"id\": 11,\n      \"source\": \"sourrrccrsss22222\",\n      \"videoSubSection\": 2\n    },{\n      \"id\": 12,\n      \"source\": \"sourrrccrsss111\",\n      \"videoSubSection\": 2\n    }]\n  },\n  {\n    \"id\": 1,\n    \"name\": \"Oc\",\n    \"subsection\": 1,\n    \"Video\": [{\n      \"id\": 13,\n      \"source\": \"sourrrcc\",\n      \"videoSubSection\": 1\n    },{\n      \"id\": 14,\n      \"source\": \"sourrrcc\",\n      \"videoSubSection\": 1\n    }]\n  }\n```\n\n```js\nvar data = [{ id: 2, name: \"Ru\", subsection: 1, Video: { id: 11, source: \"sourrrccrsss22222\", VideoSubSection: 2 } }, { id: 2, name: \"Ru\", subsection: 1, Video: { id: 12, source: \"sourrrccrsss111\", VideoSubSection: 2 } }, { id: 1, name: \"Oc\", subsection: 1, Video: { id: 13, source: \"sourrrcc\", VideoSubSection: 1 } }, { id: 1, name: \"Oc\", subsection: 1, Video: { id: 14, source: \"sourrrcc\", VideoSubSection: 1 } }],\n    merged = function (data) {\n        var r = [], o = {};\n        data.forEach(function (a) {\n            if (!(a.id in o)) {\n                o[a.id] = [];\n                r.push({ id: a.id, name: a.name, subsection: a.subsection, Video: o[a.id] });\n            }\n            o[a.id].push(a.Video);\n        });\n        return r;\n    }(data);\n\ndocument.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');\n```\n\n```text\nArray#forEach()\n```\n\n```text\nvar result = [];\nvar map = [];\n\n_.forEach(test, (o) => {\n  var temp = _.clone(o);\n  delete o.Video;\n  if (!_.some(map, o)) {\n    result.push(_.extend(o, {Video: [temp.Video]}));\n    map.push(o);\n  } else {\n    var index = _.findIndex(map, o);\n    result[index].Video.push(temp.Video);\n  }\n});\n\nconsole.log(result); // outputs what you want.\n```\n\n```text\ntest\n```\n\n```text\n_.transform(data, (result, item) => {\n  let found;\n\n  if ((found = _.find(result, { id: item.id }))) { \n    found.Video.push(item.Video);\n  } else {\n    result.push(_.defaults({ Video: [ item.Video ] }, item));\n  }\n}, []);\n```\n\n```text\ntransform()\n```\n\n========================================\n\nComments:\n- I will try when I can, the solution is elegant with few lines.\n- Work like perfectly !","metadata":{"transformedAt":"2026-08-18T18:33:34.497Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":247,"estimatedTokens":1164}}1045{"id":"stack-38791728","source":"stackoverflow","questionId":38791728,"title":"Sequelize save Data in belongsToMany created Table and Read from it(Solution at the End)","tags":["angularjs","sql-server","node.js","express","sequelize.js"],"text":"Title: Sequelize save Data in belongsToMany created Table and Read from it(Solution at the End)\nTags: angularjs, sql-server, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using for my Backend Node.js,Express.js and Sequelize for the connection to the Database.\nI have a n:m Relationship between Tasks and Keys.\n\nTasks and Keys is created by me and TaskKey through Sequelize with:\n\n**Backend**\n\n```\n// Tasks n:m Keys\n db.DictKey.belongsToMany(db.Task, { through: 'TaskKeys' , foreignKey:'key_id'});\n db.Task.belongsToMany(db.DictKey, { through: 'TaskKeys' , foreignKey: 'task_id'});\n```\n\nNow if I create a new Task on the \n\n**frontend**\n\n```\n$scope.create = () => {\n this.$http.post('/api/tasks', {\n user_id: $scope.selectUser,\n lang_id: $scope.selectLang,\n name: $scope.newTask\n });\n}\n```\n\nI want to send with that request an Array of all Keys the User selected.\n\nIn the Backend it should add an entry to `TaskKeys` for the new Task for every DictKey sent.\nFor example \n\nTable Task:\n\n```\nID | some values\n1 | some values | this is the new task created\n```\n\nSend Keys in Array[2,5,6]\n\nTaskKey / in the same moment create in this Table the Dependant Keys\n\n```\nTaskID | KeyID\n1 | 2\n1 | 5\n1 | 6\n```\n\nHow can I achieve that ?\n\nAfter that I would like to show a Task.\nTaking the Example before.\nGet task where id = 1\nng-repeat all datas and as well get all Keys thanks to the Table TaskKey.\n\nI could not find a Example which explains that and the only solution I have at the moment is at the front end with `$http.post(taskkey)` with a `foreach` for every key in the Table `TaskKey`. But later in the Live System there would be over 1000 keys, so this isn't an acceptable solution.\nIs there a good solution for that for backend? \n\n**Edit1:**\n\n```\n... working fine\n$scope.create = () => {\n this.$http.post('/api/tasks', {\n task:{\n user_id: $scope.selectUser,\n lang_id: $scope.selectLang,\n name: $scope.newTask\n },\n keys:[1,2,3,4,5]\n });\n ...\n ... \n// Creates a new Task in the DB\nexport function create(req, res) {\n return Task.create(req.body.task)\n .then(function(task){\n return task.addTaskKeys(req.body.keys);//throws 500error\n //console.log(req.body.keys);//working fine getting the Keys\n })\n .then(respondWithResult(res, 201))\n .catch(handleError(res));\n}\n...\n```\n\nReading the docs belongsToManyDoc doesnt help much because no Examples or Detailed Explained.\nIve tried several things like:\n\n- addTask/addTasks/addTaskKeys/addKey as in doc explained for adding an association\n\n- createTask/createKey/createTaskKeys for creating an association\n\nIn my backend I dont have any Functions for TaskKeys only for Tasks and Keys. But as I understood I dont need any for TaskKeys because with \n\n```\n// Tasks n:m Keys\n db.DictKey.belongsToMany(db.Task, { through: 'TaskKeys' , foreignKey:'key_id'});\n db.Task.belongsToMany(db.DictKey, { through: 'TaskKeys' , foreignKey: 'task_id'});\n```\n\ncreating Middle Table there is an association between Tasks and Keys. So normally add/create should just work and it should add instances in TaskKeys.\n\n```\nexport function create(req, res) {\n return Task.create(req.body.task)\n .then(function(task){\n return task.addTaskKeys(req.body.keys);//throws 500error\n```\n\nwith task.addTaskKeys adding Associations with the just created Task=> task_id \n\nwith req.body.keys giving him the Keys =>key_id\n\nIf I take the Example from Doc change to minde DB: \n\n```\n... example\n Project.create({ id: 11 }).then(function (project) {\n user.addProjects([project, 12]);\n });\n... mine\nreturn Task.create(req.body.task)\n .then(function(task){\n return DictKey.addTasks([task,{key_id : 1}]);//still error\n })//DictKey.addTask(task,1); still error\n```\n\nReading the BelongsToMany Association and Quoting it: \n\n user.addProject(project, { status: 'started' })\n By default the code will add projectId and userId to the UserProjects table\n\nTrying out creating with Associations:\n\n http://sequelize.readthedocs.io/en/latest/docs/associations/#creating-elements-of-a-hasmany-or-belongstomany-association\n Sorry not allowed to post more as 1 Link.\n\n```\nexport function create(req, res) {\n return Task.create({\n name: req.body.task.name,\n user_id: req.body.task.user_id,\n lang_id: req.body.task.lang_id,\n key_id:[req.body.keys]\n },{\n include: [DictKey]\n })\n```\n\nNo Error but only Creating Task not TaskKeys....\nSo what Iam doing wrong whole time? \n\n**Edit2:**\nFor Testing I inserted Data in the Table TaskKeys by Myself in MsSql.\nTaskKey / Self Created Datas with SqlQuery\n\n```\nTaskID | KeyID\n1 | 1\n1 | 2\n1 | 3\n2 | 4\n2 | 5\n```\n\ngetting it from my **frontend** \n\n```\nthis.$http.get('/api/tasks/' +2 )\n .then(response => {\n this.Tasks = response.data;\n console.log(this.Tasks);\n });\n```\n\n**backend** \n\n```\n// Gets a single Task from the DB\nexport function show(req, res) {\n return Task.findAll({\n where: {\n _id: req.params.id\n },\n include: [{\n model: DictKey\n }]\n })\n .then(handleEntityNotFound(res))\n .then(respondWithResult(res))\n .catch(handleError(res));\n}\n```\n\nConsoleOutput:\n\n```\n[Object]\nObject\n_id:2 // the searched TaskId= 2 => right\ndict_Keys:Array[2] // the Dependant 2 KeyIds => right\n```\n\nSo the table which is created is working fine.\nThe Question is now only why adding through Backend with addKey is not working by doing the same as in the Example.\nTrying the Example to check Associations:\n\n```\n// Creates a new Task in the DB\nexport function create(req, res) {\n Task.create({\n name: req.body.task.name,\n user_id: req.body.task.user_id,\n lang_id: req.body.task.lang_id\n}).then(function(task) {\n return DictKey.create({ name:req.body.task.name,notice:req.body.task.name, user_id:req.body.task.user_id })\n .then(function(key) {\n return task.hasDictKey(key).then(function(result) {\n // result would be false\n return task.addDictKey(key).then(function() {\n return task.hasDictKey(key).then(function(result) {\n // result would be true\n })\n })\n })\n })\n })\n```\n\nThrows task.hasDictKey is not a function\n\n```\ndb.Task.create({\n name: 'test',\n user_id: 266,\n lang_id: 9,\n key_id:[1,2]\n},{\n include: [db.DictKey]\n})\n```\n\nThrows dict_Keys is not associated to Task\nSo it means they are not Connected together? BUt Reading data and Inserting Data in the Database is working?\n\nJust Adding now the Example of Sequelize: \n\n```\nvar Usert = db.sequelize.define('usert', {})\nvar Project = db.sequelize.define('project', {})\nvar UserProjects = db.sequelize.define('userProjects', {\n status: Sequelize.STRING\n})\n\nUsert.belongsToMany(Project, { through: UserProjects })\nProject.belongsToMany(Usert, { through: UserProjects })\nUsert.addProject(Project, { status: 'started' })//addProject is not a Function // for real ? now not even their own is not working? :/\n```\n\n**Answer**\n\nBy Reading the Docs I thought with \n\n```\n// Tasks n:m Keys\ndb.DictKey.belongsToMany(db.Task, { through: TaskKeys , foreignKey:'key_id',otherKey:'task_id'});\ndb.Task.belongsToMany(db.DictKey, { through: TaskKeys , foreignKey: 'task_id',otherKey: 'key_id'});\n```\n\nit would automatically generate add/set/get/create Task for DictKey and add/set/get/create DictKey for Task. \n\nBut \n\n Naming strategy\n\n \n By default sequelize will use the model name (the name passed to\n sequelize.define) to figure out the name of the model when used in\n associations.\n\nMeans it adds Functions by the name of the Table Model where you go `define('dict_Keys'...`\nso add/set/get/ Dict_Key to Task.\nThat was the problem because I was using addDictkey instead of addDict_Key.\nI hope it helps someone else in the Future\n\n========================================\n\nTop Answer:\n`foreignKey` should be the same on both sides of the relation, to set the other key use the `otherKey` option.\n\n========================================\n\nCode:\n```text\n// Tasks n:m Keys\n    db.DictKey.belongsToMany(db.Task, { through: 'TaskKeys' , foreignKey:'key_id'});\n    db.Task.belongsToMany(db.DictKey, { through: 'TaskKeys' , foreignKey: 'task_id'});\n```\n\n```text\n$scope.create = () => {\n    this.$http.post('/api/tasks', {\n        user_id: $scope.selectUser,\n        lang_id: $scope.selectLang,\n        name: $scope.newTask\n    });\n}\n```\n\n```text\nID | some values\n1  | some values | this is the new task created\n```\n\n```text\nTaskID | KeyID\n1      | 2\n1      | 5\n1      | 6\n```\n\n```text\n...    working fine\n$scope.create = () => {\n            this.$http.post('/api/tasks', {\n              task:{\n              user_id: $scope.selectUser,\n              lang_id: $scope.selectLang,\n              name: $scope.newTask\n            },\n            keys:[1,2,3,4,5]\n          });\n    ...\n ... \n// Creates a new Task in the DB\nexport function create(req, res) {\n  return Task.create(req.body.task)\n  .then(function(task){\n    return task.addTaskKeys(req.body.keys);//throws 500error\n    //console.log(req.body.keys);//working fine getting the Keys\n  })\n    .then(respondWithResult(res, 201))\n    .catch(handleError(res));\n}\n...\n```\n\n```text\n// Tasks n:m Keys\n    db.DictKey.belongsToMany(db.Task, { through: 'TaskKeys' , foreignKey:'key_id'});\n    db.Task.belongsToMany(db.DictKey, { through: 'TaskKeys' , foreignKey: 'task_id'});\n```\n\n```text\nexport function create(req, res) {\n      return Task.create(req.body.task)\n      .then(function(task){\n        return task.addTaskKeys(req.body.keys);//throws 500error\n```\n\n```text\n... example\n    Project.create({ id: 11 }).then(function (project) {\n      user.addProjects([project, 12]);\n    });\n... mine\nreturn Task.create(req.body.task)\n  .then(function(task){\n    return DictKey.addTasks([task,{key_id : 1}]);//still error\n  })//DictKey.addTask(task,1); still error\n```\n\n```text\nexport function create(req, res) {\n  return Task.create({\n    name: req.body.task.name,\n    user_id: req.body.task.user_id,\n    lang_id: req.body.task.lang_id,\n    key_id:[req.body.keys]\n  },{\n    include: [DictKey]\n  })\n```\n\n```text\nTaskID | KeyID\n1      | 1\n1      | 2\n1      | 3\n2      | 4\n2      | 5\n```\n\n```text\nthis.$http.get('/api/tasks/' +2 )\n            .then(response => {\n              this.Tasks = response.data;\n              console.log(this.Tasks);\n            });\n```\n\n```text\n// Gets a single Task from the DB\nexport function show(req, res) {\n  return Task.findAll({\n    where: {\n      _id: req.params.id\n    },\n    include: [{\n      model: DictKey\n    }]\n  })\n    .then(handleEntityNotFound(res))\n    .then(respondWithResult(res))\n    .catch(handleError(res));\n}\n```\n\n```text\n[Object]\nObject\n_id:2 // the searched TaskId= 2 => right\ndict_Keys:Array[2] // the Dependant 2 KeyIds => right\n```\n\n```text\n// Creates a new Task in the DB\nexport function create(req, res) {\n  Task.create({\n  name: req.body.task.name,\n  user_id: req.body.task.user_id,\n  lang_id: req.body.task.lang_id\n}).then(function(task) {\n    return DictKey.create({ name:req.body.task.name,notice:req.body.task.name, user_id:req.body.task.user_id })\n    .then(function(key) {\n      return task.hasDictKey(key).then(function(result) {\n        // result would be false\n        return task.addDictKey(key).then(function() {\n          return task.hasDictKey(key).then(function(result) {\n            // result would be true\n          })\n        })\n      })\n    })\n  })\n```\n\n```text\ndb.Task.create({\n  name: 'test',\n  user_id: 266,\n  lang_id: 9,\n  key_id:[1,2]\n},{\n  include: [db.DictKey]\n})\n```\n\n```text\nvar Usert = db.sequelize.define('usert', {})\nvar Project = db.sequelize.define('project', {})\nvar UserProjects = db.sequelize.define('userProjects', {\n    status: Sequelize.STRING\n})\n\nUsert.belongsToMany(Project, { through: UserProjects })\nProject.belongsToMany(Usert, { through: UserProjects })\nUsert.addProject(Project, { status: 'started' })//addProject is not a Function // for real ? now not even their own is not working? :/\n```\n\n```text\n// Tasks n:m Keys\ndb.DictKey.belongsToMany(db.Task, { through: TaskKeys , foreignKey:'key_id',otherKey:'task_id'});\ndb.Task.belongsToMany(db.DictKey, { through: TaskKeys , foreignKey: 'task_id',otherKey: 'key_id'});\n```\n\n```text\nTaskKeys\n```\n\n```text\n$http.post(taskkey)\n```\n\n```text\nforeach\n```\n\n```text\nTaskKey\n```\n\n```text\ndefine('dict_Keys'...\n```\n\n```text\nthis.$http.post('/api/tasks', {\n    task: {\n        user_id: $scope.selectUser,\n        lang_id: $scope.selectLang,\n        name: $scope.newTask\n    },\n    keys: [ 2, 5, 6 ]\n});\n```\n\n```text\n...\nreturn Task.create(req.body.task)\n    .then(function(task) {\n        return task.addProjects(req.body.keys);\n    })\n    .then(respondWithResult(res, 201))\n    .catch(handleError(res));\n...\n```\n\n```text\n...\nreturn Task.findById(req.params.id, {\n    include: [ { model: db.DictKey } ]\n})\n...\n```\n\n```text\ndata\n```\n\n```text\nTask\n```\n\n```text\nm:n\n```\n\n```text\nTaskKeys\n```\n\n```text\ninclude\n```\n\n```text\nforeignKey\n```\n\n```text\notherKey\n```\n\n========================================\n\nComments:\n- Thanks for Help. Frontend is working but Backend still Problems. If you could check Edit1 ?\n- What does the console show on the server when you get the 500 error for `return task.addTaskKeys(req.body.keys);`?\n- Console.log: ...doing first create of Task.create then going taskadd `POST &#47;api&#47;tasks 500 57.938 ms - 2` BrwoserConsole Log: `POST http:&#47;&#47;localhost:9000&#47;api&#47;tasks 500 (Internal Server Error)` I tried with Hardcode values like addTask(1);//1 is sure 100% existent in Key Table Same Error\n- Can you set the `DEBUG` environment var to `*` before starting the server and try again? That should give more information... so like `DEBUG=* node server.js`\n- doing `DEBUG=express:* node index.js`, from Express Docs at Debuging. Didnt change much the output. But commenting `Task.create` out and only doing `return task.addKeys(1)` give the Error Cannot read Property of addTask of undefined?\n- Well, yeah, commenting out the code that causes `task` to be defined will cause an `undefined` error when you try to use it. There's no further output on *the server console* when you enable debug?\n- If you check Edit2: you can see i tried several other things often is the Error is not a Function or can not read Property. Now just CopyPasted the userProject Example and it says as well addProject is not a Function. After DEBUG=* the only output was the same Error 500 no more INfos to it.\n- Ive got it running.... It was a Problem with the Naming of the Functions `**Naming strategy** By default sequelize will use the model name (the name passed to sequelize.define) to figure out the name of the model when used in associations.` I was working allways with Task and DictKey the Instances of the Tables but Sequelize creates the Function with the declared name of the Table. So instead of adding addDictKey which i thought would be it was addDict_Key named after my Table. Editing my Question for Future users maybe with same Problem.\n- I Accept your Answer because it was right from beginning ;)\n- Adding `otherKey` in `&#47;&#47; Tasks n:m Keys db.DictKey.belongsToMany(db.Task, { through: 'TaskKeys' , foreignKey:'key_id',otherKey:'task_id'}); db.Task.belongsToMany(db.DictKey, { through: 'TaskKeys' , foreignKey: 'task_id',otherKey: 'key_id'});` did not resolve the Problem. It remains as the same before with the Problem","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":575,"estimatedTokens":3772}}1046{"id":"stack-33847121","source":"stackoverflow","questionId":33847121,"title":"Sequelize underscore / snake case when converted to json","tags":["json","node.js","express","sequelize.js"],"text":"Title: Sequelize underscore / snake case when converted to json\nTags: json, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nUsing Node and Sequelize, is it possible to define a model which uses camelCase for the attributes, but underscore/snake case when converted to json?\n\nCurrently;\n\n```\nvar User = seq.define('user', {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true\n },\n shortLivedToken: {\n type: Sequelize.STRING,\n field: 'short_lived_token'\n },\n longLivedToken: {\n type: Sequelize.STRING,\n field: 'long_lived_token'\n }\n}, {\n underscored: true,\n underscoredAll: true,\n});\n```\n\nTurns into when calling `response.json(user)`\n\n```\n{\n \"id\": null,\n \"shortLivedToken\": \"abcde\",\n \"longLivedToken\": \"fghji\",\n \"updated_at\": \"2015-11-21T18:32:20.181Z\",\n \"created_at\": \"2015-11-21T18:32:20.181Z\"\n}\n```\n\nAnd I want it to be \n\n```\n{\n \"id\": null,\n \"short_lived_token\": \"abcde\",\n \"long_lived_token\": \"fghij\",\n \"updated_at\": \"2015-11-21T18:32:20.181Z\",\n \"created_at\": \"2015-11-21T18:32:20.181Z\"\n}\n```\n\nAny ideas?\n\n========================================\n\nTop Answer:\n### Edit:\n\nUse the underscored option.\n\n```\nsequelize-cli model:generate --name User --attributes login:string --underscored\n```\n\nsource code\n\nHacky, but it'll work for you.\n\n```\nimport { promises as fsPromises } from 'fs';\n\nconst files = await fsPromises.readdir(path.join(/* path to directory */));\n\nconst file =\n files.filter((allFilesPaths) =>\n new RegExp(/* name of file */).test(allFilesPaths),\n )?.[0] ?? null;\n\nif (!file) throw new Error(`file not found`);\n\nconst fileContents = await fsPromises\n .readFile(path.join(/* path to file */), 'utf-8')\n .replace('updatedAt', 'updated_at')\n .replace('createdAt', 'created_at');\n```\n\nAlso, this was posted 7 years ago, so I'd dig into their docs again if I were you. Maybe they allow it now.\n\n========================================\n\nCode:\n```text\nvar User = seq.define('user', {\n    id: {\n        type: Sequelize.INTEGER,\n        primaryKey: true\n    },\n    shortLivedToken: {\n        type: Sequelize.STRING,\n        field: 'short_lived_token'\n    },\n    longLivedToken: {\n        type: Sequelize.STRING,\n        field: 'long_lived_token'\n    }\n}, {\n    underscored: true,\n    underscoredAll: true,\n});\n```\n\n```text\n{\n  \"id\": null,\n  \"shortLivedToken\": \"abcde\",\n  \"longLivedToken\": \"fghji\",\n  \"updated_at\": \"2015-11-21T18:32:20.181Z\",\n  \"created_at\": \"2015-11-21T18:32:20.181Z\"\n}\n```\n\n```text\n{\n  \"id\": null,\n  \"short_lived_token\": \"abcde\",\n  \"long_lived_token\": \"fghij\",\n  \"updated_at\": \"2015-11-21T18:32:20.181Z\",\n  \"created_at\": \"2015-11-21T18:32:20.181Z\"\n}\n```\n\n```text\nresponse.json(user)\n```\n\n```text\nsequelize-cli model:generate --name User --attributes login:string --underscored\n```\n\n```text\nimport { promises as fsPromises } from 'fs';\n\nconst files = await fsPromises.readdir(path.join(/* path to directory */));\n\nconst file =\n    files.filter((allFilesPaths) =>\n        new RegExp(/* name of file */).test(allFilesPaths),\n    )?.[0] ?? null;\n\nif (!file) throw new Error(`file not found`);\n\nconst fileContents = await fsPromises\n    .readFile(path.join(/* path to file */), 'utf-8')\n    .replace('updatedAt', 'updated_at')\n    .replace('createdAt', 'created_at');\n```\n\n========================================\n\nComments:\n- What's version of the sequelize that you use? View this stackoverflow.com/questions/18858337/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":163,"estimatedTokens":842}}1047{"id":"stack-32403158","source":"stackoverflow","questionId":32403158,"title":"Sequelize transactions rollback on raw queries doesn't work","tags":["transactions","sequelize.js","rollback"],"text":"Title: Sequelize transactions rollback on raw queries doesn't work\nTags: transactions, sequelize.js, rollback\nSource: Stack Overflow\n\nQuestion:\nSequelize rollback doesn't work on my transaction.\n\nThis is an example code:\n\n```\nreturn sequelize.transaction({\n isolationLevel: \"SERIALIZABLE\",\n autocommit: false\n },function (t) {\n\n return sequelize.query('DELETE FROM Task WHERE id=:id',\n {\n replacements:{\"id\":id},\n type: sequelize.QueryTypes.SELECT\n })\n .then(function () {\n // the query was successful but I still want to roll back\n t.rollback();\n });\n });\n```\n\nI checked the console:\n\n**Executing (aaf94974-d646-4056-9cfa-0c53f1b1b3e3): START TRANSACTION;**\n\n**Executing (aaf94974-d646-4056-9cfa-0c53f1b1b3e3): SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;**\n\n**Executing (default): DELETE FROM Task WHERE id=6**\n\n**Executing (aaf94974-d646-4056-9cfa-0c53f1b1b3e3): ROLLBACK;**\n\nBut the rollback doesn't work.\n\n========================================\n\nCode:\n```javascript\nreturn sequelize.transaction({\n      isolationLevel: \"SERIALIZABLE\",\n      autocommit: false\n    },function (t) {\n\n      return sequelize.query('DELETE FROM Task WHERE id=:id',\n      {\n        replacements:{\"id\":id},\n        type: sequelize.QueryTypes.SELECT\n      })\n      .then(function () {\n        // the query was successful but I still want to roll back\n        t.rollback();\n      });\n   });\n```\n\n```text\nreturn this.sequelize.query(query, { transaction: t }).bind(this).then(function() {\n    return this.User.create({ name: 'foo' });\n })\n```\n\n```text\nreturn sequelize.query('DELETE FROM Task WHERE id=:id',\n{\n    replacements:{\"id\":id},\n    type: sequelize.QueryTypes.SELECT\n})\n```\n\n```text\ntransaction\n```\n\n```text\nquery\n```\n\n========================================\n\nComments:\n- too old, but.. I am passing the parameter transaction in that object, but it also doesnt rollback","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":86,"estimatedTokens":467}}1048{"id":"stack-34059081","source":"stackoverflow","questionId":34059081,"title":"How do I reference an association when creating a row in sequelize without assuming the foreign key column name?","tags":["node.js","sequelize.js"],"text":"Title: How do I reference an association when creating a row in sequelize without assuming the foreign key column name?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following code:\n\n```\n#!/usr/bin/env node\n'use strict';\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('sqlite:file.sqlite');\n\nvar User = sequelize.define('User', { email: Sequelize.STRING});\nvar Thing = sequelize.define('Thing', { name: Sequelize.STRING});\nThing.belongsTo(User);\n\nsequelize.sync({force: true}).then(function () {\n return User.create({email: 'asdf@example.org'});\n}).then(function (user) {\n return Thing.create({\n name: 'A thing',\n User: user\n }, {\n include: [User]\n });\n}).then(function (thing) {\n return Thing.findOne({where: {id: thing.id}, include: [User]});\n}).then(function (thing) {\n console.log(JSON.stringify(thing));\n});\n```\n\nI get the following output:\n\n```\nohnobinki@gibby ~/public_html/turbocase1 $ ./sqltest.js\nExecuting (default): INSERT INTO `Users` (`id`,`email`,`updatedAt`,`createdAt`) VALUES (NULL,'asdf@example.org','2015-12-03 06:11:36.904 +00:00','2015-12-03 06:11:36.904 +00:00');\nExecuting (default): INSERT INTO `Users` (`id`,`email`,`createdAt`,`updatedAt`) VALUES (1,'asdf@example.org','2015-12-03 06:11:36.904 +00:00','2015-12-03 06:11:37.022 +00:00');\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n at Query.formatError (/home/ohnobinki/public_html/turbocase1/node_modules/sequelize/lib/dialects/sqlite/query.js:231:14)\n at Statement. (/home/ohnobinki/public_html/turbocase1/node_modules/sequelize/lib/dialects/sqlite/query.js:47:29)\n at Statement.replacement (/home/ohnobinki/public_html/turbocase1/node_modules/sqlite3/lib/trace.js:20:31)\n```\n\nIt seems that specifying `{include: [User]}` instructs Sequelize to create a new `User` instance matching the contents of `user`. That is not my goal. In fact, I find it hard to believe that such behaviour would ever be useful—I at least have no use for it. I want to be able to have a long-living `User` record in the database and at arbitrary times create new `Thing`s which refer to the `User`. In my shown example, I wait for the `User` to be created, but in actual code it would likely have been freshly loaded through `User.findOne()`.\n\nI have seen other questions and answers say that I have to explicitly specify the implicitly-created `UserId` column in my `Thing.create()` call. When Sequelize provides an API like `Thing.belongsTo(User)`, I *shouldn’t* have to be aware of the fact that a `Thing.UserId` field is created. So **what is the clean API-respecting way of creating a new `Thing` which refers to a particular `User` without having to guess the name of the `UserId` field?** When I load a `Thing` and specify `{include: [User]}`, I access the loaded user through the `thing.User` property. I don’t think I’m supposed to know about or try to access a `thing.UserId` field. In my `Thing.belongsTo(User)` call, I never specify `UserId`, I just treat that like an implementation detail I shouldn’t care about. How can I continue to avoid caring about that implementation detail when creating a `Thing`?\n\nThe `Thing.create()` call that works but looks wrong to me:\n\n```\nThing.create({\n name: 'A thing',\n UserId: user.id\n});\n```\n\n========================================\n\nTop Answer:\nTested on `sequelize@6.5.1 sqlite3@5.0.2` I can use `User.associations.Comments.foreignKey` as in:\n\n```\nconst Comment = sequelize.define('Comment', {\n body: { type: DataTypes.STRING },\n});\nconst User = sequelize.define('User', {\n name: { type: DataTypes.STRING },\n});\nUser.hasMany(Comment)\nComment.belongsTo(User)\nconsole.dir(User);\nawait sequelize.sync({force: true});\nconst u0 = await User.create({name: 'u0'})\nconst u1 = await User.create({name: 'u1'})\nawait Comment.create({body: 'u0c0', [User.associations.Comments.foreignKey]: u0.id});\n```\n\nThe association is also returned during creation, so you could also:\n\n```\nconst Comments = User.hasMany(Comment)\nawait Comment.create({body: 'u0c0', [Comments.foreignKey]: u0.id});\n```\n\nand on many-to-many through tables you get `foreignKey` and `otherKey` for the second foreign key.\n\n`User.associations.Comments.foreignKey` contains the `foreignKey` `UserId`.\n\nOr analogously with aliases:\n\n```\nUser.hasMany(Post, {as: 'authoredPosts', foreignKey: 'authorId'});\nPost.belongsTo(User, {as: 'author', foreignKey: 'authorId'});\n\nUser.hasMany(Post, {as: 'reviewedPosts', foreignKey: 'reviewerId'});\nPost.belongsTo(User, {as: 'reviewer', foreignKey: 'reviewerId'});\nawait sequelize.sync({force: true});\n\n// Create data.\nconst users = await User.bulkCreate([\n {name: 'user0'},\n {name: 'user1'},\n])\n\nconst posts = await Post.bulkCreate([\n {body: 'body00', authorId: users[0].id, reviewerId: users[0].id},\n {body: 'body01', [User.associations.authoredPosts.foreignKey]: users[0].id, \n [User.associations.reviewedPosts.foreignKey]: users[1].id},\n])\n```\n\nBut that syntax is so long that I'm tempted to just hardcode the keys everywhere.\n\n========================================\n\nCode:\n```text\n#!/usr/bin/env node\n'use strict';\nvar Sequelize = require('sequelize');\nvar sequelize = new Sequelize('sqlite:file.sqlite');\n\nvar User = sequelize.define('User', { email: Sequelize.STRING});\nvar Thing = sequelize.define('Thing', { name: Sequelize.STRING});\nThing.belongsTo(User);\n\nsequelize.sync({force: true}).then(function () {\n  return User.create({email: 'asdf@example.org'});\n}).then(function (user) {\n  return Thing.create({\n    name: 'A thing',\n    User: user\n  }, {\n    include: [User]\n  });\n}).then(function (thing) {\n  return Thing.findOne({where: {id: thing.id}, include: [User]});\n}).then(function (thing) {\n  console.log(JSON.stringify(thing));\n});\n```\n\n```text\nohnobinki@gibby ~/public_html/turbocase1 $ ./sqltest.js\nExecuting (default): INSERT INTO `Users` (`id`,`email`,`updatedAt`,`createdAt`) VALUES (NULL,'asdf@example.org','2015-12-03 06:11:36.904 +00:00','2015-12-03 06:11:36.904 +00:00');\nExecuting (default): INSERT INTO `Users` (`id`,`email`,`createdAt`,`updatedAt`) VALUES (1,'asdf@example.org','2015-12-03 06:11:36.904 +00:00','2015-12-03 06:11:37.022 +00:00');\nUnhandled rejection SequelizeUniqueConstraintError: Validation error\n    at Query.formatError (/home/ohnobinki/public_html/turbocase1/node_modules/sequelize/lib/dialects/sqlite/query.js:231:14)\n    at Statement.<anonymous> (/home/ohnobinki/public_html/turbocase1/node_modules/sequelize/lib/dialects/sqlite/query.js:47:29)\n    at Statement.replacement (/home/ohnobinki/public_html/turbocase1/node_modules/sqlite3/lib/trace.js:20:31)\n```\n\n```text\nThing.create({\n  name: 'A thing',\n  UserId: user.id\n});\n```\n\n```text\n{include: [User]}\n```\n\n```text\nUser\n```\n\n```text\nuser\n```\n\n```text\nUser\n```\n\n```text\nThing\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nUser.findOne()\n```\n\n```text\nUserId\n```\n\n```text\nThing.create()\n```\n\n```text\nThing.belongsTo(User)\n```\n\n```text\nThing.UserId\n```\n\n```text\nThing\n```\n\n```text\nUser\n```\n\n```text\nUserId\n```\n\n```text\nThing\n```\n\n```text\n{include: [User]}\n```\n\n```text\nthing.User\n```\n\n```text\nthing.UserId\n```\n\n```text\nThing.belongsTo(User)\n```\n\n```text\nUserId\n```\n\n```text\nThing\n```\n\n```text\nThing.create()\n```\n\n```text\nsequelize.sync({force: true})\n.then(function () {\n  return Promise.all([\n    User.create({email: 'asdf@example.org'}),\n    Thing.create({name: 'A thing'})  \n  ]);\n})\n.spread(function(user, thing) {\n  return thing.setUser(user);\n})\n.then(function(thing) {\n  console.log(JSON.stringify(thing));\n});\n```\n\n```text\n// ...\n.then(function () {\n  return models.User.create({email: 'asdf@example.org'});\n})\n.then(function(user) {\n  // Fails with SequelizeUniqueConstraintError - the User instance inherits isNewRecord from the Thing instance, but it has already been saved\n  return models.Thing.create({\n    name: 'thingthing',\n    User: user\n  }, {\n    include: [{\n      model: models.User\n    }],\n    fields: ['name'] // seems nec to specify all non-included fields because of line 277 in instance.js - another bug?\n  });\n})\n```\n\n```text\nsq.sync({ force: true })\n.then(models.User.create.bind(models.User, { email: 'asdf@example.org' }))\n.then(function(user) {\n  return sq.transaction(function(tr) {\n    return models.Thing.create({name: 'A thing'})\n    .then(function(thing) { return thing.setUser(user); });\n  });\n})\n.then(print_result.bind(null, 'Thing with User...'))\n.catch(swallow_rejected_promise.bind(null, 'main promise chain'))\n.finally(function() {\n  return sq.close();\n});\n```\n\n```text\nthing.setUser(user);\n```\n\n```text\nmodels.User.create\n```\n\n```text\nmodels.User.build\n```\n\n```text\nInstance#_setInclude\n```\n\n```text\ncreate\n```\n\n```text\nconst Comment = sequelize.define('Comment', {\n  body: { type: DataTypes.STRING },\n});\nconst User = sequelize.define('User', {\n  name: { type: DataTypes.STRING },\n});\nUser.hasMany(Comment)\nComment.belongsTo(User)\nconsole.dir(User);\nawait sequelize.sync({force: true});\nconst u0 = await User.create({name: 'u0'})\nconst u1 = await User.create({name: 'u1'})\nawait Comment.create({body: 'u0c0', [User.associations.Comments.foreignKey]: u0.id});\n```\n\n```text\nconst Comments = User.hasMany(Comment)\nawait Comment.create({body: 'u0c0', [Comments.foreignKey]: u0.id});\n```\n\n```text\nUser.hasMany(Post, {as: 'authoredPosts', foreignKey: 'authorId'});\nPost.belongsTo(User, {as: 'author', foreignKey: 'authorId'});\n\nUser.hasMany(Post, {as: 'reviewedPosts', foreignKey: 'reviewerId'});\nPost.belongsTo(User, {as: 'reviewer', foreignKey: 'reviewerId'});\nawait sequelize.sync({force: true});\n\n// Create data.\nconst users = await User.bulkCreate([\n  {name: 'user0'},\n  {name: 'user1'},\n])\n\nconst posts = await Post.bulkCreate([\n  {body: 'body00', authorId: users[0].id, reviewerId: users[0].id},\n  {body: 'body01', [User.associations.authoredPosts.foreignKey]: users[0].id, \n                   [User.associations.reviewedPosts.foreignKey]: users[1].id},\n])\n```\n\n```text\nsequelize@6.5.1 sqlite3@5.0.2\n```\n\n```text\nUser.associations.Comments.foreignKey\n```\n\n```text\nforeignKey\n```\n\n```text\notherKey\n```\n\n```text\nUser.associations.Comments.foreignKey\n```\n\n```text\nforeignKey\n```\n\n```text\nUserId\n```\n\n========================================\n\nComments:\n- But this would do an `INSERT` followed by an `UPDATE` and make it possible for the `Thing` to be created without a `User` set on it if the program terminated before `setUser()` is resolved. I think I am missing specifying `NOT NULL` in the relationship definition, but that is kind of beside the point of my question.\n- Gotcha - I've expanded my answer to include another couple of approaches that should guarantee consistency. Option 2 doesn't work but I think that's because of a bug.\n- Update: From github.com/sequelize/sequelize/issues/&hellip; it looks like Sequelize currently only supports full creates. It's not clear if these can be done without specifying the foreign key column name explicitly.\n- Option 2 is not really different from what I’m doing right now, AFAICT ;-). Looks like from the issue you reference that what I want isn’t yet supported. It looks like, with the current state of Sequelize, I will have to use option 3, transactions, to get the behavior I want. Two questions about your current option 3: 1. Could the creation of `User` be prior to the transaction (to better match the workflow I’m going for)? 2. Does the transaction actually work when you never reference `tr`? I will verify the behavior myself a minute…\n- I have edited option 3 in the above to create the user outside the transaction and pushed an updated test script to github. In my test script it isn't necessary to explicitly refer to the transaction and passing {transaction: tr} to the create and setUser call does not change the commands issued to the DB.\n- So, seems the ideal way isn’t supported by sequelize yet. The transaction option is OK and technically answers the question because I didn’t specify that the key field would be `NOT NULL` (which I haven’t tried to do yet).","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":44,"totalLines":403,"estimatedTokens":2989}}1049{"id":"stack-45902862","source":"stackoverflow","questionId":45902862,"title":"Sequelize \"unique: true\" making same unique key two times with different keyname","tags":["mysql","node.js","sequelize.js"],"text":"Title: Sequelize \"unique: true\" making same unique key two times with different keyname\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n**Test1:** Adding \"unique: true\" in email attribute.\n\n**Test2:** Adding \"unique: {args: true, msg: \"xxxxxx\"}\" in email attribute.\n\n**Using Sequelize: 4.7.5 & MySQL: 5.7.19**\n\nI'm expecting there will be one index for both the test cases.\n\nBut I'm getting **two indexes** for the Test1. Both indexes are having **same column** but **different keyname**.\n\nIs it a bug or I'm doing anything wrong?\n\n**Try the following model defs.**\n\n```\nTest1 = {\nid: {\n type: Sequelize.INTEGER.UNSIGNED,\n primaryKey: true,\n autoIncrement: true\n},\n\nemailId: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false,\n validate: {\n isEmail: {\n args: true,\n msg: 'Invalid email id.'\n }\n }\n}\n}\n\nTest2 = {\nid: {\n type: Sequelize.INTEGER.UNSIGNED,\n primaryKey: true,\n autoIncrement: true\n},\n\nemailId: {\n type: Sequelize.STRING,\n unique: {\n args: true,\n msg: 'This email id is already registered.'\n },\n allowNull: false,\n validate: {\n isEmail: {\n args: true,\n msg: 'Invalid email id.'\n }\n }\n}\n}\n```\n\n========================================\n\nCode:\n```text\nTest1 = {\nid: {\n    type: Sequelize.INTEGER.UNSIGNED,\n    primaryKey: true,\n    autoIncrement: true\n},\n\nemailId: {\n    type: Sequelize.STRING,\n    unique: true,\n    allowNull: false,\n    validate: {\n        isEmail: {\n            args: true,\n            msg: 'Invalid email id.'\n        }\n    }\n}\n}\n\n\nTest2 = {\nid: {\n    type: Sequelize.INTEGER.UNSIGNED,\n    primaryKey: true,\n    autoIncrement: true\n},\n\nemailId: {\n    type: Sequelize.STRING,\n    unique: {\n        args: true,\n        msg: 'This email id is already registered.'\n    },\n    allowNull: false,\n    validate: {\n        isEmail: {\n            args: true,\n            msg: 'Invalid email id.'\n        }\n    }\n}\n}\n```\n\n========================================\n\nComments:\n- Arrr!!!! I missed the listing in issue tracker. So I was right, its a bug.","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":117,"estimatedTokens":500}}1050{"id":"stack-47535622","source":"stackoverflow","questionId":47535622,"title":"Sequelize returning dates with wrong time","tags":["javascript","mysql","node.js","datetime","sequelize.js"],"text":"Title: Sequelize returning dates with wrong time\nTags: javascript, mysql, node.js, datetime, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nThe database and node are set as -02:00 timezone.\n\nWhen I save a register, using sequelize, it saves the register with the right date and time in its date fields. For example, if I save a register with the field moment set as '2017-01-15T23:59:59-0200' and look in the database via MySQL Workbench I will see 2017-01-16 00:00:00 in the respective column.\n\nI can even correctly find registers and filter by date and time.\n\nBut the value returned by a find operation in the field is '2017-01-16T01:59:59.000Z', meaning it was added two hours to the answer.\n\nHow could I retrive the correct date and time from MySQL using Sequelize?\n\n========================================\n\nCode:\n```text\nDate.prototype.toJSON = function(){ return this.toLocaleString(); }\n```\n\n========================================\n\nComments:\n- Oh gosh, I searched everything and never found something like this. Does this have any downside?\n- Where do you put it?","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":27,"estimatedTokens":269}}1051{"id":"stack-42946321","source":"stackoverflow","questionId":42946321,"title":"Prevent sequelize adding ending lowercase 's'","tags":["javascript","postgresql","orm","sequelize.js"],"text":"Title: Prevent sequelize adding ending lowercase 's'\nTags: javascript, postgresql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have this table defined as \n\n```\nvar T_CPCORE_INGREDIENT_UNITS = sequelize.define('T_CPCORE_INGREDIENT_UNITS'\n```\n\nAnd I have configured it with this, to freeze the table name\n\n```\nfreezeTableName: true\n```\n\nAnd I use this table as an include query in another table like this\n\n```\nrequest.models.T_CPCORE_INGREDIENTS.findById(request.params.id, {\n include: [\n {\n model: request.models.T_CPCORE_INGREDIENT_UNITS\n }\n```\n\nBut if I print the object I get returned I can see in the console that the T_CPCORE_INGREDIENT_UNITS now looks like this\n\n```\nT_CPCORE_INGREDIENT_UNITs\n```\n\nWith a lowercase 's' at the end. And this is very annoying, because sometimes in my code where I use this name have to remember to use the lowercase 's'. \nHow can I prevent this?\n\n========================================\n\nCode:\n```text\nvar T_CPCORE_INGREDIENT_UNITS = sequelize.define('T_CPCORE_INGREDIENT_UNITS'\n```\n\n```text\nfreezeTableName: true\n```\n\n```text\nrequest.models.T_CPCORE_INGREDIENTS.findById(request.params.id, {\n  include: [\n    {\n      model: request.models.T_CPCORE_INGREDIENT_UNITS\n    }\n```\n\n```text\nT_CPCORE_INGREDIENT_UNITs\n```\n\n```js\nT_CPCORE_INGREDIENTS.hasMany(T_CPCORE_INGREDIENT_UNITS, { as: 'T_CPCORE_INGREDIENT_UNITS' });\n```\n\n```js\nrequest.models.T_CPCORE_INGREDIENTS.findById(\n    request.params.id, {\n    include: [\n        {\n            model: request.models.T_CPCORE_INGREDIENT_UNITS,\n            as: 'T_CPCORE_INGREDIENT_UNITS'\n        }\n    }\n)\n```\n\n```text\nalias\n```\n\n```text\ns\n```\n\n```text\nhasMany\n```\n\n```text\nalias\n```\n\n```text\nas\n```\n\n```text\nalias\n```\n\n```text\nT_CPCORE_INGREDIENT_UNITS\n```\n\n```text\ns\n```\n\n```text\nsingular\n```\n\n```text\nplural\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":114,"estimatedTokens":451}}1052{"id":"stack-42780489","source":"stackoverflow","questionId":42780489,"title":"Sequelize: connect to database on run time based on the request","tags":["node.js","postgresql","orm","sequelize.js","sequelize-cli"],"text":"Title: Sequelize: connect to database on run time based on the request\nTags: node.js, postgresql, orm, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI am working on a node.js app where I need to connect to more than one databases. One of the database is central database which contains information common to all. And then there are country level databases where data is stored according to the countries. \n\nI am using sequelize ORM in the app.\n\nDatabase is postgresql.\n\nFramework is express.\n\nThe problem is I want to decide on runtime based on the request which database to use and models should automatically connect to the appropriate database. I have seen this question but didn't found it helpful.\n\nI have also checked in another forums but didn't find anything.\n\n========================================\n\nCode:\n```text\nimport Sequelize from 'sequelize';\n\nlet connectionsArray = [\n    'postgres://user:pass@example.com:5432/country1',\n    'postgres://user:pass@example.com:5432/country2',\n    'postgres://user:pass@example.com:5432/country3',\n];\n\nlet country1DB, country2DB, country3DB;\ncountry1DB = country2DB = country3DB = {};\ncountry1DB.Sequelize = country2DB.Sequelize = country3DB.Sequelize = Sequelize;\n\ncountry1DB.sequelize = new Sequelize(connectionsArray[0]);\ncountry2DB.sequelize = new Sequelize(connectionsArray[1]);\ncountry3DB.sequelize = new Sequelize(connectionsArray[2]);\n\n// here you need to access the models path, maybe with fs module\n// iterate over every model and import it into every country sequelize instance\n// let's assume that models' paths are in simple array\nmodels.forEach(modelFile => {\n    let model1DB = country1DB.sequelize.import(modelFile);\n    let model2DB = country2DB.sequelize.import(modelFile);\n    let model3DB = country3DB.sequelize.import(modelFile);\n\n    country1DB[model1DB.name] = model1DB;\n    country2DB[model2DB.name] = model2DB;\n    country3DB[model3DB.name] = model3DB;\n});\n\n// now every country?DB object has it's own sequelize instance and all model definitions inside\nexport {\n    country1DB,\n    country2DB,\n    country3DB\n};\n```\n\n```text\nimport { country1DB } from './databases';\n\ncountry1DB.User.findAll({...});\n```\n\n```text\nimport * as databases from './databases';\n\napp.get('/:dbIndex/users', (req, res) => {\n    databases['country' + req.params.dbIndex + 'DB'].User.find().then(user => {\n        res.json(user.toJSON());\n    });\n});\n```\n\n```text\ncountry1\n```\n\n```text\nSELECT * FROM users\n```\n\n```text\ncountry1\n```\n\n```text\nexpress\n```\n\n```text\nmiddleware\n```\n\n========================================\n\nComments:\n- The question you refer to is actually an answer to your question. Why you did not find it helpful?\n- I tried to use the same in my code but I didn't get succeeded with using models to bind to the database.\n- Thanks @piotrbienias for the response. I will try the solution in my app and will revert back with status\n- I have tried this solution. I have not used the same code. But yes your concept is right. I needed to do modifications and its running.","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":101,"estimatedTokens":762}}1053{"id":"stack-45433650","source":"stackoverflow","questionId":45433650,"title":"Sequelize: OR between parent where clause and child where clause","tags":["node.js","sequelize.js"],"text":"Title: Sequelize: OR between parent where clause and child where clause\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 2 models:\n\n```\nconst User = sequelize.define('User', {\n email: {\n type: DataTypes.STRING,\n },\n password: {\n type: DataTypes.STRING,\n },\n});\nUser.associate = (models) => {\n User.hasOne(models.Profile, {\n foreignKey: {\n name: 'user_id',\n },\n });\n};\n\nconst Profile = sequelize.define('Profile', {\n name: {\n type: DataTypes.STRING,\n },\n avatar: {\n type: DataTypes.STRING,\n },\n}, {\n tableName: 'profiles',\n freezeTableName: true,\n timestamps: false,\n});\n\nProfile.associate = (models) => {\n Profile.belongsTo(models.User, {\n foreignKey: {\n name: 'user_id',\n },\n });\n};\n```\n\nI would like to get all users where the email address OR the name matches a certain condition. Something like:\n\n```\nUser\n .all({\n where: {\n email: {\n $like: filter\n },\n },\n include: [{\n model: Profile,\n where: {\n name: {\n $like: filter\n },\n },\n }],\n })\n .then(users => res.status(200).send(users))\n .catch(error => {\n return res.sendStatus(500);\n });\n```\n\nbut it returns all users where user.email AND profile.name matches the condition. I would like to have OR between the 2 where clause.\n\nIs it possible?\n\nNote:\nI'm using Sequelize 4.0.0.\n\nUpdate:\nIn case of anybody else struggles with this, the solution is:\n\n```\nUser\n .all({\n where: {\n $or: {\n email: {\n $like: filter\n },\n '$Profile.name$': {\n $like: filter\n }\n }\n },\n include: [{\n model: Profile,\n }],\n })\n .then(users => res.status(200).send(users))\n .catch(error => {\n return res.sendStatus(500);\n });\n```\n\n========================================\n\nCode:\n```text\nconst User = sequelize.define('User', {\n    email: {\n        type: DataTypes.STRING,\n    },\n    password: {\n        type: DataTypes.STRING,\n    },\n});\nUser.associate = (models) => {\n    User.hasOne(models.Profile, {\n        foreignKey: {\n            name: 'user_id',\n        },\n    });\n};\n\nconst Profile = sequelize.define('Profile', {\n    name: {\n        type: DataTypes.STRING,\n    },\n    avatar: {\n        type: DataTypes.STRING,\n    },\n}, {\n    tableName: 'profiles',\n    freezeTableName: true,\n    timestamps: false,\n});\n\nProfile.associate = (models) => {\n    Profile.belongsTo(models.User, {\n        foreignKey: {\n            name: 'user_id',\n        },\n    });\n};\n```\n\n```text\nUser\n    .all({\n        where: {\n            email: {\n                $like: filter\n            },\n        },\n        include: [{\n            model: Profile,\n            where: {\n                name: {\n                    $like: filter\n                },\n            },\n        }],\n    })\n    .then(users => res.status(200).send(users))\n    .catch(error => {\n        return res.sendStatus(500);\n    });\n```\n\n```text\nUser\n    .all({\n        where: {\n            $or: {\n                email: {\n                    $like: filter\n                },\n                '$Profile.name$': {\n                    $like: filter\n                }\n            }\n        },\n        include: [{\n            model: Profile,\n        }],\n    })\n    .then(users => res.status(200).send(users))\n    .catch(error => {\n        return res.sendStatus(500);\n    });\n```\n\n```text\nUser\n    .all({\n        where: {\n            $or: {\n                email: {\n                    $like: filter\n                },\n                '$Profile.name$': {\n                    $like: filter\n                }\n            }\n        },\n        include: [{\n            model: Profile,\n        }],\n    })\n    .then(users => res.status(200).send(users))\n    .catch(error => {\n        return res.sendStatus(500);\n    });\n```\n\n========================================\n\nComments:\n- Thank you very much, i was looking for this, please answer your own question and mark it as solution, since this is the solution.","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":219,"estimatedTokens":945}}1054{"id":"stack-42064376","source":"stackoverflow","questionId":42064376,"title":"SequelizeDatabaseError: operator does not exist: character varying[] @> character varying","tags":["arrays","node.js","postgresql","multidimensional-array","sequelize.js"],"text":"Title: SequelizeDatabaseError: operator does not exist: character varying[] @> character varying\nTags: arrays, node.js, postgresql, multidimensional-array, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am getting the above error when i am trying to search one array value in array of arrays. My code: \n\n```\nsequelize.define('room', {\n 'id' : {'type' : DataTypes.INTEGER, 'primaryKey' : true, 'autoIncrement' : true},\n 'tutor' : {'type' : DataTypes.INTEGER, 'allowNull' : false},\n 'students' : {'type' : DataTypes.ARRAY(DataTypes.STRING), 'allowNull' : false},\n 'subject' : DataTypes.STRING,\n 'date_time' : DataTypes.DATE,\n 'status' : {'type' : DataTypes.STRING , 'defaultValue' : \"active\"},\n }\n)\n\nvar queryString = \"Select * from rooms where status = :statusVar and students @> ANY(:stuArray::character varying[]) ORDER BY CASE when :orderingVar = 'date_time DESC' then date_time end DESC, case when :orderingVar = 'date_time' THEN date_time end ASC OFFSET :offsetNumber LIMIT :limitNumber;\"\n\n return sequelize.query(queryString,{ \n replacements:{ \n statusVar: status,\n orderingVar: orderVar, \n limitNumber: itemPerPage, \n offsetNumber: ((pageNumber-1)*itemPerPage),\n tutArray: '{' + tutorUserId.toString() +'}',\n stuArray: ['{' + studName.toString() + '}']\n }, \n type: sequelize.QueryTypes.SELECT})\n```\n\nwhere studName = [Emily, John, Dexter];\n\nI want to find all records where 'students' column contains any of the student names i.e., Emily or John or Dexter\n\n========================================\n\nCode:\n```text\nsequelize.define('room', {\n    'id' : {'type' : DataTypes.INTEGER, 'primaryKey' : true, 'autoIncrement' : true},\n    'tutor' : {'type' : DataTypes.INTEGER, 'allowNull' : false},\n    'students' : {'type' : DataTypes.ARRAY(DataTypes.STRING), 'allowNull' : false},\n    'subject' : DataTypes.STRING,\n    'date_time' : DataTypes.DATE,\n    'status' : {'type' : DataTypes.STRING , 'defaultValue' : \"active\"},\n  }\n)\n\nvar queryString = \"Select * from rooms where status = :statusVar and students @> ANY(:stuArray::character varying[]) ORDER BY CASE when :orderingVar = 'date_time DESC' then date_time end DESC, case when :orderingVar = 'date_time' THEN date_time end ASC OFFSET :offsetNumber LIMIT :limitNumber;\"\n\n    return sequelize.query(queryString,{ \n                      replacements:{ \n                        statusVar: status,\n                        orderingVar: orderVar, \n                        limitNumber: itemPerPage, \n                        offsetNumber: ((pageNumber-1)*itemPerPage),\n                        tutArray: '{' + tutorUserId.toString() +'}',\n                        stuArray: ['{' + studName.toString() + '}']\n                      }, \n                        type: sequelize.QueryTypes.SELECT})\n```\n\n```text\nvar queryString = \"Select * from rooms where students && :stuArray::varchar[] and status = :statusVar ORDER BY CASE when :orderingVar = 'date_time DESC' then date_time end DESC, case when :orderingVar = 'date_time' THEN date_time end ASC OFFSET :offsetNumber LIMIT :limitNumber;\"\n```\n\n```text\nstuArray: ['{' + studName.toString() + '}']\n```\n\n```text\n['{Emily, John, Dexter}']\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":783}}1055{"id":"stack-44350238","source":"stackoverflow","questionId":44350238,"title":"In Sequelize, How do you perform a where query on an association inside of an $or statement?","tags":["associations","sequelize.js"],"text":"Title: In Sequelize, How do you perform a where query on an association inside of an $or statement?\nTags: associations, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have three models, User, Project and ProjectMember. Keeping things simple, the models have the following attributes:\n\n```\nUser\n - id\n\nProject\n - id\n - owner_id\n - is_published\n\nProjectMember\n - user_id\n - project_id\n```\n\nUsing sequelize.js, I want to find all projects where the project owner is a specific user, or where there is a project member for that project whose user is that user, or where the project is published. I imagine the raw SQL would look something like this:\n\n```\nSELECT p.*\nFROM Project p\nLEFT OUTER JOIN ProjectMember m\n ON p.id = m.project_id\nWHERE m.user_id = 2\n OR p.owner_id = 2\n OR p.is_published = true;\n```\n\nThere are plenty of examples out there on how to perform a query on an association, but I can find none on how to do so conditionally. I have been able to query just the association using this code:\n\n```\nprojModel.findAll({\n where: { },\n include: [{\n model: memberModel,\n as: 'projectMembers',\n where: { 'user_id': 2 }\n }]\n})\n```\n\nHow do I combine this where query in an $or to check the project's owner_id and is_published columns?\n\n========================================\n\nCode:\n```text\nUser\n    - id\n\nProject\n    - id\n    - owner_id\n    - is_published\n\nProjectMember\n    - user_id\n    - project_id\n```\n\n```sql\nSELECT p.*\nFROM Project p\nLEFT OUTER JOIN ProjectMember m\n    ON p.id = m.project_id\nWHERE m.user_id = 2\n    OR p.owner_id = 2\n    OR p.is_published = true;\n```\n\n```js\nprojModel.findAll({\n    where: { },\n    include: [{\n        model: memberModel,\n        as: 'projectMembers',\n        where: { 'user_id': 2 }\n    }]\n})\n```\n\n```js\nprojModel.findAll({\n    where: {\n        $or: {\n            '$projectMembers.user_id$': 2,\n            owner_id: 2,\n            is_published: true\n        }\n    },\n    include: [{\n        model: memberModel,\n        as: 'projectMembers'\n    }]\n})\n```\n\n========================================\n\nComments:\n- this gives error and i know documentation say the same thing\n- `SequelizeEagerLoadingError: Customer is associated to Deal using an alias. You've included an alias (abc), but it does not match the alias defined in your association.`\n- @MuhammadUmer It's impossible to know without more code, but it sounds like you might have defined your models incorrectly. Then again, I'm not an expert. Have you tried asking a question on SO?\n- for the record i had to find right alias using debugger... `Customer.associations....` defining with `as` had no effect... maybe if you define custom pass through table name in schema when defining association `as` tag doesn't work?","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":109,"estimatedTokens":681}}1056{"id":"stack-27028177","source":"stackoverflow","questionId":27028177,"title":"Sequelize js postgresql user defined types","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize js postgresql user defined types\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nOne of the best feature of **Postgres** (as I see it) is the user-defined data types which let me define my data model in more readable and maintainable way.\n\nDoes anyone knows/have some advice how to use it with **SequelizeJs ORM**?\n\nI can use associations, but then it will not be user-defined types and it will drag me back to old school sub-tables, which I want to avoid.\n\n========================================\n\nCode:\n```text\nsequelize.define('name', {\n  attr: 'SOME TYPE'\n});\n```\n\n```text\nCREATE TYPE\n```\n\n```text\nsequelize.query\n```\n\n========================================\n\nComments:\n- In general you get to choose ORMs *or* use of full database features.\n- @CraigRinger - generally I would agree, but in the case of Sequelize, which let you define the target db dialect, I think there is a way of defining it.","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":33,"estimatedTokens":237}}1057{"id":"stack-40913959","source":"stackoverflow","questionId":40913959,"title":"Sequelize Duplicate Key Constraint Violation","tags":["postgresql","sequelize.js"],"text":"Title: Sequelize Duplicate Key Constraint Violation\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to add a many to many relationship through an explicitly created junction table using Sequelize and Postgresql.\n\nThe tables on either side of the relationship are associated like this:\n\n```\nShop.belongsToMany(models.user, {through: 'visits' })\nUser.belongsToMany(models.shop, {through: 'visits' })\n```\n\nAnd the visits junction table primary key is defined like this:\n\n```\nid: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true // Automatically gets converted to SERIAL for postgres\n}\n```\n\nWhen I try and insert into visits I get the following error:\n\n```\nERROR: duplicate key value violates unique constraint \"visits_shopId_userId_key\"\nDETAIL: Key (\"shopId\", \"userId\")=(1, 12) already exists.\n```\n\nAfter doing a pg_dump, I have tried to remove the composite key constraint by adding constraint: false to the models, but I still get the error.\n\n(I have dropped the tables and resynced several times during the debugging process)\n\n========================================\n\nCode:\n```text\nShop.belongsToMany(models.user, {through: 'visits' })\nUser.belongsToMany(models.shop, {through: 'visits' })\n```\n\n```text\nid: {\n type: DataTypes.INTEGER,\n primaryKey: true,\n autoIncrement: true // Automatically gets converted to SERIAL for postgres\n}\n```\n\n```text\nERROR:  duplicate key value violates unique constraint \"visits_shopId_userId_key\"\nDETAIL:  Key (\"shopId\", \"userId\")=(1, 12) already exists.\n```\n\n```text\nShop.belongsToMany(models.user, {\n    through: {\n        model: 'visits',\n        unique: false\n    },\n    constraints: false\n});\n```\n\n```text\nunique: false\n```\n\n========================================\n\nComments:\n- i have this problem but i use two one to many relation to have a many to many relation , so how can i fix this issue?","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":74,"estimatedTokens":470}}1058{"id":"stack-42541077","source":"stackoverflow","questionId":42541077,"title":"How to implement 'replyingTo' and 'replies' associations on Sequelize model","tags":["javascript","sql","node.js","sequelize.js","model-associations"],"text":"Title: How to implement 'replyingTo' and 'replies' associations on Sequelize model\nTags: javascript, sql, node.js, sequelize.js, model-associations\nSource: Stack Overflow\n\nQuestion:\nI have a model in sequelize for a post. I would like that you can retrieve both the replies *to* a post, and what post the post acting as a reply to.\n\nIn theory this just needs one foreignkey, a 'replyId' field so you have the table:\n\n```\n----------------------\n|id|post |replyId|\n----------------------\n|1 |post one |null |\n|2 |replying |1 |\n|3 |replying |1 |\n----------------------\n```\n\nAnd so to get posts replying to `1`, you look for `replyId` of `1`,\n\nand to get what post `3` is replying to, you look for `id` of `1`\n\nThe sequelize relations are:\n\n```\nPost.hasMany(models.Post, { as: 'Replies' })\nPost.hasOne(models.Post, { as: 'ReplyingTo' })\n```\n\nThen when adding posts to the db:\n\n```\n//Having created `post`\npost.setReplyingTo(replyingToPost)\n//Having found `replyingToPost`\nreplyingToPost.addReplies(post)\n```\n\nBut whatever I try there is some sort of bug, like for example in the table above, where it is `null` you get id `3` and sequelize doesn't return any replies for id `2`\n\n========================================\n\nCode:\n```text\n----------------------\n|id|post     |replyId|\n----------------------\n|1 |post one |null   |\n|2 |replying |1      |\n|3 |replying |1      |\n----------------------\n```\n\n```text\nPost.hasMany(models.Post, { as: 'Replies' })\nPost.hasOne(models.Post, { as: 'ReplyingTo' })\n```\n\n```text\n//Having created `post`\npost.setReplyingTo(replyingToPost)\n//Having found `replyingToPost`\nreplyingToPost.addReplies(post)\n```\n\n```text\n1\n```\n\n```text\nreplyId\n```\n\n```text\n1\n```\n\n```text\n3\n```\n\n```text\nid\n```\n\n```text\n1\n```\n\n```text\nnull\n```\n\n```text\n3\n```\n\n```text\n2\n```\n\n```text\nPost.hasMany(models.Post, { as: 'Replies', foreignKey: 'replyId' });\n```\n\n```text\ninstanceMethods: {\n    getReplyingTo: function(){\n        return this.sequelize.models.Post.findByPrimary(this.replyId);\n    },\n    setReplyingTo: function(replyingToPost){\n        return this.update({ replyId: replyingToPost.id });\n    }\n}\n```\n\n```text\nPost.create({ post: 'post content' }).then((post) => {\n    Post.create({ post: 'reply to previous' }).then((firstReply) => {\n        firstReply.setReplyingTo(post).then((self) => {\n            // now firstReply has replyId: 1\n        });\n    });\n});\n```\n\n```sql\nUPDATE \"posts\" SET \"replyId\" = 1 WHERE \"id\" = 2;\n```\n\n```text\nfirstReply.getReplyingTo().then((replyingToPost) => {\n    // here we get the first created post\n});\n```\n\n```sql\nSELECT \"id\", \"post\", \"replyId\" FROM \"posts\" AS \"post\" WHERE \"post\".\"id\" = 1;\n```\n\n```text\nhasMany\n```\n\n```text\nhasOne\n```\n\n```text\nreplyId\n```\n\n```text\ninstanceMethods\n```\n\n```text\nreplyId\n```\n\n```text\nReplyingTo\n```\n\n```text\nPost\n```\n\n```text\nsetReplyingTo\n```\n\n========================================\n\nComments:\n- Thanks this worked perfectly! I guess its not quite in the spirit of sequelize, but i directly added a field to the model with the replyingTo username too so you wouldn't have to run getReplyingTo() each time","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":177,"estimatedTokens":772}}1059{"id":"stack-33271413","source":"stackoverflow","questionId":33271413,"title":"Sequelize OR clause with multiple models","tags":["sequelize.js"],"text":"Title: Sequelize OR clause with multiple models\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a way to write a query using SequelizeJS that contains an OR clause which references more than one model (table).\n\nI would like the sql to end up looking something like this:\n\n```\nselect *\nfrom Department\ninner join Office on Department.OfficeId = Office.Id\nwhere Office.Name like 'spokane%'\nor Department.Name like 'spokane%'\n```\n\nI've seen similar questions about filtering the joined table, with answers that look like the following.\n\n```\noptions.include = [{\n model: offices.model,\n where: {\n name: {\n $like: 'spokane%'\n }\n }\n }];\n\noptions.where = Sequelize.or(\n {\n 'name': {\n $like: 'spokane%'\n }\n });\n\ndepartments.findAndCount(options);\n```\n\nHowever this doesn't produce the correct sql.\n\nIt spits out something like this:\n\n```\nselect *\nfrom Department\ninner join Office on Department.OfficeId = Office.Id and Office.name like 'spokane%'\nwhere Department.name like 'spokane%'\n```\n\nAny help would be greatly appreciated.\n\n========================================\n\nCode:\n```text\nselect *\nfrom Department\ninner join Office on Department.OfficeId = Office.Id\nwhere Office.Name like 'spokane%'\nor Department.Name like 'spokane%'\n```\n\n```text\noptions.include = [{\n    model: offices.model,\n    where: {\n        name: {\n           $like: 'spokane%'\n        }\n    }\n  }];\n\noptions.where = Sequelize.or(\n    {\n       'name': {\n          $like: 'spokane%'\n        }\n    });\n\ndepartments.findAndCount(options);\n```\n\n```text\nselect *\nfrom Department\ninner join Office on Department.OfficeId = Office.Id and Office.name like 'spokane%'\nwhere Department.name like 'spokane%'\n```\n\n```text\noptions.where = {\n  $or: [\n    sequelize.where(sequelize.col('office.name'), { $like: 'foo'}),\n    sequelize.where(sequelize.col('department.name'), { $like: 'foo'})\n  ]\n}\n```\n\n========================================\n\nComments:\n- Thanks! I had to modify the include to make it required, but then it worked great. `{ model: offices.model, required: true }`\n- Thanks @JuanitoCROM , the `required` option helped me","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":104,"estimatedTokens":528}}1060{"id":"stack-42308315","source":"stackoverflow","questionId":42308315,"title":"How do I stop sequelize from creating an unwanted primary key when inserting data?","tags":["node.js","postgresql","sequelize.js"],"text":"Title: How do I stop sequelize from creating an unwanted primary key when inserting data?\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a sequelize model without any primary key:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const usersDoors = sequelize.define('usersDoors',\n {\n user_uid: {\n type: DataTypes.UUID,\n allowNull: false,\n },\n door_uid: {\n type: DataTypes.UUID,\n allowNull: false,\n },\n property_manager_uid: {\n type: DataTypes.UUID,\n allowNull: true,\n },\n tenant_uid: {\n type: DataTypes.UUID,\n allowNull: true,\n },\n created_at: {\n type: DataTypes.INTEGER,\n allowNull: false,\n },\n },\n {\n tableName: 'users_doors',\n indexes: [\n {\n name: 'doors_users_indexes',\n unique: true,\n fields: ['user_uid', 'door_uid', 'property_manager_uid', 'tenant_uid'],\n },\n ],\n classMethods: {\n associate: (models) => {\n usersDoors.belongsTo(models.users, { foreignKey: 'user_uid' });\n usersDoors.belongsTo(models.doors, { foreignKey: 'door_uid' });\n usersDoors.belongsTo(models.propertyManagers, { foreignKey: 'property_manager_uid' });\n usersDoors.belongsTo(models.tenants, { foreignKey: 'tenant_uid' });\n },\n },\n });\n\n return usersDoors;\n};\n```\n\nWhen I insert data (via sequelize), sequelize adds a composite primary key to the table which includes the first 2 columns (user_uid and door_uid). This is breaking my stuff and I don't want it.\n\nHow can I stop sequelize from creating an unwanted primary key when inserting data?\n\nMore details:\n\n- dialect: postgresql\n\n- sequelize (the node package) version: 3.30.2\n\n- postgresql version: psql (9.6.1, server 9.5.5)\n\n- node version (this has nothing to do with anything): 6.9.1\n\nAnd finally, here is the sequelize migration for this model:\n\n```\nconst tableName = 'users_doors';\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable(tableName, {\n user_uid: {\n type: Sequelize.UUID,\n allowNull: false,\n references: {\n model: 'users',\n key: 'uid',\n },\n },\n door_uid: {\n type: Sequelize.UUID,\n allowNull: false,\n references: {\n model: 'doors',\n key: 'uid',\n },\n },\n property_manager_uid: {\n type: Sequelize.UUID,\n allowNull: true,\n references: {\n model: 'property_managers',\n key: 'uid',\n },\n },\n tenant_uid: {\n type: Sequelize.UUID,\n allowNull: true,\n references: {\n model: 'tenants',\n key: 'uid',\n },\n },\n created_at: {\n type: Sequelize.INTEGER,\n allowNull: false,\n },\n })\n .then(() => {\n return queryInterface.addIndex('users_doors',\n ['user_uid', 'door_uid', 'property_manager_uid', 'tenant_uid'],\n {\n indexName: 'doors_users_indexes',\n indicesType: 'UNIQUE',\n });\n });\n },\n\n down: (queryInterface) => {\n return queryInterface.dropTable(tableName)\n .then(() => {\n return queryInterface.removeIndex('users_doors', ['user_uid', 'door_uid', 'property_manager_uid', 'tenant_uid']);\n });\n },\n};\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = (sequelize, DataTypes) => {\n  const usersDoors = sequelize.define('usersDoors',\n    {\n      user_uid: {\n        type: DataTypes.UUID,\n        allowNull: false,\n      },\n      door_uid: {\n        type: DataTypes.UUID,\n        allowNull: false,\n      },\n      property_manager_uid: {\n        type: DataTypes.UUID,\n        allowNull: true,\n      },\n      tenant_uid: {\n        type: DataTypes.UUID,\n        allowNull: true,\n      },\n      created_at: {\n        type: DataTypes.INTEGER,\n        allowNull: false,\n      },\n    },\n    {\n      tableName: 'users_doors',\n      indexes: [\n        {\n          name: 'doors_users_indexes',\n          unique: true,\n          fields: ['user_uid', 'door_uid', 'property_manager_uid', 'tenant_uid'],\n        },\n      ],\n      classMethods: {\n        associate: (models) => {\n          usersDoors.belongsTo(models.users, { foreignKey: 'user_uid' });\n          usersDoors.belongsTo(models.doors, { foreignKey: 'door_uid' });\n          usersDoors.belongsTo(models.propertyManagers, { foreignKey: 'property_manager_uid' });\n          usersDoors.belongsTo(models.tenants, { foreignKey: 'tenant_uid' });\n        },\n      },\n    });\n\n  return usersDoors;\n};\n```\n\n```text\nconst tableName = 'users_doors';\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.createTable(tableName, {\n      user_uid: {\n        type: Sequelize.UUID,\n        allowNull: false,\n        references: {\n          model: 'users',\n          key: 'uid',\n        },\n      },\n      door_uid: {\n        type: Sequelize.UUID,\n        allowNull: false,\n        references: {\n          model: 'doors',\n          key: 'uid',\n        },\n      },\n      property_manager_uid: {\n        type: Sequelize.UUID,\n        allowNull: true,\n        references: {\n          model: 'property_managers',\n          key: 'uid',\n        },\n      },\n      tenant_uid: {\n        type: Sequelize.UUID,\n        allowNull: true,\n        references: {\n          model: 'tenants',\n          key: 'uid',\n        },\n      },\n      created_at: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n      },\n    })\n      .then(() => {\n        return queryInterface.addIndex('users_doors',\n          ['user_uid', 'door_uid', 'property_manager_uid', 'tenant_uid'],\n          {\n            indexName: 'doors_users_indexes',\n            indicesType: 'UNIQUE',\n          });\n      });\n  },\n\n  down: (queryInterface) => {\n    return queryInterface.dropTable(tableName)\n      .then(() => {\n        return queryInterface.removeIndex('users_doors', ['user_uid', 'door_uid', 'property_manager_uid', 'tenant_uid']);\n      });\n  },\n};\n```\n\n```text\n// in sequelize model definition\nconst usersDoors = sequelize.define('usersDoors',\n{\n  id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n  },\n  user_uid: {\n      type: DataTypes.UUID,\n      allowNull: false,\n  },\n  // other fields\n\n// in the migrations file\nreturn queryInterface.createTable(tableName, {\n  id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n  },\n  user_uid: {\n      type: Sequelize.UUID,\n      allowNull: false,\n      references: {\n          model: 'users',\n          key: 'uid',\n      },\n  },\n  // other fields\n```\n\n```text\n// in users model\nusers.belongsToMany(\n    models.doors,\n    {\n        through: { model: models.usersDoors, unique: false },\n        foreignKey: 'user_uid'\n    }\n);\n\n// in doors model\ndoors.belongsToMany(\n    models.users,\n    {\n        through: { model: models.usersDoors, unique: false },\n        foreignKey: 'door_uid'\n    }\n);\n```\n\n```text\nusers\n```\n\n```text\ndoors\n```\n\n```text\nbelongsToMany\n```\n\n```text\nusers\n```\n\n```text\ndoors\n```\n\n```text\nunique index\n```\n\n```text\nuser_uid\n```\n\n```text\ndoor_uid\n```\n\n```text\nunique: false\n```\n\n```text\nthrough\n```\n\n========================================\n\nComments:\n- This kind of works as in sequelize doesn't create an additional primary key, but now it is inventing a unique constraint on those same 2 columns where as you'll notice the unique constraint I'm actually setting up is on the 4 columns...\n- I have updated the answer concerning the automatic `unique` constraint.\n- I ended up just removing the belongsToMany associations and replacing them with multiple hasMany and belongTo associations. This fixed the problem and now the only minor problem left is that sequelize is creating an `id` column as a primary key, which I've never asked for. This I can live with, however since I can simply ignore that column. Would your solution also prevent this less troublesome problem from occurring?\n- How about `usersDoors.removeAttribute('id')`? According to the documentation: \"And if your model has no primary key at all you can use Model.removeAttribute('id');\"\n- Adding `unique:false` is the solution. It works also for the case of `model.belongsTo`. I was having this issue when I used the `include` option. I hope this will help someone","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":345,"estimatedTokens":1957}}1061{"id":"stack-33970624","source":"stackoverflow","questionId":33970624,"title":"Querying multiple models with Sequelize.js ORM","tags":["node.js","sequelize.js"],"text":"Title: Querying multiple models with Sequelize.js ORM\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to select all `SPR_TYPE_UM` and `SPR_TYPE_ASSETS` for editing window, but one `SPR_TYPE_ASSETS`.\n\n```\nrouter.get('/edit/:assetId', function (req, res) {\n models.SPR_ASSET.findAll({\n include: [models.SPR_TYPE_UM, models.SPR_TYPE_ASSETS],\n // need to include all um and types here\n where: { ID_ASSET: req.params.assetId}\n }).then(function(data) {\n console.log(data);\n res.render('assets/edit', {\n title: 'Assets specification',\n data: data\n });\n });\n });\n```\n\nAssociations \n\n```\nSPR_ASSET.belongsTo(models.SPR_TYPE_UM, {foreignKey: 'ID_TYPE_UM', onUpdate: \"NO ACTION\"});\nSPR_ASSET.belongsTo(models.SPR_TYPE_ASSETS, {foreignKey: 'ID_TYPE_ASSETS', onUpdate: \"NO ACTION\"});\nSPR_TYPE_UM.hasMany(models.SPR_ASSET, {foreignKey: 'ID_TYPE_UM'});\nSPR_TYPE_ASSETS.hasMany(models.SPR_ASSET, {foreignKey: 'ID_TYPE_ASSETS'});\n```\n\nMaybe I have wrong associations, or should I do this with raw query?\nThis query give only one record from `SPR_ASSET`, `SPR_TYPE_UM` and `SPR_TYPE_ASSETS` .\n\nI need one record from `SPR_ASSET` and all records from `SPR_TYPE_UM` and `SPR_TYPE_ASSETS`.\n\n========================================\n\nCode:\n```text\nrouter.get('/edit/:assetId', function (req, res) {\n      models.SPR_ASSET.findAll({\n        include: [models.SPR_TYPE_UM, models.SPR_TYPE_ASSETS],\n        // need to include all um and types here\n        where: { ID_ASSET: req.params.assetId}\n      }).then(function(data) {\n        console.log(data);\n        res.render('assets/edit', {\n          title: 'Assets specification',\n          data: data\n        });\n      });\n    });\n```\n\n```text\nSPR_ASSET.belongsTo(models.SPR_TYPE_UM, {foreignKey: 'ID_TYPE_UM', onUpdate: \"NO ACTION\"});\nSPR_ASSET.belongsTo(models.SPR_TYPE_ASSETS, {foreignKey: 'ID_TYPE_ASSETS', onUpdate: \"NO ACTION\"});\nSPR_TYPE_UM.hasMany(models.SPR_ASSET, {foreignKey: 'ID_TYPE_UM'});\nSPR_TYPE_ASSETS.hasMany(models.SPR_ASSET, {foreignKey: 'ID_TYPE_ASSETS'});\n```\n\n```text\nSPR_TYPE_UM\n```\n\n```text\nSPR_TYPE_ASSETS\n```\n\n```text\nSPR_TYPE_ASSETS\n```\n\n```text\nSPR_ASSET\n```\n\n```text\nSPR_TYPE_UM\n```\n\n```text\nSPR_TYPE_ASSETS\n```\n\n```text\nSPR_ASSET\n```\n\n```text\nSPR_TYPE_UM\n```\n\n```text\nSPR_TYPE_ASSETS\n```\n\n```text\nrouter.get('/edit/:assetId', function (req, res) {\n    models.SPR_ASSET.findAll({\n          where: { ID_ASSET: req.params.assetId}\n        }).then(function(SPR_ASSET_DATA) {\n          models.SPR_TYPE_UM.findAll().then(function(SPR_TYPE_UM_DATA){\n              models.SPR_TYPE_ASSETS.findAll().then(function(SPR_TYPE_ASSETS_DATA){\n                  var data ={\n                      SPR_ASSET: SPR_ASSET_DATA,\n                      SPR_TYPE_UM: SPR_TYPE_UM_DATA,\n                      SPR_TYPE_ASSET: SPR_TYPE_ASSETS_DATA\n                  }\n                  console.log(data);\n                  res.render('assets/edit', {\n                  title: 'Справочник спецификаций',\n                  data: data\n                  });\n              })\n          })\n\n        });\n    });\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":123,"estimatedTokens":765}}1062{"id":"stack-69770984","source":"stackoverflow","questionId":69770984,"title":"Sequelize where query with ternary operator","tags":["javascript","node.js","express","orm","sequelize.js"],"text":"Title: Sequelize where query with ternary operator\nTags: javascript, node.js, express, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want to make a `findAll` query with *Sequelize* and I want to pass where conditions dynamically based on parameters rather than writing many `if-else` statements, is there a way to discard a condition if the passed value is null? (See the `[Op.gt]` and `[Op.lte]` below.)\n\n```\nTransaction.findAll({\n limit: limit ? limit : 20,\n where: {\n id: id,\n approved: true,\n [Op.gt]: from ? from : null,\n [Op.lte]: to ? to : null\n }\n})\n```\n\nRunning the above code gives this error:\n\ns.replace is not a function\n\n========================================\n\nCode:\n```text\nTransaction.findAll({\n    limit: limit ? limit : 20,\n    where: {\n        id: id,\n        approved: true,\n        [Op.gt]: from ? from : null,\n        [Op.lte]: to ? to : null\n    }\n})\n```\n\n```text\nfindAll\n```\n\n```text\nif-else\n```\n\n```text\n[Op.gt]\n```\n\n```text\n[Op.lte]\n```\n\n```text\nTransaction.findAll({\n    limit: limit || 20,\n    where: {\n        id: id,\n        approved: true,\n        ...(from ? { [Op.gt]: from } : {}),\n        ...(to ? { [Op.lte]: to } : {})\n    }\n})\n```\n\n========================================\n\nComments:\n- This is exactly what I needed it","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":70,"estimatedTokens":316}}1063{"id":"stack-37173678","source":"stackoverflow","questionId":37173678,"title":"Raw in attributes","tags":["sequelize.js"],"text":"Title: Raw in attributes\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\nDoes Sequelize.js support raw in attributes/columns?\n\n```\nmodels.OrgTraffic.findAll({\n\"attributes\": [\"org_name\", \"account_id\", \"account_name\", {\"raw\": \"sum(requests)\"}], ...})\n```\n\nIt seem to work for order by and group by.\n\n========================================\n\nTop Answer:\nI would advise you to use as much detailed attributes declaration as possible.\n\nYou can achieve the same effect by using :\n\n```\nmodels.OrgTraffic.findAll({\n \"attributes\": [\n \"org_name\", \n \"account_id\", \n \"account_name\", \n [ sequelize.fn(\"sum\", \"requests\"), \"mc\" ]\n ...\n ]\n})\n```\n\nNow sequelize will understand that you are calling a function and will give you back appropriate error messages if something goes wrong with that.\n\n========================================\n\nCode:\n```text\nmodels.OrgTraffic.findAll({\n\"attributes\": [\"org_name\", \"account_id\", \"account_name\", {\"raw\": \"sum(requests)\"}], ...})\n```\n\n```text\nmodels.OrgTraffic.findAll({\n\"attributes\": [\"org_name\", \"account_id\", \"account_name\", [sequelize.literal('sum(message_count)'), 'mc'], ...})\n```\n\n```text\nmodels.OrgTraffic.findAll({\n    \"attributes\": [\n        \"org_name\", \n        \"account_id\", \n        \"account_name\", \n        [ sequelize.fn(\"sum\", \"requests\"), \"mc\" ]\n        ...\n    ]\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":59,"estimatedTokens":329}}1064{"id":"stack-34540536","source":"stackoverflow","questionId":34540536,"title":"Whats the difference between instanceMethods and getterMethods in sequelizejs?","tags":["orm","sequelize.js"],"text":"Title: Whats the difference between instanceMethods and getterMethods in sequelizejs?\nTags: orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n```\nsequelize.define(\"aModel\", {\n text: DataTypes.TEXT\n}, {\n instanceMethods: {\n getme1: function() {\n return this.text.toUpperCase();\n }\n },\n getterMethods: {\n getme2: function() {\n return this.text.toUpperCase();\n }\n }\n});\n```\n\nInstanceMethods and getterMethods seem to accomplish the same thing, allowing to access virtual keys. Why would you use one over the other?\n\n========================================\n\nCode:\n```text\nsequelize.define(\"aModel\", {\n    text: DataTypes.TEXT\n}, {\n    instanceMethods: {\n        getme1: function() {\n            return this.text.toUpperCase();\n        }\n    },\n    getterMethods: {\n        getme2: function() {\n            return this.text.toUpperCase();\n        }\n    }\n});\n```\n\n```text\nvar Model = sequelize.define(\"aModel\", {\n    text: DataTypes.TEXT\n}, {\n    instanceMethods: {\n        getUpperText: function() {\n            return this.text.toUpperCase();\n        }\n    },\n    getterMethods: {\n        text: function() {\n            // use getDataValue to not enter an infinite loop\n            // http://docs.sequelizejs.com/en/latest/api/instance/#getdatavaluekey-any\n            return this.getDataValue('text').toUpperCase();\n        }\n    },\n    setterMethods: {\n        text: function(text) {\n            // use setDataValue to not enter an infinite loop\n            // http://docs.sequelizejs.com/en/latest/api/instance/#setdatavaluekey-value\n            this.setDataValue('text', text.toLowerCase());\n        }\n    }\n});\n\nModel.create({\n    text: 'foo'\n}).then(function(instance) {\n    console.log(instance.getDataValue('text')); // foo\n    console.log(instance.getUpperText()); // FOO\n    console.log(instance.text); // FOO\n\n    instance.text = 'BAR';\n\n    console.log(instance.getDataValue('text')) // bar\n    console.log(instance.text); // BAR\n});\n```\n\n```text\nModel.method()\n```\n\n```text\ntext\n```\n\n```text\ninstance.text\n```\n\n```text\ninstance.text = 'something'\n```\n\n========================================\n\nComments:\n- Please update this answer with v4 breaking changes : docs.sequelizejs.com/manual/tutorial/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":103,"estimatedTokens":555}}1065{"id":"stack-32341664","source":"stackoverflow","questionId":32341664,"title":"Install extension in PostgreSQL database via migration without superuser role?","tags":["postgresql","security","sequelize.js"],"text":"Title: Install extension in PostgreSQL database via migration without superuser role?\nTags: postgresql, security, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWe are using migrations (via Sequelize, in JavaScript) to maintain changes to our database. I have a need to add a `CREATE EXTENSION` call but since I am running as the database creator, and not superuser, I get a `permission denied to create extension`.\n\nIs there a way to modify security on a single database to allow a user to install an extension via a migration file? IOW, when I create the \"naked\" database and apply my permissions, can I set security up to allow `CREATE EXTENSION` and `DROP EXTENSION` for a specific user?\n\n========================================\n\nTop Answer:\nFor anyone still looking, here is how to create an extension via a sequelize migration. It doesn't address the secondary question of user roles however. But this works for me.\n\n```\n'use strict';\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.sequelize.query('CREATE EXTENSION extensionName;');\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.sequelize.query('DROP EXTENSION extensionName;');\n }\n};\n```\n\n========================================\n\nCode:\n```text\nCREATE EXTENSION\n```\n\n```text\npermission denied to create extension\n```\n\n```text\nCREATE EXTENSION\n```\n\n```text\nDROP EXTENSION\n```\n\n```text\n$ sequelize db:migrate --migrations-path \"migrations/postgres\" --config \"migrations/postgres\"\n$ sequelize db:migrate\n```\n\n```text\npostgres\n```\n\n```text\nCREATE/DROP EXTENSION\n```\n\n```text\npg_trgm\n```\n\n```text\n'use strict';\nmodule.exports = {\n  up: (queryInterface, Sequelize) => {\n    return queryInterface.sequelize.query('CREATE EXTENSION extensionName;');\n  },\n  down: (queryInterface, Sequelize) => {\n    return queryInterface.sequelize.query('DROP EXTENSION extensionName;');\n  }\n};\n```\n\n========================================\n\nComments:\n- Please note that if you have a `.sequelizerc` file, any config setting in there will cause a bug to surface when using the `--config` switch in the CLI. This has been reported by others in the project\n- Note that the command line two-step becomes `sequelize db:migrate --migrations-path \"migrations&#47;postgres\" --config \"migrations&#47;postgres&#47;config.json`, then `sequelize db:migrate --migrations-path \"migrations\" --config \"migrations&#47;config.json\"`. And, you must remove any `.sequelizerc` file.","metadata":{"transformedAt":"2026-08-18T18:33:34.498Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":79,"estimatedTokens":613}}1066{"id":"stack-68532884","source":"stackoverflow","questionId":68532884,"title":"Sequelize Associations: How to update parent model when creating child?","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize Associations: How to update parent model when creating child?\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIt seems i have misunderstood sequelize `.hasMany()` and `.belongsTo()` associations and how to use them in service. I have two models:\n\n```\nconst User = db.sequelize.define(\"user\", {\n uid: { /*...*/ },\n createdQuestions: {\n type: db.DataTypes.ARRAY(db.DataTypes.UUID),\n unique: true,\n allowNull: true,\n },\n});\nconst Question = db.sequelize.define(\"question\", {\n qid: { /*...*/ },\n uid: {\n type: db.DataTypes.TEXT,\n },\n});\n```\n\nGiven that one user can have many questions and each question belongs to only one user I have the following associatons:\n\n```\nUser.hasMany(Question, {\n sourceKey: \"createdQuestions\", \n foreignKey: \"uid\",\n constraints: false,\n});\nQuestion.belongsTo(User, { \n foreignKey: \"uid\", \n targetKey: \"createdQuestions\",\n constraints: false,\n});\n```\n\nWhat I want to achieve is this: After creation of a question object, the `qid` should reside in the user object under `\"createdQuestions\"` - just as the `uid` resides in the question object under `uid`. What I thought sequelize associations would do for me is to save individual calling and updating the user object. Is there a corresponding method? What I have so far is:\n\n```\nconst create_question = async (question_data) => {\n const question = { /*... question body containing uid and so forth*/ };\n\n return new Promise((resolve, rejected) => {\n Question.sync({ alter: true }).then(\n async () =>\n await db.sequelize\n .transaction(async (t) => {\n const created_question = await Question.create(question, {\n transaction: t,\n });\n })\n .then(() => resolve())\n .catch((e) => rejected(e))\n );\n });\n};\n```\n\nThis however only creates a question object but does not update the user. What am I missing here?\n\n========================================\n\nTop Answer:\nYour relation is a oneToMany relation. One User can have multiple Questions. In SQL, this kind of relation is modelled by adding an attribute to Question called userId or Uid as you did. In Sequelize, this would be achieved through a hasMany or BelongsTo like this:\n\n```\nUser.hasMany(Question)\nQuestion.belongsTo(User, {\n foreignKey: 'userId',\n constraints: false\n})\n```\n\nIn other words, I don't think you need the `CreatedQuestions` attribute under User. Only one foreign key is needed to model the oneToMany relation.\n\nNow, when creating a new question, you just need to add the userId this way\n\n```\ncreateNewQuestion = async (userId, title, body) => {\n const question = await Question.create({\n userId: userId, // or just userId\n title: title, // or just title\n body: body // or just body\n })\n return question\n}\n```\n\n**Remember, we do not store arrays in SQL**. Even if we can find a way to do it, it is not what we need. There must be always a better way.\n\n========================================\n\nCode:\n```text\nconst User = db.sequelize.define(\"user\", {\n  uid: { /*...*/  },\n  createdQuestions: {\n    type: db.DataTypes.ARRAY(db.DataTypes.UUID),\n    unique: true,\n    allowNull: true,\n  },\n});\nconst Question = db.sequelize.define(\"question\", {\n  qid: { /*...*/  },\n  uid: {\n    type: db.DataTypes.TEXT,\n  },\n});\n```\n\n```text\nUser.hasMany(Question, {\n    sourceKey: \"createdQuestions\", \n    foreignKey: \"uid\",\n    constraints: false,\n});\nQuestion.belongsTo(User, { \n    foreignKey: \"uid\", \n    targetKey: \"createdQuestions\",\n    constraints: false,\n});\n```\n\n```text\nconst create_question = async (question_data) => {\n  const question = { /*... question body containing uid and so forth*/ };\n\n  return new Promise((resolve, rejected) => {\n    Question.sync({ alter: true }).then(\n      async () =>\n        await db.sequelize\n          .transaction(async (t) => {\n            const created_question = await Question.create(question, {\n              transaction: t,\n            });\n          })\n          .then(() => resolve())\n          .catch((e) => rejected(e))\n    );\n  });\n};\n```\n\n```text\n.hasMany()\n```\n\n```text\n.belongsTo()\n```\n\n```text\nqid\n```\n\n```text\n\"createdQuestions\"\n```\n\n```text\nuid\n```\n\n```text\nuid\n```\n\n```text\nCREATE TABLE teachers (\n   name VARCHAR(32),\n   department VARCHAR(64),\n   age INTEGER\n);\n```\n\n```text\nSELECT *\nFROM classes\nWHERE teacherID = teacher_id\n```\n\n```text\nUser.hasMany(Question)\nQuestion.belongsTo(User, {\n   foreignKey: 'userId',\n   constraints: false\n})\n```\n\n```text\ncreateNewQuestion = async (userId, title, body) => {\n  const question = await Question.create({\n    userId: userId,  // or just userId\n    title: title,  // or just title\n    body: body  // or just body\n  })\n  return question\n}\n```\n\n```text\nCreatedQuestions\n```\n\n========================================\n\nComments:\n- Thanks! However, I want both models to know of each other, that is what `createdQuestions` is meant for. I - maybe naively - thought associations could achieve this. That by creation of a `Question`, this `Question` knows to which `User` it belongs to, **and** the `User` also knows which `Questions` he or her has. `Questions` beeing directly accessible from a fetched `User` without any extra calls or filtering would be very handy and my hope was, to achieve this in one go with establishing the association.\n- In that case, careful to not end up having the famous error of `cyclic dependency`. Take a look at this stackoverflow.com/questions/35116541/&hellip;\n- Yes, i know this thread and the issue, but here `constraints: false` is already set. I'm not sure, i feel like it should be fine. But if it is generally bad practice to make two models know each other, I would be thankful for a solid explanation why and count that as an answer.\n- Will provide you with that @JulianFock :)","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":214,"estimatedTokens":1423}}1067{"id":"stack-14869927","source":"stackoverflow","questionId":14869927,"title":"Sent two models to a view with Sequelize","tags":["node.js","express","sequelize.js"],"text":"Title: Sent two models to a view with Sequelize\nTags: node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI tried to send two models to a view with Sequelize but I don't know how to proceed.\n\nMy code below doesn't work.\n\n```\nPost.findAll().success( function(posts) {\n Creation.findAll().success( function(creations) {\n res.render('admin_index', {\n creations: creations,\n posts: posts\n });\n });\n});\n```\n\nAnthony\n\n========================================\n\nCode:\n```text\nPost.findAll().success( function(posts) {\n    Creation.findAll().success( function(creations) {\n        res.render('admin_index', {\n            creations: creations,\n            posts: posts\n        });\n    });\n});\n```\n\n```text\nCreation.findAll().success( function(creations) {\n    // The other stuff\n});\n```\n\n```text\nRandomQuery.findAll().success( function(creations,posts) {\n    // The other stuff\n});\n```\n\n```text\nCreation.findAll().success( function(creations) {\n    Post.findAll().success(function(posts){\n\n        res.render('admin_index', {\n            creations: creations,\n            posts: posts\n        });  \n\n    });\n});\n```\n\n========================================\n\nComments:\n- what issue do u experience?\n- Array \"posts\" isn't recognized in my view \"admin_index\"...\n- Thank's, it works! I had forgot to switch \"creations\" and \"posts\".","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":67,"estimatedTokens":333}}1068{"id":"stack-70040936","source":"stackoverflow","questionId":70040936,"title":"Sequilize - Delete ManyToMany Associations","tags":["sequelize.js","many-to-many"],"text":"Title: Sequilize - Delete ManyToMany Associations\nTags: sequelize.js, many-to-many\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequilize to program a common Student - Course relational database in NodeJS.\nThe 2 Models are associated through the automatically generated relational table `student_course`:\n\n```\nCourse.belongsToMany(Student, {\n through: \"student_course\",\n});\n\nStudent.belongsToMany(Course, {\n through: \"student_course\",\n});\n```\n\nIn order to update the courses associated to a Student I am used to delete all the entries in the association table `where: {studentId: \"id of the selected Student\"}`, and insert the new associations that the user posts.\n\nLooking at the Documentation I can see that\n\nWhen an association is defined between two models, the instances of those models gain special methods to interact with their associated counterparts source\n\nand one of these methods listed under the paragraph **\"Foo.belongsToMany(Bar, { through: Baz })\"** is the `fooInstance.removeBars()` which I thought would be the perfect choice to my needs.\n\nBut `student.removeCourses()` generates the following SQL query:\n\n```\nDELETE FROM `student_course` WHERE `studentId` = 6 AND `courseId` IN (NULL)\n```\n\nand because of `courseId IN (NULL)` condition the query is not working, i.e. nothing is deleted. It works if I specify the `courseId` like for example `student.removeCourses([1,2,3])`.\n\nBut how do I delete all the entries associated to one students? Should I query all the Courses and fill an array with their id?\nPlease let me know if I should post some example code.\n\nThank you!\n\n========================================\n\nCode:\n```text\nCourse.belongsToMany(Student, {\n  through: \"student_course\",\n});\n\nStudent.belongsToMany(Course, {\n  through: \"student_course\",\n});\n```\n\n```sql\nDELETE FROM `student_course` WHERE `studentId` = 6 AND `courseId` IN (NULL)\n```\n\n```text\nstudent_course\n```\n\n```text\nwhere: {studentId: \"id of the selected Student\"}\n```\n\n```text\nfooInstance.removeBars()\n```\n\n```text\nstudent.removeCourses()\n```\n\n```text\ncourseId IN (NULL)\n```\n\n```text\ncourseId\n```\n\n```text\nstudent.removeCourses([1,2,3])\n```\n\n========================================\n\nComments:\n- I have the same problem as you\n- Mark the answer of @DinoStray as correct, to help more people know the solution.","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":89,"estimatedTokens":576}}1069{"id":"stack-69710076","source":"stackoverflow","questionId":69710076,"title":"How to format this association fetching sequelize","tags":["javascript","node.js","sequelize.js"],"text":"Title: How to format this association fetching sequelize\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have an association many to many with two tables, products and orders. In my pivot table i save the id, quantity and price of the product. When I fetch the product i need the name of this product, but to get the name I need to get in the product table. The response of my fetching return like this\n\n```\n{\n \"id\": 111,\n \"name\": \"Matheus\",\n \"phonenumber\": \"69993750103\",\n \"reference\": null,\n \"value_subtotal\": \"10.000\",\n \"value_delivery\": \"5.000\",\n \"value_total\": \"15.000\",\n \"status\": \"pending\",\n \"products\": [\n {\n \"name\": \"Açai 350ml\",\n \"OrdersProducts\": {\n \"quantity\": 2,\n \"price\": \"0.000\"\n }\n },\n {\n \"name\": \"acai 350ml\",\n \"OrdersProducts\": {\n \"quantity\": 3,\n \"price\": \"0.000\"\n }\n }\n ]\n}\n```\n\nbut i need the json in this format\n\n```\n{\n \"id\": 111,\n \"name\": \"Matheus\",\n \"street\": \"Rua olavo bilac\",\n \"phonenumber\": \"69993750103\",\n \"number\": \"3511\",\n \"reference\": null,\n \"note\": \"Retirar o morango\",\n \"value_subtotal\": \"10.000\",\n \"value_delivery\": \"5.000\",\n \"value_total\": \"15.000\",\n \"status\": \"pending\",\n \"createdAt\": \"2021-10-20T18:26:25.000Z\",\n \"updatedAt\": \"2021-10-20T18:26:25.000Z\",\n \"products\": [\n {\n \"name\": \"Açai 350ml\",\n // here the difference, i want create a single object in the return, with all data i need of the product\n \"quantity\": 2,\n \"price\": \"0.000\"\n }\n },\n {\n \"name\": \"acai 350ml\",\n \"quantity\": 3,\n \"price\": \"0.000\"\n \n }\n ]\n}\n```\n\nMy controller\n\n```\nasync getOrder(req, res) {\n const { id } = req.params;\n\n const order = await Orders.findByPk(id, {include: [{\n association: 'products',\n attributes: ['name'],\n through: {\n attributes:['quantity', 'price'],\n \n \n },\n raw: true,\n }]})\n if (!order) return res.status(404).send({ message: 'order ${`id`}' })\n return res.json(order);\n },\n```\n\n========================================\n\nTop Answer:\nMaybe you can implement the query without the association but using model.\n\n```\nasync getOrder(req, res) {\n const { id } = req.params;\n\n const order = await Orders.findByPk(id, {include: [{\n model: Product,\n attributes: ['name'],\n include: [{\n association: \"OrdersProducts\",\n attributes:['quantity', 'price'], \n raw: true,\n }],\n }]})\n if (!order) return res.status(404).send({ message: 'order ${`id`}' })\n return res.json(order);\n},\n```\n\nYou will still get order.quantity and order.price as a name at product as properties.\n\n========================================\n\nCode:\n```text\n{\n    \"id\": 111,\n    \"name\": \"Matheus\",\n    \"phonenumber\": \"69993750103\",\n    \"reference\": null,\n    \"value_subtotal\": \"10.000\",\n    \"value_delivery\": \"5.000\",\n    \"value_total\": \"15.000\",\n    \"status\": \"pending\",\n    \"products\": [\n        {\n            \"name\": \"Açai 350ml\",\n            \"OrdersProducts\": {\n                \"quantity\": 2,\n                \"price\": \"0.000\"\n            }\n        },\n        {\n            \"name\": \"acai 350ml\",\n            \"OrdersProducts\": {\n                \"quantity\": 3,\n                \"price\": \"0.000\"\n            }\n        }\n    ]\n}\n```\n\n```text\n{\n    \"id\": 111,\n    \"name\": \"Matheus\",\n    \"street\": \"Rua olavo bilac\",\n    \"phonenumber\": \"69993750103\",\n    \"number\": \"3511\",\n    \"reference\": null,\n    \"note\": \"Retirar o morango\",\n    \"value_subtotal\": \"10.000\",\n    \"value_delivery\": \"5.000\",\n    \"value_total\": \"15.000\",\n    \"status\": \"pending\",\n    \"createdAt\": \"2021-10-20T18:26:25.000Z\",\n    \"updatedAt\": \"2021-10-20T18:26:25.000Z\",\n    \"products\": [\n        {\n            \"name\": \"Açai 350ml\",\n            // here the difference, i want create a single object in the return, with all data i need of the product\n            \"quantity\": 2,\n            \"price\": \"0.000\"\n            }\n        },\n        {\n            \"name\": \"acai 350ml\",\n            \"quantity\": 3,\n            \"price\": \"0.000\"\n            \n        }\n    ]\n}\n```\n\n```text\nasync getOrder(req, res) {\n        const { id } = req.params;\n\n        const order = await Orders.findByPk(id, {include: [{\n            association: 'products',\n            attributes: ['name'],\n            through: {\n                attributes:['quantity', 'price'],\n                \n                \n            },\n            raw: true,\n        }]})\n        if (!order) return res.status(404).send({ message: 'order ${`id`}' })\n        return res.json(order);\n    },\n```\n\n```text\nvar a = {\n  \"id\": 111,\n  \"name\": \"Matheus\",\n  \"phonenumber\": \"69993750103\",\n  \"reference\": null,\n  \"value_subtotal\": \"10.000\",\n  \"value_delivery\": \"5.000\",\n  \"value_total\": \"15.000\",\n  \"status\": \"pending\",\n  \"products\": [{\n      \"name\": \"Açai 350ml\",\n      \"OrdersProducts\": {\n        \"quantity\": 2,\n        \"price\": \"0.000\"\n      }\n    },\n    {\n      \"name\": \"acai 350ml\",\n      \"OrdersProducts\": {\n        \"quantity\": 3,\n        \"price\": \"0.000\"\n      }\n    }\n  ]\n};\n\nvar orders = [];\norders.push(a);\n\nvar updatedOrders = orders.map(function(order) {\n  order.products.forEach(function(product) {\n    product.price = product.OrdersProducts.price;\n    product.quantity = product.OrdersProducts.quantity;\n    delete product.OrdersProducts;\n  });\n  return order;\n});\nconsole.log(updatedOrders);\n```\n\n```text\nasync getOrder(req, res) {\n    const { id } = req.params;\n\n    const order = await Orders.findByPk(id, {include: [{\n        model: Product,\n        attributes: ['name'],\n        include: [{\n            association: \"OrdersProducts\",\n            attributes:['quantity', 'price'], \n            raw: true,\n        }],\n    }]})\n    if (!order) return res.status(404).send({ message: 'order ${`id`}' })\n    return res.json(order);\n},\n```\n\n```text\nconst order = {\n\"id\": 111,\n\"name\": \"Matheus\",\n\"phonenumber\": \"69993750103\",\n\"reference\": null,\n\"value_subtotal\": \"10.000\",\n\"value_delivery\": \"5.000\",\n\"value_total\": \"15.000\",\n\"status\": \"pending\",\n\"products\": [\n    {\n        \"name\": \"Açai 350ml\",\n        \"OrdersProducts\": {\n            \"quantity\": 2,\n            \"price\": \"0.000\"\n        }\n    },\n    {\n        \"name\": \"acai 350ml\",\n        \"OrdersProducts\": {\n            \"quantity\": 3,\n            \"price\": \"0.000\"\n        }\n    }\n  ]\n```\n\n```text\norder.products = order.products.map(({OrdersProducts, ...other}) => ({...other, ...OrdersProducts}));\n```\n\n========================================\n\nComments:\n- Are you okay to manipulate data within your controller ?\n- Yea, this is just a project to learn more about node js, and what is the correct way to manipulate data?\n- I suppose that you are using mongodb. You can achieve this by either adding some methods to your schema, or doing data manipulation after fetching the data. One thing more: You have `\"status\": \"pending\",` in your sample object. This means an unresolved promise(related data was not fetched yet).\n- Can you post your schemas together with sample data from the other collection(table)\n- The pending status is reference the order not the promise, i'm using mysql\n- While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":301,"estimatedTokens":1821}}1070{"id":"stack-70541443","source":"stackoverflow","questionId":70541443,"title":"sequelize not Include all children if any one matches","tags":["sequelize.js","amazon-rds"],"text":"Title: sequelize not Include all children if any one matches\nTags: sequelize.js, amazon-rds\nSource: Stack Overflow\n\nQuestion:\nI am having three association tables back to back. That means item_level_1 have many item_level_2 and item_level_2 have many item_level_3. I used a search query to find any parent or child having a name containing the search text. That means if I type `abc`, then I need to return all parent or child with full details(parents and children). But in my case, if item_level_3 has `abc` in the name, it returns the parent details, but it just only returns the specific child with `abc` from item_level_3. I need to return all children inside item_level_3 where the same parent.\n\nI am using MySQL database in AWS with node\n\nI checked https://sequelize.org/master/manual/eager-loading.html#complex-where-clauses-at-the-top-level and tried different combinations. But not help. I might miss something. But I cannot find it.\n\n```\nexports.searchItems = (body) => {\n return new Promise((resolve, reject) => {\n let searchText = body.searchText.toLowerCase();\n let limit = body.limit;\n let offset = body.offset;\n \n db.item_level_1.findAndCountAll({\n where: {\n [Sequelize.Op.or]: [\n Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_1.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.item_level_3.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n ],\n\n [Sequelize.Op.and]: [\n Sequelize.where(Sequelize.col(\"item_level_1.status\"), Sequelize.Op.eq, body.status)\n ]\n },\n offset: offset,\n limit: limit,\n distinct: true,\n subQuery: false,\n attributes: ['id', 'name'],\n include: [\n {\n model: db.item_level_2,\n as: 'item_level_2',\n where: {\n status: body.status\n },\n attributes: ['id', 'name'],\n required: true,\n include: [{\n model: db.item_level_3,\n as: 'item_level_3',\n where: {\n status: body.status\n },\n required: false,\n attributes: ['id', 'name']\n }]\n }\n ]\n }).then(result => {\n resolve({ [KEY_STATUS]: 1, [KEY_MESSAGE]: \"items listed successfully\", [KEY_DATA]: result.rows, [KEY_TOTAL_COUNT]: result.count });\n }).catch(error => {\n reject({ [KEY_STATUS]: 0, [KEY_MESSAGE]: \"items list failed\", [KEY_ERROR]: error });\n });\n })\n}\n```\n\n**Expected result**\n\n```\n{\n \"status\": 1,\n \"message\": \"Rent items listed successfully\",\n \"data\": [\n {\n \"id\": 21,\n \"name\": \"this is test parent one\",\n \"item_level_2\": [\n {\n \"id\": 39,\n \"name\": \"this is second test parent one\",\n \"item_level_3\": {\n \"id\": 9,\n \"name\": \"this is the child description with abc\"\n }\n },\n {\n \"id\": 40,\n \"name\": \"this is second test parent two\",\n \"item_level_3\": {\n \"id\": 6,\n \"name\": \"this is the child description with def\"\n }\n },\n {\n \"id\": 41,\n \"name\": \"this is second test parent three\",\n \"item_level_3\": {\n \"id\": 70,\n \"name\": \"this is the child description with ghi\"\n }\n }\n ]\n }\n ],\n \"totalCount\": 1\n}\n```\n\n**Actual result**\n\n```\n{\n \"status\": 1,\n \"message\": \"Rent items listed successfully\",\n \"data\": [\n {\n \"id\": 21,\n \"name\": \"this is test parent one\",\n \"item_level_2\": [\n {\n \"id\": 39,\n \"name\": \"this is second test parent one\",\n \"item_level_3\": {\n \"id\": 9,\n \"name\": \"this is the child description with abc\"\n }\n }\n ]\n }\n ],\n \"totalCount\": 1\n}\n```\n\n**item_level_1 model**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const item_level_1 = sequelize.define(\"item_level_1\", {\n id: { type: INTEGER, primaryKey: true, autoIncrement: true },\n name: { type: STRING },\n status: { type: BOOLEAN, defaultValue: 0 }\n }, {\n timestamps: false,\n freezeTableName: true,\n })\n item_level_1.associate = function (models) {\n item_level_1.hasMany(models.item_level_2, { as: 'item_level_2' });\n };\n return item_level_1;\n\n}\n```\n\n**item_level_2 model**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const item_level_2 = sequelize.define(\"item_level_2\", {\n id: { type: INTEGER, primaryKey: true, autoIncrement: true },\n name: { type: STRING },\n status: { type: BOOLEAN, defaultValue: 0 },\n itemLevel2Id: { type: INTEGER },\n itemLevel1Id: { type: INTEGER }\n }, {\n timestamps: false,\n freezeTableName: true,\n })\n item_level_2.associate = function (models) {\n item_level_2.belongsTo(models.item_level_3, { as: 'item_level_3', foreignKey: 'itemLevel2Id' });\n };\n return item_level_2;\n\n}\n```\n\n**item_level_2 model**\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const item_level_3 = sequelize.define(\"item_level_3\", {\n id: { type: INTEGER, primaryKey: true, autoIncrement: true },\n name: { type: STRING },\n status: { type: BOOLEAN, defaultValue: 0 }\n }, {\n timestamps: false,\n freezeTableName: true,\n })\n return item_level_3;\n\n}\n```\n\n========================================\n\nTop Answer:\nUnfortunately i think a subquery is unavoidable. You need to find lvl_2 ids first from the matching lvl_3 items.\n\n```\nconst itemsLevel2 = await db.item_level_2.findAll(\n { \n attributes: [Sequelize.col(\"item_level_2.id\"), 'id2'],\n where: \n {[Sequelize.Op.and]: [\n Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.item_level_3.name\")), Sequelize.Op.like, '%' + searchText + '%'), \n Sequelize.where(Sequelize.col(\"item_level_2.status\"), Sequelize.Op.eq, body.status)\n ]},\n include: [{\n model: db.item_level_3,\n as: 'item_level_3',\n where: {\n status: body.status\n },\n required: true,\n attributes: ['name']\n }]\n }\n)\nids = itemsLevel2.map(item => item.id);\n```\n\nAnd then use the required ids like that:\n\n```\nexports.searchItems = (body) => {\n return new Promise((resolve, reject) => {\n let searchText = body.searchText.toLowerCase();\n let limit = body.limit;\n let offset = body.offset;\n \n db.item_level_1.findAndCountAll({\n where: {\n [Sequelize.Op.or]: [\n Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_1.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n Sequelize.where(Sequelize.col(\"item_level_2.id\"), Sequelize.Op.in, ids),\n ],\n\n [Sequelize.Op.and]: [\n Sequelize.where(Sequelize.col(\"item_level_1.status\"), Sequelize.Op.eq, body.status)\n ]\n },\n offset: offset,\n limit: limit,\n distinct: true,\n subQuery: false,\n attributes: ['id', 'name'],\n include: [\n {\n model: db.item_level_2,\n as: 'item_level_2',\n where: {\n status: body.status\n },\n attributes: ['id', 'name'],\n required: true,\n include: [{\n model: db.item_level_3,\n as: 'item_level_3',\n where: {\n status: body.status\n },\n required: true,\n attributes: ['id', 'name']\n }]\n }\n ]\n }).then(result => {\n resolve({ [KEY_STATUS]: 1, [KEY_MESSAGE]: \"items listed successfully\", [KEY_DATA]: result.rows, [KEY_TOTAL_COUNT]: result.count });\n }).catch(error => {\n reject({ [KEY_STATUS]: 0, [KEY_MESSAGE]: \"items list failed\", [KEY_ERROR]: error });\n });\n })\n}\n```\n\n========================================\n\nCode:\n```js\nexports.searchItems = (body) => {\n    return new Promise((resolve, reject) => {\n        let searchText = body.searchText.toLowerCase();\n        let limit = body.limit;\n        let offset = body.offset;\n        \n        db.item_level_1.findAndCountAll({\n            where: {\n                [Sequelize.Op.or]: [\n                    Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_1.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n                    Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n                    Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.item_level_3.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n                ],\n\n                [Sequelize.Op.and]: [\n                    Sequelize.where(Sequelize.col(\"item_level_1.status\"), Sequelize.Op.eq, body.status)\n                ]\n            },\n            offset: offset,\n            limit: limit,\n            distinct: true,\n            subQuery: false,\n            attributes: ['id', 'name'],\n            include: [\n                {\n                    model: db.item_level_2,\n                    as: 'item_level_2',\n                    where: {\n                        status: body.status\n                    },\n                    attributes: ['id', 'name'],\n                    required: true,\n                    include: [{\n                        model: db.item_level_3,\n                        as: 'item_level_3',\n                        where: {\n                            status: body.status\n                        },\n                        required: false,\n                        attributes: ['id', 'name']\n                    }]\n                }\n        ]\n        }).then(result => {\n            resolve({ [KEY_STATUS]: 1, [KEY_MESSAGE]: \"items listed successfully\", [KEY_DATA]: result.rows, [KEY_TOTAL_COUNT]: result.count });\n        }).catch(error => {\n            reject({ [KEY_STATUS]: 0, [KEY_MESSAGE]: \"items list failed\", [KEY_ERROR]: error });\n        });\n    })\n}\n```\n\n```json\n{\n  \"status\": 1,\n  \"message\": \"Rent items listed successfully\",\n  \"data\": [\n    {\n      \"id\": 21,\n      \"name\": \"this is test parent one\",\n      \"item_level_2\": [\n        {\n          \"id\": 39,\n          \"name\": \"this is second test parent one\",\n          \"item_level_3\": {\n            \"id\": 9,\n            \"name\": \"this is the child description with abc\"\n          }\n        },\n        {\n          \"id\": 40,\n          \"name\": \"this is second test parent two\",\n          \"item_level_3\": {\n            \"id\": 6,\n            \"name\": \"this is the child description with def\"\n          }\n        },\n        {\n          \"id\": 41,\n          \"name\": \"this is second test parent three\",\n          \"item_level_3\": {\n            \"id\": 70,\n            \"name\": \"this is the child description with ghi\"\n          }\n        }\n      ]\n    }\n  ],\n  \"totalCount\": 1\n}\n```\n\n```json\n{\n  \"status\": 1,\n  \"message\": \"Rent items listed successfully\",\n  \"data\": [\n    {\n      \"id\": 21,\n      \"name\": \"this is test parent one\",\n      \"item_level_2\": [\n        {\n          \"id\": 39,\n          \"name\": \"this is second test parent one\",\n          \"item_level_3\": {\n            \"id\": 9,\n            \"name\": \"this is the child description with abc\"\n          }\n        }\n      ]\n    }\n  ],\n  \"totalCount\": 1\n}\n```\n\n```js\nmodule.exports = (sequelize, DataTypes) => {\n    const item_level_1 = sequelize.define(\"item_level_1\", {\n        id: { type: INTEGER, primaryKey: true, autoIncrement: true },\n        name: { type: STRING },\n        status: { type: BOOLEAN, defaultValue: 0 }\n    }, {\n        timestamps: false,\n        freezeTableName: true,\n    })\n    item_level_1.associate = function (models) {\n        item_level_1.hasMany(models.item_level_2, { as: 'item_level_2' });\n    };\n    return item_level_1;\n\n}\n```\n\n```js\nmodule.exports = (sequelize, DataTypes) => {\n    const item_level_2 = sequelize.define(\"item_level_2\", {\n        id: { type: INTEGER, primaryKey: true, autoIncrement: true },\n        name: { type: STRING },\n        status: { type: BOOLEAN, defaultValue: 0 },\n        itemLevel2Id: { type: INTEGER },\n        itemLevel1Id: { type: INTEGER }\n    }, {\n        timestamps: false,\n        freezeTableName: true,\n    })\n    item_level_2.associate = function (models) {\n        item_level_2.belongsTo(models.item_level_3, { as: 'item_level_3', foreignKey: 'itemLevel2Id' });\n    };\n    return item_level_2;\n\n}\n```\n\n```js\nmodule.exports = (sequelize, DataTypes) => {\n    const item_level_3 = sequelize.define(\"item_level_3\", {\n        id: { type: INTEGER, primaryKey: true, autoIncrement: true },\n        name: { type: STRING },\n        status: { type: BOOLEAN, defaultValue: 0 }\n    }, {\n        timestamps: false,\n        freezeTableName: true,\n    })\n    return item_level_3;\n\n}\n```\n\n```text\nabc\n```\n\n```text\nabc\n```\n\n```text\nabc\n```\n\n```text\nitem_level_2.hasMany(item_level_3, { as: 'item_level_3' });\n// This extra association will be used only for filtering.\nitem_level_2.hasMany(item_level_3, { as: 'filter' });\n```\n\n```js\ndb.item_level_1.findAndCountAll({\n    where: {\n        [Sequelize.Op.or]: [\n             Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_1.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n             Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n             // Use the filter association to filter data.\n             Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.filter.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n        ],\n        ...\n        include: [\n            {\n                model: db.item_level_2,\n                as: 'item_level_2',\n                where: {\n                    status: body.status\n                },\n                attributes: ['id', 'name'],\n                required: true,\n                include: [\n                    {\n                        model: db.item_level_3,\n                        as: 'item_level_3',\n                        where: {\n                            status: body.status\n                        },\n                        required: false,\n                        attributes: ['id', 'name']  // This should fetch all associated data. \n                    },\n                    {\n                        model: db.item_level_3,\n                        as: 'filter',\n                        where: {\n                            status: body.status\n                        },\n                        required: false,\n                        attributes: []  // Do not fetch any data from this association. This is only for filtering.\n                    }\n                ]\n            }\n        ]\n    }\n})\n```\n\n```js\nconst escapedSearchText = sequelize.escape(`%${searchText}%`);\n```\n\n```js\nconst inQueryOptions = {\n    attributes: ['itemLevel1Id'],  // This attribute name and the one in group could be different for your table.\n    include: [{\n        attributes: [],\n        model: db.item_level_3,\n        as: 'item_level_3',\n        where: {\n            name: {\n                [Sequelize.Op.like]: escapedSearchText\n            }\n        }\n    }],\n    group: 'itemLevel1Id',\n    having: Sequelize.literal('COUNT(*) > 0')\n};\n```\n\n```js\nconst Model = require(\"sequelize/lib/model\");\n// This is required when the inline query has `include` options, this 1 line make sure to serialize the query correctly.\nModel._validateIncludedElements.bind(db.item_level_2)(inQueryOptions);\n  \n// Then, pass the query options to queryGenerator.\n// slice(0, -1) is to remove the last \";\" as I will use this query inline of the main query.\nconst inQuery = db.sequelize.getQueryInterface().queryGenerator.selectQuery('item_level_2', inQueryOptions, db.item_level_2).slice(0, -1);\n```\n\n```sql\nSELECT `item_level_2`.`itemLevel1Id` \nFROM `item_level_2` AS `item_level_2` \nINNER JOIN `item_level_3` AS `item_level_3` \n    ON `item_level_2`.`itemLevel3Id` = `item_level_3`.`id` \n    AND `item_level_3`.`name` LIKE '%def%' \nGROUP BY `itemLevel1Id` \nHAVING COUNT(*) > 0\n```\n\n```js\ndb.item_level_1.findAndCountAll({\n    subQuery: false,\n    distinct: true,\n    where: {\n        [Op.or]: [\n            Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_1.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n            Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n            {\n                id: {\n                    // This is where I am inserting the inline query.\n                    [Op.in]: Sequelize.literal(`(${inQuery})`)\n                }\n            }\n        ]\n    },\n    attributes: ['id', 'name'],\n    include: [{\n        attributes: ['id', 'name'],\n        model: db.item_level_2,\n        as: 'item_level_2',\n        required: true,\n        include: [{\n            attributes: ['id', 'name'],\n            model: db.item_level_3,\n            as: 'item_level_3',\n            required: false,\n        }]\n    }]\n});\n```\n\n```text\nitem_level_2\n```\n\n```text\nitem_level_3\n```\n\n```text\nitem_level_3\n```\n\n```text\nitem_level_2\n```\n\n```text\nitem_level_2\n```\n\n```text\nitem_level_1\n```\n\n```text\nitem_level_2\n```\n\n```text\nsearchText\n```\n\n```text\nitem_level_1\n```\n\n```text\nitem_level_2\n```\n\n```text\nitem_level_3\n```\n\n```text\nbelongsTo\n```\n\n```text\nWHERE EXISTS\n```\n\n```text\nitem_level_3\n```\n\n```text\nIN\n```\n\n```text\nitem_level_3\n```\n\n```text\nSequelize.literal\n```\n\n```text\nitem_level_1\n```\n\n```text\nsearchText\n```\n\n```text\nitem_level_3\n```\n\n```text\nitem_level_2\n```\n\n```text\nitem_level_3\n```\n\n```text\nGROUP\n```\n\n```text\nHAVING\n```\n\n```text\nitem_level_1\n```\n\n```text\nHAVING\n```\n\n```text\nitem_level_1\n```\n\n```text\nitem_level_3\n```\n\n```text\nsearchText\n```\n\n```text\nitem_level_3\n```\n\n```text\ninQuery\n```\n\n```text\nconst itemsLevel2 = await db.item_level_2.findAll(\n    {           \n        attributes: [Sequelize.col(\"item_level_2.id\"), 'id2'],\n        where: \n        {[Sequelize.Op.and]: [\n            Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.item_level_3.name\")), Sequelize.Op.like, '%' + searchText + '%'), \n            Sequelize.where(Sequelize.col(\"item_level_2.status\"), Sequelize.Op.eq, body.status)\n        ]},\n        include: [{\n            model: db.item_level_3,\n            as: 'item_level_3',\n            where: {\n                status: body.status\n            },\n            required: true,\n            attributes: ['name']\n        }]\n    }\n)\nids = itemsLevel2.map(item => item.id);\n```\n\n```text\nexports.searchItems = (body) => {\n    return new Promise((resolve, reject) => {\n        let searchText = body.searchText.toLowerCase();\n        let limit = body.limit;\n        let offset = body.offset;\n        \n        db.item_level_1.findAndCountAll({\n            where: {\n                [Sequelize.Op.or]: [\n                    Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_1.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n                    Sequelize.where(Sequelize.fn('lower', Sequelize.col(\"item_level_2.name\")), Sequelize.Op.like, '%' + searchText + '%'),\n                    Sequelize.where(Sequelize.col(\"item_level_2.id\"), Sequelize.Op.in, ids),\n                ],\n\n                [Sequelize.Op.and]: [\n                    Sequelize.where(Sequelize.col(\"item_level_1.status\"), Sequelize.Op.eq, body.status)\n                ]\n            },\n            offset: offset,\n            limit: limit,\n            distinct: true,\n            subQuery: false,\n            attributes: ['id', 'name'],\n            include: [\n                {\n                    model: db.item_level_2,\n                    as: 'item_level_2',\n                    where: {\n                        status: body.status\n                    },\n                    attributes: ['id', 'name'],\n                    required: true,\n                    include: [{\n                        model: db.item_level_3,\n                        as: 'item_level_3',\n                        where: {\n                            status: body.status\n                        },\n                        required: true,\n                        attributes: ['id', 'name']\n                    }]\n                }\n        ]\n        }).then(result => {\n            resolve({ [KEY_STATUS]: 1, [KEY_MESSAGE]: \"items listed successfully\", [KEY_DATA]: result.rows, [KEY_TOTAL_COUNT]: result.count });\n        }).catch(error => {\n            reject({ [KEY_STATUS]: 0, [KEY_MESSAGE]: \"items list failed\", [KEY_ERROR]: error });\n        });\n    })\n}\n```\n\n========================================\n\nComments:\n- should not it be: item_level_2.hasMany(item_level_3, {as: 'item_level_3', foreignKey: 'itemLevel3Id'}) ? I see you include item_level_3 from item_level_2\n- @niour the above mentioned association is correct because of the relationship between the table(see the newly added last paragraph in the question). I am getting the correct results if I am not search in level 3. But I need to search in level 3 also. Did I missed anything that you are asking?\n- I still don't get it. Maybe you had to right it like: item_level_2.belongsTo(models.item_level_3, { as: 'item_level_3 }); and use an thought table. Or maybe you had to tweak a bit the models. Like using a source key at item_level_3 like: item_level_2.belongs(models.item_level_3, { as: 'item_level_3, sourceKey: itemLevel3Id}, ); At least we all agree that a subquery should be used. Emma's first approached looked really promising though. If you make any changes to the models please try using that also and tell us your feedback\n- @niour Agree. If OP can change it like 2 hasManys: `item_level_1.hasMany(item_level_2)` and `item_level_2.hasMany(item_level_3)`, first option should work and that is simpler. However, if I respect OP's original `hasMany` & `belongsTo`, this is technically `belongsToMany` association between `item_level_1` and `item_level_3` through mapping table (`item_level_2`). `belongsToMany` is useful when I don't have to search mapping table with OR options with other tables. However, since OP is searching the mapping table, subquery is unavoidable (unless I am unaware of other options).\n- Thank you very much for the answer. I have two points which hopes we don't need a sub query. First is sequelize.org/master/manual/&hellip;. The second is, in my case I have only three levels and we can assume we can use sub query. But in some other cases multiple hierarchy will be a problem. So i can see this is a common scenario. So assumed there is a built in solution. I am very new to Sequelize. So my above assumptions might be wrong or I missed some steps provided in the above link (already tried many steps). Could you please your thoughts.\n- I am extremely sorry, I missed the association details in the question. Could you please take a look at the bottom of the question?\n- I updated the entire question. Could you please take a look\n- Thank you very much for the answer.\n- I checked the above solution. Unfortunately not worked. Because, my association is opposite. I am using `item_level_2.belongsTo(item_level_3, { as: 'item_level_3', foreignKey: 'itemLevel3Id' });`. Because item_level_2 having a field itemLevel3Id where the id of level 3\n- I am extremely sorry, I missed the association details in the question. Could you please take a look at the bottom of the question?\n- @KIRANKJ I updated my answer. As I mentioned above, it won't be as your expected result unless you discard some of the `item_level_2`'s id and name.\n- Did you mean, the search is mainly happening in level 1 and level 3?\n- Not really. You can search level2 but please take a look at result JSON compare against your expected result. My result have 3 level2 objects and within each level2, there is 1 level3 object. This is because mappings within level2 table is unique, you cannot have a single id and name of level2.\n- are we missing lv2_1's othe sibling childs?. Because in my expectation, item_level_3 is an array\n- Based on `hasMany` and `belongsTo` mapping table, I assume you have each mapping per record (1: lv1-abc, 2: lv1-def, 3: lv1-hij where the left number is id of level2). But I could be wrong so could you show the model definition for all of lv1, 2, 3 tables?\n- Your response is correct. I just wrote the expected json which was different from what I am really getting. I just typed the simplified form in an editor and I wrongly wrote the array for `item_level_2`. So I updated my entire question with real data. Also I tried `Sequelize.literal(`EXISTS (SELECT 1 FROM \"item_level_3\" WHERE (lower(\"name\") LIKE '%${searchText}%'))`)`. But getting an empty result with `\"totalCount\": 0`. When I tried the same in MySQL workbench I can see there is an error related to `EXISTS`. Did I miss anything? Also, I am sorry for my wrong question\n- Cool. It could be due to DB difference. my bad, I didn't ask you which DB you are using. I was testing with Postgres. let me try on MySQL.\n- Updated for MySQL.\n- I checked it. But now I am getting all results irrespective of the search text. That means I am getting all siblings of `abc` which is our requirement works fine. But I am getting all other rows from `item_level_1`\n- I just tried `SELECT * FROM item_level_3 where EXISTS (SELECT 1 FROM item_level_3 WHERE (lower(name) LIKE '%abc%'))` this in MySql workbench and getting all rows from `item_level_3`. So Basically we will get all data\n- Ah that's right. SELECT query in `EXISTS` doesn't take care of associations so it is looking for whether the searchText exists ever in a whole level3 table. This is more complex than I thought. Adding the associations in `EXISTS` could solve it but it will add more complexity. In this case, perhaps `IN` query is easier. I couldn't avoid using subquery but at least using queryGenerator, I could write it in a single query. Please take a look again and sorry it is taking so long.\n- Thank you. I still have some doubts. In inQueryOptions, I can see `attributes: ['itemLevel1Id']`. But my model does not have such a column or relationship. Can I put just `id'?.Also, In`Model._validateIncludedElements` , from where the `Model` should import\n- `itemLevel1Id` or similar column *should* be generated by Sequelize if you don't have it defined explicitly. Try looking `SELECT * FROM item_level_2` to see what column do you have for foreignKey to item_level_1. You need to group by item_level_1's id so `id` (item_level_2's) won't be correct. Forgot to add Model's import. I added in answer.\n- you're right, I put `itemLevel1Id` there itself. Also I replaced `Model._validateIncludedElements` with `db.item_level_3._validateIncludedElements` and it seems worked. I did not import and use `Model`. After that I checked by importing the `Model` too. That time also it worked. Which above method should I ? Anyway, Great.... You saved me. That you very much\n- could you please let me know which is the correct way as described in the above comment\n- I based off from stackoverflow.com/questions/47652112/&hellip; but if other syntax works for you, I am not sure which is better, tbh.\n- I probably should also mention to make sure to escape the `searchText` which is passed to `Sequelize.literal`. The function doesn't escape, so anything within `literal` should not be dynamic or should be escaped.\n- in my case your previous version is working fine. Did I missed anything?\n- Please check the \"Important Note\" in the answer (I included in the answer). When you use `literal`, you need special care to avoid security vulnerability.\n- I am sorry for out of scope question. But could you please take a look at stackoverflow.com/questions/70668105/&hellip;\n- Try the first solution in this answer using 2 `hasMany` associations. Or `IN` query with subquery might be faster.\n- In the above example we have 3 hierarchy. But in my latest question it has only two. So I am little bit confused about the `2 hasMany solution`. Did you mean `IN query with sub query` is your final answer for this question OR `noir's` answer?. `Note: the mapping table can contain millions of data`\n- I tried escaping. But sequelize.escape not found. So I found that `var SqlString = require('sequelize&#47;lib&#47;sql-string');`, SqlString.escape(). But after including this, it is not searching for level 3 items. So I removed for now\n- At least I confirmed the `escape` function exists from v5+. If you are using Sequelize 5 or greater, you supposed to have the function available. Make sure you are calling the instance function ((db).sequelize.escape) not static function (Sequelize.escape). Also pass entire string including \"%\" to escape function and remove \"%\" from `[Op:like]`.\n- I tried db.sequelize as well as Sequelize. None have the function. So I just googled and got the sqlstring. I write like this SqlString.escape(`%${searchText}%`). No error happened. But if I put anything in the search string our search not returning level 3. I can see the back tick is not visible in the comment. Interpret as hilight.\n- you need to export the sequelize instance from mydbfile to make it work with `const db = require('mydbfile'); db.sequelize.escape`. You can console.log the escaped string and also the generated query on console to debug further. if your `searchText` is \"abc\", you should simply get \"%abc%\" from the escape function.\n- 1) Do we need it only in subquery Or do we need to add it in where conditions wherever search text appears? 2) The advantage will be anybody cannot inject SQL queries with search text?\n- 1) when you have dynamic content in `Sequelize.literal`. in your case only for item_level_3. 2) correct. All dynamic SQL has to be escaped to prevent SQL injection and Sequelize does escape for many parts but specifically Sequelize calls out `literal` is where they don't escape.\n- unfortunately db.sequelize.escape() not found. But I logged with sql string which is same as mentioned with ABC example above. But the result getting after executing the entire API is not same","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":49,"totalLines":826,"estimatedTokens":7233}}1071{"id":"stack-67643820","source":"stackoverflow","questionId":67643820,"title":"Sequelize beforeConnect hook with sequelize-typescript not running","tags":["node.js","sequelize.js","typescript1.8","sequelize-typescript"],"text":"Title: Sequelize beforeConnect hook with sequelize-typescript not running\nTags: node.js, sequelize.js, typescript1.8, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI am trying to run sequelize beforeConnect hook to be able to change credential on running sequelize instance. I am literally copy paste what is written in sequelize docs:\n\nhttps://sequelize.org/master/manual/hooks.html#connection-hooks\n\n```\nthis.sequelize = new Sequelize({ config } as SequelizeOptions);\n this.sequelize.beforeConnect((config) => {\n config.password = \"postgres\";\n })\n```\n\nI am using `\"sequelize\": \"6.5.0\"` and `\"sequelize-typescript\": \"2.1.0\"`\n\nIt is displaying this error:\n\nProperty 'beforeConnect' does not exist on type 'Sequelize'. Did you mean to access the static member 'Sequelize.beforeConnect' instead?ts(2576)\n\nAnd if I try to access it as static method it just does not run\n`Sequelize.beforeConnect(...)`\n\n*At least when I use it as a static method it compiles but says that `config.password` is a read only. Which is not because the sequalize docs shows exactly this one. Is that just bad types from `sequelize-typescript`?*\n\n========================================\n\nCode:\n```text\nthis.sequelize = new Sequelize({ config } as SequelizeOptions);\n            this.sequelize.beforeConnect((config) => {\n                config.password = \"postgres\";\n            })\n```\n\n```text\n\"sequelize\": \"6.5.0\"\n```\n\n```text\n\"sequelize-typescript\": \"2.1.0\"\n```\n\n```text\nSequelize.beforeConnect(...)\n```\n\n```text\nconfig.password\n```\n\n```text\nsequelize-typescript\n```\n\n========================================\n\nComments:\n- Did you ever find a solution to this? I'm suffering from the same problem?","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":61,"estimatedTokens":421}}1072{"id":"stack-61363658","source":"stackoverflow","questionId":61363658,"title":"Sequelize: Check if table exist and empty","tags":["mysql","node.js","database","sequelize.js"],"text":"Title: Sequelize: Check if table exist and empty\nTags: mysql, node.js, database, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI want check a table and if table is empty create a record.\n\nmy code:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const About = sequelize.define(\"About\",\n {\n id: {\n type: DataTypes.BIGINT,\n autoIncrement: true,\n allowNull: false,\n primaryKey: true,\n },\n title: DataTypes.STRING(150),\n content: DataTypes.TEXT(\"medium\"),\n },\n {\n freezeTableName: true,\n timestamps: false,\n },\n );\n\n About.findAll()\n .then(about => {\n if (about.length === 0) {\n About.create({\n title: \"About Us\",\n content: \"Lorem ipsum dolor sit amet...\",\n });\n }\n });\n\n return About;\n};\n```\n\nBut when table doesn't exist I get this error:\n\nExecuting (default): SELECT `id`, `title`, `content` FROM `About` AS `About`;\n\nUnhandled rejection SequelizeDatabaseError: Table 'mydb.about' doesn't exist\n\nhow can I handle this issue?\n\n========================================\n\nCode:\n```js\nmodule.exports = (sequelize, DataTypes) => {\n    const About = sequelize.define(\"About\",\n        {\n            id: {\n                type: DataTypes.BIGINT,\n                autoIncrement: true,\n                allowNull: false,\n                primaryKey: true,\n            },\n            title: DataTypes.STRING(150),\n            content: DataTypes.TEXT(\"medium\"),\n        },\n        {\n            freezeTableName: true,\n            timestamps: false,\n        },\n    );\n\n    About.findAll()\n    .then(about => {\n        if (about.length === 0) {\n            About.create({\n                title: \"About Us\",\n                content: \"Lorem ipsum dolor sit amet...\",\n            });\n        }\n    });\n\n    return About;\n};\n```\n\n```text\nid\n```\n\n```text\ntitle\n```\n\n```text\ncontent\n```\n\n```text\nAbout\n```\n\n```text\nAbout\n```\n\n```js\nmodule.exports = (sequelize, DataTypes) => {\n    const About = sequelize.define(\"About\",\n        {\n            title: DataTypes.STRING(150),\n            content: DataTypes.TEXT(\"medium\"),\n        },\n        {\n            freezeTableName: true,\n            timestamps: false,\n        },\n    );\n\n    About.sync();\n\n    About.findOrCreate({\n        where: {id: 1},\n        defaults: {\n            title: \"About Us\",\n            content: \"Lorem ipsum dolor sit amet...\",\n        },\n    });\n\n    return About;\n};\n```\n\n```text\n.sync()\n```\n\n```text\n.findOrCreate()\n```\n\n```text\n.findAll()\n```\n\n========================================\n\nComments:\n- Take a look at usage-of-mysqls-if-exists\n- Thanks but I want a solution with Sequelize.\n- Sorry, didn't realize that\n- you can try to call describeTable of QueryInterface (to get QI call getQueryInterface in sequelize) to get information about a table.","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":152,"estimatedTokens":676}}1073{"id":"stack-63125741","source":"stackoverflow","questionId":63125741,"title":"how to set mysql datetype length with sequelize-cli","tags":["mysql","node.js","sequelize.js","sequelize-cli"],"text":"Title: how to set mysql datetype length with sequelize-cli\nTags: mysql, node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\n*sequelize/CLI version: \"sequelize-cli\": \"^6.2.0\",\"sequelize\": \"^6.3.3\"*\n\ni'm using this to generate a mysql user table\n\n```\nnpx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string\n```\n\nexpect to generate an atrribute with length with sequelize-cli\n\n```\nfirstName:DataTypes.STRING(20) // model with length\n\nnpx sequelize-cli model:generate --name User --attributes firstName:string // how to add length with cli?\n```\n\ndidnt find anything through the documentation and the source code, is this no need? please, anyone knows what's going on here?\n\n========================================\n\nCode:\n```text\nnpx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string\n```\n\n```text\nfirstName:DataTypes.STRING(20) // model with length\n\nnpx sequelize-cli model:generate --name User --attributes firstName:string // how to add length with cli?\n```\n\n```js\nclass MyModel extends Sequelize.Model { }\nMyModel.init({\n    name: {\n        type: Sequelize.DataTypes.STRING(100),\n        allowNull: false,\n        validate: {\n            notNull: true,\n            notEmpty: true,\n            len: [2, 100]\n        }\n    },\n    description: {\n        type: Sequelize.DataTypes.STRING(5000),\n        allowNull: false,\n        validate: {\n            notNull: true,\n            notEmpty: true,\n            len: [100, 5000]\n        }\n    }\n}, { sequelize: sequelizeInstance });\n```\n\n```js\nqueryInterface.createTable(\n    'MyModel',\n    {\n        name: {\n            type: Sequelize.DataTypes.STRING(100),\n            allowNull: false,\n            validate: {\n                notNull: true,\n                notEmpty: true,\n                len: [2, 100]\n            }\n        },\n        description: {\n            type: Sequelize.DataTypes.STRING(5000),\n            allowNull: false,\n            validate: {\n                notNull: true,\n                notEmpty: true,\n                len: [100, 5000]\n            }\n        }\n    }\n);\n```\n\n```js\nqueryInterface.createTable(\n    'MyModel',\n    {\n        id: {\n            type: Sequelize.DataTypes.INTEGER,\n            primaryKey: true,\n            autoIncrement: true\n        },\n        name: {\n            type: Sequelize.DataTypes.STRING(100),\n            allowNull: false\n        },\n        description: {\n            type: Sequelize.DataTypes.STRING(5000),\n            allowNull: false\n        },\n        createdAt: {\n            type: Sequelize.DataTypes.DATE,\n            allowNull: false,\n        },\n        updatedAt: {\n            type: Sequelize.DataTypes.DATE,\n            allowNull: false,\n        },\n        MyOtherModelId: {\n            type: Sequelize.DataTypes.INTEGER,\n            allowNull: false,\n            references: {\n                model: 'MyOtherModel'\n            },\n            onUpdate: 'cascade',\n            onDelete: 'restrict'\n        }\n    }\n);\n```\n\n```text\nsequelize-cli model:generate --name MyModel\n```\n\n========================================\n\nComments:\n- Just to clarify. You create the model first, run the command and use the model code you wrote to update the migration file? I guess you don't overwrite the previous model file, you just edit that directly?\n- @Lauro235 I don't get what you mean by overwriting previous model file. Sorry it was so long ago that I don't remember exact details. I was just using the cli for boilerplate with field names only. Then I edit model file for exact needs and paste it into migration file. There was no way to make cli do that for you. After all the time I don't know if my answer is still valid or not. I no longer use sequlize. Maybe they improved/changed how the cli works.","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":133,"estimatedTokens":956}}1074{"id":"stack-59664765","source":"stackoverflow","questionId":59664765,"title":"How to generate query on join table using Sequelize?","tags":["sql","node.js","sequelize.js"],"text":"Title: How to generate query on join table using Sequelize?\nTags: sql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nLet us say there are two tables namely User and User Role.\nThe relationship between user and user role is one to many.\nSequelize model for the user is as following -\n\n```\nconst user = sequelize.define(\n 'user', {\n id: {\n type: DataTypes.BIGINT,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n field: 'id'\n },\n userName: {\n type: DataTypes.STRING(200),\n allowNull: false,\n field: 'username'\n },\n password: {\n type: DataTypes.STRING(200),\n allowNull: false,\n field: 'password'\n }\n }, {\n tableName: 'user'\n }\n);\n```\n\nSequelize model for user role is as follwing -\n\n```\nconst userRole = sequelize.define(\n 'userRole', {\n id: {\n type: DataTypes.BIGINT,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n field: 'id'\n },\n userId: {\n type: DataTypes.BIGINT,\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n field: 'user_id'\n },\n password: {\n type: DataTypes.STRING(200),\n allowNull: false,\n field: 'password'\n }\n }, {\n tableName: 'userRole'\n }\n);\n```\n\nSequelize association is defined as follows -\n\n```\nuser.hasMany(models.userRole, { foreignKey: 'user_id', as: 'roles' });\nuserRole.belongsTo(models.user, { foreignKey: 'user_id', as: 'user' });\n```\n\nI want to generate the following query using \n\n```\nSequelize -\nSELECT * \nFROM USER \n INNER JOIN (SELECT user_role.user_id, \n role \n FROM user_role \n INNER JOIN USER tu \n ON tu.id = user_role.user_id \n GROUP BY user_id \n ORDER BY role) AS roles \n ON USER.id = roles.user_id;\n```\n\nI am developing an API which will be consumed by the front end grid for showing user info. There is search functionality on role attribute of user role table. If any of role of a specific user is matched then I expect a user record with all the roles which are associated with that user.\n\n========================================\n\nTop Answer:\nYou have to use include (regarding the doc : https://sequelize.org/master/manual/models-usage.html#-code-findandcountall--code----search-for-multiple-elements-in-the-database--returns-both-data-and-total-count)\n\nExemple :\n\n```\nModels.User.findAll({\n where :{\n id: userId\n },\n group: ['roles.user_id'],\n order: [['roles.role', 'ASC']] //or DESC, as you want\n include: {\n model: Models.UserRole,\n as: 'roles',\n attributes: ['user_id', 'role'],\n required: true\n },\n })\n```\n\nHope it helps you\n\n========================================\n\nCode:\n```text\nconst user = sequelize.define(\n  'user', {\n    id: {\n      type: DataTypes.BIGINT,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true,\n      field: 'id'\n    },\n    userName: {\n      type: DataTypes.STRING(200),\n      allowNull: false,\n      field: 'username'\n    },\n    password: {\n      type: DataTypes.STRING(200),\n      allowNull: false,\n      field: 'password'\n    }\n  }, {\n    tableName: 'user'\n  }\n);\n```\n\n```text\nconst userRole = sequelize.define(\n  'userRole', {\n    id: {\n      type: DataTypes.BIGINT,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true,\n      field: 'id'\n    },\n    userId: {\n      type: DataTypes.BIGINT,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true,\n      field: 'user_id'\n    },\n    password: {\n      type: DataTypes.STRING(200),\n      allowNull: false,\n      field: 'password'\n    }\n  }, {\n    tableName: 'userRole'\n  }\n);\n```\n\n```text\nuser.hasMany(models.userRole, { foreignKey: 'user_id', as: 'roles' });\nuserRole.belongsTo(models.user, { foreignKey: 'user_id', as: 'user' });\n```\n\n```text\nSequelize -\nSELECT * \nFROM   USER \n       INNER JOIN (SELECT user_role.user_id, \n                          role \n                   FROM   user_role \n                          INNER JOIN USER tu \n                                  ON tu.id = user_role.user_id \n                   GROUP  BY user_id \n                   ORDER  BY role) AS roles \n               ON USER.id = roles.user_id;\n```\n\n```text\nUser.hasMany(models.UserRole, { foreignKey: 'user_id', as: 'roles2' });\n```\n\n```text\nconst userInfo = await User.findAndCountAll({\n  include: [\n    {\n      model: UserRole,\n      attributes: ['id', 'role'],\n      as: 'roles',\n      where: { [Op.or]: [{ role: { [Op.like]: '%MANAGER%' } },\n      required: true\n    },\n    {\n      model: UserRole,\n      attributes: ['id', 'role'],\n      as: 'roles2',\n      required: true\n    } \n  ],\n  where: whereStatement,\n});\n```\n\n```js\nModels.User.findAll({\n    where :{\n      id: userId\n    },\n    group: ['roles.user_id'],\n    order: [['roles.role', 'ASC']] //or DESC, as you want\n    include: {\n      model: Models.UserRole,\n      as: 'roles',\n      attributes: ['user_id', 'role'],\n      required: true\n    },\n  })\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":231,"estimatedTokens":1183}}1075{"id":"stack-59938831","source":"stackoverflow","questionId":59938831,"title":"How can I store just the TIME on MySQL with Sequelize","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: How can I store just the TIME on MySQL with Sequelize\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow can I store just the Time HH:MM:SS with sequelize?\nI tried it with the Time as a String and also as a Date Object, but I always get an Error.\nthis is my function:\n\n```\nconst dateCollection = await bookingTime.create({\n date: element.date,\n timeFrom: \"12:00:00\" || element.timeFrom,\n timeTo: element.timeTo\n })\n```\n\nThe \"12:00:00\" is just for Test purpose.\n\nAnd this is My Sequelize Model:\n\n```\ntimeFrom: {\n type: DataTypes.TIME,\n allowNull: false,\n },\n timeTo: {\n type: DataTypes.TIME,\n allowNull: false,\n },\n```\n\nMy Error:\n\n```\n\"original\": {\n \"code\": \"ER_TRUNCATED_WRONG_VALUE\",\n \"errno\": 1292,\n \"sqlState\": \"22007\",\n \"sqlMessage\": \"Incorrect date value: 'Invalid date' for column 'date' at row 1\",\n \"sql\": \"INSERT INTO `bookingTime` (`id`,`date`,`timeFrom`,`timeTo`) VALUES (DEFAULT,?,?,?);\",\n \"parameters\": [\n \"Invalid date\",\n \"12:00:00\",\n \"13:00:00\"\n ]\n},\n```\n\nDDL:\n\n```\nCREATE TABLE `bookingTime` (\n `id` int(13) NOT NULL AUTO_INCREMENT,\n `date` date DEFAULT NULL,\n `timeFrom` time DEFAULT NULL,\n `timeTo` time DEFAULT NULL,\n `bookingID` int(11) NOT NULL,\n `machineID` int(11) NOT NULL,\n PRIMARY KEY (`id`),\n KEY `FKmachineBT_idx` (`machineID`),\n KEY `FKbookingBT_idx` (`bookingID`),\n CONSTRAINT `FKbookingBT` FOREIGN KEY (`bookingID`) REFERENCES `booking` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,\n CONSTRAINT `FKmachineBT` FOREIGN KEY (`machineID`) REFERENCES `machine` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION\n)\n```\n\nThanks in advance for any Answers\n\n========================================\n\nCode:\n```text\nconst dateCollection = await bookingTime.create({\n            date: element.date,\n            timeFrom: \"12:00:00\" || element.timeFrom,\n            timeTo: element.timeTo\n        })\n```\n\n```text\ntimeFrom: {\n        type: DataTypes.TIME,\n        allowNull: false,\n    },\n    timeTo: {\n        type: DataTypes.TIME,\n        allowNull: false,\n    },\n```\n\n```text\n\"original\": {\n    \"code\": \"ER_TRUNCATED_WRONG_VALUE\",\n    \"errno\": 1292,\n    \"sqlState\": \"22007\",\n    \"sqlMessage\": \"Incorrect date value: 'Invalid date' for column 'date' at row 1\",\n    \"sql\": \"INSERT INTO `bookingTime` (`id`,`date`,`timeFrom`,`timeTo`) VALUES (DEFAULT,?,?,?);\",\n    \"parameters\": [\n        \"Invalid date\",\n        \"12:00:00\",\n        \"13:00:00\"\n    ]\n},\n```\n\n```text\nCREATE TABLE `bookingTime` (\n  `id` int(13) NOT NULL AUTO_INCREMENT,\n  `date` date DEFAULT NULL,\n  `timeFrom` time DEFAULT NULL,\n  `timeTo` time DEFAULT NULL,\n  `bookingID` int(11) NOT NULL,\n  `machineID` int(11) NOT NULL,\n  PRIMARY KEY (`id`),\n  KEY `FKmachineBT_idx` (`machineID`),\n  KEY `FKbookingBT_idx` (`bookingID`),\n  CONSTRAINT `FKbookingBT` FOREIGN KEY (`bookingID`) REFERENCES `booking` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,\n  CONSTRAINT `FKmachineBT` FOREIGN KEY (`machineID`) REFERENCES `machine` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION\n)\n```\n\n```text\ndate: {\n        type: DataTypes.DATEONLY(),\n        allowNull: false,\n        set (valueToBeSet) { \n            this.setDataValue('date', valueToBeSet)\n        }\n    },\n    timeFrom: {\n        type: DataTypes.TIME,\n        allowNull: false,\n        set (valueToBeSet) { \n            this.setDataValue('timeFrom', valueToBeSet)\n        }\n    },\n    timeTo: {\n        type: DataTypes.TIME,\n        allowNull: false,\n        set (valueToBeSet) { \n            this.setDataValue('timeTo', valueToBeSet)\n        }\n    },\n```\n\n========================================\n\nComments:\n- Please provide the error what you got\n- I have provided it right now thanks\n- Fine! Also your 'booking Time ' table structure will be much appreciate. Looks as you created table with date type column instead time. Look MySQL date & time types here: dev.mysql.com/doc/refman/8.0/en/date-and-time-types.html\n- Thanks I hope this will help\n- Reference here: Sequelize Setters\n- For me worked with something like this: `this.setDataValue('timeFrom', this.sequelize.fn('SEC_TO_TIME', valueToBeSet))` instead of `this.setDataValue('timeFrom', valueToBeSet)`","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":155,"estimatedTokens":1034}}1076{"id":"stack-68355980","source":"stackoverflow","questionId":68355980,"title":"sequelize - how to set validate rule for Date field","tags":["node.js","validation","sequelize.js"],"text":"Title: sequelize - how to set validate rule for Date field\nTags: node.js, validation, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a DATE field called `completedAt`, which should only accept the value on or after the current datetime.\n\nI think I have to add a validate rule on `completedAt`, but I don't know how to add the condition\n\n```\nconst Sequelize = require('sequelize');\nconst DataTypes = Sequelize.DataTypes;\n\nmodule.exports = function (app) {\n const sequelizeClient = app.get('sequelizeClient');\n const homework = sequelizeClient.define('homework', {\n ...,\n completedAt: {\n type: DataTypes.DATE,\n validate: {//What should I do here}\n },\n }, \n });\n\n homework.associate = function (models) {\n };\n\n return homework;\n};\n```\n\n========================================\n\nTop Answer:\nYou can use the dedicated **isAfter** validation provided by sequelize.\n\nisAfter: \"2011-11-05\", // only allow date strings after a specific date\n\nIn cases where you need to check if a date is after a certain date that makes a lot of sense. In cases where you want to check if a date is equal to and after a certain date then using a custom validator might be more straight up rather than using isAfter and reduce the value date. But it's still an option:\n\n```\ncompletedAt: {\n type: DataTypes.DATE,\n validate: {\n isAfter: new Date(new Date().getTime() - 1).toISOString()\n }\n},\n```\n\nThe sequelize docs has a page which includes all validations available: Validations & Constraints\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\nconst DataTypes = Sequelize.DataTypes;\n\nmodule.exports = function (app) {\n  const sequelizeClient = app.get('sequelizeClient');\n  const homework = sequelizeClient.define('homework', {\n    ...,\n    completedAt: {\n      type: DataTypes.DATE,\n      validate: {//What should I do here}\n    },\n  }, \n  });\n\n  homework.associate = function (models) {\n  };\n\n  return homework;\n};\n```\n\n```text\ncompletedAt\n```\n\n```text\ncompletedAt\n```\n\n```text\ncompletedAt: {\n    type: DataTypes.DATE,\n    validate: {\n      customValidator(value) {\n        if (new Date(value) < new Date()) {\n          throw new Error(\"invalid date\");\n        }\n      },\n    },\n  },\n```\n\n```text\ncompletedAt: {\n  type: DataTypes.DATE,\n  validate: {\n    isAfter: new Date(new Date().getTime() - 1).toISOString()\n  }\n},\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.499Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":105,"estimatedTokens":588}}1077{"id":"stack-59979766","source":"stackoverflow","questionId":59979766,"title":"Find Count From Other Table in Sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: Find Count From Other Table in Sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have a problem in sequelize with node js. I want product count according to category.\n\nMy category model is define as:\n\n```\nconst Sequelize = require('sequelize');\nconst sequelize = require('../configs/db-connection.config');\nconst Product = require('../models/product.model');\nconst Category = sequelize.define(\n 'category',\n {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false\n },\n },\n { timestamps: true }\n);\nCategory.hasMany(Product);\nProduct.belongsTo(Category);\nmodule.exports = Category;\n```\n\nMy product model is define as:\n\n```\nconst Sequelize = require('sequelize');\nconst sequelize = require('../configs/db-connection.config');\nconst Product = sequelize.define(\n 'product',\n {\n id: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n allowNull: false,\n autoIncrement: true\n },\n name: {\n type: Sequelize.STRING,\n allowNull: false\n },\n categoryRef: {\n type: Sequelize.INTEGER,\n allowNull: false,\n foreignKey: true,\n references: {\n model: CATEGORY.TABLE_NAME,\n key: 'id'\n }\n } \n },\n { timestamps: true }\n);\n\nmodule.exports = Product;\n```\n\nHere each category is connected to product as a foreignKey in product model like categoryRef.\nLet me give you an example one category is Devices and its product will be Laptop, Monitor, CPU etc. If devices have 3 products then it will return 3 as a count in category.\nHere each object in array represents to category obj and I want to add an extra field i.e. count in category obj and it will give me the count of products which is stored as a foreignKey in product table. \n\nMy expected result is:\n\n```\n[\n {\n id: 1,\n name: 'Devices',\n createdAt: '2020-01-17T12:08:10.000Z',\n updatedAt: '2020-01-17T12:11:22.000Z',\n count:3\n },\n {\n id: 2,\n name: 'appliances',\n createdAt: '2020-01-23T07:59:27.000Z',\n updatedAt: '2020-01-23T08:12:54.000Z',\n count:0\n },\n {\n id: 3,\n name: 'furniture',\n createdAt: '2020-01-23T08:51:35.000Z',\n updatedAt: '2020-01-23T08:51:35.000Z',\n count:0\n },\n];\n```\n\nI already applied following sql query on database which gives perfect result:\n\n```\nSELECT inventory.categories.*, count(products.categoryRef) as count\nfrom inventory.categories\nleft join inventory.products\non (inventory.categories.id = inventory.products.categoryRef)\ngroup by\ninventory.categories.id\n```\n\nBut I don't know how to convert it into sequelize methods.\nPlease help me to find out the solution which methods I need to use to get the desired output.\nThanks in Advance.\n\n========================================\n\nCode:\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = require('../configs/db-connection.config');\nconst Product = require('../models/product.model');\nconst Category = sequelize.define(\n  'category',\n  {\n    id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      allowNull: false,\n      autoIncrement: true\n    },\n    name: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n  },\n  { timestamps: true }\n);\nCategory.hasMany(Product);\nProduct.belongsTo(Category);\nmodule.exports = Category;\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = require('../configs/db-connection.config');\nconst Product = sequelize.define(\n  'product',\n  {\n    id: {\n      type: Sequelize.INTEGER,\n      primaryKey: true,\n      allowNull: false,\n      autoIncrement: true\n    },\n    name: {\n      type: Sequelize.STRING,\n      allowNull: false\n    },\n    categoryRef: {\n      type: Sequelize.INTEGER,\n      allowNull: false,\n      foreignKey: true,\n      references: {\n        model: CATEGORY.TABLE_NAME,\n        key: 'id'\n      }\n    }   \n  },\n  { timestamps: true }\n);\n\nmodule.exports = Product;\n```\n\n```text\n[\n  {\n    id: 1,\n    name: 'Devices',\n    createdAt: '2020-01-17T12:08:10.000Z',\n    updatedAt: '2020-01-17T12:11:22.000Z',\n    count:3\n  },\n  {\n    id: 2,\n    name: 'appliances',\n    createdAt: '2020-01-23T07:59:27.000Z',\n    updatedAt: '2020-01-23T08:12:54.000Z',\n    count:0\n  },\n  {\n    id: 3,\n    name: 'furniture',\n    createdAt: '2020-01-23T08:51:35.000Z',\n    updatedAt: '2020-01-23T08:51:35.000Z',\n    count:0\n  },\n];\n```\n\n```text\nSELECT inventory.categories.*, count(products.categoryRef) as count\nfrom inventory.categories\nleft join inventory.products\non (inventory.categories.id = inventory.products.categoryRef)\ngroup by\ninventory.categories.id\n```\n\n```text\nCategory.findAll({\n        attributes: {\n          include: [\n            [\n              Sequelize.fn('COUNT', Sequelize.col('products.categoryRef')),\n              'productsCount'\n            ]\n          ]\n        },\n        include: [\n          {\n            model: Product,\n            attributes: []\n          }\n        ],\n        group: ['id']\n      });\n```\n\n```text\nattributes\n```\n\n```text\ninclude\n```\n\n========================================\n\nComments:\n- let me know if you have any query\n- It gives me this error: In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'inventory.category.id'; this is incompatible with sql_mode=only_full_group_by\n- Thanks bro now it's working. Can you please tell me about the resource where I can learn sequelize?\n- let me know if you have any query\n- Hi sorry to say but the problem is not resolved yet, it gives me the error of Unknown column 'categoryId' in 'field list' How to specify that we have key name of categoryRef in model not categoryId?\n- i think you have to use categories.id instead of categorie.id in query\n- See this is the error: Unknown column 'products.categoryId' in 'on clause'\n- Error: Unknown column 'product.id' in 'field list'\n- I got the solution actually, I forgot to add foreignKey associations in models. Can you explain what is the use of constraints in models either it is true or false?\n- great keep it up\n- Can you tell me the usage of constraints field in models?\n- we are here using categoryRef in our product model to reference category model like foreign key in sql table\n- main uses of constraints field is depending on which constraints field we are making here we are using foreign key, for define primary key field we need to use pk constraints and so on","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":254,"estimatedTokens":1568}}1078{"id":"stack-55557934","source":"stackoverflow","questionId":55557934,"title":"Getting Error When I Start multiple select query inside loop TimeoutError: ResourceRequest timed out","tags":["mysql","node.js","localhost","sequelize.js"],"text":"Title: Getting Error When I Start multiple select query inside loop TimeoutError: ResourceRequest timed out\nTags: mysql, node.js, localhost, sequelize.js\nSource: Stack Overflow\n\nQuestion:\n- I'm using nodeJs Express Framework.\n\n- I'm using mysql database with sequelizejs library and using querying for retrieve data.\n\nI am getting timeout error when I fired select query for almost 50,00,000 records.\n\nI have done the server timeout but not worked.\nI have done the pooling method in sequlizeJs But not worked.\n\n```\nfunction fetchNamesData(req, name) {\n return new Promise((resolve, reject) => {\n const names = req.app.locals.models.names_data;\n names.findAll({\n where: {\n name: name\n },\n order: [['date', 'DESC']],\n limit: 50\n })\n .then(function (dbRes) {\n console.log(dbRes.length);\n resolve(dbRes);\n })\n .catch(function (dbErr) {\n console.log(dbErr);\n return reject(dbErr);\n });\n });\n}\n\nallNames.forEach(element => {\n//console.log(element.dataValues.name);\nfetchNamesData(req, element.dataValues.name).then((dbRes) => {\n//here I will have all the records\n}).catch((dbErr) => { console.log(dbErr) });\n```\n\nvar allNames = {having almost 7000 names}\nnow I iterate this obj and each names having 50 record in database\nI want to get that all record like 50*7000 = 3,50,000.\n\n========================================\n\nTop Answer:\n**What happens in your case is :**\n\nLooping through 7000 names and at same time hitting 7000 queries in mySql , and mysql will create queue for executing 7000 queries at same time cause load on machine. Either you can update your configuration to handle such load OR\n\n**Solution to this :** Try to put some timeout b/w each queries , this way you will be able to fetch more records , \n\n```\nallNames.forEach(element => {\n setTimeout(() => { // {\n //here I will have all the records\n }).catch((dbErr) => {\n console.log(dbErr)\n });\n },500); // <----------- HERE -------------\n});\n```\n\n========================================\n\nCode:\n```text\nfunction fetchNamesData(req, name) {\n    return new Promise((resolve, reject) => {\n        const names = req.app.locals.models.names_data;\n        names.findAll({\n            where: {\n                name: name\n            },\n            order: [['date', 'DESC']],\n            limit: 50\n        })\n            .then(function (dbRes) {\n                console.log(dbRes.length);\n                resolve(dbRes);\n            })\n            .catch(function (dbErr) {\n                console.log(dbErr);\n                return reject(dbErr);\n            });\n    });\n}\n\nallNames.forEach(element => {\n//console.log(element.dataValues.name);\nfetchNamesData(req, element.dataValues.name).then((dbRes) => {\n//here I will have all the records\n}).catch((dbErr) => { console.log(dbErr) });\n```\n\n```text\nallNames.forEach(element => {\n    setTimeout(() => { // <----------- HERE -------------\n        fetchNamesData(req, element.dataValues.name).then((dbRes) => {\n            //here I will have all the records\n        }).catch((dbErr) => {\n            console.log(dbErr)\n        });\n    },500); // <----------- HERE -------------\n});\n```\n\n========================================\n\nComments:\n- thank you for answering Vivek but I don't want to loose any single sec while retrieving data. and your suggestion will cost me like 16 days If I'm not wrong about calculation...\n- but I've tried it but no luck..still I'm getting this error","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":116,"estimatedTokens":846}}1079{"id":"stack-43382636","source":"stackoverflow","questionId":43382636,"title":"Unit testing and mocking mySQL database in Node.js","tags":["mysql","node.js","unit-testing","sqlite","sequelize.js"],"text":"Title: Unit testing and mocking mySQL database in Node.js\nTags: mysql, node.js, unit-testing, sqlite, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn my Node.js API I'm connecting to a mySQL database using promise-mysql. I'm using Sequelize as ORM. I want to unit test each micro service interacting with the database.\n\nObviously during the tests, I don't want to create a real database connection since unit tests should not rely on dependencies like database connections. Rather I want to mock it, using either an in-memory or on-disc database like sqlite3.\n\nI've tried migrating the SQL dump to sqlite3 but I get errors since the dump is not compatible with sqlite3. The data set is modest in size.\n\nCan you recommend an approach?\n\n========================================\n\nCode:\n```text\nmysql in memory table\n```\n\n```text\nsqlite3\n```\n\n========================================\n\nComments:\n- What Node.js module would you use for mysql in-memory tabled? Doesn't look like promise-mysql supports this.\n- check dev.mysql.com/doc/refman/5.7/en/memory-storage-engine.html\n- I ended up dumping my SQL database into CSV files and then loading the CSV files into sqlite3 using an on-disc database. It works well with smaller data sets. Here the gist: gist.github.com/ChristianRich/a7e086c76ecd0db1c78ae5e15b1160&zwnj;&#8203;6d","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":30,"estimatedTokens":331}}1080{"id":"stack-56725239","source":"stackoverflow","questionId":56725239,"title":"Associate in Sequelize not working as intended","tags":["javascript","node.js","postgresql","express","sequelize.js"],"text":"Title: Associate in Sequelize not working as intended\nTags: javascript, node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to associate two tables in Sequelize but I am getting the SequelizeEagerLoadingError that one table is not associated to another despite trying all the available fixes on this platform.\n\nI have two tables, User and Item.\n\nUser (user.js)\n\n```\nconst User = dbconnection.sequelize.define('users', {\n id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},\n name: {\n type: Sequelize.STRING(80),\n allowNull: false\n },\n email: {\n type: Sequelize.STRING(120),\n allowNull: false,\n unique: true\n },\n dob: {\n type: Sequelize.DATEONLY,\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(256),\n allowNull: false\n }\n\n});\n\nUser.associate = models => {\n User.hasMany(models.Item, { as: 'items',foreignKey: 'user_id' })\n}\n\ndbconnection.sequelize.sync({ force: false })\n .then(() => {\n //console.log('Table created!')\n });\n\nmodule.exports = {\n User\n};\n```\n\nItem (item.js)\n\n```\nconst Item = dbconnection.sequelize.define('items', {\n id: { type: Sequelize.INTEGER, unique: true, autoIncrement: true, primaryKey: true},\n item: {\n type: Sequelize.STRING(80),\n allowNull: true\n },\n item_type: {\n type: Sequelize.STRING(10),\n allowNull: false\n },\n comment: {\n type: Sequelize.STRING(1000),\n allowNull: true\n },\n user_id: {\n type: Sequelize.INTEGER,\n allowNull: false,\n references: { model: 'users', key: 'id' }\n },\n});\n\nItem.associate = models => {\n Item.belongsTo(models.User, { as: 'users',foreignKey: 'user_id' })\n}\n\ndbconnection.sequelize.sync({ force: false })\n .then(() => {\n // console.log('Table created!')\n })\n});\n\nmodule.exports = {\n Item\n};\n```\n\nUser hasMany(Item) while Item belongsTo(User) as shown above.\n\nHowever, when I make a query to the Item table (as below),\n\n```\nconst usersdb = require('./userdb')\nconst itemsdb = require('./itemdb')\n\nclass ItemsController {\n static async getAllItems(req, res, next) {\n try{\n let allitems = await itemsdb.Item.findAll({\n include: [{\n model: usersdb.User\n }]\n })\n return {items: allitems, status: true}\n }\n catch (e) {\n return {items: e, status: false}\n }\n }\n}\n\nmodule.exports = ItemsController;\n```\n\nI get the SequelizeEagerLoadingError that \"users is not associated to items!\"\n\nI have tried all the available fixes including this and this among others but to no success.\n\n========================================\n\nCode:\n```text\nconst User = dbconnection.sequelize.define('users', {\n    id:  { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},\n    name: {\n        type:  Sequelize.STRING(80),\n        allowNull: false\n    },\n    email: {\n        type:  Sequelize.STRING(120),\n        allowNull: false,\n        unique: true\n    },\n    dob: {\n        type: Sequelize.DATEONLY,\n        allowNull: false\n    },\n    password: {\n        type:  Sequelize.STRING(256),\n        allowNull: false\n    }\n\n});\n\nUser.associate = models => {\n    User.hasMany(models.Item, { as: 'items',foreignKey: 'user_id' })\n}\n\ndbconnection.sequelize.sync({ force: false })\n    .then(() => {\n        //console.log('Table created!')\n    });\n\nmodule.exports = {\n    User\n};\n```\n\n```text\nconst Item = dbconnection.sequelize.define('items', {\n    id:  { type: Sequelize.INTEGER, unique: true, autoIncrement: true, primaryKey: true},\n    item: {\n        type: Sequelize.STRING(80),\n        allowNull: true\n    },\n    item_type: {\n        type: Sequelize.STRING(10),\n        allowNull: false\n    },\n    comment: {\n        type: Sequelize.STRING(1000),\n        allowNull: true\n    },\n    user_id: {\n        type: Sequelize.INTEGER,\n        allowNull: false,\n        references: { model: 'users', key: 'id' }\n    },\n});\n\nItem.associate = models => {\n    Item.belongsTo(models.User, { as: 'users',foreignKey: 'user_id' })\n}\n\ndbconnection.sequelize.sync({ force: false })\n    .then(() => {\n        // console.log('Table created!')\n    })\n});\n\nmodule.exports = {\n    Item\n};\n```\n\n```text\nconst usersdb = require('./userdb')\nconst itemsdb = require('./itemdb')\n\nclass ItemsController {\n    static async getAllItems(req, res, next) {\n        try{\n            let allitems = await itemsdb.Item.findAll({\n                include: [{\n                    model: usersdb.User\n                }]\n            })\n            return {items: allitems, status: true}\n        }\n        catch (e) {\n            return {items: e, status: false}\n        }\n    }\n}\n\nmodule.exports = ItemsController;\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n  const User = sequelize.define('User', {\n    email: {\n        type:  DataTypes(120),\n        allowNull: false,\n        unique: true\n    },\n    dob: {\n        type: DataTypes.DATEONLY,\n        allowNull: false\n    },\n    password: {\n        type:  DataTypes.STRING(256),\n        allowNull: false\n    }\n  }, {});\n  User.associate = function(models) {\n    User.hasMany(models.Item, {as: 'Item', foreignKey: 'user_id'})\n  };\n  return User;\n};\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n  const Item = sequelize.define('Item', {\n    item: {\n      type: DataTypes.STRING(80),\n      allowNull: true\n    },\n    item_type: {\n      type: DataTypes.STRING(10),\n      allowNull: false\n    },\n    comment: {\n      type: DataTypes.STRING(1000),\n      allowNull: true\n    },\n    user_id: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      references: { model: 'User', key: 'id' }\n    }\n  }, {});\n  Item.associate = function(models) {\n    Item.belongsTo(models.User, { as: 'User',foreignKey: 'user_id' })\n  };\n  return Item;\n};\n```\n\n```text\nconst Item = require('../models').Item\nconst User = require('../models').User\n\nclass ItemsController {\n    static async getAllItems() {\n        try{\n            let allitems = await Item.findAll({\n                include: [{\n                    model: User,\n                    as: 'User'\n                }]\n            })\n            return {items: allitems, status: true}\n        }\n        catch (e) {\n            return {items: e, status: false}\n        }\n    }\n}\n\nmodule.exports = ItemsController;\n```\n\n```text\nsequelize model:create --name ModelName --attributes columnName:columnType\n```\n\n```text\nsequelize db:migrate\n```\n\n```text\nsequelize.sync({force: false/true})\n```\n\n========================================\n\nComments:\n- You should use an alias you defined in an Item model for user, also I think you should use alias items instead of user in a User model, it makes a more sense to me and maybe problem is a duplicity in aliases. Last thing is you should use a synch method once after all associations not in all models, it is not a good approach.\n- @RichardSol&#225;r I have corrected the aliases but is still not working.\n- Can you reproduce it in some example code and a repo?\n- I have finally found a workaround. First, I dropped the tables. Second, I generated migrations and models using the \" sequelize model:create --name ModelName --attributes columnName:columnType \" command. I then used the generated models to associate the two tables just as I had done earlier. Lastly, I ran the \" sequelize db:migrate \" command to create the tables and on running the query, IT WORKED!\n- so it looks a sync method in model was a problem\n- sure, was also thinking the same","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":317,"estimatedTokens":1824}}1081{"id":"stack-43690972","source":"stackoverflow","questionId":43690972,"title":"error : connect ECONNREFUSED","tags":["mysql","node.js","sequelize.js","econnrefused"],"text":"Title: error : connect ECONNREFUSED\nTags: mysql, node.js, sequelize.js, econnrefused\nSource: Stack Overflow\n\nQuestion:\nI am running a node app with mysql as my database(also using sequelize as ORM). Whenever I run the \"app.js\" file with \"node\" command, I get an error:\n\n{ [Error: connect ECONNREFUSED 127.0.0.1:3306]\n code: 'ECONNREFUSED',\n errno: 'ECONNREFUSED',\n syscall: 'connect',\n address: '127.0.0.1',\n port: 3306,\n fatal: true }\n\n```\nmy code in the app.js file:\n\nvar mysql = require(\"mysql\");\n\nvar connection = mysql.createConnection({\n host: \"localhost\",\n user: \"root\",\n password: \"password\",\n database: \"openshare\"\n});\n\nconnection.connect(function(err){\n if(err){\n console.log(err);\n } else {\n console.log(\"no errors\");\n }\n});\n```\n\n========================================\n\nTop Answer:\nI had the same issue trying to connect node to a database in Cloud9. he fix was to \n\n**run the database and node in the same Cloud9 workspace.**\n\nThough this might be obvious to more experienced coders, I wrongly thought that I had the two workspaces communicating.\n\n========================================\n\nCode:\n```text\nmy code in the app.js file:\n\nvar  mysql = require(\"mysql\");\n\nvar connection = mysql.createConnection({\n  host: \"localhost\",\n  user: \"root\",\n  password: \"password\",\n  database: \"openshare\"\n});\n\nconnection.connect(function(err){\n  if(err){\n    console.log(err);\n  } else {\n    console.log(\"no errors\");\n  }\n});\n```\n\n```js\nvar connection = mysql.createConnection({\n  host: \"localhost\",\n  user: \"seth40047\",\n  password: \"\",\n  database: \"c9\"\n});\n```\n\n========================================\n\nComments:\n- Nothing was listening at 127.0.0.1:3306. MySQL wasn't running there, or running on a different port.\n- Thanks that fixes it, but after that I get another error with the same code running: { [Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES)] code: 'ER_ACCESS_DENIED_ERROR', errno: 1045, sqlState: '28000', fatal: true }\n- So you used an invalid username or password, or that user didn't have 'localhost ' access.\n- for root user mysql default password is empty string\n- @Adiii Not in my experience. Every time I've installed it I've been asked to *specify* a root password.\n- forums.mysql.com/read.php?34,140320,140324\n- dev.mysql.com/doc/refman/5.5/en/resetting-permissions.html\n- Thanks for help guys, your comments lead me towards the answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":89,"estimatedTokens":602}}1082{"id":"stack-47168244","source":"stackoverflow","questionId":47168244,"title":"Sequelize: joining table on a subquery","tags":["postgresql","sequelize.js"],"text":"Title: Sequelize: joining table on a subquery\nTags: postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to join a table on a subquery, but I don't know how to express it using Sequelize ORM. This is the raw SQL I want to run:\n\n```\nSELECT *\nFROM table_a a\nLEFT OUTER JOIN (SELECT * FROM table_b b WHERE col = VAL) ON a.id = b.id;\n```\n\nI tried \n\n```\nA.findAll({\n include: [\n {\n model: B,\n where: { col: val },\n }\n ]\n}).then(...);\n```\n\nbut that doesn't get me the query I want. Instead it changes the `join` to an `INNER JOIN`, and joins on `col = VALUE` instead. Is there a way to do a join on the result of a subquery? I am using Postgres if it matters.\n\nUpdate: After making the following change, the resulting query now uses a LEFT OUTER JOIN as expected:\n\n```\ninclude: [\n {\n model: B,\n where: { col: val },\n required: false,\n }\n]\n```\n\nHowever, it is still joining on col = VALUE, the generated query looks like:\n\n```\nSELECT * FROM table_a a \nLEFT OUTER JOIN table_b b ON a.id = b.id AND b.col = VALUE;\n```\n\n========================================\n\nCode:\n```text\nSELECT *\nFROM table_a a\nLEFT OUTER JOIN (SELECT * FROM table_b b WHERE col = VAL) ON a.id = b.id;\n```\n\n```text\nA.findAll({\n    include: [\n        {\n            model: B,\n            where: { col: val },\n        }\n    ]\n}).then(...);\n```\n\n```text\ninclude: [\n    {\n        model: B,\n        where: { col: val },\n        required: false,\n    }\n]\n```\n\n```text\nSELECT * FROM table_a a \nLEFT OUTER JOIN table_b b ON a.id = b.id AND b.col = VALUE;\n```\n\n```text\njoin\n```\n\n```text\nINNER JOIN\n```\n\n```text\ncol = VALUE\n```\n\n```text\nSELECT * FROM table_a a\nLEFT OUTER JOIN (SELECT * FROM table_b b WHERE col = VAL) ON a.id = b.id;\n\nSELECT * FROM table_a a \nLEFT OUTER JOIN table_b b ON a.id = b.id AND b.col = VALUE;\n```\n\n========================================\n\nComments:\n- there are differences if one need to limit the many records in table_b to one and sorted\n- Yes, but that's not this question.","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":107,"estimatedTokens":494}}1083{"id":"stack-39393119","source":"stackoverflow","questionId":39393119,"title":"Sequelize belongsToMany self reference not creating foreign key","tags":["node.js","sequelize.js"],"text":"Title: Sequelize belongsToMany self reference not creating foreign key\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm creating a self-referencing belongsToMany relationship with sequelize with a model as the through argument.\n\nHowever when it creates the table it only creates a foreign key for one of the relationships.\n\nModel:\n\n```\nconst client = sequelize.define('client', {\n ClientId: {\n type: DataTypes.UUID,\n primaryKey: true,\n allowNull: false,\n defaultValue: DataTypes.UUIDV4()\n },\n AccessMode: {\n type: DataTypes.ENUM('allow_all', 'deny_all', 'selective'),\n allowNull: false\n }\n}, {\n classMethods: {\n associate: function (models) {\n // Tons of other relationships here\n\n client.belongsToMany(models.client, {\n through: models.clientAccess,\n as: 'clientsWithAccess',\n foreignKey: 'ClientId'\n });\n\n client.belongsToMany(models.client, {\n through: models.clientAccess,\n as: 'accessToClients',\n foreignKey: 'AccessingClientId'\n });\n\n }\n }\n\n});\n```\n\nThe through model:\n\n```\nconst clientAccess = sequelize.define('clientAccess', {\n Access: {\n type: DataTypes.ENUM('allow', 'deny'),\n allowNull: false\n }\n}, {\n timestamps: false\n});\n```\n\nThe resulting table only has the column AccessMode and AccessingClientId. And for some reason AccessingClientId is set as the primary key.\n\nIf I switch the placements of the belongsToMany() statements then the name of the field in the table is also reversed.\n\n========================================\n\nCode:\n```text\nconst client = sequelize.define('client', {\n    ClientId: {\n        type: DataTypes.UUID,\n        primaryKey: true,\n        allowNull: false,\n        defaultValue: DataTypes.UUIDV4()\n    },\n    AccessMode: {\n        type: DataTypes.ENUM('allow_all', 'deny_all', 'selective'),\n        allowNull: false\n    }\n}, {\n    classMethods: {\n        associate: function (models) {\n            // Tons of other relationships here\n\n            client.belongsToMany(models.client, {\n                through: models.clientAccess,\n                as: 'clientsWithAccess',\n                foreignKey: 'ClientId'\n            });\n\n            client.belongsToMany(models.client, {\n                through: models.clientAccess,\n                as: 'accessToClients',\n                foreignKey: 'AccessingClientId'\n            });\n\n        }\n    }\n\n});\n```\n\n```text\nconst clientAccess = sequelize.define('clientAccess', {\n    Access: {\n        type: DataTypes.ENUM('allow', 'deny'),\n        allowNull: false\n    }\n}, {\n    timestamps: false\n});\n```\n\n```text\nclient.belongsToMany(models.client, {\n            through: models.clientAccess,\n            as: 'clientsWithAccess',\n            foreignKey: 'ClientId',\n            otherKey: 'AccessingClientId'\n        });\n\n        client.belongsToMany(models.client, {\n            through: models.clientAccess,\n            as: 'accessToClients',\n            foreignKey: 'AccessingClientId',\n            otherKey: 'ClientId'\n        });\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":127,"estimatedTokens":735}}1084{"id":"stack-49846852","source":"stackoverflow","questionId":49846852,"title":"How to define a sequalize table field which has multiple attributes","tags":["javascript","node.js","postgresql","express","sequelize.js"],"text":"Title: How to define a sequalize table field which has multiple attributes\nTags: javascript, node.js, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am working on a project with nodejs, postgres, sequelize and express and trying to insert values to a seqaulzied database table from an API response , which contains an array of objects. API response contains the below location field.\n\n```\n\"description\": \"Hello\",\n\"location\": [\n {\n \"path\": \"Hekki\",\n \"address\": \"test\"\n }\n],\n```\n\nAnd I have a table mapping for this something similar to below.\n\n```\nconst model = db.define('Tablename', {\n description: Sequelize.TEXT,\n location: {\n path: Sequelize.STRING,\n address: Sequelize.STRING,\n },\n```\n\nBut this won't work since this is not an array definition and the syntax is also not valid.\n\nThe location field has two attributes. How should I handle this properly.\n\nCould someone help me to write the proper table definition for this?\n\n========================================\n\nCode:\n```text\n\"description\": \"Hello\",\n\"location\": [\n    {\n        \"path\": \"Hekki\",\n        \"address\": \"test\"\n    }\n],\n```\n\n```text\nconst model = db.define('Tablename', {\n    description: Sequelize.TEXT,\n    location: {\n         path: Sequelize.STRING,\n         address: Sequelize.STRING,\n    },\n```\n\n========================================\n\nComments:\n- Yes I did create a separate table for locations. there is no other way perhaps. :)\n- BTW, the JSON field can be also used.","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":61,"estimatedTokens":368}}1085{"id":"stack-52368657","source":"stackoverflow","questionId":52368657,"title":"Why does my Sequelize / Typescript function error with \"Two different types with this name exist, but they are unrelated.\"?","tags":["typescript","sequelize.js","sequelize-typescript"],"text":"Title: Why does my Sequelize / Typescript function error with \"Two different types with this name exist, but they are unrelated.\"?\nTags: typescript, sequelize.js, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI'm using `sequelize-typescript`, and my code is:\n\n```\nimport Promise from \"bluebird\";\nimport { IncomingCall } from '../models/IncomingCall';\nexport function incoming(requestBody: object): Promise {\n return IncomingCall.create({\n CallSid: requestBody.CallSid\n });\n}\n```\n\nBut the error I get is:\n\n```\n[ts]\nType 'Bluebird' is not assignable to type 'Bluebird'. Two different types with this name exist, but they are unrelated.\n Types of property 'then' are incompatible.\n```\n\nMy `IncomingCall` is:\n\n```\nimport { Model, Column, Table, DataType } from \"sequelize-typescript\";\n\n@Table\nexport class IncomingCall extends Model {\n\n @Column\n CallSid: string;\n\n @Column\n AccountSid: string;\n\n @Column(DataType.JSON)\n rawData: string;\n\n}\n```\n\nHow do I get this to work properly?\n\n========================================\n\nTop Answer:\n`export class IncomingCall extends Model` seems incorrect as you assign to a type parameter a type that does not exist at definition time. I guess something like `export class IncomingCall extends Model` is better, or you could define the shape of your model in another interface altogether.\n\n========================================\n\nCode:\n```text\nimport Promise from \"bluebird\";\nimport { IncomingCall } from '../models/IncomingCall';\nexport function incoming(requestBody: object): Promise<IncomingCall> {\n  return IncomingCall.create({\n    CallSid: requestBody.CallSid\n  });\n}\n```\n\n```text\n[ts]\nType 'Bluebird<import(\"/src/models/IncomingCall\").IncomingCall>' is not assignable to type 'Bluebird<import(\"/src/models/IncomingCall\").IncomingCall>'. Two different types with this name exist, but they are unrelated.\n  Types of property 'then' are incompatible.\n```\n\n```text\nimport { Model, Column, Table, DataType } from \"sequelize-typescript\";\n\n@Table\nexport class IncomingCall extends Model<IncomingCall> {\n\n  @Column\n  CallSid: string;\n\n  @Column\n  AccountSid: string;\n\n  @Column(DataType.JSON)\n  rawData: string;\n\n}\n```\n\n```text\nsequelize-typescript\n```\n\n```text\nIncomingCall\n```\n\n```text\nexport function incoming(requestBody: object): Promise<any> {\n```\n\n```text\nexport class IncomingCall extends Model<IncomingCall>\n```\n\n```text\nexport class IncomingCall extends Model<{ Callsid: string; AccountsId: string; rawData: string; }>\n```\n\n========================================\n\nComments:\n- That's what I thought as well, but apparently, that's how to define models with this package: github.com/RobinBuschmann/sequelize-typescript#model-definit&zwnj;&#8203;ion\n- so you have more than one definition of promise in your project? the one in bluebird and the one in lib.es5\n- lib.es5.core. you can check with the traceResolution flag in the compiler options","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":115,"estimatedTokens":725}}1086{"id":"stack-58535870","source":"stackoverflow","questionId":58535870,"title":"TypeError: Modelname.findById is not a function with sequelize nodejs","tags":["node.js","sequelize.js","sequelize-cli"],"text":"Title: TypeError: Modelname.findById is not a function with sequelize nodejs\nTags: node.js, sequelize.js, sequelize-cli\nSource: Stack Overflow\n\nQuestion:\nI want to find value from table with respect to Id passed in api. When using findByID to find one record I am getting below errro.\n\n```\nTypeError: Modelname.findById is not a function\n```\n\n========================================\n\nCode:\n```text\nTypeError: Modelname.findById is not a function\n```\n\n```text\nfindById\n```\n\n```text\nfindByPk\n```\n\n```text\nBook.findByPk(someId)\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":29,"estimatedTokens":133}}1087{"id":"stack-56238164","source":"stackoverflow","questionId":56238164,"title":"Fetch associated models after fetching the Model","tags":["node.js","sequelize.js","model-associations"],"text":"Title: Fetch associated models after fetching the Model\nTags: node.js, sequelize.js, model-associations\nSource: Stack Overflow\n\nQuestion:\nI have a model \"Task\". One Task belongs to exactly one User and one User has many Tasks. So this is a one to many relation. Now I can fetch User with their Task as follows.\n\n```\nUser.findByPk(41, {include: [Task]});\n```\n\nBut I don't want to fetch Task while fetching user. Instead I would like to fetch Task something like.\n\n```\nvar user = await User.findByPk(41); \nvar tasks = await user.load(Task);\n```\n\nIs there any method provided by Sequelize models to load the associations later.\n\n========================================\n\nCode:\n```text\nUser.findByPk(41, {include: [Task]});\n```\n\n```text\nvar user = await User.findByPk(41);    \nvar tasks = await user.load(Task);\n```\n\n```text\nvar user = await User.findByPk(41);\nvar tasks = await user.getTasks();\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":36,"estimatedTokens":224}}1088{"id":"stack-46998715","source":"stackoverflow","questionId":46998715,"title":"How do I access the Sequelize model inside of the Trails model","tags":["node.js","sequelize.js","trailsjs"],"text":"Title: How do I access the Sequelize model inside of the Trails model\nTags: node.js, sequelize.js, trailsjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to get https://github.com/jarrodconnolly/sequelize-slugify to work within my Trails setup, but I can't see a way of accessing the Model that is created by Sequelize inside of the Trails model. The plugin example says I need to do something like:\n\n```\nSequelizeSlugify.slugifyModel(SequelizeModelHere, {\n source: ['title'],\n suffixSource: ['year']\n});\n```\n\nI noticed that trails creates a Sequelize model and adds it to the service locator under `this.app.orm[model.globalId]`, I however can't access this inside of the Trails model itself as it would not have been created by then. I wanted to do this all inside of the model itself, but if there is no way of doing this, I will do it in a Service instead.\n\n========================================\n\nCode:\n```text\nSequelizeSlugify.slugifyModel(SequelizeModelHere, {\n    source: ['title'],\n    suffixSource: ['year']\n});\n```\n\n```text\nthis.app.orm[model.globalId]\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":29,"estimatedTokens":268}}1089{"id":"stack-58422169","source":"stackoverflow","questionId":58422169,"title":"Query data from another table referenced by a foreign key with Sequelize and Postgres","tags":["node.js","reactjs","postgresql","express","sequelize.js"],"text":"Title: Query data from another table referenced by a foreign key with Sequelize and Postgres\nTags: node.js, reactjs, postgresql, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a NextJs NodeJs Express app with Postrges as a database, I'm also running two servers and using axios for get and post requests to and from my api endpoints.\n\nI have two tables: Company and Bank, The primary key from the Bank table is referenced in the Company table as a foreign key. Company can have only one bank.\n\n```\nIf I have a Bank table:\nBankId Bank Name Account Number\n1 New Bank 123456789\n\nCompany table:\nCompanyId Company Name BankId\n1 Newer Company 1\n```\n\nI want to show data for the company:\n\n```\nCompany Name: Newer Company\nBank Name: New Bank\nAccount Number: 123456789\n```\n\nHere are my files:\n\nCompany model:\nmodels/companyData.js\n\n```\nconst Sequelize = require ('sequelize');\nconst db = require('../config/database');\nconst bank = require('./bank');\n\nconst companyData = db.define('companyData', {\n companyId: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n company_name: {\n type: Sequelize.STRING\n },\n bankId: {\n type: Sequelize.INTEGER,\n references: {\n model: 'bank', \n key: 'bankId',\n }\n }\n}, {\n freezeTableName: true\n})\n\nbank.hasOne(companyData);\n\nmodule.exports = companyData;\n```\n\nBank model:\nmodels/bank.js\n\n```\nconst Sequelize = require('sequelize');\nconst db = require('../config/database');\n\nconst Bank = db.define('bank', {\n bankId: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n bank_name: {\n type: Sequelize.STRING\n },\n account_number: {\n type: Sequelize.BIGINT\n }\n}, {\n freezeTableName: true\n})\n\nmodule.exports = Bank;\n```\n\nHere is a Component containing state and input fields for creating a new Company:\ncomponents/newCompanyData.js\n\n```\nimport React from 'react';\nimport axios from 'axios';\n\nclass newCompanyData extends React.Component {\n\n state = {\n company_name: '',\n bankId: '',\n }\n\n onChangeCompanyName = (e) => {\n this.setState({\n company_name: e.target.value\n })\n }\n\n onChangeBankId = (e) => {\n this.setState({\n bankId: e.target.value\n })\n }\n\n onSubmit = (e) => {\n e.preventDefault()\n\n axios.post('http://localhost:9000/api/company', {\n company_name: this.state.company_name,\n bankId: this.state.bankId,\n })\n .then(res => {\n console.log(res);\n }).catch(err => console.log(err))\n }\n\n onReset = (e) => {\n this.setState({\n company_name: '',\n bankId: '',\n })\n }\n\n render() {\n return (\n \n \n Company name:\n\n \n\n Bank Id:\n\n \n\n \n\n Submit\n\n \n \n \n )\n }\n}\n\nexport default newCompanyData;\n```\n\nI then send request to this api endpoint to create a table if it doesn't exist or just fill in the new row:\nroutes/api/company.js\n\n```\nconst express = require('express');\nconst router = express.Router();\nconst DB = require('../../config/database');\nconst companyData = require('../../models/companyData');\n\nrouter.post('/', (req, res) => {\n const data = req.body;\n\n DB.sync().then(function() {\n return companyData.create({\n company_name: data.company_name,\n bankId: data.bankId,\n });\n }).then(function () { \n res.send(req.body);\n console.log('Success!')\n });\n })\n\nmodule.exports = router;\n```\n\nSo it does create a table and fills in all the data, however the issue is when I want to print all data from the company table including the data from the bank table that is referenced by the bankId:\npages/viewCompany.js\n\n```\nimport React from 'react';\nimport axios from 'axios';\n\nclass listCompany extends React.Component {\n\n state = {\n data: []\n }\n\n componentDidMount = () => {\n axios.get('http://localhost:9000/api/listcompany')\n .then((response) => {\n console.log(response.data);\n this.setState({data: response.data.response})\n }).catch(err => {\n console.log(err);\n }); \n }\n\n render() {\n return (\n \n \n\n### Company List\n\n \n )\n }\n}\n\nexport default listCompany;\n```\n\nI sent a get request to this API endpoint but it doesnt return it properly:\nroutes/api/listcompany.js\n\n```\nconst express = require('express');\nconst router = express.Router();\nconst Bank = require('../../models/bank');\nconst companyData = require('../../models/companyData');\n\nrouter.get('/', (req, res) => {\n companyData.findAll({\n include: [{\n model: Bank\n }]}).then(function(response) {\n console.log(response);\n res.send({response});\n }).catch(function(err){\n console.log('Oops! something went wrong, : ', err);\n });\n })\n\nmodule.exports = router;\n```\n\nI have a feeling I don't connect it well enough in the model stage, and also when sending a query. I appreciate all help I can get. Thanks.\n\n========================================\n\nTop Answer:\n```\nconst bank = require('./bank');\n```\n\nThis statement will not import the Bank Model properly. In sequelize in order to import a model from a model definition you have to use `sequelize.import( // path to file)`. In order to import model correctly use following:\n\n```\nconst bank = sequelize.import('./bank');\n```\n\n**Note:** Here `seuqelize` is an instance of `Sequelize` and not the class itsself. `seuqelize` variable is the database connection you created using something like\n\n```\nconst sequelize = new Sequelize(DB_NAME, DB_USERNAME, DB_PASSWORD, { ...options })\n```\n\n========================================\n\nCode:\n```text\nIf I have a Bank table:\nBankId    Bank Name    Account Number\n1         New Bank     123456789\n\nCompany table:\nCompanyId   Company Name    BankId\n1           Newer Company   1\n```\n\n```text\nCompany Name: Newer Company\nBank Name: New Bank\nAccount Number: 123456789\n```\n\n```text\nconst Sequelize = require ('sequelize');\nconst db = require('../config/database');\nconst bank = require('./bank');\n\nconst companyData = db.define('companyData', {\n    companyId: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    company_name: {\n        type: Sequelize.STRING\n    },\n    bankId: {\n        type: Sequelize.INTEGER,\n        references: {\n           model: 'bank', \n           key: 'bankId',\n        }\n    }\n}, {\n    freezeTableName: true\n})\n\nbank.hasOne(companyData);\n\nmodule.exports = companyData;\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst db = require('../config/database');\n\nconst Bank = db.define('bank', {\n    bankId: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    bank_name: {\n        type: Sequelize.STRING\n    },\n    account_number: {\n        type: Sequelize.BIGINT\n    }\n}, {\n    freezeTableName: true\n})\n\nmodule.exports = Bank;\n```\n\n```text\nimport React from 'react';\nimport axios from 'axios';\n\nclass newCompanyData extends React.Component {\n\n        state = {\n            company_name: '',\n            bankId: '',\n        }\n\n    onChangeCompanyName = (e) => {\n        this.setState({\n            company_name: e.target.value\n        })\n    }\n\n    onChangeBankId = (e) => {\n        this.setState({\n            bankId: e.target.value\n        })\n    }\n\n    onSubmit = (e) => {\n        e.preventDefault()\n\n        axios.post('http://localhost:9000/api/company', {\n            company_name: this.state.company_name,\n            bankId: this.state.bankId,\n        })\n        .then(res => {\n            console.log(res);\n        }).catch(err => console.log(err))\n    }\n\n    onReset = (e) => {\n        this.setState({\n            company_name: '',\n            bankId: '',\n        })\n    }\n\n    render() {\n        return (\n            <div>\n                <form>\n                    Company name:<br/>\n                    <input type=\"text\" name=\"companyname\" onChange={this.onChangeCompanyName} value={this.state.company_name}></input><br/>\n                    Bank Id:<br/>\n                    <input type=\"number\" name=\"bankid\" onChange={this.onChangeBankId} value={this.state.bankId}></input><br/>\n                    <br/>\n                    <button type=\"submit\" onClick={this.onSubmit}>Submit</button><br/>\n                    <input type=\"button\" value=\"Reset Form\" onClick={this.onReset} />\n                </form>\n            </div>\n        )\n    }\n}\n\nexport default newCompanyData;\n```\n\n```text\nconst express = require('express');\nconst router = express.Router();\nconst DB = require('../../config/database');\nconst companyData = require('../../models/companyData');\n\nrouter.post('/', (req, res) => {\n    const data = req.body;\n\n    DB.sync().then(function() {\n        return companyData.create({\n            company_name: data.company_name,\n            bankId: data.bankId,\n        });\n      }).then(function () { \n          res.send(req.body);\n          console.log('Success!')\n      });\n    })\n\nmodule.exports = router;\n```\n\n```text\nimport React from 'react';\nimport axios from 'axios';\n\nclass listCompany extends React.Component {\n\n    state = {\n        data: []\n    }\n\n    componentDidMount = () =>  {\n        axios.get('http://localhost:9000/api/listcompany')\n            .then((response) => {\n                console.log(response.data);\n                this.setState({data: response.data.response})\n            }).catch(err => {\n                console.log(err);\n              });  \n    }\n\n    render() {\n        return (\n            <div>\n                <h1>Company List</h1>\n            </div>\n        )\n    }\n}\n\nexport default listCompany;\n```\n\n```text\nconst express = require('express');\nconst router = express.Router();\nconst Bank = require('../../models/bank');\nconst companyData = require('../../models/companyData');\n\nrouter.get('/', (req, res) => {\n        companyData.findAll({\n            include: [{\n            model: Bank\n        }]}).then(function(response) {\n            console.log(response);\n            res.send({response});\n          }).catch(function(err){\n            console.log('Oops! something went wrong, : ', err);\n          });\n    })\n\nmodule.exports = router;\n```\n\n```text\nconst Sequelize = require ('sequelize');\nconst db = require('../config/database');\nconst Bank = require('./bank');\n\nconst companyData = db.define('companyData', {\n    companyId: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    company_name: {\n        type: Sequelize.STRING\n    },\n    bankingId: {\n        type: Sequelize.INTEGER,\n        references: {\n           model: Bank, \n           key: 'bankId',\n        }\n    }\n}, {\n    freezeTableName: true\n})\n\nmodule.exports = companyData;\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst db = require('../config/database');\nconst companyData = require('./companyData');\n\nconst Bank = db.define('bank', {\n    bankId: {\n        type: Sequelize.INTEGER,\n        primaryKey: true,\n        autoIncrement: true\n    },\n    bank_name: {\n        type: Sequelize.STRING\n    },\n    account_number: {\n        type: Sequelize.BIGINT\n    }\n}, {\n    freezeTableName: true\n})\n\nBank.belongsTo(companyData, {foreignKey: 'bankingId'});\ncompanyData.hasOne(Bank, {foreignKey: 'bankId'});\n```\n\n```text\nconst express = require('express');\nconst router = express.Router();\nconst Bank = require('../../models/bank');\nconst companyData = require('../../models/companyData');\n\nrouter.get('/', (req, res) => {\n        companyData.findAll({\n          include: [{\n            model: Bank,\n            attributes: ['bankId', 'bank_name', 'account_number']  \n          }],\n        }).then(function(response) {\n            console.log(response);\n            res.send({response});\n          }).catch(function(err){\n            console.log('Oops! something went wrong, : ', err);\n          });\n    })\n```\n\n```text\nconst bank = require('./bank');\n```\n\n```text\nconst bank = sequelize.import('./bank');\n```\n\n```text\nconst sequelize = new Sequelize(DB_NAME, DB_USERNAME, DB_PASSWORD, { ...options })\n```\n\n```text\nsequelize.import( // path to file)\n```\n\n```text\nseuqelize\n```\n\n```text\nSequelize\n```\n\n```text\nseuqelize\n```\n\n========================================\n\nComments:\n- I had issues implementing this fix because I wasn't able to call that instance from the config while where I create the Database connection. However I did manage to get it to work after almost 10 days of trial and error. Thanks for the answer though, it did push me to the right direction though.","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":584,"estimatedTokens":3022}}1090{"id":"stack-48396275","source":"stackoverflow","questionId":48396275,"title":"Sequelize - How to set association, save entity and return the saved entity with the associated entity","tags":["node.js","sequelize.js"],"text":"Title: Sequelize - How to set association, save entity and return the saved entity with the associated entity\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to create an association between an existing (user) entity and save the new entity (visit).\n\nI've read the sequelize docs and can't see a better way of doing this than saving the first entity using async/await, then fetching it again passing `include` as an option. See below.\n\n```\nexport const createVisit = async(req, res) => {\n req.assert('BusinessId', 'Must pass businessId').notEmpty();\n req.assert('UserId', 'Must pass customerId').notEmpty();\n\n const visit = await new Visit({\n UserId: req.body.UserId,\n BusinessId: req.body.BusinessId,\n redemption: false,\n })\n .save()\n .catch((error) => {\n res.status(400).send({ error });\n });\n\n const visitWithUser = await Visit.findById(visit.id, {include: [{model: User, attributes: ['firstName','lastName','facebook', 'gender','email']}]})\n\n res.status(200).send({ visit: visitWithUser })\n};\n```\n\nIs there a way to save the entity and get sequelize to return the saved entity along with any associations?\n\n========================================\n\nCode:\n```text\nexport const createVisit = async(req, res) => {\n  req.assert('BusinessId', 'Must pass businessId').notEmpty();\n  req.assert('UserId', 'Must pass customerId').notEmpty();\n\n  const visit = await new Visit({\n    UserId: req.body.UserId,\n    BusinessId: req.body.BusinessId,\n    redemption: false,\n  })\n  .save()\n   .catch((error) => {\n    res.status(400).send({ error });\n  });\n\n    const visitWithUser = await Visit.findById(visit.id, {include: [{model: User, attributes: ['firstName','lastName','facebook', 'gender','email']}]})\n\n    res.status(200).send({ visit: visitWithUser })\n};\n```\n\n```text\ninclude\n```\n\n```text\nVisit.create({\n    UserId: req.body.UserId,\n    BusinessId: req.body.BusinessId,\n    redemption: false,\n}, {\n  include: [User]\n}).then(function(comment) {\n    console.log(comment.user.id);\n});\n```\n\n========================================\n\nComments:\n- Currently I think this is the only way to go about this. There's an issue on github that's asking to support this functionality.\n- Ok - Thanks a lot for answering.\n- @Powderham, will you please check the answer?\n- I was initially hesitant to step away from using new, but this causes later problems with using new for a side effect: link Therefore I can accept this as the answer","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":79,"estimatedTokens":611}}1091{"id":"stack-55963695","source":"stackoverflow","questionId":55963695,"title":"JavaScript heap out of memory while updating the mongodb","tags":["node.js","mongodb","mongoose","sequelize.js"],"text":"Title: JavaScript heap out of memory while updating the mongodb\nTags: node.js, mongodb, mongoose, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to synchronize data between to data stores, the source is mssql and the destination is MongoDB. In this syncing process I am getting a memory heap error. I am not sure why this happens and I am fully aware that the following code may not be the best, but for now I am just trying to understand why the allocation error is coming.\n\nI am compiling my code with babel, in development I am just using babel-node.\n\n```\ntry {\n const response = await sqlDataStore.findAll({\n attributes: ['id', 'Name'],\n });\n /* eslint no-restricted-syntax: 0 */\n for (const item of response) {\n /* eslint no-await-in-loop: 0 */\n await this.Model.updateOne({}, item, { upsert: true });\n }\n} catch (err) {\n console.log(err);\n}\n```\n\nIf I understand correctly the heap error is caused by the for loop, so that would mean that every await statement is cached in the memory. I would have expected that every await statement is cleared from the memory because I am not assigning it to any variable.\n\n**Updated:**\n\nGladly I found already a solution due to another post: Bulk upsert in MongoDB using mongoose\n\nMy Code:\n\n```\nconst response = await sqlDataStore.findAll({\n attributes: ['id', 'Name'],\n });\n\n const bulkUpdate = response.map(doc => ({\n updateOne: {\n filter: { _id: doc.id },\n update: doc.dataValues,\n upsert: true,\n },\n }));\n\n this.Model.collection.bulkWrite(bulkUpdate);\n```\n\nIf someone is using this solution it should be kept in mind that this also could crash for lots amount of data. The solution provided in the other posts suggests that the data should be processed in buckets of 1000 until every document is updated/inserted.\n\nJust for interest and technical understanding I would appreciate an explanation of what exactly I did wrong in my first code.\n\n========================================\n\nCode:\n```text\ntry {\n  const response = await sqlDataStore.findAll({\n    attributes: ['id', 'Name'],\n  });\n  /* eslint no-restricted-syntax: 0 */\n  for (const item of response) {\n    /* eslint no-await-in-loop: 0 */\n    await this.Model.updateOne({}, item, { upsert: true });\n  }\n} catch (err) {\n  console.log(err);\n}\n```\n\n```text\nconst response = await sqlDataStore.findAll({\n    attributes: ['id', 'Name'],\n  });\n\n  const bulkUpdate = response.map(doc => ({\n    updateOne: {\n      filter: { _id: doc.id },\n      update: doc.dataValues,\n      upsert: true,\n    },\n  }));\n\n  this.Model.collection.bulkWrite(bulkUpdate);\n```\n\n========================================\n\nComments:\n- Just to be sure, does the code run fine with just the first SQL query? I.e., it's not that it's just too huge an amount of data being brought in?\n- yea it is definitely fine for the sql query and the amount of data is also not that big there are just 2401 rows.\n- check this one eslint.org/docs/rules/no-await-in-loop\n- Hi I understand that the operations are delayed but that is not my question, the question is if they are indeed stored in the memory and if that is expected behavior even though I am not storing the response in any variable.\n- I guess this is because your execution is completely blocked the next execution and will be in memory until your entire execution is complete. Check the link I have shared.\n- Your execution should be parallel instead of synchronous and you should collect the result of every await in some variable which will make your execution more memory efficient as your call stack is not getting free after the execution which causing you out of memory exception.It is not about variable memory, it is actually about function call stack which is causing you this exception.\n- Thank you very much that makes everything clear I try to keep that in mind for future references\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":97,"estimatedTokens":968}}1092{"id":"stack-53281798","source":"stackoverflow","questionId":53281798,"title":"AVOID DUPLICATES in sequelize query","tags":["mysql","database","express","sequelize.js"],"text":"Title: AVOID DUPLICATES in sequelize query\nTags: mysql, database, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\ni'm implementing a like system for a project. And I need some help with a query. \n\nBasically i have 2 buttons (upvote and downvote) that call my function and give the id of a thread, the username voting, and the vote ( 1 or -1).\n\n```\naddPositiveorNegativeLikes = function(thread_id, username, vote) {\n\n sequelize.query('INSERT INTO Likes (thread_id, userId, vote, createdAt, updatedAt) \n VALUES((?), (SELECT id FROM Users WHERE username=(?)), (?), (?), (?)) \n ON DUPLICATE KEY UPDATE thread_id=(?), userId=(SELECT id FROM Users WHERE username=(?))',{\n\n replacements: [thread_id, username, vote, new Date(), new Date(), thread_id, username]\n }) \n}\n```\n\nBut now in my Likes table althought thread_id and userId ara both primary keys, inserts multiple repeated \"Likes\". \n\nHow I can modify my query so it deletes an existing vote and replaces it for a new one??\n\nHere is my Like model:\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\nconst Like = sequelize.define('Like', {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: DataTypes.INTEGER\n },\n userId: {\n allowNull: false,\n primaryKey: true,\n type: DataTypes.INTEGER\n },\n thread_id: {\n allowNull: false,\n primaryKey: true,\n type: DataTypes.INTEGER\n },\n createdAt: {\n allowNull: false,\n type: DataTypes.DATE\n },\n updatedAt: {\n allowNull: false,\n type: DataTypes.DATE\n },\n vote: {\n type: DataTypes.INTEGER\n }\n}, {});\n Like.associate = function(models) {\n // associations can be defined here\n };\nreturn Like;\n};\n```\n\n========================================\n\nCode:\n```text\naddPositiveorNegativeLikes = function(thread_id, username, vote) {\n\n sequelize.query('INSERT INTO Likes (thread_id, userId, vote, createdAt, updatedAt) \n VALUES((?), (SELECT id FROM Users WHERE username=(?)), (?), (?), (?)) \n ON DUPLICATE KEY UPDATE thread_id=(?), userId=(SELECT id FROM Users WHERE username=(?))',{\n\n replacements: [thread_id, username, vote, new Date(), new Date(), thread_id, username]\n }) \n}\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\nconst Like = sequelize.define('Like', {\n  id: {\n      allowNull: false,\n      autoIncrement: true,\n      primaryKey: true,\n      type: DataTypes.INTEGER\n  },\n  userId: {\n      allowNull: false,\n      primaryKey: true,\n      type: DataTypes.INTEGER\n  },\n  thread_id: {\n      allowNull: false,\n      primaryKey: true,\n      type: DataTypes.INTEGER\n  },\n  createdAt: {\n      allowNull: false,\n      type: DataTypes.DATE\n  },\n  updatedAt: {\n      allowNull: false,\n      type: DataTypes.DATE\n  },\n  vote: {\n      type: DataTypes.INTEGER\n  }\n}, {});\n Like.associate = function(models) {\n // associations can be defined here\n };\nreturn Like;\n};\n```\n\n```text\nuserId: {\n    allowNull: false,\n    unique:\"vote_user\" // <------ HERE\n    type: DataTypes.INTEGER\n},\nthread_id: {\n    allowNull: false,\n    unique:\"vote_user\" // <------ HERE\n    type: DataTypes.INTEGER\n},\n```\n\n```text\n// Creating two objects with the same value will throw an error. The unique property can be either a\n // boolean, or a string. If you provide the same string for multiple columns, they will form a\n // composite unique key.\n uniqueOne: { type: Sequelize.STRING,  unique: 'compositeIndex' },\n uniqueTwo: { type: Sequelize.INTEGER, unique: 'compositeIndex' },\n```\n\n```text\nLike.create({ userId : 1 , thread_id : 1 }).then(data => {\n    // success\n}).catch(err => {\n    // error if same data exists\n})\n// <--- this will check that if there any entry with userId 1 and thread_id 1 , \n// if yes , then this will throw error\n// if no then will create an entry for that\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.500Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":151,"estimatedTokens":926}}1093{"id":"stack-33043204","source":"stackoverflow","questionId":33043204,"title":"Sequelize returns lowercase letter when inserting a one letter uppercase letter?","tags":["javascript","mysql","sequelize.js"],"text":"Title: Sequelize returns lowercase letter when inserting a one letter uppercase letter?\nTags: javascript, mysql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nHow come sequelize inserts and returns a lowercase letter when I insert a one letter uppercase letter? \n\n**Example**: I insert \"N\" and it saves \"n\" instead of \"N\". \n\nI inserted it the following:\n\n```\nconsole.log(toBeInserted) // let's say toBeInserted = \"N\" \n db.dataset.findOrCreate({\n where:{\n name: toBeInserted\n }\n })\n .spread(function(inserted, created) {\n console.log(inserted); //here I get back inserted = \"n\"\n })\n```\n\nLooking at the SQL DB, I can see that `\"n\"` was stored and not `\"N\"`.\n\nBut once the input value consists of at least two letters, sequelize saves it correctly:\n\n```\nconsole.log(toBeInserted) // toBeInserted = \"Hi\" \n db.dataset.findOrCreate({\n where:{\n name: toBeInserted\n }\n })\n .spread(function(inserted, created) {\n console.log(inserted); //here I get back inserted = \"Hi\"\n })\n```\n\nIn the DB, the value `\"Hi\"` was saved correctly.\n\nCould anybody explain to me why that is happening and how I can prevent this? I want sequelize to save the values just like I inserted it, i.e. if I want to insert \"N\" (uppercase letter \"N\") it should save \"N\".\n\n***Edit:***\nSequelize is able to save lowercase and uppercase one letter only inputs. However it seems like the method findOrCreate() isn't able to recognize uppercase from lowercase letter once you create it.\n\nExample: I've got an empty database and I create the following input:\n\n```\nconsole.log(toBeInserted) // toBeInserted = \"A\" \n db.dataset.findOrCreate({\n where:{\n name: toBeInserted\n }\n })\n .spread(function(inserted, created) {\n console.log(inserted + \" \" + created); //here I get back inserted = \"A true\"\n })\n```\n\nI check my DB, and indeed the are saved there with the correct upper/lower case.\n\nAfter that I'll create the following data:\n\n```\nconsole.log(toBeInserted) // toBeInserted = \"a\" \n db.dataset.findOrCreate({\n where:{\n name: toBeInserted\n }\n })\n .spread(function(inserted, created) {\n console.log(inserted + \" \" + created); //here I get back inserted = \"a false\"\n })\n```\n\nI check my DB again and the data hasn't changed.\n\n========================================\n\nCode:\n```text\nconsole.log(toBeInserted) // let's say toBeInserted = \"N\" \n  db.dataset.findOrCreate({\n    where:{\n      name: toBeInserted\n    }\n  })\n  .spread(function(inserted, created) {\n    console.log(inserted); //here I get back inserted = \"n\"\n  })\n```\n\n```text\nconsole.log(toBeInserted) // toBeInserted = \"Hi\" \n  db.dataset.findOrCreate({\n    where:{\n      name: toBeInserted\n    }\n  })\n  .spread(function(inserted, created) {\n    console.log(inserted); //here I get back inserted = \"Hi\"\n  })\n```\n\n```text\nconsole.log(toBeInserted) // toBeInserted = \"A\" \n      db.dataset.findOrCreate({\n        where:{\n          name: toBeInserted\n        }\n      })\n      .spread(function(inserted, created) {\n        console.log(inserted + \" \" + created); //here I get back inserted = \"A true\"\n      })\n```\n\n```text\nconsole.log(toBeInserted) // toBeInserted = \"a\" \n      db.dataset.findOrCreate({\n        where:{\n          name: toBeInserted\n        }\n      })\n      .spread(function(inserted, created) {\n        console.log(inserted + \" \" + created); //here I get back inserted = \"a false\"\n      })\n```\n\n```text\n\"n\"\n```\n\n```text\n\"N\"\n```\n\n```text\n\"Hi\"\n```\n\n========================================\n\nComments:\n- Nope. I tested it with different letters. Always the same outcome. It would save the standard letter instead the capital letter. But ok, I'll look further into that. Thanks for answering.\n- Short question: If you have already created an input, let's say \"N\" in your DB with sequelize and you want to create another one letter input with findOrCreate(), in this case \"n\". Does sequelize creates a new dataset \"n\" or returns the existing dataset \"N\"?\n- If I send \"n\" and it doesn't exist, it creates it.","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":147,"estimatedTokens":981}}1094{"id":"stack-36441286","source":"stackoverflow","questionId":36441286,"title":"Resolve \"IS A\" relationship with graphql-sequelize","tags":["sequelize.js","graphql-js","graphql-sequelize"],"text":"Title: Resolve \"IS A\" relationship with graphql-sequelize\nTags: sequelize.js, graphql-js, graphql-sequelize\nSource: Stack Overflow\n\nQuestion:\nI'm using `graphql`, `sequelize` and `graphql-sequelize`, and I'm having some troubles to resolve a \"IS A\" relationship.\n\nMy sequelize models are the following:\n\n```\n// models.js\n\n// User table\nlet User = sequelize.define('user', {\n id: Sequelize.INTEGER\n name: Sequelize.STRING\n});\n\n// Patient table\nlet Patient = sequelize.define('patient', {\n bloodType: Sequelize.STRING\n});\n// Defines \"IS A\" relationship: [Patient] IS A [User]\nPatient.belongsTo(models.User, {\n foreignKey: {\n name: 'id',\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n foreignKeyConstraint: true\n})\n\n// Doctor table\nlet Doctor = sequelize.define('doctor', {\n registry: Sequelize.STRING\n});\n// Defines \"IS A\" relationship: [Doctor] IS A [User]\nDoctor.belongsTo(models.User, {\n foreignKey: {\n name: 'id',\n type: DataTypes.INTEGER,\n primaryKey: true\n },\n foreignKeyConstraint: true\n})\n```\n\nAnd this is my graphql schema:\n\n```\n// graphql.js\nimport resolver from 'graphql-sequelize';\nimport * as models from './models';\n\nlet userType = new GraphQLObjectType({\n name: 'User',\n fields: {\n id: { type: new GraphQLNonNull(GraphQLInt) },\n name: { type: GraphQLString }\n }\n});\n\nlet patientType = new GraphQLObjectType({\n name: 'Patient',\n fields: {\n id: { type: new GraphQLNonNull(GraphQLInt) },\n bloodType: { type: GraphQLString },\n user: {\n type: new GraphQLNonNull(userType),\n // IMPORTANT!\n // How can I call resolver if I don't have a assotiation property like Patient.User?\n resolve: resolver()\n }\n }\n});\n\n// [doctorType omitted]\n\nlet schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: {\n users: {\n type: userType,\n resolve: resolver(models.User)\n },\n patients: {\n type: patientType,\n resolve: resolver(models.Patient)\n }\n // [doctor field omitted]\n }\n })\n});\n```\n\nCalling the `resolver` method on the fields of the schema (`users` and `patients`) works fine, but my question is how to call resolver in the `patientType` to return its user since I don't have an association property.\n\nThanks.\n\n========================================\n\nCode:\n```js\n// models.js\n\n// User table\nlet User = sequelize.define('user', {\n    id: Sequelize.INTEGER\n    name: Sequelize.STRING\n});\n\n// Patient table\nlet Patient = sequelize.define('patient', {\n    bloodType: Sequelize.STRING\n});\n// Defines \"IS A\" relationship: [Patient] IS A [User]\nPatient.belongsTo(models.User, {\n    foreignKey: {\n      name: 'id',\n      type: DataTypes.INTEGER,\n      primaryKey: true\n    },\n    foreignKeyConstraint: true\n})\n\n// Doctor table\nlet Doctor = sequelize.define('doctor', {\n  registry: Sequelize.STRING\n});\n// Defines \"IS A\" relationship: [Doctor] IS A [User]\nDoctor.belongsTo(models.User, {\n    foreignKey: {\n      name: 'id',\n      type: DataTypes.INTEGER,\n      primaryKey: true\n    },\n    foreignKeyConstraint: true\n})\n```\n\n```js\n// graphql.js\nimport resolver from 'graphql-sequelize';\nimport * as models from './models';\n\nlet userType = new GraphQLObjectType({\n    name: 'User',\n    fields: {\n        id: { type: new GraphQLNonNull(GraphQLInt) },\n        name: { type: GraphQLString }\n    }\n});\n\nlet patientType = new GraphQLObjectType({\n    name: 'Patient',\n    fields: {\n        id: { type: new GraphQLNonNull(GraphQLInt) },\n        bloodType: { type: GraphQLString },\n        user: {\n            type: new GraphQLNonNull(userType),\n            // IMPORTANT!\n            // How can I call resolver if I don't have a assotiation property like Patient.User?\n            resolve: resolver()\n        }\n    }\n});\n\n// [doctorType omitted]\n\nlet schema = new GraphQLSchema({\n  query: new GraphQLObjectType({\n    name: 'Query',\n    fields: {\n        users: {\n            type: userType,\n            resolve: resolver(models.User)\n        },\n        patients: {\n            type: patientType,\n            resolve: resolver(models.Patient)\n        }\n        // [doctor field omitted]\n    }\n  })\n});\n```\n\n```text\ngraphql\n```\n\n```text\nsequelize\n```\n\n```text\ngraphql-sequelize\n```\n\n```text\nresolver\n```\n\n```text\nusers\n```\n\n```text\npatients\n```\n\n```text\npatientType\n```\n\n```text\nmodels.Patient.User = Patient.belongsTo(models.User, {\n    foreignKey: {\n      name: 'id',\n      type: DataTypes.INTEGER,\n      primaryKey: true\n    },\n    foreignKeyConstraint: true\n})\n```\n\n```text\nimport * as models from '../path/models'\n\nlet patientType = new GraphQLObjectType({\n    name: 'Patient',\n    fields: {\n        id: { type: new GraphQLNonNull(GraphQLInt) },\n        bloodType: { type: GraphQLString },\n        user: {\n            type: new GraphQLNonNull(userType),\n            resolve: resolver(models.default.Patient.User)\n            // alternatively you could the following as sequelize always stores assotiations in associations\n            // resolve: resolver(models.default.Patient.associations.User)\n        }\n    }\n});\n```\n\n```text\nbelongsTo\n```\n\n```text\nresolve\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":252,"estimatedTokens":1245}}1095{"id":"stack-55955192","source":"stackoverflow","questionId":55955192,"title":"Sequelize : Only returning one of many result for a nested include","tags":["node.js","sequelize.js"],"text":"Title: Sequelize : Only returning one of many result for a nested include\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have 3 tables: \n\n- Job post\n\n- recruitment phase\n\n- Interview slot\n\nTheir association is,\njobpost **has many** recruitment phases and \nrecruitment phase **has many** interview slots\n\nI am able to get all the recruitment phases of a job post by including the recruitmentphase association and group clause. \n\n```\nconst jobPosts = await JobPost.unscoped().findAll({\n where,\n include: [\n {\n model: db.RecruitmentPhase,\n include: [{\n model: db.InterviewSlot,\n },\n\n ],\n group: ['RecruitmentPhases.id'],\n });\n```\n\nBut I am only getting one interview slot for the recruitment phase, event though there are **many** interviewslots for that recruitment phase.\n\nI tried to do group clause inside include. \n\n```\nconst jobPosts = await JobPost.unscoped().findAll({\n where,\n include: [\n {\n model: db.RecruitmentPhase,\n group: ['InterviewSlots.id'],\n include: [{\n model: db.InterviewSlot,\n },\n\n ],\n group: ['RecruitmentPhases.id'],\n });\n```\n\nbut it also giving only **one** interview slot\n\n**EDIT**\n\njobpost model :\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const jobPost = sequelize.define('JobPost', {\n id: {\n type: DataTypes.BIGINT,\n allowNull: true,\n autoIncrement: true,\n primaryKey: true,\n },\n jobTitle: {\n type: DataTypes.STRING(150),\n allowNull: true,\n },\n\n }, {\n timestamps: true,\n defaultScope: {\n attributes: { exclude: ['createdAt', 'updatedAt'] },\n },\n });\n jobPost.associate = (models) => {\n jobPost.hasMany(models.RecruitmentPhase);\n };\n return jobPost;\n};\n```\n\nRecruitment phase model :\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const recruitmentPhase = sequelize.define('RecruitmentPhase', {\n id: {\n type: DataTypes.BIGINT,\n allowNull: true,\n autoIncrement: true,\n primaryKey: true,\n },\n\n phaseName: {\n type: DataTypes.STRING(200),\n allowNull: true,\n },\n\n }, {\n timestamps: true,\n });\n recruitmentPhase.associate = (models) => {\n recruitmentPhase.belongsTo(models.JobPost);\n recruitmentPhase.hasMany(models.InterviewSlot);\n };\n return recruitmentPhase;\n};\n```\n\nInterview slot model : \n\n```\nmodule.exports = (sequelize, DataTypes) => {\n const interviewSlot = sequelize.define('InterviewSlot', {\n id: {\n type: DataTypes.BIGINT,\n allowNull: true,\n autoIncrement: true,\n primaryKey: true,\n },\n interviewDate: {\n type: DataTypes.DATE,\n allowNull: true,\n },\n });\n interviewSlot.associate = (models) => {\n interviewSlot.belongsTo(models.RecruitmentPhase);\n };\n return interviewSlot;\n};\n```\n\n========================================\n\nTop Answer:\nRemove `group: ['RecruitmentPhases.id'],` in order to see the details of InterviewSlots. As is, you're seeing a summary of interview slots...\n\n========================================\n\nCode:\n```text\nconst jobPosts = await JobPost.unscoped().findAll({\n            where,\n            include: [\n            {\n                model: db.RecruitmentPhase,\n                include: [{\n                    model: db.InterviewSlot,\n                },\n\n            ],\n            group: ['RecruitmentPhases.id'],\n        });\n```\n\n```text\nconst jobPosts = await JobPost.unscoped().findAll({\n                where,\n                include: [\n                {\n                    model: db.RecruitmentPhase,\n                    group: ['InterviewSlots.id'],\n                    include: [{\n                        model: db.InterviewSlot,\n                    },\n\n                ],\n                group: ['RecruitmentPhases.id'],\n            });\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const jobPost = sequelize.define('JobPost', {\n        id: {\n            type: DataTypes.BIGINT,\n            allowNull: true,\n            autoIncrement: true,\n            primaryKey: true,\n        },\n        jobTitle: {\n            type: DataTypes.STRING(150),\n            allowNull: true,\n        },\n\n    }, {\n        timestamps: true,\n        defaultScope: {\n            attributes: { exclude: ['createdAt', 'updatedAt'] },\n        },\n    });\n    jobPost.associate = (models) => {\n        jobPost.hasMany(models.RecruitmentPhase);\n    };\n    return jobPost;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const recruitmentPhase = sequelize.define('RecruitmentPhase', {\n        id: {\n            type: DataTypes.BIGINT,\n            allowNull: true,\n            autoIncrement: true,\n            primaryKey: true,\n        },\n\n        phaseName: {\n            type: DataTypes.STRING(200),\n            allowNull: true,\n        },\n\n    }, {\n        timestamps: true,\n    });\n    recruitmentPhase.associate = (models) => {\n        recruitmentPhase.belongsTo(models.JobPost);\n        recruitmentPhase.hasMany(models.InterviewSlot);\n    };\n    return recruitmentPhase;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n    const interviewSlot = sequelize.define('InterviewSlot', {\n        id: {\n            type: DataTypes.BIGINT,\n            allowNull: true,\n            autoIncrement: true,\n            primaryKey: true,\n        },\n        interviewDate: {\n            type: DataTypes.DATE,\n            allowNull: true,\n        },\n    });\n    interviewSlot.associate = (models) => {\n        interviewSlot.belongsTo(models.RecruitmentPhase);\n    };\n    return interviewSlot;\n};\n```\n\n```text\ngroup: ['RecruitmentPhases.id', 'RecruitmentPhases->InterviewSlots.id'],\n```\n\n```text\ngroup: ['RecruitmentPhases.id'],\n```\n\n```text\nconst rec = await db.RecruitmentPhase.findAll({\n    include:[{model: db.JobPost, where:{ id:job_id }}, {model: db.InterviewSlot}]\n});\nres.json(rec)\n//Expected JSON Data\n{\n  \"RecruitmentPhase\":[\n    {\n      \"id\":1,\n      \"phaseName\":\"Phase 1\",\n      \"JobPosts\": {\n        \"id\":1,\n        \"jobTitle\":\"XYZ\"\n      },\n      \"InterviewSlots\":[\n        {//inteview slot #1 data},\n        {//interview slot #2 data}\n      ]\n    },\n    {\n      \"id\":2,\n      \"phaseName\":\"Phase 2\",\n      \"JobPosts\": {\n        \"id\":1,\n        \"jobTitle\":\"XYZ\"\n      },\n      \"InterviewSlots\":[\n        {//inteview slot #1 data},\n        {//interview slot #2 data}\n      ]\n    }\n  ]\n}\n```\n\n```text\nJobPost\n```\n\n```text\nRecruitmentPhase\n```\n\n```text\nRecruitmentPhases\n```\n\n```text\nInterviewSlots\n```\n\n```text\nRecruitmentPhase\n```\n\n========================================\n\nComments:\n- Post your models to further analyze them\n- if I remove ['RecruitmentPhases.id'] i wont be getting multiple recruitment phases.\n- Can you display the data you expect to see as the outcome of your query?\n- I've tried this but I got something like `column \\\"JobPost.id\\\" must appear in the GROUP BY clause or be used in an aggregate function`\n- Then I tried something like `group: ['JobPost.id', 'RecruitmentPhases.id', 'RecruitmentPhases->InterviewSlots.id']`, that's at the root object, but didn't work, still getting only 1 row for InterviewSlot\n- i have jobpost id. From where I need to get all the recruitmentphases for that jobpost. And for each recruitment phase, I need to get all of the recruitmentphases\n- A downvote? You just have to add a `where` clause to the query. Updated the answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":325,"estimatedTokens":1773}}1096{"id":"stack-43504657","source":"stackoverflow","questionId":43504657,"title":"What is used in Nodejs - Sequelize for removing spaces when insert in DB using","tags":["node.js","sequelize.js"],"text":"Title: What is used in Nodejs - Sequelize for removing spaces when insert in DB using\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've used `Trim()` method to remove spaces from data before insert in DB. I'm using Nodejs and Sequelize. But is there something that is used to do that and for example if I have array, to pass this array, not to loop through all elements to strip spaces?\nThanks.\n\n========================================\n\nCode:\n```text\nTrim()\n```\n\n```text\nDROP TABLE IF EXISTS tmp;\n CREATE TABLE tmp ('txt' varchar(50));\n DROP TRIGGER IF EXISTS insert_tmp;\n CREATE TRIGGER insert_tmp BEFORE INSERT ON tmp FOR EACH ROW SET NEW.txt=TRIM(NEW.txt);\n INSERT INTO tmp VALUES (\"        abc   \"), (\"efg      \");\n SELECT txt, LENGTH(txt) FROM tmp;\n```\n\n========================================\n\nComments:\n- perhaps your specific db can help with this at the sql level. stackoverflow.com/questions/1571180/auto-trim-database-entri&zwnj;&#8203;es\n- I'm using Mysql. I'm not sure if that will work.\n- Thank you. I've just tested it in Phpmyadmin and it is working. I only used query to create trigger cause I have existing table.","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":30,"estimatedTokens":288}}1097{"id":"stack-32062555","source":"stackoverflow","questionId":32062555,"title":"Sequelize.js updateAttributes does not save partial data","tags":["node.js","postgresql","sequelize.js"],"text":"Title: Sequelize.js updateAttributes does not save partial data\nTags: node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nWhen updating data partially, data does not persist. For example, I call the following (where data is an object):\n\n```\naccount.updateAttributes(data).then(function(updated) {\n res.send(updated);\n return next();\n\n})['catch'](function(err) {\n log.error(err);\n return next(new restify.InternalError(err.message));\n});\n```\n\n========================================\n\nTop Answer:\nI guess you want to pass updated data to next middleware. But you used `res.send(updated)`. It terminates middleware and return the response.\n\nYou can use to pass the updated data with the following;\n\n```\naccount.updateAttributes(data).then(function(updated) {\n req.updatedAccount = updated;\n return next();\n})['catch'](function(err) {\n log.error(err);\n return next(new restify.InternalError(err.message));\n});\n```\n\nSo you can attach the updated data to your request object and send with it to next middleware. And you can use the data in next middleware with `req.updatedAccount`.\n\nI hope it works.\n\n========================================\n\nCode:\n```text\naccount.updateAttributes(data).then(function(updated) {\n        res.send(updated);\n        return next();\n\n})['catch'](function(err) {\n       log.error(err);\n           return next(new restify.InternalError(err.message));\n});\n```\n\n```text\nbeforeValidate\n```\n\n```text\naccount.updateAttributes(data).then(function(updated) {\n  req.updatedAccount = updated;\n  return next();\n})['catch'](function(err) {\n  log.error(err);\n  return next(new restify.InternalError(err.message));\n});\n```\n\n```text\nres.send(updated)\n```\n\n```text\nreq.updatedAccount\n```\n\n========================================\n\nComments:\n- github.com/sequelize/sequelize/issues/4346","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":79,"estimatedTokens":453}}1098{"id":"stack-43070293","source":"stackoverflow","questionId":43070293,"title":"return value from promise Sequelize","tags":["node.js","sequelize.js"],"text":"Title: return value from promise Sequelize\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm working with Sequelize, but I'm having trouble to get my requisition's return.\n\nThis is what I got so far:\n\n```\nvar m = Messagem.findAll({}).then((mensagens)=>{\nconsole.log(mensagens); // i have a reponse :D\nreturn mensagens;\n});\n\nconsole.log(m);\n\nPromise {\n_bitField: 2097152,\n_fulfillmentHandler0: undefined,\n_rejectionHandler0: undefined,\n_promise0: undefined,\n_receiver0: undefined,\n_boundTo: Messagem }\n```\n\nWhat am I doing wrong?\n\nAny help is appreciated!\n\n========================================\n\nCode:\n```text\nvar m = Messagem.findAll({}).then((mensagens)=>{\nconsole.log(mensagens); //  i have a reponse :D\nreturn mensagens;\n});\n\nconsole.log(m);\n\nPromise {\n_bitField: 2097152,\n_fulfillmentHandler0: undefined,\n_rejectionHandler0: undefined,\n_promise0: undefined,\n_receiver0: undefined,\n_boundTo: Messagem }\n```\n\n```text\nconsole.log(m);\n```\n\n```text\nm.then(console.log);\n```\n\n```text\nconsole.log(await m);\n```\n\n```text\n.then()\n```\n\n```text\nm\n```\n\n```text\nasync\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":73,"estimatedTokens":271}}1099{"id":"stack-32013871","source":"stackoverflow","questionId":32013871,"title":"Sequelize: effects of \"unique\" property in model definition","tags":["node.js","postgresql","orm","sequelize.js"],"text":"Title: Sequelize: effects of \"unique\" property in model definition\nTags: node.js, postgresql, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize v3.5.1 with PostgreSQL v9.4.4 on a NodeJS server project.\n\nIn the model definition, it's not entirely clear to me what are the effects of adding the option `unique: true` to a property.\n\nLet's take this code for example:\n\n```\nsequelize.define('User', {\n email: {\n type: Sequelize.STRING,\n unique: true\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false\n }\n});\n```\n\nDoes this mean that PostgreSQL will build a unique index on `email`? So, is it just a shorthand method for this?\n\n```\nsequelize.define('User', {\n email: {\n type: Sequelize.STRING,\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false\n }\n}, {\n indexes: [\n {\n unique: true,\n fields: ['email']\n }\n ]\n});\n```\n\nIf so, will such index speed up table queries for email, or just ensure uniqueness?\n\nThanks!\n\n========================================\n\nCode:\n```text\nsequelize.define('User', {\n  email: {\n    type: Sequelize.STRING,\n    unique: true\n  },\n  password: {\n    type: Sequelize.STRING,\n    allowNull: false\n  }\n});\n```\n\n```text\nsequelize.define('User', {\n  email: {\n    type: Sequelize.STRING,\n  },\n  password: {\n    type: Sequelize.STRING,\n    allowNull: false\n  }\n}, {\n  indexes: [\n    {\n      unique: true,\n      fields: ['email']\n    }\n  ]\n});\n```\n\n```text\nunique: true\n```\n\n```text\nemail\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":91,"estimatedTokens":361}}1100{"id":"stack-77830144","source":"stackoverflow","questionId":77830144,"title":"How to utilise Postgres RLS for Application level users?","tags":["node.js","postgresql","sequelize.js","supabase"],"text":"Title: How to utilise Postgres RLS for Application level users?\nTags: node.js, postgresql, sequelize.js, supabase\nSource: Stack Overflow\n\nQuestion:\nI want to structure an application with scalability in mind and use postgres RLS for user authorization\n\n- I have a Node JS & Express server\n\n- I have a sequelize connection to postgres instance with connection pool set up\n\n```\nconst sequelize = new Sequelize({\n database: 'your_database',\n username: 'your_username',\n password: 'your_password',\n host: 'your_host',\n dialect: 'postgres',\n pool: {\n max: 10,\n min: 0,\n acquire: 30000,\n idle: 10000,\n },\n});\nexport default sequelizeClient;\n```\n\n- For my APIs I have middleware that reads JWT\n\n- After parsing this JWT, I get user role and user ID\n\n- Now to utilise Postgres RLS, I'm thinking of doing a\n\n```\nawait sequelize.query(`SET ROLE ${userRole}`);\nawait sequelize.query('SET LOCAL jwt.claims.userId = :userId', {\n replacements: { userId },\n });\n```\n\nwhere userId and userRole comes from JWT parsed in the middleware\n6. Then going ahead with executing all the SQL queries for that API and this sql role and local variable will be used in the RLS policy to authorize the operation or reject it\n\nExample code for one such API:\n\n```\nasync function getUserData(userId, userRole) {\n try {\n await sequelize.query(`SET ROLE ${userRole}`);\n await sequelize.query('SET LOCAL jwt.claims.userId = :userId', {\n replacements: { userId },\n });\n\n // Perform your Sequelize operations\n const userData = await User.findByPk(userId, { raw: true });\n return userData;\n } catch (err) {\n console.log('ERROR: ', err);\n }\n}\n```\n\nNow my questions are as follows:\n\nAre there any chances of the SET LOCAL variable interfering with two different user's\nsimultaneous API calls?\nWill sequelize ensure that subsequent queries (Set local, role and user find query)\nwill be executed in the same connection from the connection pool?\n\n- Can two distinct API queries from distinct APIs endup using the same connection while one API is processing?\n\n- Does Sequelize asks for a connection from connection pool for every individual queries?\n\nI know supabase does similar stuff, but I want my own backend server, but if there is a way to utilise sequelize with supervisor provided by supabase for similar functionality please suggest that too.\n\nAlso if there is a better and more robust way to handle this please suggest it. Thank you\n\n========================================\n\nCode:\n```text\nconst sequelize = new Sequelize({\n database: 'your_database',\n username: 'your_username',\n password: 'your_password',\n host: 'your_host',\n dialect: 'postgres',\n pool: {\n   max: 10,\n   min: 0,\n   acquire: 30000,\n   idle: 10000,\n },\n});\nexport default sequelizeClient;\n```\n\n```text\nawait sequelize.query(`SET ROLE ${userRole}`);\nawait sequelize.query('SET LOCAL jwt.claims.userId = :userId', {\n      replacements: { userId },\n    });\n```\n\n```text\nasync function getUserData(userId, userRole) {\n  try {\n    await sequelize.query(`SET ROLE ${userRole}`);\n    await sequelize.query('SET LOCAL jwt.claims.userId = :userId', {\n      replacements: { userId },\n    });\n\n    // Perform your Sequelize operations\n    const userData = await User.findByPk(userId, { raw: true });\n    return userData;\n  } catch (err) {\n    console.log('ERROR: ', err);\n }\n}\n```\n\n========================================\n\nComments:\n- I have removed the (general) tag since this is a very product specific question.\n- \"*Are there any chances of the SET LOCAL variable interfering with two different user's simultaneous API calls?*\" - yes. You **must** use a dedicated connection/client for each user (i.e. for each API call), and ideally a separate transaction.","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":127,"estimatedTokens":921}}1101{"id":"stack-73200103","source":"stackoverflow","questionId":73200103,"title":"Find ONLY soft deleted rows with Sequelize","tags":["sqlite","sequelize.js"],"text":"Title: Find ONLY soft deleted rows with Sequelize\nTags: sqlite, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm running a database on sequelize and sqlite and I use soft-deletes to basically archive the data.\n\nI'm aware that with `.findAll(paranoid: false)` I can find all rows including the soft deleted ones. However I would like to find ONLY the soft-deleted ones.\n\nIs there any way to achieve this? Or is there perhaps a way to do \"set operations\" with two data results, like finding the relative complement of one in the other?\n\n========================================\n\nCode:\n```text\n.findAll(paranoid: false)\n```\n\n```text\ndeletedAt: { [Op.not]: null }\n```\n\n```text\nconst projects = await db.Project.findAndCountAll({\n        paranoid: false,\n        order: [['createdAt', 'DESC']],\n        where: { employer_id: null, deletedAt: { [Op.not]: null } },\n        limit: parseInt(size),\n        offset: (page - 1) * parseInt(size),\n});\n```\n\n========================================\n\nComments:\n- soft delete is having a `deleted_at` (column name can be different for you) updated with a datetime value when the data is deleted. So, you can query with where option, `deleted_at` is not null.\n- Thank you very much. This does what I needed. In my case it looked like this: `model.findAll({ where: {deletedAt: {[Op.not]: null}}, paranoid: false });` Maybe you wanna post this as an answer to the question, so I can accept your answer.","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":37,"estimatedTokens":359}}1102{"id":"stack-29414740","source":"stackoverflow","questionId":29414740,"title":"Sequelize associations: set[Models] adds new models instead of associating existing ones","tags":["javascript","node.js","sequelize.js"],"text":"Title: Sequelize associations: set[Models] adds new models instead of associating existing ones\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm using Sequelize and I'm trying to create associations between two different tables, where `x.belongsTo(y)` and `y.hasMany(x)`. After having done `x.setY(yInstance)` and `y.getXs()` it seems only new rows have been added to x and no associations to my already created instances have been created.\n\n```\nvar Promise = require(\"bluebird\"),\n Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize(\"Test\", \"postgres\", \"password\", {\n host: \"localhost\",\n dialect: \"postgres\",\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n }\n});\nvar Schedule = sequelize.define(\"Schedule\", {\n website: {\n type: Sequelize.STRING\n }\n});\nvar SiteConfig = sequelize.define(\"SiteConfig\", {\n systemType: {\n type: Sequelize.STRING\n }\n});\nvar Selector = sequelize.define(\"Selector\", {\n type: {\n type: Sequelize.STRING\n },\n content: {\n type: Sequelize.STRING\n }\n});\nSelector.belongsTo(SiteConfig);\nSiteConfig.hasMany(Selector);\n\nvar testSchedule = {\n website: \"google.com\"\n};\nvar testSiteConfig = {\n systemType: \"one\"\n};\nvar testSelectors = [\n {type: \"foo\", content: \"foo\"},\n {type: \"foo\", content: \"bar\"}\n];\n\nPromise.all([\n Schedule.sync({force: true}),\n SiteConfig.sync({force: true}),\n Selector.sync({force: true})\n]).then(function () {\n return Promise.all([\n Schedule.create(testSchedule),\n SiteConfig.create(testSiteConfig),\n Selector.bulkCreate(testSelectors)\n ]);\n}).spread(function (schedule, siteConfig, selectors) {\n return Promise.map(selectors, function (selector) {\n return selector.setSiteConfig(siteConfig);\n }).then(function (array) {\n return siteConfig.getSelectors();\n }).each(function (selector) {\n // This is where I expect \"foo\" and \"bar\" but instead get null\n console.log(\"Selector content:\", selector.get(\"content\"));\n });\n});\n```\n\nI'd expect this code to add a `SiteConfigId` column to my `Selectors` so that my `siteConfig.getSelectors()` would return my testSelectors. How can I achieve this?\n\n========================================\n\nCode:\n```text\nvar Promise = require(\"bluebird\"),\n    Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize(\"Test\", \"postgres\", \"password\", {\n    host: \"localhost\",\n    dialect: \"postgres\",\n    pool: {\n        max: 5,\n        min: 0,\n        idle: 10000\n    }\n});\nvar Schedule = sequelize.define(\"Schedule\", {\n    website: {\n        type: Sequelize.STRING\n    }\n});\nvar SiteConfig = sequelize.define(\"SiteConfig\", {\n    systemType: {\n        type: Sequelize.STRING\n    }\n});\nvar Selector = sequelize.define(\"Selector\", {\n    type: {\n        type: Sequelize.STRING\n    },\n    content: {\n        type: Sequelize.STRING\n    }\n});\nSelector.belongsTo(SiteConfig);\nSiteConfig.hasMany(Selector);\n\nvar testSchedule = {\n    website: \"google.com\"\n};\nvar testSiteConfig = {\n    systemType: \"one\"\n};\nvar testSelectors = [\n    {type: \"foo\", content: \"foo\"},\n    {type: \"foo\", content: \"bar\"}\n];\n\n\n\nPromise.all([\n    Schedule.sync({force: true}),\n    SiteConfig.sync({force: true}),\n    Selector.sync({force: true})\n]).then(function () {\n    return Promise.all([\n        Schedule.create(testSchedule),\n        SiteConfig.create(testSiteConfig),\n        Selector.bulkCreate(testSelectors)\n    ]);\n}).spread(function (schedule, siteConfig, selectors) {\n    return Promise.map(selectors, function (selector) {\n        return selector.setSiteConfig(siteConfig);\n    }).then(function (array) {\n        return siteConfig.getSelectors();\n    }).each(function (selector) {\n        // This is where I expect \"foo\" and \"bar\" but instead get null\n        console.log(\"Selector content:\", selector.get(\"content\"));\n    });\n});\n```\n\n```text\nx.belongsTo(y)\n```\n\n```text\ny.hasMany(x)\n```\n\n```text\nx.setY(yInstance)\n```\n\n```text\ny.getXs()\n```\n\n```text\nSiteConfigId\n```\n\n```text\nSelectors\n```\n\n```text\nsiteConfig.getSelectors()\n```\n\n```text\ntest=# select * from \"Selectors\";\n id | type | content |         createdAt          |         updatedAt          | SiteConfigId \n----+------+---------+----------------------------+----------------------------+--------------\n  1 | foo  | foo     | 2015-04-05 20:38:55.282-07 | 2015-04-05 20:38:55.282-07 |             \n  2 | foo  | bar     | 2015-04-05 20:38:55.282-07 | 2015-04-05 20:38:55.282-07 |             \n  3 |      |         | 2015-04-05 20:38:55.282-07 | 2015-04-05 20:38:55.311-07 |            1\n  4 |      |         | 2015-04-05 20:38:55.282-07 | 2015-04-05 20:38:55.31-07  |            1\n```\n\n```text\nvar BPromise = require(\"bluebird\");\nvar Sequelize = require(\"sequelize\");\n\nvar sequelize = new Sequelize('test', 'root', 'password', {\n  host: \"localhost\",\n  dialect: \"postgres\",\n  pool: {\n    max: 5,\n    min: 0,\n    idle: 10000\n  }\n});\n\nvar Schedule = sequelize.define(\"Schedule\", {\n  website: {\n    type: Sequelize.STRING\n  }\n});\n\nvar SiteConfig = sequelize.define(\"SiteConfig\", {\n  systemType: {\n    type: Sequelize.STRING\n  }\n});\n\nvar Selector = sequelize.define(\"Selector\", {\n  type: {\n    type: Sequelize.STRING\n  },\n  content: {\n    type: Sequelize.STRING\n  }\n});\n\nSelector.belongsTo(SiteConfig);\nSiteConfig.hasMany(Selector);\n\nvar testSchedule = {\n  website: \"google.com\"\n};\nvar testSiteConfig = {\n  systemType: \"one\"\n};\nvar testSelectors = [\n  {type: \"foo\", content: \"foo\"},\n  {type: \"foo\", content: \"bar\"}\n];\n\nsequelize.sync({ force: true })\n.then(function(result) {\n  return BPromise.all([\n    Schedule.create(testSchedule),\n    SiteConfig.create(testSiteConfig),\n    Selector.bulkCreate(testSelectors, { returning: true })\n  ]);\n})\n.then(function(result) {\n  var siteConfig = result[1];\n  var selectors = result[2];\n\nreturn siteConfig.addSelectors(selectors);\n})\n.then(function (result) {\n  return this.siteConfig.getSelectors();\n})\n.each(function(result) {\n  console.log('boomshakalaka:', result.get());\n})\n.catch(function(error) {\n  console.log(error);\n});\n```\n\n```text\nsetSiteConfig()\n```\n\n```text\nsetSiteConfig\n```\n\n```text\naddSelectors\n```\n\n```text\nPromise\n```\n\n```text\nBPromise\n```\n\n```text\nPromise\n```\n\n```text\nSequelize.Promise\n```\n\n```text\nspread\n```\n\n```text\nPromise.all\n```\n\n```text\n.spread()\n```\n\n========================================\n\nComments:\n- I should also add that I use sequelize.sync() instead of syncing each individual model.\n- Thanks, your code worked just as expected! I realized though, that the primary problem with my code was that I was using `bulkCreate` for the testSelectors instead of `create`, which returned the inserted rows without ID's. From the docs: docs.sequelizejs.com/en/latest/docs/instances/&hellip; It seems your code could have the same problem (although it doesn't in practice), can you help me show why it works or maybe edit your answer to iterate over testSelectors (instead of bulkCreate) and I'll happily mark it as accepted :)","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":305,"estimatedTokens":1709}}1103{"id":"stack-40516529","source":"stackoverflow","questionId":40516529,"title":"Underscore gets removed","tags":["mysql","node.js","sequelize.js"],"text":"Title: Underscore gets removed\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSequelize removes the underscore in my foreign key.\n\n`Role.belongsToMany(User, { foreignKey: 'user_id', through: UserRole });`\n\nResults in this:\n\n`Unknown column 'UserRole.UserId' in 'field list'`\n\nbecause the column is named user_id, and not UserId.\n\nEven with the `underscore: true` option set, it does that.\n\nIs there a way of solving this, it is driving me nuts because, I don't know if I am doing it wrong or sequelize is.\n\nUserRole.js:\n\n```\nmodule.exports = {\n attributes: {\n roleId: {\n type: Sequelize.INTEGER(11),\n field: 'role_id',\n primaryKey: true\n },\n userId: {\n type: Sequelize.INTEGER(11),\n field: 'user_id',\n primaryKey: true\n }\n },\n associations: function() {\n UserRole.belongsTo(User, { foreignKey: 'user_id' });\n UserRole.hasOne(Role, { foreignKey: 'id' });\n },\n options: {\n tableName: 'user_roles',\n timestamps: false,\n classMethods: {},\n instanceMethods: {},\n hooks: {}\n }\n}\n```\n\nRole.js\n\n```\nmodule.exports = {\n attributes: {\n id: {\n type: Sequelize.INTEGER(11),\n primaryKey: true\n },\n name: {\n type: Sequelize.STRING(50),\n },\n description: {\n type: Sequelize.STRING(50),\n },\n },\n associations: function() {\n Role.belongsToMany(User, { foreignKey: 'user_id', through: UserRole });\n },\n options: {\n tableName: 'roles',\n timestamps: false,\n classMethods: {},\n instanceMethods: {},\n hooks: {}\n }\n}\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n  attributes: {\n    roleId: {\n      type: Sequelize.INTEGER(11),\n      field: 'role_id',\n      primaryKey: true\n    },\n    userId: {\n      type: Sequelize.INTEGER(11),\n      field: 'user_id',\n      primaryKey: true\n    }\n  },\n  associations: function() {\n      UserRole.belongsTo(User, { foreignKey: 'user_id' });\n      UserRole.hasOne(Role, { foreignKey: 'id' });\n  },\n  options: {\n    tableName: 'user_roles',\n    timestamps: false,\n    classMethods: {},\n    instanceMethods: {},\n    hooks: {}\n  }\n}\n```\n\n```text\nmodule.exports = {\n  attributes: {\n    id: {\n      type: Sequelize.INTEGER(11),\n      primaryKey: true\n    },\n    name: {\n      type: Sequelize.STRING(50),\n    },\n    description: {\n      type: Sequelize.STRING(50),\n    },\n  },\n  associations: function() {\n    Role.belongsToMany(User, { foreignKey: 'user_id', through: UserRole });\n  },\n  options: {\n    tableName: 'roles',\n    timestamps: false,\n    classMethods: {},\n    instanceMethods: {},\n    hooks: {}\n  }\n}\n```\n\n```text\nRole.belongsToMany(User, { foreignKey: 'user_id', through: UserRole });\n```\n\n```text\nUnknown column 'UserRole.UserId' in 'field list'\n```\n\n```text\nunderscore: true\n```\n\n```text\nunderscore\n```\n\n========================================\n\nComments:\n- Are you sure you've tried with the `underscore` option turned on? I don't see that in your code here and it's important.\n- @tadman I should probably sleep, forgot to add the `underscored` option to the User model. Thanks a lot!\n- Happens to the best of us. Glad you got it!","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":158,"estimatedTokens":753}}1104{"id":"stack-71935072","source":"stackoverflow","questionId":71935072,"title":"how to set order on include aggregate function alias in sequelize?","tags":["node.js","sequelize.js"],"text":"Title: how to set order on include aggregate function alias in sequelize?\nTags: node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nBelow is my code\n\n```\nexport async function getMany(page: number, recordsPerPage: number, condition: any = {}, order: any, attributes: string[] = [], other: object = {}) {\n try {\n let { count, rows }: any = await User.findAndCountAll({\n attributes: {\n include: [[sequelize.literal('(SELECT SUM(reputation) FROM scores where scores.user_id = User.id)'), 'reputation']],\n exclude: attributes,\n },\n where: condition,\n distinct: true,\n include: [\n {\n model: Skill,\n as: 'skills',\n attributes: ['skill'],\n through: { attributes: [] },\n },\n ],\n order: order,\n offset: page,\n limit: recordsPerPage,\n ...other,\n logging: console.log,\n });\n return { count, rows };\n } catch (e) {\n return false;\n }\n}\n```\n\nI want to set order by reputation field which is alias of sum function column. i want my data in highest to lowest reputation.\n\n========================================\n\nCode:\n```text\nexport async function getMany(page: number, recordsPerPage: number, condition: any = {}, order: any, attributes: string[] = [], other: object = {}) {\n    try {\n        let { count, rows }: any = await User.findAndCountAll({\n            attributes: {\n                include: [[sequelize.literal('(SELECT SUM(reputation) FROM scores where scores.user_id = User.id)'), 'reputation']],\n                exclude: attributes,\n            },\n            where: condition,\n            distinct: true,\n            include: [\n                {\n                    model: Skill,\n                    as: 'skills',\n                    attributes: ['skill'],\n                    through: { attributes: [] },\n                },\n            ],\n            order: order,\n            offset: page,\n            limit: recordsPerPage,\n            ...other,\n            logging: console.log,\n        });\n        return { count, rows };\n    } catch (e) {\n        return false;\n    }\n}\n```\n\n```text\norder: [[sequelize.literal('table alias name goes here'), 'DESC']]\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":77,"estimatedTokens":516}}1105{"id":"stack-67259916","source":"stackoverflow","questionId":67259916,"title":"How do I update a foreign key (belongsTo) in Sequelize","tags":["javascript","mysql","model","sequelize.js","belongs-to"],"text":"Title: How do I update a foreign key (belongsTo) in Sequelize\nTags: javascript, mysql, model, sequelize.js, belongs-to\nSource: Stack Overflow\n\nQuestion:\nI have the following model:\n\n```\n'use strict';\nconst {Model} = require('sequelize');\nmodule.exports = (sequelize, DataTypes) => {\n class Key extends Model {\n static associate(models) {\n Key.belongsTo(models.User, {\n foreignKey: 'userId',\n onDelete: 'CASCADE'\n });\n }\n };\n Key.init({\n keyType: DataTypes.STRING,\n key: DataTypes.JSON\n }, {\n sequelize,\n modelName: 'Key',\n });\n return Key;\n};\n```\n\nI then try to create a row, after receiving `userId`, `keyType` and `key`:\n\n```\n...\nconst Key = KeyModel(sequelize, Sequelize);\nconst createKey = async (userid, keyType, key) => {\n const result = await Key.create({userId, keyType, key});\n return result;\n}\n```\n\nThe row gets created successfully in the DB, and i get back an ID (the `createdAt` and `updatedAt` are updated as well), but the `userId` is null.\n\nHow should I pass it to the `create` method so the value gets to the DB? Am I missing something in the model?\n\nPS: the DB is MySQL 8.\n\n========================================\n\nCode:\n```text\n'use strict';\nconst {Model} = require('sequelize');\nmodule.exports = (sequelize, DataTypes) => {\n  class Key extends Model {\n    static associate(models) {\n      Key.belongsTo(models.User, {\n        foreignKey: 'userId',\n        onDelete: 'CASCADE'\n      });\n    }\n  };\n  Key.init({\n    keyType: DataTypes.STRING,\n    key: DataTypes.JSON\n  }, {\n    sequelize,\n    modelName: 'Key',\n  });\n  return Key;\n};\n```\n\n```text\n...\nconst Key = KeyModel(sequelize, Sequelize);\nconst createKey = async (userid, keyType, key) => {\n  const result = await Key.create({userId, keyType, key});\n  return result;\n}\n```\n\n```text\nuserId\n```\n\n```text\nkeyType\n```\n\n```text\nkey\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nuserId\n```\n\n```text\ncreate\n```\n\n```text\n'use strict';\nconst {Model} = require('sequelize');\nmodule.exports = (sequelize, DataTypes) => {\n  class Key extends Model {\n    static associate(models) {\n      Key.belongsTo(models.User, {\n        foreignKey: 'keyId',\n        targetKey: 'userId'\n        onDelete: 'CASCADE'\n      });\n    }\n  };\n  Key.init({\n    keyId: DataTypes.STRING,\n    keyType: DataTypes.STRING,\n    key: DataTypes.JSON\n  }, {\n    sequelize,\n    modelName: 'Key',\n  });\n  return Key;\n};\n\nconst Key = KeyModel(sequelize, Sequelize);\nconst createKey = async (userId, keyType, key) => {\n  const result = await Key.create({keyId: userId, keyType, key});\n  return result;\n}\n```\n\n========================================\n\nComments:\n- Are you saying I should add the foreign key to the model explicitly? That negates the need for the association. The migration, that was created automatically, already has a userId field defined.\n- My thought is, that it should be a foreignkey - column at key table and a targetkey - column at user table. So i added a column keyId to key model.\n- Upon further research, it looks like I may need to explicitly add the foreign key field to my model, so I'll mark your answer correct. I'm not really thrilled with it, but it's time to move on. Thanks for taking the time to answer!","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":147,"estimatedTokens":796}}1106{"id":"stack-45704458","source":"stackoverflow","questionId":45704458,"title":"Sequelize: Modify output of date timestamp using Getters","tags":["javascript","sql","node.js","postgresql","sequelize.js"],"text":"Title: Sequelize: Modify output of date timestamp using Getters\nTags: javascript, sql, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI need to convert my `signup_at` timestamp to a certain format each time it's selected from the database.\n\nI want to use a getter for this, but it doesn't appear to be returning the modified data. It continues to return the same date object stored in the database.\n\n```\nvar moment = require(\"moment\");\n\nvar Referral = sequelize.define(\"referral\", {\n id: {\n allowNull: false,\n type: DataTypes.CHAR(24),\n unique: true,\n primaryKey: true\n },\n active: {\n allowNull: false,\n type: DataTypes.BOOLEAN,\n defaultValue: true\n },\n name: {\n allowNull: true,\n type: DataTypes.STRING\n },\n method: {\n allowNull: true,\n type: DataTypes.STRING\n },\n signup_at: {\n allowNull: false,\n type: DataTypes.DATE,\n get: function() {\n return moment(this.getDataValue(\"signup_at\")).format(\"MM/DD/YYYY\");\n }\n }\n});\n\nReferral.findAll({\n where: {\n active: true\n },\n raw: true\n}).then(function(referrals) {\n console.log(referrals);\n});\n```\n\n========================================\n\nCode:\n```text\nvar moment = require(\"moment\");\n\nvar Referral = sequelize.define(\"referral\", {\n    id: {\n      allowNull: false,\n      type: DataTypes.CHAR(24),\n      unique: true,\n      primaryKey: true\n    },\n    active: {\n      allowNull: false,\n      type: DataTypes.BOOLEAN,\n      defaultValue: true\n    },\n    name: {\n      allowNull: true,\n      type: DataTypes.STRING\n    },\n    method: {\n      allowNull: true,\n      type: DataTypes.STRING\n    },\n    signup_at: {\n      allowNull: false,\n      type: DataTypes.DATE,\n      get: function() {\n        return moment(this.getDataValue(\"signup_at\")).format(\"MM/DD/YYYY\");\n      }\n    }\n});\n\n\nReferral.findAll({\n where: {\n  active: true\n },\n raw: true\n}).then(function(referrals) {\n  console.log(referrals);\n});\n```\n\n```text\nsignup_at\n```\n\n```text\nReferral.findAll({\n    where: {\n        active: true\n    },\n    raw: false\n}).then(function (referrals) {\n    referrals.forEach(function (referral, index, array) {\n        var value = referral.get();\n        console.log(value);\n    });\n});\n```\n\n```text\nraw = true\n```\n\n```text\nraw\n```\n\n```text\nget\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":126,"estimatedTokens":551}}1107{"id":"stack-48536774","source":"stackoverflow","questionId":48536774,"title":"Use ILIKE in sequelize where clause(JSON column)","tags":["json","node.js","postgresql","sequelize.js"],"text":"Title: Use ILIKE in sequelize where clause(JSON column)\nTags: json, node.js, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have JSON column where I have stored data like -\n\n```\n{ tag : [\"as\",\"bs\",\"cs\"] }\n```\n\nI want to search within this column with `ILIKE` and I believe JSON datatype is just string so I used query like - \n\n```\nSELECT * FROM public.\"Transactions\" WHERE tags::text ILIKE '%as%'\n```\n\nabove query works fine in sql \n\nI need to implement this with sequelize model with no success\ncode I used is \n\n```\nlet searchQuery = [\n {\n payee: {\n [Op.iLike]: '%' + search + '%'\n }\n },\n {\n tags: {\n [Op.iLike]: '%as%'\n }\n }\n ];\n```\n\n***gives error as***\n\n Unhandled rejection SequelizeDatabaseError: operator does not exist:\n json ~~* unknown\n\n========================================\n\nCode:\n```text\n{ tag : [\"as\",\"bs\",\"cs\"] }\n```\n\n```text\nSELECT * FROM public.\"Transactions\" WHERE tags::text ILIKE '%as%'\n```\n\n```text\nlet searchQuery = [\n        {\n            payee: {\n                [Op.iLike]: '%' + search + '%'\n            }\n        },\n        {\n            tags: {\n                [Op.iLike]: '%as%'\n            }\n        }\n    ];\n```\n\n```text\nILIKE\n```\n\n```text\nt=# select '{ \"tag\" : [\"as\",\"bs\",\"cs\"] }'::json::text ilike '%as%';\n ?column?\n----------\n t\n(1 row)\n```\n\n```text\nt=# select ('{ \"tag\" : [\"as\",\"bs\",\"cs\"] }'::json)->'tag'->>0 = 'as';\n ?column?\n----------\n t\n(1 row)\n```\n\n```text\nt=# select '{ \"tag\" : [\"as\",\"bs\",\"cs\"] }'::json::jsonb @> '{\"tag\":[\"as\"]}'::jsonb;\n ?column?\n----------\n t\n(1 row)\n```\n\n```text\n~~\n```\n\n```text\nILIKE\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":103,"estimatedTokens":392}}1108{"id":"stack-66965204","source":"stackoverflow","questionId":66965204,"title":"How to retrieve a list of values from a list of objects?","tags":["javascript","node.js","object","orm","sequelize.js"],"text":"Title: How to retrieve a list of values from a list of objects?\nTags: javascript, node.js, object, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nSo I have a list of objects like this formed by Sequelize query:\n\n```\n[\n Likes {\n dataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' },\n _previousDataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' },\n _changed: Set(0) {},\n _options: {\n isNewRecord: false,\n _schema: null,\n _schemaDelimiter: '',\n raw: true,\n attributes: [Array]\n },\n isNewRecord: false\n },\n Likes {\n dataValues: { PlaceId: '417f55a6-1d64-491f-9c00-8f3094f3f53a' },\n _previousDataValues: { PlaceId: '417f55a6-1d64-491f-9c00-8f3094f3f53a' },\n _changed: Set(0) {},\n _options: {\n isNewRecord: false,\n _schema: null,\n _schemaDelimiter: '',\n raw: true,\n attributes: [Array]\n },\n isNewRecord: false\n }\n]\n```\n\nI am getting various exceptions when querying because I get either a list like that: [{PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd'}, {PlaceId: 'e678yt6-c846-46b5-aa25-6534d67326au'}] or an empty list: [].\n\nI tried out Object.values as well as valueOf, map and other built in methods - even a manual for cycle and I do not really get why don't they work. What methods of achieving that can you suggest?\n\nSolution:\n\n```\nreturn models.Likes.findAll({\n where: {\n UserId: req.user.id\n },\n attributes: ['PlaceId']\n }).then(likes => {\n var values;\n try {\n values = likes.map(entity => entity.get('PlaceId'))\n }\n catch (e){\n console.log(e);\n }\n models.Place.findAll({\n where: {\n id: {\n [Sequelize.Op.notIn]: values\n }\n },\n limit: 24\n })\n```\n\nThis is the final working solution written thanks to one of the suggestions. Mapping with (entity => entity.get) did the trick. Best regards to everybody who commented and helped.\n\nIf anybody needs, the thing does a sequelize query from one table to then query another table with a \"NOT IN\". In SQL query 2ould look like that:\n\n```\n\"SELECT \"id\", \"coordinates\", \"place_name\", \"description\", \"category\", \"createdAt\", \"updatedAt\" FROM \"Places\" AS \"Place\" WHERE \"Place\".\"id\" NOT IN ('e61d2360-c846-46b5-aa25-6534d38276dd', '417f55a6-1d64-491f-9c00-8f3094f3f53a') LIMIT 24;\"\n```\n\n========================================\n\nCode:\n```text\n[\n  Likes {\n    dataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' },\n    _previousDataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' },\n    _changed: Set(0) {},\n    _options: {\n      isNewRecord: false,\n      _schema: null,\n      _schemaDelimiter: '',\n      raw: true,\n      attributes: [Array]\n    },\n    isNewRecord: false\n  },\n  Likes {\n    dataValues: { PlaceId: '417f55a6-1d64-491f-9c00-8f3094f3f53a' },\n    _previousDataValues: { PlaceId: '417f55a6-1d64-491f-9c00-8f3094f3f53a' },\n    _changed: Set(0) {},\n    _options: {\n      isNewRecord: false,\n      _schema: null,\n      _schemaDelimiter: '',\n      raw: true,\n      attributes: [Array]\n    },\n    isNewRecord: false\n  }\n]\n```\n\n```text\nreturn  models.Likes.findAll({\n            where: {\n                UserId: req.user.id\n            },\n            attributes: ['PlaceId']\n        }).then(likes => {\n            var values;\n            try {\n                values = likes.map(entity => entity.get('PlaceId'))\n            }\n            catch (e){\n                console.log(e);\n            }\n            models.Place.findAll({\n                where: {\n                    id: {\n                        [Sequelize.Op.notIn]: values\n                    }\n                },\n                limit: 24\n            })\n```\n\n```text\n\"SELECT \"id\", \"coordinates\", \"place_name\", \"description\", \"category\", \"createdAt\", \"updatedAt\" FROM \"Places\" AS \"Place\" WHERE \"Place\".\"id\" NOT IN ('e61d2360-c846-46b5-aa25-6534d38276dd', '417f55a6-1d64-491f-9c00-8f3094f3f53a') LIMIT 24;\"\n```\n\n```js\nconst FirstTable = sequelize.model(`FirstTable`)\nconst list = await FirstTable.findAll({\n    attributes: [`PlaceId`]\n})\n    .then(data => {\n        return data.map(entity => entity.get('PlaceId'))\n    })\nconsole.log(list)\n```\n\n```js\n[\n  'e61d2360-c846-46b5-aa25-6534d38276dd',\n  'e678yt6-c846-46b5-aa25-6534d67326au'\n]\n```\n\n========================================\n\nComments:\n- The right approach is using `map` can you please show what you tried there?\n- This is not a valid `Array` (Uncaught SyntaxError: Unexpected token '{')\n- In your example you have an object `dataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' }` and not an array\n- @mplungjan it is an array of objects (console logged and copies, just put one object in the example, so that it would not be overloaded). Added a list of two to clearify\n- @KooiInc console logged and coppied fully - should be valid\n- @MonikaGornostajūtė Sorry, Your examples do not match your description. `[{\"placeid\":\"xxx\"},{\"placeid\":\"zzz\"}]` is an array of objects. This: `Likes { dataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' }, _previousDataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' },` is not\n- @mplungjan sorry for misleading, I make an assumption that if several things are in [ ] braces (like it is in an example) - it is an array. I know that Likes { dataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' }, _previousDataValues: { PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd' } itself is not an array, but several of those together - is, as I thought.\n- `I get either a list like that: [{PlaceId: 'e61d2360-c846-46b5-aa25-6534d38276dd'}, {PlaceId: 'e678yt6-c846-46b5-aa25-6534d67326au'}] or an empty list: [].` so I expected `dataValues: [ here is an array ]`\n- thank you so much!, applied this to the code and it worked, apparently, mapping without => expression was my mistake","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":168,"estimatedTokens":1414}}1109{"id":"stack-68317398","source":"stackoverflow","questionId":68317398,"title":"Sequelize - Build dynamic where clause with 'Op.or'","tags":["javascript","sequelize.js"],"text":"Title: Sequelize - Build dynamic where clause with 'Op.or'\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI had this code block working with Sequelize v5. But since switching to v6, it seems to be erroring out. I am getting the error: `Error: Invalid value { customer_id: 'dg5j5435r4gfd' }`.\n\nAnd here is the code that creates the where condition block:\n\n```\nlet whereBlock = {\n deleted_at: null,\n };\n\n if (args.includeCore) {\n if (customerID !== 'all') {\n // whereBlock[Op.or] = [\n // { customer_id: customerID },\n // { customer_id: coreCustomerID },\n // ];\n whereBlock[Op.or] = [];\n whereBlock[Op.or].push({\n customer_id: customerID,\n });\n whereBlock[Op.or].push({ customer_id: coreCustomerID });\n }\n } else {\n whereBlock.customer_id = customerID;\n }\n```\n\nI was using the commented code. And then I tried the code below that. Both are producing the same error. But when I remove all that code from the if block and just put in `whereBlock.customer_id = customerID;`, then it works fine. So I know the issue is how I am constructing the where condition.\n\n**Update:** As requested, here is my `Sheets` model where the where clause is being run on.\n\n```\n'use strict';\n\nexport default (sequelize, DataTypes) => {\n return sequelize.define(\n 'Sheet',\n {\n id: {\n type: DataTypes.UUID,\n primaryKey: true,\n defaultValue: DataTypes.UUIDV4,\n },\n sheet_name: {\n type: DataTypes.STRING,\n isAlphaNumeric: true,\n required: true,\n allowNull: true,\n len: [3, 80],\n },\n sheet_file_name: {\n type: DataTypes.STRING,\n unique: true,\n isAlphaNumeric: true,\n required: false,\n allowNull: true,\n },\n brand_name: {\n type: DataTypes.STRING,\n unique: false,\n isAlphaNumeric: true,\n required: false,\n allowNull: true,\n },\n customer_id: {\n // fk in customers table\n type: DataTypes.TINYINT(2).UNSIGNED,\n required: true,\n allowNull: false,\n },\n chemical_id: {\n // fk in loads table\n type: DataTypes.SMALLINT.UNSIGNED,\n required: true,\n allowNull: false,\n },\n load_id: {\n // fk in loads table\n type: DataTypes.SMALLINT.UNSIGNED,\n required: true,\n allowNull: false,\n },\n active: {\n type: DataTypes.BOOLEAN,\n required: true,\n allowNull: false,\n defaultValue: true,\n },\n created_at: {\n type: DataTypes.DATE,\n },\n updated_at: {\n type: DataTypes.DATE,\n },\n deleted_at: {\n type: DataTypes.DATE,\n },\n },\n {\n underscored: true,\n paranoid: false,\n }\n );\n};\n```\n\nAnd in my index I have this to associate sheets with customers: `db.Sheet.belongsTo(db.Customer);`\n\nAlso here is the full code where the `whereBlock` is used, if that helps:\n\n```\nconst files = await db.Sheet.findAll({\n raw: true,\n attributes: [\n 'sheet_name',\n 'sheet_file_name',\n ['brand_name', 'brand'],\n 'updated_at',\n 'active',\n [Sequelize.col('Chemical.name'), 'chemical'],\n [Sequelize.col('Load.value'), 'load'],\n ],\n include: [\n {\n model: db.Load.scope(null),\n required: true,\n as: 'Load',\n attributes: ['value'],\n },\n {\n model: db.Chemical.scope(null),\n required: true,\n as: 'Chemical',\n attributes: ['name'],\n },\n ],\n // model: model,\n where: whereBlock,\n order: [['active', 'DESC']],\n });\n```\n\n**TLDR:** So here is what it comes down to:\n\n```\nwhereBlock = {\n deleted_at: null,\n customer_id: customerID,\n // [Op.or]: [\n // { customer_id: customerID },\n // { customer_id: coreCustomerID },\n // ],\n};\n```\n\nThat code above works, but the commented code errors out with: `Error: Invalid value { customer_id: '123456' }`\n\n========================================\n\nCode:\n```js\nlet whereBlock = {\n        deleted_at: null,\n    };\n\n    if (args.includeCore) {\n        if (customerID !== 'all') {\n            // whereBlock[Op.or] = [\n            //  { customer_id: customerID },\n            //  { customer_id: coreCustomerID },\n            // ];\n            whereBlock[Op.or] = [];\n            whereBlock[Op.or].push({\n                customer_id: customerID,\n            });\n            whereBlock[Op.or].push({ customer_id: coreCustomerID });\n        }\n    } else {\n        whereBlock.customer_id = customerID;\n    }\n```\n\n```js\n'use strict';\n\nexport default (sequelize, DataTypes) => {\n    return sequelize.define(\n        'Sheet',\n        {\n            id: {\n                type: DataTypes.UUID,\n                primaryKey: true,\n                defaultValue: DataTypes.UUIDV4,\n            },\n            sheet_name: {\n                type: DataTypes.STRING,\n                isAlphaNumeric: true,\n                required: true,\n                allowNull: true,\n                len: [3, 80],\n            },\n            sheet_file_name: {\n                type: DataTypes.STRING,\n                unique: true,\n                isAlphaNumeric: true,\n                required: false,\n                allowNull: true,\n            },\n            brand_name: {\n                type: DataTypes.STRING,\n                unique: false,\n                isAlphaNumeric: true,\n                required: false,\n                allowNull: true,\n            },\n            customer_id: {\n                // fk in customers table\n                type: DataTypes.TINYINT(2).UNSIGNED,\n                required: true,\n                allowNull: false,\n            },\n            chemical_id: {\n                // fk in loads table\n                type: DataTypes.SMALLINT.UNSIGNED,\n                required: true,\n                allowNull: false,\n            },\n            load_id: {\n                // fk in loads table\n                type: DataTypes.SMALLINT.UNSIGNED,\n                required: true,\n                allowNull: false,\n            },\n            active: {\n                type: DataTypes.BOOLEAN,\n                required: true,\n                allowNull: false,\n                defaultValue: true,\n            },\n            created_at: {\n                type: DataTypes.DATE,\n            },\n            updated_at: {\n                type: DataTypes.DATE,\n            },\n            deleted_at: {\n                type: DataTypes.DATE,\n            },\n        },\n        {\n            underscored: true,\n            paranoid: false,\n        }\n    );\n};\n```\n\n```js\nconst files = await db.Sheet.findAll({\n                raw: true,\n                attributes: [\n                    'sheet_name',\n                    'sheet_file_name',\n                    ['brand_name', 'brand'],\n                    'updated_at',\n                    'active',\n                    [Sequelize.col('Chemical.name'), 'chemical'],\n                    [Sequelize.col('Load.value'), 'load'],\n                ],\n                include: [\n                    {\n                        model: db.Load.scope(null),\n                        required: true,\n                        as: 'Load',\n                        attributes: ['value'],\n                    },\n                    {\n                        model: db.Chemical.scope(null),\n                        required: true,\n                        as: 'Chemical',\n                        attributes: ['name'],\n                    },\n                ],\n                // model: model,\n                where: whereBlock,\n                order: [['active', 'DESC']],\n            });\n```\n\n```js\nwhereBlock = {\n    deleted_at: null,\n    customer_id: customerID,\n    // [Op.or]: [\n    //  { customer_id: customerID },\n    //  { customer_id: coreCustomerID },\n    // ],\n};\n```\n\n```text\nError: Invalid value { customer_id: 'dg5j5435r4gfd' }\n```\n\n```text\nwhereBlock.customer_id = customerID;\n```\n\n```text\nSheets\n```\n\n```text\ndb.Sheet.belongsTo(db.Customer);\n```\n\n```text\nwhereBlock\n```\n\n```text\nError: Invalid value { customer_id: '123456' }\n```\n\n```js\nexport default (db) => {\n    const Op = db.Sequelize.Op;\n```\n\n```text\nOp\n```\n\n```text\nsequelize\n```\n\n```text\nimport Op from 'sequelize';\n```\n\n```text\nOp\n```\n\n```text\nOp\n```\n\n```text\n[Op.or]\n```\n\n```text\n[Op.Op.or]\n```\n\n```text\nimport Op.Op from 'sequelize';\n```\n\n```text\nOp\n```\n\n========================================\n\nComments:\n- Could you post your model?\n- I'm not sure why I couldn't have gotten a nice clean error in my console along the lines of `\"or\" command not recgonized on line xxx`","metadata":{"transformedAt":"2026-08-18T18:33:34.501Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":374,"estimatedTokens":2003}}1110{"id":"stack-42872007","source":"stackoverflow","questionId":42872007,"title":"NodeJs: Data Transformers like in Laravel PHP Framework","tags":["javascript","node.js","rest","sequelize.js"],"text":"Title: NodeJs: Data Transformers like in Laravel PHP Framework\nTags: javascript, node.js, rest, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI've created multiple REST API projects using the Laravel framework and basing my code structure on the Laracasts tutorial. However we are deciding to move some projects using NodeJs as a backend. I'm beginning to learn node and I'm trying to replicate it in Node. I was able to do it for a singe object response but for multiple objects I can't seem to make it work.\n\nHere is my controller:\n\n```\nindex(req,res) {\n User\n .findAll()\n .then(function(users){\n res.json(api.respond(transfomer.transformCollection(users)));\n })\n .catch(function(error){\n res.json(api.respondWithError('users not found',error));\n });\n }\n```\n\napi controller:\n\nmodule.exports = {\n\n```\n// response w/o error\n respond: function(data,msg,status) {\n if (msg == null) {\n return {\n 'status': status || true,\n 'data': data\n };\n } else {\n return {\n 'status': true,\n 'message': msg,\n 'data': data\n };\n }\n },\n\n // response with error\n respondWithError: function(msg,error) {\n var self = this;\n var status = false;\n var data = {\n 'error': error\n };\n return this.respond(data,msg,status);\n },\n};\n```\n\ntransformer.js\n\n```\nmodule.exports = {\n\n // single transformation\n transform (user) {\n return {\n 'id' : user.id,\n 'username': user.username,\n 'firstname': user.firstname,\n 'lastname': user.lastname,\n 'address': user.address,\n 'phone': user.phone,\n 'mobile': user.mobile,\n 'status': user.status\n };\n },\n\n //\n transformCollection(users) {\n var self = this;\n var data = [];\n for (var i = 0; i sample output\n\n```\n{\n \"status\": true,\n \"data\": [ \n {\n \"id\": 1,\n \"username\": \"b@email.com\",\n \"firstname\": \"Jon\",\n \"lastname\": \"Doe\",\n \"address\": \"Homes\",\n \"phone\": \"+966501212121\",\n \"mobile\": \"+966501212121\",\n \"status\": \"NOT VERIFIED\"\n },\n {\n \"id\": 1,\n \"username\": \"b@email.com\",\n \"firstname\": \"Jon\",\n \"lastname\": \"Doe\",\n \"address\": \"Homes\",\n \"phone\": \"+966501212121\",\n \"mobile\": \"+966501212121\",\n \"status\": \"NOT VERIFIED\"\n },\n {\n \"id\": 1,\n \"username\": \"b@email.com\",\n \"firstname\": \"Jon\",\n \"lastname\": \"Doe\",\n \"address\": \"Homes\",\n \"phone\": \"+966501212121\",\n \"mobile\": \"+966501212121\",\n \"status\": \"NOT VERIFIED\"\n },\n {\n \"id\": 1,\n \"username\": \"b@email.com\",\n \"firstname\": \"Jon\",\n \"lastname\": \"Doe\",\n \"address\": \"Homes\",\n \"phone\": \"+966501212121\",\n \"mobile\": \"+966501212121\",\n \"status\": \"NOT VERIFIED\"\n },\n ]\n}\n```\n\nSorry for asking this as I'm a bit newb with node. Is it possible to achieve that output as I tried different ways but Im still getting errors. Btw I'm using sequelize for the database.\n\nThanks.\n\n========================================\n\nTop Answer:\nI've found the answer to my question since sequelize is returning the results as an object with additional properties aside from the database results I had to modify the controller to set and convert the results to raw in order for me to get the array of objects from the query results from the database.\n\n```\nindex(req,res) {\n User\n .findAll({ raw: true }) // added \"raw: true\"\n .then(function(users){\n res.json(api.respond(transfomer.transformCollection(users)));\n })\n .catch(function(error){\n res.json(api.respondWithError('users not found',error));\n });\n },\n```\n\nThis will return the array of objects from the database and from there the data transformer is working properly. Thank you for all the help.\n\n========================================\n\nCode:\n```text\nindex(req,res) {\n    User\n      .findAll()\n      .then(function(users){\n        res.json(api.respond(transfomer.transformCollection(users)));\n      })\n      .catch(function(error){\n        res.json(api.respondWithError('users not found',error));\n      });\n  }\n```\n\n```text\n// response w/o error\n  respond: function(data,msg,status) {\n    if (msg == null) {\n      return {\n        'status': status || true,\n        'data': data\n      };\n    } else {\n      return {\n        'status': true,\n        'message': msg,\n        'data': data\n      };\n    }\n  },\n\n  // response with error\n  respondWithError: function(msg,error) {\n    var self = this;\n    var status = false;\n    var data = {\n      'error': error\n    };\n    return this.respond(data,msg,status);\n  },\n};\n```\n\n```text\nmodule.exports = {\n\n  // single transformation\n  transform (user) {\n    return {\n      'id' : user.id,\n      'username': user.username,\n      'firstname': user.firstname,\n      'lastname': user.lastname,\n      'address': user.address,\n      'phone': user.phone,\n      'mobile': user.mobile,\n      'status': user.status\n    };\n  },\n\n  //\n  transformCollection(users) {\n    var self = this;\n    var data = [];\n    for (var i = 0; i <= users.length; i++) {\n        data.push(this.transform(users[i]));\n    }\n    return data;\n  }\n\n};\n```\n\n```text\n{\n  \"status\": true,\n  \"data\": [ \n    {\n        \"id\": 1,\n        \"username\": \"b@email.com\",\n        \"firstname\": \"Jon\",\n        \"lastname\": \"Doe\",\n        \"address\": \"Homes\",\n        \"phone\": \"+966501212121\",\n        \"mobile\": \"+966501212121\",\n        \"status\": \"NOT VERIFIED\"\n    },\n    {\n        \"id\": 1,\n        \"username\": \"b@email.com\",\n        \"firstname\": \"Jon\",\n        \"lastname\": \"Doe\",\n        \"address\": \"Homes\",\n        \"phone\": \"+966501212121\",\n        \"mobile\": \"+966501212121\",\n        \"status\": \"NOT VERIFIED\"\n    },\n    {\n        \"id\": 1,\n        \"username\": \"b@email.com\",\n        \"firstname\": \"Jon\",\n        \"lastname\": \"Doe\",\n        \"address\": \"Homes\",\n        \"phone\": \"+966501212121\",\n        \"mobile\": \"+966501212121\",\n        \"status\": \"NOT VERIFIED\"\n    },\n    {\n        \"id\": 1,\n        \"username\": \"b@email.com\",\n        \"firstname\": \"Jon\",\n        \"lastname\": \"Doe\",\n        \"address\": \"Homes\",\n        \"phone\": \"+966501212121\",\n        \"mobile\": \"+966501212121\",\n        \"status\": \"NOT VERIFIED\"\n    },\n  ]\n}\n```\n\n```js\nconst options = {\n    raw: true, \n    attributes: ['id', 'name', 'code', 'createdAt','updatedAt']\n};\n\ncountry.findAndCountAll(options).then(querySnapshot => {\n    const total = querySnapshot.count;\n    resolve({\n        docs: querySnapshot.rows, \n        total: total\n    })  \n}).catch((err) => {\n    reject(err)\n});\n```\n\n```text\nindex(req,res) {\n    User\n      .findAll({ raw: true }) // added \"raw: true\"\n      .then(function(users){\n        res.json(api.respond(transfomer.transformCollection(users)));\n      })\n      .catch(function(error){\n        res.json(api.respondWithError('users not found',error));\n      });\n  },\n```\n\n========================================\n\nComments:\n- In your controller you are calling `transform(user)` but you have `users`, not `user`.\n- I don't know Larval, but you can read about `middleware` available on the popular nodejs frameworks like `express`, I guess they can help you achive what you want. And on a side note, you can drop the `$` prefix for variables :)\n- @RonDadon I don't think this is middleware. I used middleware for jwt token authentication on this code. It is just transforming data. Loop through the multiple objects returned from the db and format each object the way we want from the format.\n- you are calling `transform` instead of `transformCollection`\n- What error do you get?\n- @piotrbienias I get an empty data set.","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":314,"estimatedTokens":1793}}1111{"id":"stack-48772448","source":"stackoverflow","questionId":48772448,"title":"sequelize with cls not getting current context","tags":["mysql","node.js","logging","sequelize.js","continuation-local-storag"],"text":"Title: sequelize with cls not getting current context\nTags: mysql, node.js, logging, sequelize.js, continuation-local-storag\nSource: Stack Overflow\n\nQuestion:\nI am trying to log mysql queries using sequelize cls and logger module.\nIn this i am loosing the context of namespace `Request-Id` and it prints either blank or some random previous `Request-Id`\n\nNode Version : 8.9.4 \n\nSequelize : 4.33.4\n\ncls-hooked : 4.2.2\n\nAny help/solution is appreciated.\n\nmysql.js\n\n```\nconst parameterStore = require( './parameterStore.js' );\nvar config = require( './config/main.js' )[ process.env.STAGE || 'local' ];\nvar mysqlConfig = config.MYSQL;\n\nvar logger = require( '../../lib/logger.js' );\n\nvar Sequelize = require( 'sequelize' );\n\nfunction MySQL() {\n\n}\n\nMySQL.prototype.getSequelizeMysqlConnection = function() {\n return new Promise( async function( resolve, reject ) {\n try{\n var credentials = await parameterStoreInstance.getMySqlDbCredentials()\n .then( function( data ) {\n return data;\n } )\n .catch( function( error ) {\n throw error;\n } );\n sequelize = new Sequelize (\n {\n database: mysqlConfig.DATABASE,\n username: credentials.USERNAME,\n password: credentials.PASSWORD,\n host: mysqlConfig.HOST,\n port: mysqlConfig.PORT,\n dialect: 'mysql',\n pool: {\n max: 3,\n min: 0,\n idle: 10000,\n acquire: 20000\n },\n logging: sequelizeLogger,\n benchmark: true\n } );\n return resolve( sequelize );\n } catch( error ) {\n reject( error );\n }\n } );\n};\n\nfunction sequelizeLogger( query, time ) {\n logger.debug( query + ` [${ time }ms]` );\n}\n\nmodule.exports = MySQL;\n```\n\nlogger.js\n\n```\nconst winston = require('winston');\nconst date_time = require('moment-timezone');\nconst on_headers = require('on-headers');\nconst on_finished = require('on-finished');\n// const continuation_local_storage = require('continuation-local-storage');\nconst continuation_local_storage = require('cls-hooked');\nconst Promise = require('bluebird');\nconst continuation_local_storage_bluebird = require('cls-bluebird');\nconst redis = require('redis');\nconst continuation_local_storage_redis = require('cls-redis');\nvar appName = undefined;\nvar Sequelize = require('sequelize');\n\nconst winston_config = winston.config;\n\nvar winstonLogger = new winston.Logger({\n transports: [\n new winston.transports.Console({\n level : process.env.STAGE === 'prod' ? 'info' : 'debug',\n showLevel : false\n } )\n ],\n exitOnError: false\n});\n\nvar getNamespace = continuation_local_storage.getNamespace;\nvar createNamespace = continuation_local_storage.createNamespace;\nvar createRequest = createNamespace( 'Request-Id' );\nvar getRequest = getNamespace( 'Request-Id' );\ncontinuation_local_storage_bluebird( createRequest );\ncontinuation_local_storage_redis( createRequest );\nSequelize.useCLS( createRequest );\n\nfunction logger() {\n}\n\nlogger.prototype.log = function( level, ...message ) {\n // body...\n var combinedMessage = combineMessage( message );\n winstonLogger.log( formatterMessage( level, combinedMessage ) );\n};\n\nlogger.prototype.info = function( ...message ) {\n // body...\n var combinedMessage = combineMessage( message );\n winstonLogger.info( formatterMessage( 'info', combinedMessage ) );\n};\n\nlogger.prototype.debug = function( ...message ) {\n // body...\n var combinedMessage = combineMessage( message );\n winstonLogger.debug( formatterMessage( 'debug', combinedMessage ) );\n};\n\nlogger.prototype.error = function( ...message ) {\n // body...\n var combinedMessage = combineMessage( message );\n winstonLogger.error( formatterMessage( 'error', combinedMessage ) );\n};\n\nlogger.prototype.getNamespace = function() {\n // body...\n return getRequest;\n};\n\nlogger.prototype.useSequelizeCls = function( serviceSequelize ) {\n // body...\n serviceSequelize.useCLS( createRequest );\n Sequelize = serviceSequelize;\n return serviceSequelize;\n};\n\nlogger.prototype.logger = function( appNameLocal ) { \n // var createRequest = createNamespace( 'Request-Id' );\n // continuation_local_storage_bluebird( createRequest );\n // continuation_local_storage_redis( createRequest );\n // Sequelize.useCLS(createRequest);\n return function( req, res, next ) {\n // create requestId and append it in header as Request-Id...\n appName = appNameLocal;\n createRequest.run( function( context ) {\n req._logStartTime = process.hrtime();\n on_finished( res, function() {\n res._logEndTime = process.hrtime();\n res._logDiffTime = process.hrtime( req._logStartTime );\n winstonLogger.info( formatterHTTP( 'info', req, res ) );\n } );\n\n var requestId = req.get( 'Request-Id' ) || req.headers[ 'Request-Id' ] || '';\n // createRequest.bindEmitter( req );\n // createRequest.bindEmitter( res );\n createRequest.set( 'Request-Id', requestId );\n if( requestId === '' ) {\n winstonLogger.error( formatterMessage( 'error', 'Request-Id not found in headers.' ) )\n }\n next();\n } );\n };\n};\n\nfunction formatterMessage( logLevel, message ) {\n var timestamp = dateTimeIST();\n logLevel = getLogLevel( logLevel );\n var requestId = getRequestId();\n var serviceName = getServiceName();\n var formattedMessage = `[${ timestamp }] [${ logLevel }] [${ requestId }] [${ serviceName }] ${ message }`;\n return formattedMessage;\n}\n\nfunction dateTimeIST() {\n return `${ date_time( new Date() ).tz('Asia/Kolkata').format('YYYY-MM-DD HH:mm:ss.SSS') }`;\n}\n\nfunction getLogLevel( logLevel ) {\n return logLevel.toLowerCase();\n}\n\nfunction getRequestId() {\n // var getRequest = getNamespace( 'Request-Id' );\n return getRequest.get( 'Request-Id' ) || '';\n // return getRequest && getRequest.get( 'Request-Id' ) ? getRequest.get( 'Request-Id' ) : '';\n}\n\nfunction getRequestIdAfterFinished( req ) {\n return ( req.get( 'Request-Id' ) || req.headers[ 'Request-Id' ] || '' );\n}\n\nfunction getServiceName() {\n return appName || process.env.APP_NAME || 'local';\n}\n\nfunction formatterHTTP( logLevel, req, res ) {\n var timestamp = dateTimeIST();\n logLevel = getLogLevel( logLevel );\n var requestId = getRequestIdAfterFinished( req );\n var serviceName = getServiceName();\n var httpMessage = buildHTTPMessage( req, res );\n var formattedHTTPMessage = `[${ timestamp }] [${ logLevel }] [${ requestId }] [${ serviceName }] ${ httpMessage }`;\n return formattedHTTPMessage;\n}\n\nfunction buildHTTPMessage( req, res ) {\n return `[${ req.method }] [${ req.originalUrl || req.url }] [${ res.getHeader( 'Content-Length' ) ? res.statusCode : 504 }] [${ res.getHeader( 'Content-Length' ) || 0 }] [${ ( ( res._logEndTime[ 0 ] - req._logStartTime[ 0 ] ) * 1e3 + ( res._logEndTime[ 1 ] - req._logStartTime[ 1 ] ) * 1e-6 ).toFixed(3) }ms]`;\n}\n\nfunction combineMessage( message ) {\n return message.join( ' ' );\n}\n\nmodule.exports = new logger();\n```\n\n========================================\n\nCode:\n```text\nconst parameterStore = require( './parameterStore.js' );\nvar config = require( './config/main.js' )[ process.env.STAGE || 'local' ];\nvar mysqlConfig = config.MYSQL;\n\nvar logger = require( '../../lib/logger.js' );\n\nvar Sequelize = require( 'sequelize' );\n\nfunction MySQL() {\n\n}\n\nMySQL.prototype.getSequelizeMysqlConnection = function() {\n    return new Promise( async function( resolve, reject ) {\n        try{\n            var credentials = await parameterStoreInstance.getMySqlDbCredentials()\n            .then( function( data ) {\n                return data;\n            } )\n            .catch( function( error ) {\n                throw error;\n            } );\n            sequelize = new Sequelize (\n            {\n                database: mysqlConfig.DATABASE,\n                username: credentials.USERNAME,\n                password: credentials.PASSWORD,\n                host: mysqlConfig.HOST,\n                port: mysqlConfig.PORT,\n                dialect: 'mysql',\n                pool: {\n                    max: 3,\n                    min: 0,\n                    idle: 10000,\n                    acquire: 20000\n                },\n                logging: sequelizeLogger,\n                benchmark: true\n            } );\n            return resolve( sequelize );\n        } catch( error ) {\n            reject( error );\n        }\n    } );\n};\n\nfunction sequelizeLogger( query, time ) {\n    logger.debug( query + ` [${ time }ms]` );\n}\n\nmodule.exports = MySQL;\n```\n\n```text\nconst winston = require('winston');\nconst date_time = require('moment-timezone');\nconst on_headers = require('on-headers');\nconst on_finished = require('on-finished');\n// const continuation_local_storage = require('continuation-local-storage');\nconst continuation_local_storage = require('cls-hooked');\nconst Promise = require('bluebird');\nconst continuation_local_storage_bluebird = require('cls-bluebird');\nconst redis = require('redis');\nconst continuation_local_storage_redis = require('cls-redis');\nvar appName = undefined;\nvar Sequelize = require('sequelize');\n\nconst winston_config = winston.config;\n\nvar winstonLogger = new winston.Logger({\n  transports: [\n    new winston.transports.Console({\n        level : process.env.STAGE === 'prod' ? 'info' : 'debug',\n        showLevel : false\n    } )\n  ],\n  exitOnError: false\n});\n\n\nvar getNamespace = continuation_local_storage.getNamespace;\nvar createNamespace = continuation_local_storage.createNamespace;\nvar createRequest = createNamespace( 'Request-Id' );\nvar getRequest = getNamespace( 'Request-Id' );\ncontinuation_local_storage_bluebird( createRequest );\ncontinuation_local_storage_redis( createRequest );\nSequelize.useCLS( createRequest );\n\nfunction logger() {\n}\n\nlogger.prototype.log = function( level, ...message ) {\n    // body...\n    var combinedMessage = combineMessage( message );\n    winstonLogger.log( formatterMessage( level, combinedMessage ) );\n};\n\nlogger.prototype.info = function( ...message ) {\n    // body...\n    var combinedMessage = combineMessage( message );\n    winstonLogger.info( formatterMessage( 'info', combinedMessage ) );\n};\n\nlogger.prototype.debug = function( ...message ) {\n    // body...\n    var combinedMessage = combineMessage( message );\n    winstonLogger.debug( formatterMessage( 'debug', combinedMessage ) );\n};\n\nlogger.prototype.error = function( ...message ) {\n    // body...\n    var combinedMessage = combineMessage( message );\n    winstonLogger.error( formatterMessage( 'error', combinedMessage ) );\n};\n\nlogger.prototype.getNamespace = function() {\n    // body...\n    return getRequest;\n};\n\nlogger.prototype.useSequelizeCls = function( serviceSequelize ) {\n    // body...\n    serviceSequelize.useCLS( createRequest );\n    Sequelize = serviceSequelize;\n    return serviceSequelize;\n};\n\nlogger.prototype.logger = function( appNameLocal ) { \n    // var createRequest = createNamespace( 'Request-Id' );\n    // continuation_local_storage_bluebird( createRequest );\n    // continuation_local_storage_redis( createRequest );\n    // Sequelize.useCLS(createRequest);\n    return function( req, res, next ) {\n        // create requestId and append it in header as Request-Id...\n        appName = appNameLocal;\n        createRequest.run( function( context ) {\n            req._logStartTime = process.hrtime();\n            on_finished( res, function() {\n                res._logEndTime = process.hrtime();\n                res._logDiffTime = process.hrtime( req._logStartTime );\n                winstonLogger.info( formatterHTTP( 'info', req, res ) );\n            } );\n\n            var requestId = req.get( 'Request-Id' ) || req.headers[ 'Request-Id' ] || '';\n            // createRequest.bindEmitter( req );\n            // createRequest.bindEmitter( res );\n            createRequest.set( 'Request-Id', requestId );\n            if( requestId === '' ) {\n                winstonLogger.error( formatterMessage( 'error', 'Request-Id not found in headers.' ) )\n            }\n            next();\n        } );\n    };\n};\n\nfunction formatterMessage( logLevel, message ) {\n    var timestamp = dateTimeIST();\n    logLevel = getLogLevel( logLevel );\n    var requestId = getRequestId();\n    var serviceName = getServiceName();\n    var formattedMessage = `[${ timestamp }] [${ logLevel }] [${ requestId }] [${ serviceName }] ${ message }`;\n    return formattedMessage;\n}\n\nfunction dateTimeIST() {\n    return `${ date_time( new Date() ).tz('Asia/Kolkata').format('YYYY-MM-DD HH:mm:ss.SSS') }`;\n}\n\nfunction getLogLevel( logLevel ) {\n    return logLevel.toLowerCase();\n}\n\nfunction getRequestId() {\n    // var getRequest = getNamespace( 'Request-Id' );\n    return getRequest.get( 'Request-Id' ) || '';\n    // return getRequest && getRequest.get( 'Request-Id' ) ? getRequest.get( 'Request-Id' ) : '';\n}\n\nfunction getRequestIdAfterFinished( req ) {\n    return ( req.get( 'Request-Id' ) || req.headers[ 'Request-Id' ] || '' );\n}\n\nfunction getServiceName() {\n    return appName || process.env.APP_NAME || 'local';\n}\n\nfunction formatterHTTP( logLevel, req, res ) {\n    var timestamp = dateTimeIST();\n    logLevel = getLogLevel( logLevel );\n    var requestId = getRequestIdAfterFinished( req );\n    var serviceName = getServiceName();\n    var httpMessage = buildHTTPMessage( req, res );\n    var formattedHTTPMessage = `[${ timestamp }] [${ logLevel }] [${ requestId }] [${ serviceName }] ${ httpMessage }`;\n    return formattedHTTPMessage;\n}\n\nfunction buildHTTPMessage( req, res ) {\n    return `[${ req.method }] [${ req.originalUrl || req.url }] [${ res.getHeader( 'Content-Length' ) ? res.statusCode : 504 }] [${ res.getHeader( 'Content-Length' ) || 0 }] [${ ( ( res._logEndTime[ 0 ] - req._logStartTime[ 0 ] ) * 1e3 + ( res._logEndTime[ 1 ] - req._logStartTime[ 1 ] ) * 1e-6 ).toFixed(3) }ms]`;\n}\n\nfunction combineMessage( message ) {\n    return message.join( ' ' );\n}\n\nmodule.exports = new logger();\n```\n\n```text\nRequest-Id\n```\n\n```text\nRequest-Id\n```\n\n========================================\n\nComments:\n- How are you using async-local-storage with sequelize, do you have some wrapper around it that is making it compatible with \"namespace\" API so you can just use it as a drop-in replacement for cls-hooked?\n- Can you please provide your code example of using async-local-storage?\n- @Sim Yes, cls-hooked is also using async hooks and so does async-local-storage, so having the same code but with different module being required and following its initialization procedure. Although, recently tried express-http-context and found that putting app.use(httpContext.middleware); in the end also solves the problem ;)\n- @hereischen mostly i changed the initialization and required module in logger.js file if you still want it then i will update this post :)\n- stackoverflow.com/questions/55611335/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":454,"estimatedTokens":3592}}1112{"id":"stack-35844612","source":"stackoverflow","questionId":35844612,"title":"exclude fields on post, put request in epilogue","tags":["express","sequelize.js","epilogue"],"text":"Title: exclude fields on post, put request in epilogue\nTags: express, sequelize.js, epilogue\nSource: Stack Overflow\n\nQuestion:\nI am using expressjs with sequalize ORM. My user model is some what like\n\n```\nmodule.exports = function (sequelize, DataTypes) {\n var User = sequelize.define('user', {\n userName: {\n type: DataTypes.STRING\n },\n isAdmin: {\n type: DataTypes.Boolean\n }\n })\n }\n```\n\nbut I dont want to allow the request to set isAdmin to be set to true or false on POST/PUT. But i want isAdmin on get request.\n\nI know about excludeAttributes property but it removes the fields on `GET` request only.\n\n========================================\n\nCode:\n```text\nmodule.exports = function (sequelize, DataTypes) {\n var User = sequelize.define('user', {\n    userName: {\n      type: DataTypes.STRING\n    },\n    isAdmin: {\n      type: DataTypes.Boolean\n    }\n   })\n  }\n```\n\n```text\nGET\n```\n\n```text\nvar rest = require('epilogue')\nvar userResource = rest.resource({\n   model: DB.User,\n   readOnlyAttributes: ['isAdmin']\n});\n```\n\n```text\nreadOnlyAttributes\n```\n\n```text\ndchester/epilogue#master\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- oh i didn't notice this. Works perfectly. Hope epilogue publishes this ASAP","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":68,"estimatedTokens":313}}1113{"id":"stack-39849040","source":"stackoverflow","questionId":39849040,"title":"Sequelize include as property instead of node","tags":["javascript","orm","sequelize.js"],"text":"Title: Sequelize include as property instead of node\nTags: javascript, orm, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nIn Sequelize, is there a proper way to do a query with an include, but instead of showing the included entity in a node, showing the included entity properties with the main models properties?\n\nExample:\n\n```\n// Project belongsTo Customer\n\nProject.findAll({\n include: [{\n model: Customer\n }]\n})\n```\n\nActual result:\n\n```\n{\n name: 'Project X',\n customer: {\n name: 'Customer Y',\n street: 'Paddington street'\n }\n}\n```\n\nExpected result:\n\n```\n{\n name: 'Project X',\n customer_name: 'Customer Y',\n customer_street: 'Paddington street'\n}\n```\n\n========================================\n\nTop Answer:\nI know this is an old question, but I had a similar question and found a Sequelize solution. So for the OP's example, the solution would be this:\n\n```\nProject.findAll({\n attributes: [\n [sequelize.col('Customer.name'), 'customer_name'],\n [sequelize.col('Customer.street'), 'customer_street'],\n ],\n include: [{\n model: Customer,\n attributes: [], // Make sure no nested attributes are returned\n }]\n})\n```\n\n========================================\n\nCode:\n```text\n// Project belongsTo Customer\n\nProject.findAll({\n  include: [{\n      model: Customer\n  }]\n})\n```\n\n```text\n{\n  name: 'Project X',\n  customer: {\n   name: 'Customer Y',\n   street: 'Paddington street'\n  }\n}\n```\n\n```text\n{\n  name: 'Project X',\n  customer_name: 'Customer Y',\n  customer_street: 'Paddington street'\n}\n```\n\n```text\nProject.findAll({\n    include: [{\n        model: Customer\n    }]\n}).then(projects => {\n    return projects.map(project => {\n        Object.keys(project.customer).forEach(key => {\n            project['customer_' + key] = project.customer[key];\n        })\n        delete project.customer;\n        return project;\n    })\n})\n```\n\n```text\nProject.findAll({\n  attributes: [\n    [sequelize.col('Customer.name'), 'customer_name'],\n    [sequelize.col('Customer.street'), 'customer_street'],\n  ],\n  include: [{\n     model: Customer,\n     attributes: [], // Make sure no nested attributes are returned\n  }]\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":118,"estimatedTokens":524}}1114{"id":"stack-38293900","source":"stackoverflow","questionId":38293900,"title":"nodejs singelton for database connection with sequalize","tags":["mysql","node.js","sequelize.js"],"text":"Title: nodejs singelton for database connection with sequalize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm just being curious. What is the proper way to open a database connection in nodejs with requires and dependency injection?\n\nIn php I would have created a connection once as a singleton in an global variable. However this seems not to be best practice in node. Thus I had the following questions:\n\n- Where would you open a db connection in node?\n\n- Would you open the db connection once or multiple times?\n\n- How can I open the db connection only once while keeping es6 module imports?\n\n- How can I open multiple db connections through es6 module loading?\n\n- If I import the same database multiple times, does it result in multiple connections?\n\n- I rather know and like to control how many connections are opend by my server. E.g. if I write a backend worker with low db access I rather only open one db connection there as running an express server I'd like to open a connection per request. How can I achieve this?\n\nI do know there are similar questions however the not fully seem to answer my question:\n\n- Singlton in Node ES6\n\n- Where to connect to the database in node?\n\n- NodeJS Express Dependency Injection and Database Connections\n\nSo my basic idea is:\n\n```\n/* DbService.js */\nvar Sequelize = require('sequelize');\nmodule.export = new Sequelize('database', 'username')\n```\n\nsame with models / instances\n\n```\n/* Foo.js */\nvar db = require(\"DbService.js\");\nexport var Foo = db.define('foo', {...});\n```\n\nAnd in the code I than load the db / model by\n\n```\n/* server.js */\n\nimport Foo from './Foo';\nFoo.findById('123').then(function(foo) {\n ...\n};\n\nvar db = require(\"DbService.js\"); \ndb.query(\"SELECT * FROM `test`\");\n```\n\nHowever in my mind this allways opens a seperate db connection and this feels wrong. So how would you do this probably?\n\n========================================\n\nCode:\n```text\n/* DbService.js */\nvar Sequelize = require('sequelize');\nmodule.export = new Sequelize('database', 'username')\n```\n\n```text\n/* Foo.js */\nvar db = require(\"DbService.js\");\nexport var Foo = db.define('foo', {...});\n```\n\n```text\n/* server.js */\n\nimport Foo from './Foo';\nFoo.findById('123').then(function(foo) {\n    ...\n};\n\nvar db = require(\"DbService.js\");    \ndb.query(\"SELECT * FROM `test`\");\n```\n\n```text\nnew Sequelize\n```\n\n```text\nnew Sequelize()\n```\n\n```text\nSequelize\n```\n\n========================================\n\nComments:\n- Ok and if not Sequalize ... how can I implement something like this myself?\n- @Manuel you can use `createPool` of node-mysql module.\n- I thought of a own service like an rest api, cacheing or background tasks api","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":106,"estimatedTokens":671}}1115{"id":"stack-30828527","source":"stackoverflow","questionId":30828527,"title":"How would you test this route code?","tags":["javascript","node.js","unit-testing","express","sequelize.js"],"text":"Title: How would you test this route code?\nTags: javascript, node.js, unit-testing, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following route code. `User` is a sequelize model, `jwt` is for creating a JWT token. \n\nI want to avoid hitting the db, so I want to stub out both dependencies.\n\nUser.create returns a Promise. I want to be able to assert that res.json is actually being called. I think my mock User.create should return a real promise and fulfill that promise. \n\nI want to assert that `res.json` is called. My test method is exiting before the Promise is fulfilled. I'm not returning the Promise from my route, so I can't return it from the `it` in my test.\n\nGiven that I want to mock the dependencies, please show me how you would test this?\n\nIf you have a suggestion how to how better structure this code please let me know.\n\n```\nmodule.exports = function(User, jwt) {\n 'use strict';\n\n return function(req, res) {\n User.create(req.body)\n .then(function(user) {\n var token = jwt.sign({id: user.id}); \n res.json({token: token});\n })\n .catch(function(e) {\n });\n };\n};\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = function(User, jwt) {\n  'use strict';\n\n  return function(req, res) {\n    User.create(req.body)\n    .then(function(user) {\n      var token = jwt.sign({id: user.id}); \n      res.json({token: token});\n    })\n    .catch(function(e) {\n    });\n  };\n};\n```\n\n```text\nUser\n```\n\n```text\njwt\n```\n\n```text\nres.json\n```\n\n```text\nit\n```\n\n```text\nnpm install mocha\nnpm install q\n```\n\n```text\nvar jwt = require('./jwt.js');\nvar User = require('./user.js');\nvar route = require('./route.js');\n\ndescribe('Testing Route Create User', function () {\n  it('should respond using json', function (done) {\n    var user = {\n      username: 'wilson',\n      age: 29\n    };\n\n    var res = {};\n    var req = {};\n    var routeHandler = route(User, jwt);\n\n    req.body = user;\n\n    res.json = function (data) {\n      done();\n    }\n\n    routeHandler(req, res);\n  });\n});\n```\n\n```text\nmocha\n```\n\n========================================\n\nComments:\n- Thanks. I was trying to avoid using done, but that works well enough.","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":108,"estimatedTokens":541}}1116{"id":"stack-40980856","source":"stackoverflow","questionId":40980856,"title":"Sequelize wrong foreign key name when creating tables","tags":["javascript","mysql","node.js","express","sequelize.js"],"text":"Title: Sequelize wrong foreign key name when creating tables\nTags: javascript, mysql, node.js, express, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm starting to play around with node express and Sequelize. I the example of `Sequelize/express` from them git page, but I'm having a problem when I execute de app. All the tables are created right and shows no errors, but when I look at the tables instead of creating a foreign key named `secretariaid` to reference the secretaria table, its creating a field named `secretarumid` with throws and error when trying to use the database. \nI'm a bit confuse about were is the error: \n\n models and migrations created using sequelize model:create.\n\noficina.js\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var Oficina = sequelize.define('Oficina', {\n nombre_oficina: DataTypes.STRING,\n direccion: DataTypes.STRING,\n telefono: DataTypes.STRING,\n interno: DataTypes.STRING,\n email: DataTypes.STRING\n }, {\n classMethods: {\n associate: function(models) {\n Oficina.belongsTo(models.Secretaria, {\n onDelete: \"CASCADE\",\n foreignKey: {\n allowNull: false\n }\n });\n }\n }\n });\n return Oficina;\n};\n```\n\nsecretaria.js\n\n```\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n var Secretaria = sequelize.define('Secretaria', {\n nombre_secretaria: DataTypes.STRING\n }, {\n classMethods: {\n associate: function(models) {\n Secretaria.hasMany(models.Oficina);\n }\n }\n });\n return Secretaria;\n};\n```\n\nsync() on www.js\n\n```\nmodels.sequelize.sync().then(function() {\n /**\n * Listen on provided port, on all network interfaces.\n */\n\n server.listen(port);\n server.on('error', onError);\n server.on('listening', onListening);\n});\n```\n\nIt seams that the name is the problem, if instead of \"Secretaria\" i use \"Secre\" it works fine, but \"Secret\" or \"Secret\" + any other letter does not pluralize the table secretaria and the foreign key end up \"secretariumId\".\n Is \"Secret+++++\" some kind of reserved word ?\n\nUPDATE\n\n```\n\"use strict\";\nmodule.exports = function(sequelize, DataTypes) {\n var Secretaria = sequelize.define(\"Secretaria\",\n {\n nombre: DataTypes.STRING\n }, \n {\n classMethods: {\n associate: function(models) {\n Secretaria.hasMany(models.Oficina)\n }\n },\n name: {\n singular: 'secretaria',\n plural: 'secretarias',\n },\n tableName: \"secretarias\"\n });\n\n return Secretaria;\n};\n```\n\nUsing the options name fixes the foreign key problem, and tableName is fixing the pluralization. Now everything is working fine.\n\n========================================\n\nCode:\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var Oficina = sequelize.define('Oficina', {\n    nombre_oficina: DataTypes.STRING,\n    direccion: DataTypes.STRING,\n    telefono: DataTypes.STRING,\n    interno: DataTypes.STRING,\n    email: DataTypes.STRING\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Oficina.belongsTo(models.Secretaria, {\n          onDelete: \"CASCADE\",\n          foreignKey: {\n            allowNull: false\n          }\n        });\n      }\n    }\n  });\n  return Oficina;\n};\n```\n\n```text\n'use strict';\nmodule.exports = function(sequelize, DataTypes) {\n  var Secretaria = sequelize.define('Secretaria', {\n    nombre_secretaria: DataTypes.STRING\n  }, {\n    classMethods: {\n      associate: function(models) {\n        Secretaria.hasMany(models.Oficina);\n      }\n    }\n  });\n  return Secretaria;\n};\n```\n\n```text\nmodels.sequelize.sync().then(function() {\n  /**\n   * Listen on provided port, on all network interfaces.\n   */\n\n  server.listen(port);\n  server.on('error', onError);\n  server.on('listening', onListening);\n});\n```\n\n```text\n\"use strict\";\nmodule.exports = function(sequelize, DataTypes) {\n  var Secretaria = sequelize.define(\"Secretaria\",\n  {\n    nombre: DataTypes.STRING\n  }, \n  {\n    classMethods: {\n      associate: function(models) {\n        Secretaria.hasMany(models.Oficina)\n      }\n    },\n    name: {\n      singular: 'secretaria',\n      plural: 'secretarias',\n    },\n    tableName: \"secretarias\"\n  });\n\n  return Secretaria;\n};\n```\n\n```text\nSequelize/express\n```\n\n```text\nsecretariaid\n```\n\n```text\nsecretarumid\n```\n\n```text\nvar Secretaria = sequelize.define('Secretaria', {\n    nombre_secretaria: DataTypes.STRING\n  },\n  name: {\n    singular: 'secretaria',\n    plural: 'secretarias',\n  },\n  freezeTableName: true, // table name is singular \"Secreteria\"\n```\n\n```text\noptions.name\n```\n\n```text\nSequelize.define\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n```text\nfreezeTableName: true/false,\n```\n\n========================================\n\nComments:\n- Thanks for the answer, that example and the link to the define documentation help me fix the problem.","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":227,"estimatedTokens":1160}}1117{"id":"stack-31901204","source":"stackoverflow","questionId":31901204,"title":"Express Sequelize and Passport.js authentication strategy not working","tags":["node.js","postgresql","express","passport.js","sequelize.js"],"text":"Title: Express Sequelize and Passport.js authentication strategy not working\nTags: node.js, postgresql, express, passport.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have the following authentication strategy for Express and Sequelize using passport.js:\n\n```\nvar LocalStrategy = require('passport-local').Strategy;\nvar User = require('../../models').User;\n\nmodule.exports = function (passport) {\n\n passport.use('register', new LocalStrategy({\n passReqToCallback: true,\n usernameField: 'email'\n }, function (req, email, password, done) {\n\n //var findOrCreateUser = function () {\n // find a user in Mongo with provided username\n User.findOrCreate({where: {email: email}}).spread(\n function (user, created) {\n // In case of any error, return using the done method\n //if (err) {\n // console.log('Error in SignUp: ' + err);\n // return done(err);\n //}\n\n if (email !== req.param('email-confirm')) {\n console.log('Registration: Email address do not match');\n return done(null, false, {message: 'Email addresses do not match'});\n }\n\n // already exists\n if (user) {\n console.log('User ' + email + ' is already registered.');\n return done(null, false, {'message': 'The email ' + email + ' is already registered.'});\n } else {\n\n // if there is no user with that email\n // create the user\n var newUser = new User();\n\n // set the user's local credentials\n newUser.email = email;\n newUser.password = password;\n\n // save the user\n newUser.save(function (err) {\n if (err) {\n console.log('Error in Saving user: ' + err);\n throw err;\n }\n console.log('New user registration', newUser);\n return done(null, newUser);\n });\n }\n });\n //};\n //// Delay the execution of findOrCreateUser and execute the method\n //// in the next tick of the event loop\n //process.nextTick(findOrCreateUser);\n })\n );\n\n};\n```\n\nThe problem is that when I execute the code it fails to insert into the db with the following error:\n\n```\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): START TRANSACTION;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): SET autocommit = 1;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): SELECT \"id\", \"email\", \"password\", \"lastLogin\", \"createdAt\", \"updatedAt\", \"deletedAt\" FROM \"Users\" AS \"User\" WHERE (\"User\".\"deletedAt\" IS NULL AND \"User\".\"email\" = 'user@email.com') LIMIT 1;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): COMMIT;\nUnhandled rejection TypeError: Object [object SequelizeInstance:User] has no method 'isModified'\n at sequelize.define.instanceMethods.save (/home/otis/Developer/Project/models/users.js:24:26)\n at Model.create (/home/otis/Developer/Project/node_modules/sequelize/lib/model.js:1735:6)\n at Object. (/home/otis/Developer/Project/node_modules/sequelize/lib/model.js:1837:17)\n at Object.tryCatcher (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/util.js:26:23)\n at Promise._settlePromiseFromHandler (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:503:31)\n at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:577:18)\n at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:128:12)\n at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)\n at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n at process._tickCallback (node.js:415:13)\n```\n\nI know it is during the user creation because if I get it to error with the same email address that all works. But if it starts to create a user it errors out, and the web page stalls.\n\nUpdate: If I run it with just `.find`:\n\n```\nExecuting (default): SELECT \"id\", \"email\", \"password\", \"lastLogin\", \"createdAt\", \"updatedAt\", \"deletedAt\" FROM \"Users\" AS \"User\" WHERE (\"User\".\"deletedAt\" IS NULL AND \"User\".\"email\" = 'user@email.com') LIMIT 1;\nUnhandled rejection TypeError: expecting an array, a promise or a thenable\n\n See https://github.com/petkaantonov/bluebird/wiki/Error:-expecting-an-array,-a-promise-or-a-thenable\n\n at PromiseArray.init [as _init] (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise_array.js:42:27)\n at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:575:21)\n at Promise._settlePromises (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:693:14)\n at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:123:16)\n at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)\n at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n at process._tickCallback (node.js:415:13)\n```\n\nUpdate: removed `.spread`:\n\n```\nExecuting (default): SELECT \"id\", \"email\", \"password\", \"lastLogin\", \"createdAt\", \"updatedAt\", \"deletedAt\" FROM \"Users\" AS \"User\" WHERE (\"User\".\"deletedAt\" IS NULL AND \"User\".\"email\" = 'user@email.com') LIMIT 1;\nexpress deprecated req.param(name): Use req.params, req.body, or req.query instead middlewares/authentication/registration-strategy.js:21:39\nUnhandled rejection TypeError: object is not a function\n at null. (/home/otis/Developer/Project/middlewares/authentication/registration-strategy.js:35:39)\n at tryCatcher (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/util.js:26:23)\n at Promise._settlePromiseFromHandler (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:503:31)\n at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:577:18)\n at Promise._settlePromises (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:693:14)\n at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:123:16)\n at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)\n at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n at process._tickCallback (node.js:415:13)\n```\n\n========================================\n\nCode:\n```text\nvar LocalStrategy = require('passport-local').Strategy;\nvar User = require('../../models').User;\n\nmodule.exports = function (passport) {\n\n    passport.use('register', new LocalStrategy({\n            passReqToCallback: true,\n            usernameField: 'email'\n        }, function (req, email, password, done) {\n\n            //var findOrCreateUser = function () {\n            // find a user in Mongo with provided username\n            User.findOrCreate({where: {email: email}}).spread(\n                function (user, created) {\n                    // In case of any error, return using the done method\n                    //if (err) {\n                    //    console.log('Error in SignUp: ' + err);\n                    //    return done(err);\n                    //}\n\n                    if (email !== req.param('email-confirm')) {\n                        console.log('Registration: Email address do not match');\n                        return done(null, false, {message: 'Email addresses do not match'});\n                    }\n\n                    // already exists\n                    if (user) {\n                        console.log('User ' + email + ' is already registered.');\n                        return done(null, false, {'message': 'The email ' + email + ' is already registered.'});\n                    } else {\n\n\n                        // if there is no user with that email\n                        // create the user\n                        var newUser = new User();\n\n                        // set the user's local credentials\n                        newUser.email = email;\n                        newUser.password = password;\n\n                        // save the user\n                        newUser.save(function (err) {\n                            if (err) {\n                                console.log('Error in Saving user: ' + err);\n                                throw err;\n                            }\n                            console.log('New user registration', newUser);\n                            return done(null, newUser);\n                        });\n                    }\n                });\n            //};\n            //// Delay the execution of findOrCreateUser and execute the method\n            //// in the next tick of the event loop\n            //process.nextTick(findOrCreateUser);\n        })\n    );\n\n};\n```\n\n```text\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): START TRANSACTION;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): SET autocommit = 1;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): SELECT \"id\", \"email\", \"password\", \"lastLogin\", \"createdAt\", \"updatedAt\", \"deletedAt\" FROM \"Users\" AS \"User\" WHERE (\"User\".\"deletedAt\" IS NULL AND \"User\".\"email\" = 'user@email.com') LIMIT 1;\nExecuting (fa4929e4-6b35-40ce-9e02-daf80af507e1): COMMIT;\nUnhandled rejection TypeError: Object [object SequelizeInstance:User] has no method 'isModified'\n    at sequelize.define.instanceMethods.save (/home/otis/Developer/Project/models/users.js:24:26)\n    at Model.create (/home/otis/Developer/Project/node_modules/sequelize/lib/model.js:1735:6)\n    at Object.<anonymous> (/home/otis/Developer/Project/node_modules/sequelize/lib/model.js:1837:17)\n    at Object.tryCatcher (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/util.js:26:23)\n    at Promise._settlePromiseFromHandler (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:503:31)\n    at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:577:18)\n    at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:128:12)\n    at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)\n    at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n    at process._tickCallback (node.js:415:13)\n```\n\n```text\nExecuting (default): SELECT \"id\", \"email\", \"password\", \"lastLogin\", \"createdAt\", \"updatedAt\", \"deletedAt\" FROM \"Users\" AS \"User\" WHERE (\"User\".\"deletedAt\" IS NULL AND \"User\".\"email\" = 'user@email.com') LIMIT 1;\nUnhandled rejection TypeError: expecting an array, a promise or a thenable\n\n    See https://github.com/petkaantonov/bluebird/wiki/Error:-expecting-an-array,-a-promise-or-a-thenable\n\n    at PromiseArray.init [as _init] (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise_array.js:42:27)\n    at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:575:21)\n    at Promise._settlePromises (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:693:14)\n    at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:123:16)\n    at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)\n    at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n    at process._tickCallback (node.js:415:13)\n```\n\n```text\nExecuting (default): SELECT \"id\", \"email\", \"password\", \"lastLogin\", \"createdAt\", \"updatedAt\", \"deletedAt\" FROM \"Users\" AS \"User\" WHERE (\"User\".\"deletedAt\" IS NULL AND \"User\".\"email\" = 'user@email.com') LIMIT 1;\nexpress deprecated req.param(name): Use req.params, req.body, or req.query instead middlewares/authentication/registration-strategy.js:21:39\nUnhandled rejection TypeError: object is not a function\n    at null.<anonymous> (/home/otis/Developer/Project/middlewares/authentication/registration-strategy.js:35:39)\n    at tryCatcher (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/util.js:26:23)\n    at Promise._settlePromiseFromHandler (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:503:31)\n    at Promise._settlePromiseAt (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:577:18)\n    at Promise._settlePromises (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:693:14)\n    at Async._drainQueue (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:123:16)\n    at Async._drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:133:10)\n    at Async.drainQueues (/home/otis/Developer/Project/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)\n    at process._tickCallback (node.js:415:13)\n```\n\n```text\n.find\n```\n\n```text\n.spread\n```\n\n```text\nnew\n```\n\n```text\nbuild\n```\n\n```text\ncreate\n```\n\n========================================\n\nComments:\n- what happens if you replace `findOrCreate` with just `find` ? since you're creating user later, there is no need to use it.\n- remove `spread`: `findOne({email: email}).then(function(user){ ... })`\n- sorry what do you mean?\n- `spread` expects array of values, or promises. But `findOne&#47;find` returns single value. So replace `User.findOne().spread()` with `User.findOne({email: email}).then(function(user){ ... })`","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":266,"estimatedTokens":3495}}1118{"id":"stack-33596558","source":"stackoverflow","questionId":33596558,"title":"N:M association error when using include.through","tags":["sequelize.js"],"text":"Title: N:M association error when using include.through\nTags: sequelize.js\nSource: Stack Overflow\n\nQuestion:\n### Scenario\n\nA User can have many Tag objects. A Tag object belongs to one user. A Tag has many Transactions. A Transaction belongs to one Tag. Users have many Transactions. A Transaction can have many User.\n\n### Models\n\n```\nvar User = sequelize.define('User', {\n id: {\n type: Sequelize.BIGINT,\n autoIncrement: true,\n primaryKey: true\n },\n\n ...\n\n }, { timestamps: false, freezeTableName: true, tableName: 'register'});\n\nvar Tag = sequelize.define('Tag', {\n tagId: {\n type: Sequelize.STRING(50),\n primaryKey: true,\n allowNull: false\n },\n\n ...\n\n }, { timestamps: false, freezeTableName: true, tableName: 'tag'});\n\nvar Transaction = sequelize.define('Transaction', {\n id: {\n type: Sequelize.BIGINT,\n autoIncrement: true,\n primaryKey: true\n },\n active: {\n type: Sequelize.BOOLEAN,\n defaultValue: true\n }\n }, { timestamps: false, freezeTableName: true, tableName: 'transaction'});\n\nvar UserTx = sequelize.define('UserTx', {\n id: {\n type: Sequelize.BIGINT,\n autoIncrement: true,\n primaryKey: true\n }\n },\n { timestamps: false, freezeTableName: true, tableName: 'user_transaction'});\n```\n\n### Relations\n\n```\nUser.hasMany(Tag, {foreignKey: 'owner_id', foreignKeyConstraint: true});\nTag.belongsTo(User, {foreignKey: 'owner_id', foreignKeyConstraint: true});\n\nTag.hasMany(Transaction, {foreignKey: 'tag_id', foreignKeyConstraint: true});\nTransaction.belongsTo(Tag, {foreignKey: 'tag_id', foreignKeyConstraint: true});\n\nUser.belongsToMany(Transaction, {through: {model: UserTx, unique: false}, foreignKey: 'user_id'});\nTransaction.belongsToMany(User, {through: {model: UserTx, unique: false}, foreignKey: 'tx_id'});\n```\n\n### Problem\n\nI am trying to return a list of Tag objects owned by a given user, in addition to Tag objects that the user has associated Transactions for. In plain SQL:\n\n```\nselect * from tag \nleft outer join transaction on tag.\"tagId\" = transaction.tag_id \nleft outer join user_transaction on transaction.id = user_transaction.tx_id \nwhere tag.owner_id = ? or user_transaction.user_id = ?\n```\n\nMy current Sequelize query:\n\n```\nTag.findAll({\n where: { owner_id: userId }, // missing OR user_transaction.user_id = userId\n include: [{\n model: Transaction,\n attributes: ['id'],\n through: {model: UserTx, where: {user_id: userId}, attributes: ['user_id', 'tx_id']},\n where: {\n active: true\n },\n required: false, // include Tags that do not have an associated Transaction\n }]\n})\n```\n\nWhen this query is called, I get the following error:\n\n```\nUnhandled rejection TypeError: Cannot call method 'replace' of undefined\nat Object.module.exports.removeTicks (/site/services/node_modules/sequelize/lib/utils.js:343:14)\nat Object.module.exports.addTicks (/site/services/node_modules/sequelize/lib/utils.js:339:29)\nat Object.QueryGenerator.quoteIdentifier (/site/services/node_modules/sequelize/lib/dialects/postgres/query-generator.js:843:20)\nat generateJoinQueries (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1207:72)\nat Object. (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1388:27)\nat Array.forEach (native)\nat Object.QueryGenerator.selectQuery (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1387:10)\nat QueryInterface.select (/site/services/node_modules/sequelize/lib/query-interface.js:679:25)\nat null. (/site/services/node_modules/sequelize/lib/model.js:1386:32)\n```\n\nSetting a breakpoint in the removeTicks function and setting a watch on 's' (the column name attribute), I notice the following:\n\n```\ns = \"Transactions\"\ns = \"Transactions.id\"\ns = \"Transactions.undefined\" // should be Transactions.UserTx ?\ns = \"user_id\"\ns = \"Transactions.undefined.user_id\"\ns = \"Transactions.undefined\"\ns = \"tx_id\"\ns = \"Transactions.undefined.tx_id\"\n```\n\nIs my usage of N:M incorrect? I have used the 'through' construct in a 'find' query elsewhere with success, but as this 'through' is nested in an include, it seems to be behaving differently (such as requiring me to pass through.model explicitly)\n\nAny help would be much appreciated!\n\n========================================\n\nCode:\n```text\nvar User = sequelize.define('User', {\n      id: {\n          type: Sequelize.BIGINT,\n          autoIncrement: true,\n          primaryKey: true\n      },\n\n      ...\n\n  }, { timestamps: false, freezeTableName: true, tableName: 'register'});\n\n\nvar Tag = sequelize.define('Tag', {\n      tagId: {\n          type: Sequelize.STRING(50),\n          primaryKey: true,\n          allowNull: false\n      },\n\n      ...\n\n  }, { timestamps: false, freezeTableName: true, tableName: 'tag'});\n\n\nvar Transaction = sequelize.define('Transaction', {\n      id: {\n          type: Sequelize.BIGINT,\n          autoIncrement: true,\n          primaryKey: true\n      },\n      active: {\n          type: Sequelize.BOOLEAN,\n          defaultValue: true\n      }\n  }, { timestamps: false, freezeTableName: true, tableName: 'transaction'});\n\n\nvar UserTx = sequelize.define('UserTx', {\n    id: {\n        type: Sequelize.BIGINT,\n        autoIncrement: true,\n        primaryKey: true\n    }\n  },\n  { timestamps: false, freezeTableName: true, tableName: 'user_transaction'});\n```\n\n```text\nUser.hasMany(Tag, {foreignKey: 'owner_id', foreignKeyConstraint: true});\nTag.belongsTo(User, {foreignKey: 'owner_id', foreignKeyConstraint: true});\n\nTag.hasMany(Transaction, {foreignKey: 'tag_id', foreignKeyConstraint: true});\nTransaction.belongsTo(Tag, {foreignKey: 'tag_id', foreignKeyConstraint: true});\n\nUser.belongsToMany(Transaction, {through: {model: UserTx, unique: false}, foreignKey: 'user_id'});\nTransaction.belongsToMany(User, {through: {model: UserTx, unique: false}, foreignKey: 'tx_id'});\n```\n\n```text\nselect * from tag \nleft outer join transaction on tag.\"tagId\" = transaction.tag_id \nleft outer join user_transaction on transaction.id = user_transaction.tx_id \nwhere tag.owner_id = ? or user_transaction.user_id = ?\n```\n\n```text\nTag.findAll({\n      where: { owner_id: userId }, // missing OR user_transaction.user_id = userId\n      include: [{\n        model: Transaction,\n        attributes: ['id'],\n        through: {model: UserTx, where: {user_id: userId}, attributes: ['user_id', 'tx_id']},\n        where: {\n          active: true\n        },\n        required: false, // include Tags that do not have an associated Transaction\n      }]\n})\n```\n\n```text\nUnhandled rejection TypeError: Cannot call method 'replace' of undefined\nat Object.module.exports.removeTicks (/site/services/node_modules/sequelize/lib/utils.js:343:14)\nat Object.module.exports.addTicks (/site/services/node_modules/sequelize/lib/utils.js:339:29)\nat Object.QueryGenerator.quoteIdentifier (/site/services/node_modules/sequelize/lib/dialects/postgres/query-generator.js:843:20)\nat generateJoinQueries (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1207:72)\nat Object.<anonymous> (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1388:27)\nat Array.forEach (native)\nat Object.QueryGenerator.selectQuery (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1387:10)\nat QueryInterface.select (/site/services/node_modules/sequelize/lib/query-interface.js:679:25)\nat null.<anonymous> (/site/services/node_modules/sequelize/lib/model.js:1386:32)\n```\n\n```text\ns = \"Transactions\"\ns = \"Transactions.id\"\ns = \"Transactions.undefined\" // should be Transactions.UserTx ?\ns = \"user_id\"\ns = \"Transactions.undefined.user_id\"\ns = \"Transactions.undefined\"\ns = \"tx_id\"\ns = \"Transactions.undefined.tx_id\"\n```\n\n```text\nfunction using_two_findall(user_id) {\n  var tags_associated_via_tx = models.tag.findAll({\n    include: [{\n      model: models.transaction,\n      include: [{\n        model: models.user,\n        where: { id: user_id }\n      }]\n    }]\n  });\n\n  var tags_owned_by_user = models.tag.findAll({\n    where: { owner_id: user_id }\n  });\n\n  return Promise.all([tags_associated_via_tx, tags_owned_by_user])\n  .spread(function(tags_associated_via_tx, tags_owned_by_user) {\n    // dedupe the two arrays of tags:\n    return _.uniq(_.flatten(tags_associated_via_tx, tags_owned_by_user), 'id')\n  });\n}\n```\n\n```text\nfunction using_raw_query(user_id) {\n  var sql = 'select s05.tag.id, s05.tag.owner_id from s05.tag ' +\n            'where s05.tag.owner_id = ' + user_id + ' ' +\n            'union ' +\n            'select s05.tag.id, s05.tag.owner_id from s05.tag, s05.transaction, s05.user_tx ' +\n            'where s05.tag.id = s05.transaction.tag_id and s05.user_tx.tx_id = s05.transaction.id and ' +\n            's05.user_tx.user_id = ' + user_id;\n\n  return sq.query(sql, { type: sq.QueryTypes.SELECT})\n  .then(function(data_array) {\n    return _.map(data_array, function(data) {\n      return models.tag.build(data, { isNewRecord: false });;\n    });\n  })\n  .catch(function(err) {\n    console.error(err);\n    console.error(err.stack);\n    return err;\n  });\n}\n```\n\n```text\nTypeError: Cannot call method 'replace' of undefined\n```\n\n```text\nthrough.where\n```\n\n========================================\n\nComments:\n- Submitted an issue to sequelize github here: github.com/sequelize/sequelize/issues/4866\n- Thanks for your effort to diagnose the problem, as well as following up by posting an issue on Github. I ended up doing two separate findAll queries. Excellent tip with using lodash's dedupe function.","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":297,"estimatedTokens":2350}}1119{"id":"stack-74907168","source":"stackoverflow","questionId":74907168,"title":"what is the best updating method in sequelize","tags":["mysql","node.js","sequelize.js"],"text":"Title: what is the best updating method in sequelize\nTags: mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to update a row on my table but after updating the row i want to have it so i can return in in the response\ni am wondering which is better for performance and best practice\nwhen using sequlize\nwhich is better ?\n\n```\nconst updatedRows= await Product.update(\n{ name, image, price, categoryId },\n{ where: { id: prodId } }\n);\nconst updatedProduct = await Product.findByPk(prodId);\n```\n\nOR\n\n```\nconst product = await Product.findByPk(prodId);\nproduct.update( { name, image, price, categoryId });\nawait product.save()\n```\n\nand the updatedProduct here is the product itself\n\n========================================\n\nCode:\n```text\nconst updatedRows= await Product.update(\n{ name, image, price, categoryId },\n{ where: { id: prodId } }\n);\nconst updatedProduct = await Product.findByPk(prodId);\n```\n\n```text\nconst product = await Product.findByPk(prodId);\nproduct.update( { name, image, price, categoryId });\nawait product.save()\n```\n\n```text\nconst product = await Product.findByPk(prodId);\n\nif (product) {\nawait product.update( { name, image, price, categoryId });\n} else {\nthrow new Error('product not found') // res.status(400).send({error: 'product not found'});\n}\n```\n\n========================================\n\nComments:\n- Show us the generated SQL.\n- It would be nice to give a brief explanation of how this works / how it solves the problem.","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":60,"estimatedTokens":368}}1120{"id":"stack-23284305","source":"stackoverflow","questionId":23284305,"title":"how to import modules that require arguments","tags":["node.js","express","module","sequelize.js"],"text":"Title: how to import modules that require arguments\nTags: node.js, express, module, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nthis is my files sturcture:\n\n```\n-models\n -user.js\n -room.js\n -database.js\n-controllers\n -createRoom.js\n -routes.js\n ..\n```\n\nuser.js and room.js are modules i want to import in database.js. right now im doing like this:\n\nin database.js:\n\n```\nvar mysql = require('mysql');\nvar Sequelize = require('sequelize');\nvar db = new Sequelize('test', 'root', 'root', {\ndialect: \"mysql\", \nport: 3306\n\n})\nvar User = require('./user.js')(Sequelize, db);\nvar Room = require('./room.js')(Sequelize, db);\n\nmodule.exports = function(){\n\n //code... \n\n};\n```\n\nin user.js/room.js\n\n```\nmodule.exports = function (Sequelize, db) { \n\nvar Room = db.define('Room', {\n room_id : {type: Sequelize.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true},\n})\n\ndb\n .sync({force: true})\n .complete(function (err) {})\n```\n\nso far so good, but when i need to import user.js or room.js in other files besides database.js(eg, createRoom.js), i have trouble importing them because theres no Sequelize and db defined like in the database.js. does it mean i have to connect to the database and require Sequelize again whenever i need to use user.js and room.js module in other files? is there a better way to work around this?? thanks!\n\n========================================\n\nCode:\n```text\n-models\n    -user.js\n    -room.js\n    -database.js\n-controllers\n    -createRoom.js\n    -routes.js\n    ..\n```\n\n```text\nvar mysql = require('mysql');\nvar Sequelize = require('sequelize');\nvar db = new Sequelize('test', 'root', 'root', {\ndialect: \"mysql\", \nport: 3306\n\n})\nvar User = require('./user.js')(Sequelize, db);\nvar Room = require('./room.js')(Sequelize, db);\n\n\nmodule.exports = function(){\n\n    //code...   \n\n};\n```\n\n```text\nmodule.exports = function (Sequelize, db) { \n\nvar Room = db.define('Room', {\n    room_id : {type: Sequelize.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true},\n})\n\ndb\n .sync({force: true})\n .complete(function (err) {})\n```\n\n```text\n//init code as seen\nmodule.exports.Room = Room\n```\n\n```text\nrequire('../models/database').Room\n```\n\n```text\nmodule.export = { Sequelize: Sequelize, db : db}\n```\n\n```text\nvar dbModule = require('./database')\n module.exports = dbModule.Sequelize.define('Room', /*....*/)\n```\n\n```text\nmodule.exports = roomInit\n\nfunction roomInit(Sequelize, db) { \n\n  roomInit.Room = db.define('Room', {\n    room_id : {type: Sequelize.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true}\n})\n\n db\n   .sync({force: true})\n   .complete(function (err) {})\n }\n```\n\n```text\nrequire('./room').Room\n```\n\n========================================\n\nComments:\n- Hi, thanks for you reply. the #2 looks like a good approach to me but Sequelize and db dont seem to be exported. it said dbModule.Sequelize was undefined.\n- if your database.js looks exactly like in your example then just attach new properties after the main export. in your example there is a module.exports= function already, so you have to attach additional exports to it\n- what do you mean by attaching?\n- module.exports = function(){}; module.exports.Sequelize = Sequelize; module.exports.db = db;","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":145,"estimatedTokens":805}}1121{"id":"stack-70740071","source":"stackoverflow","questionId":70740071,"title":"How to compare two columns not having same value using sequelize orm","tags":["database","postgresql","sequelize.js"],"text":"Title: How to compare two columns not having same value using sequelize orm\nTags: database, postgresql, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI have two fields in my table `dispatchCount & qty`.\n\nI want to `findOne` tuple where `dispatchCount` is not equal to `qty`\n\nI want to do something similar to this (Mysql Select Rows Where two columns do not have the same value) but using sequelize ORM.\n\nI don't want to write the raw query myself bcz there are a lot of aliases & things like that. So how can I do the following using sequelize\n\n```\nSELECT *\nFROM my_table\nWHERE column_a != column_b\n```\n\n========================================\n\nCode:\n```sql\nSELECT *\nFROM my_table\nWHERE column_a != column_b\n```\n\n```text\ndispatchCount & qty\n```\n\n```text\nfindOne\n```\n\n```text\ndispatchCount\n```\n\n```text\nqty\n```\n\n```js\nlet en = Entity.findOne({\n    where: {\n        dispatchCount : {\n            [Op.ne]: sequelize.col(\"qty\");\n        }\n    }\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":53,"estimatedTokens":238}}1122{"id":"stack-14700570","source":"stackoverflow","questionId":14700570,"title":"Node.js Sequelize ManyToMany relations producing incorrect SQL","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Node.js Sequelize ManyToMany relations producing incorrect SQL\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm having a problem with sequelize ManyToMany relations.\n\nHere are my models...\n\n```\nvar db = {\n\n players: sequelize.define('players', {\n name: Sequelize.STRING\n }),\n\n teams: sequelize.define('teams', {\n name: Sequelize.STRING\n }), \n\n init: function() {\n\n this.players.hasMany(this.teams, {joinTableName: 'teams_has_players'});\n this.teams.hasMany(this.players, {joinTableName: 'teams_has_players'});\n\n this.players.sync();\n this.teams.sync();\n\n }\n\n};\n```\n\nHere's the find\n\n```\ndb.players.findAll({\n where: {team_id: 1},\n include: ['teams']\n}).success(function(results) {\n // print the results\n});\n```\n\nThe above find will produce the following SQL:\n\n```\nSELECT \n players . *,\n teams.name AS `teams.name`,\n teams.id AS `teams.id`\nFROM\n players\n LEFT OUTER JOIN\n teams_has_players ON teams_has_players.player_id = players.id\n LEFT OUTER JOIN\n teams ON teams.id = teams_has_players.team_id\nWHERE\n players.team_id = '1';\n```\n\nWhat appears to be wrong with this is that the WHERE statement should be `WHERE teams.team_id = '1'`\n\nWhere am I going wrong with this?\n\nThanks in advance\n\n========================================\n\nCode:\n```text\nvar db = {\n\n    players: sequelize.define('players', {\n        name: Sequelize.STRING\n    }),\n\n    teams: sequelize.define('teams', {\n        name: Sequelize.STRING\n    }),   \n\n\n    init: function() {\n\n        this.players.hasMany(this.teams, {joinTableName: 'teams_has_players'});\n        this.teams.hasMany(this.players, {joinTableName: 'teams_has_players'});\n\n        this.players.sync();\n        this.teams.sync();\n\n    }\n\n};\n```\n\n```text\ndb.players.findAll({\n    where:      {team_id: 1},\n    include:    ['teams']\n}).success(function(results) {\n    // print the results\n});\n```\n\n```text\nSELECT \n    players . *,\n    teams.name AS `teams.name`,\n    teams.id AS `teams.id`\nFROM\n    players\n        LEFT OUTER JOIN\n    teams_has_players ON teams_has_players.player_id = players.id\n        LEFT OUTER JOIN\n    teams ON teams.id = teams_has_players.team_id\nWHERE\n    players.team_id = '1';\n```\n\n```text\nWHERE teams.team_id = '1'\n```\n\n```text\ndb.players.findAll\n```\n\n```text\nwhere: { team_id: 1 }\n```\n\n```text\nWHERE players.team_id = '1'\n```\n\n```text\nteams\n```\n\n```text\nteam_id\n```\n\n```text\nid\n```\n\n```text\ninclude\n```\n\n========================================\n\nComments:\n- Thanks for letting me know it wasn't a bug, i've changed the find to... db.teams.findAll({ where: {id: req.params.team_id}, include: ['players'] }).success(function(results) { res.json(results); }); and it works as expected. Thanks for sequelize Sascha, just wish there was more documentation.\n- yeah many things have to be improved. if spare time would just be enough to do everything at once :)","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":156,"estimatedTokens":715}}1123{"id":"stack-66291003","source":"stackoverflow","questionId":66291003,"title":"Passing options to Sequelize hook not working","tags":["node.js","sequelize.js","hook"],"text":"Title: Passing options to Sequelize hook not working\nTags: node.js, sequelize.js, hook\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to pass options to a Sequelize hook, but when I try to access the passed options within the hook, they are always undefined.\nAnyone got an idea what I am overseeing?\n\nHere's the query:\n\n```\ndb.customer.findAll({\n where: searchObject,\n offset: offset,\n limit: limit,\n order: orderOptions\n }, {\n user: req.user\n }).then(customers => {\n// more code here\n```\n\nAnd here's the model including the hook definition:\n\n```\nconst db = require(\"../server/database\");\nconst Sequelize = require('sequelize');\nconst Op = Sequelize.Op;\n\nmodule.exports = function (sequelize, Sequelize) {\n\n var Customer = sequelize.define('customer', {\n id: {\n autoIncrement: true,\n primaryKey: true,\n allowNull: false,\n type: Sequelize.INTEGER\n },\n salutation: {\n type: Sequelize.TEXT\n },\n title: {\n type: Sequelize.TEXT\n },\n firstName: {\n type: Sequelize.TEXT\n },\n lastName: {\n type: Sequelize.TEXT\n }\n }, {\n freezeTableName: true\n });\n\n Customer.beforeFindAfterExpandIncludeAll((instance, options) => {\n console.log(options);\n });\n\n return Customer;\n}\n```\n\n========================================\n\nCode:\n```text\ndb.customer.findAll({\n            where: searchObject,\n            offset: offset,\n            limit: limit,\n            order: orderOptions\n        }, {\n            user: req.user\n        }).then(customers => {\n// more code here\n```\n\n```text\nconst db = require(\"../server/database\");\nconst Sequelize = require('sequelize');\nconst Op = Sequelize.Op;\n\nmodule.exports = function (sequelize, Sequelize) {\n\n  var Customer = sequelize.define('customer', {\n    id: {\n      autoIncrement: true,\n      primaryKey: true,\n      allowNull: false,\n      type: Sequelize.INTEGER\n    },\n    salutation: {\n      type: Sequelize.TEXT\n    },\n    title: {\n      type: Sequelize.TEXT\n    },\n    firstName: {\n      type: Sequelize.TEXT\n    },\n    lastName: {\n      type: Sequelize.TEXT\n    }\n  }, {\n    freezeTableName: true\n  });\n\n  Customer.beforeFindAfterExpandIncludeAll((instance, options) => {\n    console.log(options);\n  });\n\n  return Customer;\n}\n```\n\n```text\ndb.customer.findAll({\n            where: searchObject,\n            offset: offset,\n            limit: limit,\n            order: orderOptions,\n            user: req.user\n        }).then(customers => {\n// more code here\n```\n\n```text\nCustomer.beforeFindAfterExpandIncludeAll((instance) => {\n    console.log(instance.user); // This logs the user object correctly\n  });\n```\n\n========================================\n\nComments:\n- What version of sequelize are you using?\n- I am using Sequelize v6.3.5\n- Can you tell me how the \"user\" object is defined and where?\n- The req.user object is set by passport once a user logs in. The variable is set and shown correctly when logging it to the console.\n- @Max I think \"user\" param being used in findAll function is causing the error. sequelize.org/master/class/lib/&hellip; Have a look at the documentation. Please try removing the \"user\" param and run the query. If you need to use \"user\" as a param in the query, you might need to modify the model of customer such that it contains \"user\" as a field and then use the suitable case with user inside where clause.\n- I don't think that's the issue. Take a look here: stackoverflow.com/questions/38257369/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:34.502Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":141,"estimatedTokens":843}}1124{"id":"stack-72110005","source":"stackoverflow","questionId":72110005,"title":"Sequelize ORDER BY ASC numeric string","tags":["javascript","mysql","node.js","sequelize.js"],"text":"Title: Sequelize ORDER BY ASC numeric string\nTags: javascript, mysql, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nplease help in this matter. So my scenario is that I have driver app (flutter) that fetch ongoing orders that needed to be delivered. I would like to fetch orders according to `order` column ASC, I already set that in my backend. Here is the code:\n\n```\nstatic async getOngoingOrders(driverId, cb) {\n try {\n const orders = {\n instant: [],\n scheduled: [],\n };\n\n // @scheduled\n if (!orders.instant.length) {\n const scheduledOrders = await BatchOrder.findAll({\n where: {\n deliveryDate: {\n [Op.gte]: moment().format(\"YYYY-MM-DD\"),\n [Op.lt]: moment().add(1, \"days\").format(\"YYYY-MM-DD\"),\n },\n },\n include: [\n {\n model: BatchSchedule,\n attributes: [\"id\", \"name\", \"start\", \"end\"],\n },\n {\n model: BatchDriver,\n where: {\n DriverId: driverId,\n status: \"Driver on the Way\",\n },\n attributes: [\"status\", \"DriverId\"],\n include: [\n {\n model: Order,\n where: {\n status: {\n [Op.not]: [\"Not Delivered\", \"Complained\"],\n },\n },\n attributes: [\"id\", \"orderId\", \"status\", \"order\"],\n include: [\n {\n model: User,\n attributes: [\"fullName\", \"phoneNumber\", \"uid\"],\n },\n {\n model: Address,\n attributes: [\n \"name\",\n \"address\",\n \"details\",\n \"notes\",\n \"longitude\",\n \"latitude\",\n ],\n },\n ],\n // ******* here is the ASC *******\n order: [[\"order\", \"ASC\"]],\n },\n ],\n },\n ],\n attributes: [\"id\", \"deliveryDate\"],\n });\n\n const formattedScheduledOrder = scheduledOrders.map((batch) => {\n const formattedOrder = {\n name: batch.BatchSchedule.name,\n start: batch.BatchSchedule.start.substr(0, 5),\n end: batch.BatchSchedule.end.substr(0, 5),\n Orders: [],\n };\n\n let delivered = 0;\n\n batch.BatchDrivers[0].Orders.map((order) => {\n if (\n order.status === \"Delivered\"\n ) {\n delivered++;\n } else {\n formattedOrder.Orders.push({\n id: order.id,\n order: order.order,\n orderId: order.orderId,\n fullName: order.User.fullName,\n phoneNumber: order.User.phoneNumber,\n firestoreId: order.User.uid,\n Address: {\n name: order.Address.name,\n address: order.Address.address,\n details: order.Address.details,\n notes: order.Address.notes,\n longitude: order.Address.longitude,\n latitude: order.Address.latitude,\n },\n });\n }\n });\n\n formattedOrder.delivered = `${delivered}/${batch.BatchDrivers[0].Orders.length}`;\n\n return formattedOrder;\n });\n\n orders.scheduled = formattedScheduledOrder;\n // ***** tried add this, but got another problem, explanation below *****\n // orders.scheduled.map((v) =>\n // v.Orders.length > 1\n // ? v.Orders.sort((a, b) => a.order - b.order)\n // : v.Orders\n // );\n // console.log(orders.scheduled);\n }\n\n cb(null, orders);\n} catch (err) {\n cb(err, null);\n}\n}\n```\n\nHere what I got in Insomnia/Postman\n\nhttps://i.sstatic.net/C9o1z.png\n\nAs above image, it doesn't effected by `order: [[\"order\", \"ASC\"]]`.\n\nI also have tried to change `order: [[Sequelize.literal(\"Orders.order\"), \"ASC\"]]`.\n\nI also have tried to add map loop as mentioned in above commented code. With that loop I got what I wanted/expected, but I receive another problem. The problem is that in driver app there is a button to change the status (PATCH) of order to `delivered/not delivered`, when That button is clicked I will get\n\n```\n// in ongoing orders\n{\n instant: [],\n scheduled: []\n}\n```\n\nPlease let me know if there are any more info needed, Thanks :)\n\n**EDITED**\n\nScreenshot of query when fetch on going orders from driver side\n\nhttps://i.sstatic.net/0r2Uj.png\n\nScreenshot of fetch orders from user side (INSOMNIA/POSTMAN)\n\nhttps://i.sstatic.net/RvKaj.png\n\nScreenshot of Orders table\n\nhttps://i.sstatic.net/sRFAp.png\n\n**EDITED (2)**\n\nScreenshot of query after adding `separate: true`\n\nhttps://i.sstatic.net/eCBhm.png\n\nScreenshot fetch ongoing orders after adding `separate: true`\n\nhttps://i.sstatic.net/i5ZVm.png\n\nI added `separate: true` like below:\n\n```\ninclude: [\n {\n model: Order,\n *** here ***\n separate: true,\n where: ....\n }\n]\n```\n\n========================================\n\nCode:\n```text\nstatic async getOngoingOrders(driverId, cb) {\n     try {\n       const orders = {\n       instant: [],\n       scheduled: [],\n     };\n\n     // @scheduled\n     if (!orders.instant.length) {\n      const scheduledOrders = await BatchOrder.findAll({\n        where: {\n         deliveryDate: {\n          [Op.gte]: moment().format(\"YYYY-MM-DD\"),\n          [Op.lt]: moment().add(1, \"days\").format(\"YYYY-MM-DD\"),\n        },\n      },\n      include: [\n        {\n          model: BatchSchedule,\n          attributes: [\"id\", \"name\", \"start\", \"end\"],\n        },\n        {\n          model: BatchDriver,\n          where: {\n            DriverId: driverId,\n            status: \"Driver on the Way\",\n          },\n          attributes: [\"status\", \"DriverId\"],\n          include: [\n            {\n              model: Order,\n              where: {\n                status: {\n                  [Op.not]: [\"Not Delivered\", \"Complained\"],\n                },\n              },\n              attributes: [\"id\", \"orderId\", \"status\", \"order\"],\n              include: [\n                {\n                  model: User,\n                  attributes: [\"fullName\", \"phoneNumber\", \"uid\"],\n                },\n                {\n                  model: Address,\n                  attributes: [\n                    \"name\",\n                    \"address\",\n                    \"details\",\n                    \"notes\",\n                    \"longitude\",\n                    \"latitude\",\n                  ],\n                },\n              ],\n              // ******* here is the ASC *******\n              order: [[\"order\", \"ASC\"]],\n            },\n          ],\n        },\n      ],\n      attributes: [\"id\", \"deliveryDate\"],\n    });\n\n    const formattedScheduledOrder = scheduledOrders.map((batch) => {\n      const formattedOrder = {\n        name: batch.BatchSchedule.name,\n        start: batch.BatchSchedule.start.substr(0, 5),\n        end: batch.BatchSchedule.end.substr(0, 5),\n        Orders: [],\n      };\n\n      let delivered = 0;\n\n      batch.BatchDrivers[0].Orders.map((order) => {\n        if (\n          order.status === \"Delivered\"\n        ) {\n          delivered++;\n        } else {\n          formattedOrder.Orders.push({\n            id: order.id,\n            order: order.order,\n            orderId: order.orderId,\n            fullName: order.User.fullName,\n            phoneNumber: order.User.phoneNumber,\n            firestoreId: order.User.uid,\n            Address: {\n              name: order.Address.name,\n              address: order.Address.address,\n              details: order.Address.details,\n              notes: order.Address.notes,\n              longitude: order.Address.longitude,\n              latitude: order.Address.latitude,\n            },\n          });\n        }\n      });\n\n      formattedOrder.delivered = `${delivered}/${batch.BatchDrivers[0].Orders.length}`;\n\n      return formattedOrder;\n    });\n\n    orders.scheduled = formattedScheduledOrder;\n    // ***** tried add this, but got another problem, explanation below *****\n    // orders.scheduled.map((v) =>\n    //   v.Orders.length > 1\n    //     ? v.Orders.sort((a, b) => a.order - b.order)\n    //     : v.Orders\n    // );\n    // console.log(orders.scheduled);\n  }\n\n  cb(null, orders);\n} catch (err) {\n  cb(err, null);\n}\n}\n```\n\n```text\n// in ongoing orders\n{\n instant: [],\n scheduled: []\n}\n```\n\n```text\ninclude: [\n {\n  model: Order,\n  *** here ***\n  separate: true,\n  where: ....\n }\n]\n```\n\n```text\norder\n```\n\n```text\norder: [[\"order\", \"ASC\"]]\n```\n\n```text\norder: [[Sequelize.literal(\"Orders.order\"), \"ASC\"]]\n```\n\n```text\ndelivered/not delivered\n```\n\n```text\nseparate: true\n```\n\n```text\nseparate: true\n```\n\n```text\nseparate: true\n```\n\n========================================\n\nComments:\n- Did you try to indicate `separate: true` in `Order` include? At least it could help to sort alphabetically.\n- @Anatoly Yes I've tried to add `separate: true`, I received empty array `Orders: []` when I fetch ongoing orders\n- Can you check what SQL queries were generated for orders?\n- @Anatoly I'm sorry, I didn't get what you mean. I've added extra information, hopefully that's what you meant\n- I see that order fetched along with BatchDrivers so you propably misplaced `separate` option. Can you update the Sequelize query in the post with `separate` option?\n- @Anatoly I updated the post & added separate option, let me know if more info needed. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:34.503Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":365,"estimatedTokens":2082}}1125{"id":"stack-13794890","source":"stackoverflow","questionId":13794890,"title":"Recommendations regarding sharing model code in node.js and browser","tags":["javascript","node.js","sequelize.js"],"text":"Title: Recommendations regarding sharing model code in node.js and browser\nTags: javascript, node.js, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI am using Sequelize as my server side ORM. Is there a recommended approach towards sharing the Model code (especially the validations) with my client application ?\n\nPlease don't recommend solutions which require me to move to a NoSQL database. Currently that is not an option for me. While I really Sequelize as an ORM, I am willing to move onto some other model implementation if it is beneficial.\n\n========================================\n\nTop Answer:\nAt present there does not seem to be an end to end solution ie. a model library which you could just require in either browser or server and define your models - where methods like save, update would be polymorphic requiring the developer to just extend standard model classes and use them on either client or server. \n\nHowever, for people looking for a similar solution - I recommend using JSON schema validators, which are quite hassle free and provide a simple means to your validation logic between client and server.\n\n========================================\n\nComments:\n- This is good to see new libraries filling up the gaps in Node.js ecosystem.","metadata":{"transformedAt":"2026-08-18T18:33:34.503Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":20,"estimatedTokens":314}}1126{"id":"stack-61532849","source":"stackoverflow","questionId":61532849,"title":"Sequelize hasMany association returns only a single object","tags":["sequelize.js","feathers-sequelize"],"text":"Title: Sequelize hasMany association returns only a single object\nTags: sequelize.js, feathers-sequelize\nSource: Stack Overflow\n\nQuestion:\nThe `hasMany` association should return a list of object, rights? I have a `user` record and a few `connections` records connected to it.\n\nmodel `connections`:\n\n```\nuserId: {\n field: 'user_id',\n type: DataTypes.STRING,\n allowNull: false\n }\n```\n\nmodel `users`:\n\n```\n(users as any).associate = function associate(models: any) {\n models.users.hasMany(models.connections, {\n as: 'connections',\n foreignKey: 'user_id'\n });\n };\n```\n\nI include the `connections` model by adding it to the sequelize query params:\n\n```\ninclude: [{ model: context.app.service('connections').Model, as: 'connections' }],\n```\n\nThe end result is that the `connections` property in the `user` response is a single object instead of an array of objects.\nI logged the Sequelize’s query executions and tried directly in the DB the raw query that Sequelize does for this particular call and it returns a list of records, as it should. But when I query it through the API, it returns just a single object instead of an array.\n\n========================================\n\nTop Answer:\nFixed:\n\n```\n.findAll({\n raw : false // Documentation: https://sequelize.org/master/manual/raw-queries.html\n\n```\n// Only Set this to true if you don't have a model definition for your query.\nraw: false,\n```\n\n========================================\n\nCode:\n```text\nuserId: {\n      field: 'user_id',\n      type: DataTypes.STRING,\n      allowNull: false\n    }\n```\n\n```text\n(users as any).associate = function associate(models: any) {\n    models.users.hasMany(models.connections, {\n      as: 'connections',\n      foreignKey: 'user_id'\n    });\n  };\n```\n\n```text\ninclude: [{ model: context.app.service('connections').Model, as: 'connections' }],\n```\n\n```text\nhasMany\n```\n\n```text\nuser\n```\n\n```text\nconnections\n```\n\n```text\nconnections\n```\n\n```text\nusers\n```\n\n```text\nconnections\n```\n\n```text\nconnections\n```\n\n```text\nuser\n```\n\n```text\n{\n  include: [{ model: ...],\n  raw: true \n}\n```\n\n```text\nraw\n```\n\n```text\nsequelize\n```\n\n```text\nraw: true\n```\n\n```text\ndefaultValues\n```\n\n```text\n.get()\n```\n\n```text\nraw: true\n```\n\n```text\ninclude\n```\n\n```text\n.findAll({\n   raw : false // <===\n})\n```\n\n```text\n// Only Set this to true if you don't have a model definition for your query.\nraw: false,\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.503Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":157,"estimatedTokens":675}}1127{"id":"stack-60479741","source":"stackoverflow","questionId":60479741,"title":"Get instances where count of relationship is zero with Sequelize","tags":["javascript","sequelize.js"],"text":"Title: Get instances where count of relationship is zero with Sequelize\nTags: javascript, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nBelow is the syntax to count the relationship on a model via Sequelize\n\n```\nconst files = await db.File.findAll({\n attributes: {\n include: [\n [Sequelize.fn('COUNT', 'Tags.id'), 'tagCount']\n ]\n },\n include: [\n {\n model: db.Tag,\n as: 'tags',\n attributes: [],\n duplicate: false\n }\n ],\n group: 'File.id',\n order: [\n [Sequelize.literal('`tagCount`'), 'DESC']\n ]\n })\n```\n\nWhat do I require to make this code return only Files that has zero tags associated to them?\n\n### Edit\n\nAs per answer provided by @Soham, it does achieve the intended result but cannot be paginated. Generated query is:\n\n```\nSELECT `File`.`id`,\n`File`.`originalId`,\n`File`.`signature`,\n`File`.`referrer_url`,\n`File`.`preview_url`,\n`File`.`preview_extension`,\n`File`.`original_url`,\n`File`.`original_extension`,\n`File`.`provider`,\n`File`.`previewedAt`,\n`File`.`viewedAt`,\n`File`.`blacklistedAt`,\n`File`.`queuedAt`,\n`File`.`startedAt`,\n`File`.`downloadedAt`,\n`File`.`createdAt`,\n`File`.`updatedAt`,\nCOUNT(`tags`.`id`) AS `tagCount`,\n`tags->FileTags`.`createdAt` AS `tags.FileTags.createdAt`,\n`tags->FileTags`.`updatedAt` AS `tags.FileTags.updatedAt`,\n`tags->FileTags`.`fileId` AS `tags.FileTags.fileId`,\n`tags->FileTags`.`tagId` AS `tags.FileTags.tagId` \nFROM `Files` AS `File` \nLEFT OUTER JOIN `FileTags` AS `tags->FileTags` \nON `File`.`id` = `tags->FileTags`.`fileId` \nLEFT OUTER JOIN `Tags` AS `tags` \nON `tags`.`id` = `tags->FileTags`.`tagId` \nGROUP BY `File`.`id` \nHAVING `tagCount` = 0 \nORDER BY `tagCount` DESC;\n```\n\nWhen I add offset and limit to the query as per below\n\n```\nreturn super.findAll({\n offset: 0,\n limit: 24,\n attributes: {\n include: [\n [Sequelize.literal('COUNT(`tags`.`id`)'), 'tagCount']\n ]\n },\n include: [\n {\n model: db.Tag,\n as: 'tags',\n attributes: [],\n duplicate: false\n }\n ],\n group: 'File.id',\n order: [\n [Sequelize.literal('`tagCount`'), 'DESC']\n ],\n having: { tagCount: 0 }\n })\n```\n\nand this outputs the following\n\n```\nSELECT `File`.*,\n `tags->FileTags`.`createdAt` AS `tags.FileTags.createdAt`,\n `tags->FileTags`.`updatedAt` AS `tags.FileTags.updatedAt`,\n `tags->FileTags`.`fileId` AS `tags.FileTags.fileId`,\n `tags->FileTags`.`tagId` AS `tags.FileTags.tagId` \n FROM (SELECT `File`.`id`,\n `File`.`originalId`,\n `File`.`signature`,\n `File`.`referrer_url`,\n `File`.`preview_url`,\n `File`.`preview_extension`,\n `File`.`original_url`,\n `File`.`original_extension`,\n `File`.`provider`,\n `File`.`previewedAt`,\n `File`.`viewedAt`,\n `File`.`blacklistedAt`,\n `File`.`queuedAt`,\n `File`.`startedAt`,\n `File`.`downloadedAt`,\n `File`.`createdAt`,\n `File`.`updatedAt`,\n COUNT(`tags`.`id`) AS `tagCount` \n FROM `Files` AS `File` \n GROUP BY `File`.`id` \n HAVING `tagCount` = 0 \n ORDER BY `tagCount` DESC LIMIT 0,\n 24) AS `File` \n LEFT OUTER JOIN `FileTags` AS `tags->FileTags` \n ON `File`.`id` = `tags->FileTags`.`fileId` \n LEFT OUTER JOIN `Tags` AS `tags` \n ON `tags`.`id` = `tags->FileTags`.`tagId` \n ORDER BY `tagCount` DESC;\n```\n\n========================================\n\nTop Answer:\ni cant add a comment on an answer, so please see my answer as a comment on the upvoted one.\n\n```\nSequelize.fn('COUNT', 'Tags.id')\n```\n\nshould be\n\n```\nSequelize.fn('COUNT', Sequelize.col('Tags.id'))\n```\n\nif 'Tags.id' is not wrapped with Sequelize.col() the generated sql looks like: COUNT('Tags.id').\n\nworking example:\n\n```\nconst files = await db.File.findAll({\n attributes: {\n include: [\n [Sequelize.fn('COUNT', Sequelize.col('Tags.id')), 'tagCount']\n ]\n },\n include: [\n {\n model: db.Tag,\n as: 'tags',\n attributes: [],\n duplicate: false\n }\n ],\n group: 'File.id',\n order: [\n [Sequelize.literal('`tagCount`'), 'DESC']\n ],\n having: { tagCount : 0 },\n subQuery: false\n})\n```\n\n========================================\n\nCode:\n```text\nconst files = await db.File.findAll({\n      attributes: {\n        include: [\n          [Sequelize.fn('COUNT', 'Tags.id'), 'tagCount']\n        ]\n      },\n      include: [\n        {\n          model: db.Tag,\n          as: 'tags',\n          attributes: [],\n          duplicate: false\n        }\n      ],\n      group: 'File.id',\n      order: [\n        [Sequelize.literal('`tagCount`'), 'DESC']\n      ]\n    })\n```\n\n```text\nSELECT `File`.`id`,\n`File`.`originalId`,\n`File`.`signature`,\n`File`.`referrer_url`,\n`File`.`preview_url`,\n`File`.`preview_extension`,\n`File`.`original_url`,\n`File`.`original_extension`,\n`File`.`provider`,\n`File`.`previewedAt`,\n`File`.`viewedAt`,\n`File`.`blacklistedAt`,\n`File`.`queuedAt`,\n`File`.`startedAt`,\n`File`.`downloadedAt`,\n`File`.`createdAt`,\n`File`.`updatedAt`,\nCOUNT(`tags`.`id`) AS `tagCount`,\n`tags->FileTags`.`createdAt` AS `tags.FileTags.createdAt`,\n`tags->FileTags`.`updatedAt` AS `tags.FileTags.updatedAt`,\n`tags->FileTags`.`fileId` AS `tags.FileTags.fileId`,\n`tags->FileTags`.`tagId` AS `tags.FileTags.tagId` \nFROM `Files` AS `File` \nLEFT OUTER JOIN `FileTags` AS `tags->FileTags` \nON `File`.`id` = `tags->FileTags`.`fileId` \nLEFT OUTER JOIN `Tags` AS `tags` \nON `tags`.`id` = `tags->FileTags`.`tagId` \nGROUP BY `File`.`id` \nHAVING `tagCount` = 0 \nORDER BY `tagCount` DESC;\n```\n\n```text\nreturn super.findAll({\n      offset: 0,\n      limit: 24,\n      attributes: {\n        include: [\n          [Sequelize.literal('COUNT(`tags`.`id`)'), 'tagCount']\n        ]\n      },\n      include: [\n        {\n          model: db.Tag,\n          as: 'tags',\n          attributes: [],\n          duplicate: false\n        }\n      ],\n      group: 'File.id',\n      order: [\n        [Sequelize.literal('`tagCount`'), 'DESC']\n      ],\n      having: { tagCount: 0 }\n    })\n```\n\n```text\nSELECT `File`.*,\n `tags->FileTags`.`createdAt` AS `tags.FileTags.createdAt`,\n `tags->FileTags`.`updatedAt` AS `tags.FileTags.updatedAt`,\n `tags->FileTags`.`fileId` AS `tags.FileTags.fileId`,\n `tags->FileTags`.`tagId` AS `tags.FileTags.tagId` \n FROM (SELECT `File`.`id`,\n `File`.`originalId`,\n `File`.`signature`,\n `File`.`referrer_url`,\n `File`.`preview_url`,\n `File`.`preview_extension`,\n `File`.`original_url`,\n `File`.`original_extension`,\n `File`.`provider`,\n `File`.`previewedAt`,\n `File`.`viewedAt`,\n `File`.`blacklistedAt`,\n `File`.`queuedAt`,\n `File`.`startedAt`,\n `File`.`downloadedAt`,\n `File`.`createdAt`,\n `File`.`updatedAt`,\n COUNT(`tags`.`id`) AS `tagCount` \n FROM `Files` AS `File` \n GROUP BY `File`.`id` \n HAVING `tagCount` = 0 \n ORDER BY `tagCount` DESC LIMIT 0,\n 24) AS `File` \n LEFT OUTER JOIN `FileTags` AS `tags->FileTags` \n ON `File`.`id` = `tags->FileTags`.`fileId` \n LEFT OUTER JOIN `Tags` AS `tags` \n ON `tags`.`id` = `tags->FileTags`.`tagId` \n ORDER BY `tagCount` DESC;\n```\n\n```text\nconst files = await db.File.findAll({\n  attributes: {\n    include: [\n      [Sequelize.fn('COUNT', 'Tags.id'), 'tagCount']\n    ]\n  },\n  include: [\n    {\n      model: db.Tag,\n      as: 'tags',\n      attributes: [],\n      duplicate: false\n    }\n  ],\n  group: 'File.id',\n  order: [\n    [Sequelize.literal('`tagCount`'), 'DESC']\n  ],\n  having: { tagCount : 0 },\n  subQuery: false\n})\n```\n\n```text\nSequelize.fn('COUNT', 'Tags.id')\n```\n\n```text\nSequelize.fn('COUNT', Sequelize.col('Tags.id'))\n```\n\n```text\nconst files = await db.File.findAll({\n    attributes: {\n    include: [\n      [Sequelize.fn('COUNT', Sequelize.col('Tags.id')), 'tagCount']\n    ]\n  },\n  include: [\n    {\n      model: db.Tag,\n      as: 'tags',\n      attributes: [],\n      duplicate: false\n    }\n  ],\n  group: 'File.id',\n  order: [\n    [Sequelize.literal('`tagCount`'), 'DESC']\n  ],\n  having: { tagCount : 0 },\n  subQuery: false\n})\n```\n\n========================================\n\nComments:\n- This doesn't seem to work and also can't find any reference in docs about this attribute. Can you point to a link so I can verify the implementation?\n- You can refer to examples given here github.com/sequelize/sequelize/issues/7975\n- Thanks for the reference. I had a try and after fixing an issue with the query (changing Sequelize.fn to Sequelize.literal) it works. However I am unable to paginate this query due to it using having (experienced similar in php when using Laravel).\n- Can you please your modified Sequelize statement and the query generated by Sequelize?\n- Edited original question with details requested. I am thinking maybe my approach is wrong, is there another way to query for a model A that does have no associations with model B without using `having`?\n- Also, adding limit and offset generates an error `SequelizeDatabaseError: SQLITE_ERROR: no such column: tags.id`\n- @jjoey, I have updated my answer. Please set `subQuery: false`, I think that shall solve the pagination issue.\n- The `having` part should be `Sequelize.where(Sequelize.fn('COUNT', 'Tags.id'), Op.eq, 0)`\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:34.503Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":363,"estimatedTokens":2232}}1128