Sequelize: Getting TypeError when using multiple sequelize.fn in query

Created on 14 Mar 2016  路  3Comments  路  Source: sequelize/sequelize

I have two models, campaign and donation. The campaign model has many donations. I am trying to run a query against the campaigns model to get a campaign by id including the donations associated with that campaign in addition to the sum and count of the donations.

Here's the query that I'm using:

Campaign.findById(campaignId, 
  {
    include: [
      {
        model: Donations
      }
    ],
    attributes: {
      include: ['Campaign.id', [
        sequelize.fn('COUNT', sequelize.col('Donations.id')), 'numberOfDonations',
        sequelize.fn('SUM', sequelize.col('Donations.amount')), 'amountRaised'
      ]]
    },
    group: [ 'Campaign.id', 'Donations.id' ]
  }
).then(function(campaign) {
  resolve(campaign);
})

Which is throwing the error Error: TypeError: s.replace is not a function

However, when I remove one of the sequelize.fn(...) attributes and keep one, it works exactly as expected. It's only letting me get either the count or the the sum of the donations with the campaign.
I am using sequelize version 3.19.3 with postgresql.

Most helpful comment

attributes: {
  include: [
    'id',
    [sequelize.fn('COUNT', sequelize.col('Donations.id')), 'numberOfDonations',]
    [sequelize.fn('SUM', sequelize.col('Donations.amount')), 'amountRaised']
  ]
}

All 3 comments

Smethings off with your attributes.include array, each of your fn/alias pairs should be an array, not an array around two sets.

attributes: {
  include: [
    'id',
    [sequelize.fn('COUNT', sequelize.col('Donations.id')), 'numberOfDonations',]
    [sequelize.fn('SUM', sequelize.col('Donations.amount')), 'amountRaised']
  ]
}

That worked! Thank you very much for the very quick reply!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

couds picture couds  路  3Comments

mickhansen picture mickhansen  路  3Comments

evantahler picture evantahler  路  3Comments

kasparsklavins picture kasparsklavins  路  3Comments

ryanwalters picture ryanwalters  路  3Comments