Counting associated entries with Sequelize

Use findAll() with include() and sequelize.fn() for the COUNT: Location.findAll({ attributes: { include: [[Sequelize.fn(“COUNT”, Sequelize.col(“sensors.id”)), “sensorCount”]] }, include: [{ model: Sensor, attributes: [] }] }); Or, you may need to add a group as well: Location.findAll({ attributes: { include: [[Sequelize.fn(“COUNT”, Sequelize.col(“sensors.id”)), “sensorCount”]] }, include: [{ model: Sensor, attributes: [] }], group: [‘Location.id’] })

sequelize subquery as field

Your best option is: return Customer.findAll({ attributes: Object.keys(Customer.attributes).concat([ [sequelize.literal(‘(SELECT SUM(“Orders”.”amount”) FROM “Orders” WHERE “Orders”.”CustomerId” = “Customer”.”id”)’), ‘totalAmount’] ]) }); This looks like an extension to issue #1869: Querying on the through model/join table is not possible currently unfortuneatly. Your question is also tangentially related to this one, where the question there was sort of a … Read more

How to auto generate migrations with Sequelize CLI from Sequelize models?

If you don’t want to recreate your model from scratch, you can manually generate a migration file using the following CLI command: sequelize migration:generate –name [name_of_your_migration] This will generate a blank skeleton migration file. While it doesn’t copy your model structure over to the file, I do find it easier and cleaner than regenerating everything. … Read more

ECONNREFUSED for Postgres on nodeJS with dockers

Your DATABASE_URL refers to 127.0.0.1, which is the loopback adapter (more here). This means “connect to myself”. When running both applications (without using Docker) on the same host, they are both addressable on the same adapter (also known as localhost). When running both applications in containers they are not both on localhost as before. Instead … Read more

Sequelize model association won’t create a new column

All models should be registered in one place as long as their associations: database.js const fs = require(‘fs’) const path = require(‘path’) const Sequelize = require(‘sequelize’) const db = {} const models = path.join(__dirname, ‘models’) // correct it to path where your model files are const sequelize = new Sequelize(/* your connection settings here */) … Read more