sequelize count code example

Example 1: sequelize count in include

Location.findAll({
    attributes: { 
        include: [[Sequelize.fn("COUNT", Sequelize.col("sensors.id")), "sensorCount"]] 
    },
    include: [{
        model: Sensor, attributes: []
    }]
});

Example 2: sequelize get where

// Example
const Tokens = db.define('tokens', {
    guid: {
        type: sequelize.STRING
    }
});
// The basics of Sequelize Get Where
Tokens.findAll({
        where: { guid: 'guid12345' }
    }).then(tokens => {
        console.log(tokens);
    }).catch(err => console.log('error: ' + err));;
// is equal to >> SELECT * FROM Tokens WHERE guid = 'guid12345'

Example 3: sequelize max

exports.getMinPrice = () => Item.findAll({    attributes: [[sequelize.fn('min', sequelize.col('price')), 'minPrice']],  });

Example 4: sequelize count all

Project.count().then(c => {
  console.log("There are " + c + " projects!")
})

Project.count({ where: {'id': {[Op.gt]: 25}} }).then(c => {
  console.log("There are " + c + " projects with an id greater than 25.")
})

Example 5: count in sequelize example

exports.getItemSaleCount = () => SaleItem.findAll({    attributes: ['itemId', [sequelize.fn('count', sequelize.col('itemId')), 'count']],    group : ['SaleItem.itemId'],    raw: true,    order: sequelize.literal('count DESC')  });

Example 6: sequelize findall 2 attributes

Model.findAll({
  attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
});