sequelize group by fn count becomes undefined

Viewed 2991

My query is as shown below :

db.test.findAll({
  group: ['source'],
  attributes: ['source', [Sequelize.fn('COUNT', 'source'), 'count']],
  order: [
    [Sequelize.literal('count'), 'DESC']
  ]
}).then((sources) => {
  sources.forEach((info) => {
    console.log('sorce name :' + info.source + " count : " + info.count);
  })
}).catch((err) => {
  console.log(err);
})

So, here what happens is info.source name is printed perfectly. But info.count is undefined even if it is shown in the response ?

2 Answers

Sequelize is trying to map result to test model, use raw: true to prevent that...

db.test.findAll({
  group: ['source'],
  attributes: ['source', [Sequelize.fn('COUNT', 'source'), 'count']],
  order: [
    [Sequelize.literal('count'), 'DESC']
  ],
  raw: true, // <-- HERE
})

Just came across this issue myself. Instead of having to use raw: true, you can use instance.get('attribute'), so in your case

sources.forEach((info) => {
  console.log('source name :' + info.source + " count : " + info.get('count');
})

You could also do info.dataValues.count

Related