Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hsn0x/17d0917c7cc4dae20b4469bffffa7a8b to your computer and use it in GitHub Desktop.
Save hsn0x/17d0917c7cc4dae20b4469bffffa7a8b to your computer and use it in GitHub Desktop.
How to speed up Sequelize with complicated includes

How to speed up Sequelize with complicated includes

Sometimes queries can get complicated with many include statements. This can significantly slow down the response.

const stageWithMeta = await db.stage.findOne({
      where: { id },
      include: [
        {
          model: db.workTimeLog,
          include: [{ model: db.user }],
        },
        {
          model: db.incomeExpense,
        },
      ],
    });

One way to make thing faster is to add separate: true to the include.

const stageWithMeta = await db.stage.findOne({
      where: { id },
      include: [
        {
          model: db.workTimeLog,
          separate: true,
          include: [{ model: db.user }],
        },
        {
          model: db.incomeExpense,
          separate: true,
        },
      ],
    });

This is only supported for hasMany associations.

doc

If true, runs a separate query to fetch the associated instances, only supported for hasMany associations

Sequelize will run separate queries and merge the result in memory, instead of making a huge query with many JOIN statements.

#code #note

source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment