Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findAndCountAll count gets a bigger number than the actual returned data

Tags:

sequelize.js

I am using Sequelize findAndCountAll() for my website's pagination.

The findAndCountAll() returns the total items number(3990) is bigger than the actual returned data number (3770).

Does anyone know how to make the findAndCountAll() returns the total items number which is the same as the actual data returned?

The table which I use findAndCountAll() queries including two other tables, like the code below:

const patientModel: IIncludeOptions = {
    model: Patient,
    attributes: ["deviceId", "firstName", "lastName"],
};

const deviceModel: IIncludeOptions = {
    model: Device,
    required: true,
    attributes: ["deviceId", "deviceSerialNumber"],
    include: [patientModel],
};

const eventCodeModel: IIncludeOptions = {
    model: EventCode,
    required: true,
    attributes: ["name"],
};

const opts: IFindOptions = {
    ...pageSizeLimit,
    offset : offsetNum,
    attributes: ["id", "deviceId", "eventId", "dispatchedAt", "message", "createdAt"],
    include: [
        deviceModel,
        eventCodeModel,
    ],
    order: sortBy,
};

const resCount = await DeviceEvent.findAndCountAll(opts).then((response) => {
    const totalItems = response.count;
    return {
        totalItems,
        currentPage: page || 1,
    };
});
like image 438
JavaScript Rookie Avatar asked Oct 15 '25 22:10

JavaScript Rookie


2 Answers

What worked for me is adding distinct: true to the query. Without this Sequelize returns the count for the values without an inner join/required: true.

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

In the code used in the question, this would be:

const opts: IFindOptions = {
    ...pageSizeLimit,
    offset : offsetNum,
    attributes: ["id", "deviceId", "eventId", "dispatchedAt", "message", "createdAt"],
    include: [
        deviceModel,
        eventCodeModel,
    ],
    order: sortBy,
    distinct: true,
};

Details for this are mentioned here - Count issue in findandCountAll

like image 115
Vaulstein Avatar answered Oct 19 '25 15:10

Vaulstein


You have to set separate: true in your option when you have one-to-many associations, for example :

users.findAndCountAll({
include:[{model:messages,as:"messages",separate:true}]
}) 
like image 44
mohammad tavassolian Avatar answered Oct 19 '25 15:10

mohammad tavassolian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!