question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Sequelize findAndCountAll returns wrong count when association models included

See original GitHub issue

What are you doing?

I have Post model. Post model has attachment(oneToMany),users(oneToMany), I’m trying to fetch posts with attachments using sequelize findAndCountAll

// POST MODEL
module.exports = (sequelize, DataTypes) => {
     const Post = sequelize.define(
        'Post',
        {
            id: {
                primaryKey: true,
                type: DataTypes.UUID
            },
            title: DataTypes.STRING(50)
        },
        {
            tableName: 'post',
            timestamps: true
        }
    );

    Post.associate = models => {
        Post.hasMany(models.PostAttachment, {
            as: 'attachment',
            foreignKey: 'postId'
        });
    };

    return Post;
};
// POST ATTACHMENT
module.exports = (sequelize, DataTypes) => {
    const PostAttachment = sequelize.define(
        'PostAttachment',
        {
            id: {
                primaryKey: true,
                type: DataTypes.UUID
            },
            key: DataTypes.STRING
        },
        {
            tableName: 'postAttachment',
            timestamps: true
        }
    );

    PostAttachment.associate = models => {
        PostAttachment.belongsTo(models.Feed, {
            as: 'post',
            foreignKey: 'postId'
        });
    };

    return PostAttachment;
};

POST TABLE

id title createdAt updatedAt
f8d68fc0-48b1-4e90-af73-c9a4dc577461 Title1 2018-05-23 16:47:09.228000 +00:00 2018-05-23 16:47:09.228000 +00:00
01a528d2-8696-465f-8739-2b32bc52ceca Title2 2018-05-23 16:47:09.228000 +00:00 2018-05-23 16:47:09.228000 +00:00

POST ATTACHMENT TABLE

id key postId createdAt updatedAt
410819f6-d1c4-44f4-9a52-edbac765e714 Key1 f8d68fc0-48b1-4e90-af73-c9a4dc577461 2018-05-23 16:47:09.228000 +00:00 2018-05-23 16:47:09.228000 +00:00
754ca095-4967-4472-a0f4-1a8e2d761a24 Key2 f8d68fc0-48b1-4e90-af73-c9a4dc577461 2018-05-23 16:47:09.228000 +00:00 2018-05-23 16:47:09.228000 +00:00

SEQUELIZE QUERY

const posts = Post.findAndCountAll({
    include: ['attachment', 'users', 'x count of models']
});

 return {
    "posts": posts.rows,
    "total": posts.count
};

What do you expect to happen?

I’m expecting get 2 posts and total sum 2

{
"posts": [{...},{...}],
"total": 2
}

What is actually happening?

I’m getting 2 posts and total sum 4

{
"posts": [{...},{...}],
"total": 4
}

Dialect: postgres Dialect version: XXX Database version: PostgreSQL 10.3 on x86_64-apple-darwin17.3.0, compiled by Apple LLVM version 9.0.0 (clang-900.0.39.2), 64-bit Sequelize version: ^4.37.8

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:37
  • Comments:15 (1 by maintainers)

github_iconTop GitHub Comments

128reactions
ErnestoSalazarcommented, May 31, 2018

@tumdav try adding distinct:true to the findAndCountAll passed object that should do the trick, i had the same problem few days ago and that solve it

const posts = Post.findAndCountAll({
    include: ['attachment', 'users', 'x count of models'],
    distinct:true
});
14reactions
JamesMGreenecommented, Nov 4, 2019

Give this workaround a try:

// Add a permanent global hook to prevent unknowingly hitting this Sequelize bug:
//   https://github.com/sequelize/sequelize/issues/10557
sequelize.addHook('beforeCount', function (options) {
  if (this._scope.include && this._scope.include.length > 0) {
    options.distinct = true
    options.col = this._scope.col || options.col || `"${this.options.name.singular}".id`
  }

  if (options.include && options.include.length > 0) {
    options.include = null
  }
})
Read more comments on GitHub >

github_iconTop Results From Across the Web

findAndCountAll count gets a bigger number than the actual ...
The table which I use findAndCountAll() queries including two other tables, like the code below: const patientModel: IIncludeOptions = { model: ...
Read more >
Model - Sequelize
async findAndCountAll(options: object): Promise<{count: number|number[], rows: Model[]}> ... set plain to false to return all values of all returned rows.
Read more >
sequelize query use column name instead model name
The count part of findAndCountAll incorrectly generates the distinct reference: filter from the scope is correctly used, but the reference is ambiguous count( ......
Read more >
[Solved]-Sequelize query returning the wrong number of rows ...
Coding example for the question Sequelize query returning the wrong number of rows when models are included (findAndCountAll)-sequelize.js.
Read more >
Model usage - Manual | Sequelize
findAndCountAll - Search for multiple elements in the database, returns both data and total count. This is a convenience method that combines findAll...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found