[Fixed] Sequelize select only chosen attributes

Issue

I am using MySQL database, when I am doing:

models.modelA.findAll({
            attributes: [
               ['modelA.id','id']
            ],
            raw: true,
            include:
                [
                    {
                        model: models.modelB,
                        required: true
                    }
                ]

        }).then(function (tenants) {

        });

Nevertheless that I’ve selected only id, Sequelize is retrieving all attributes, from related table as well so I’m getting {id, … All attributes here}.

How I can prevent this? Sometimes I want to select only 2/3 columns and Sequelize is always selecting all of them what is not efficient.

Solution

You can do something like the following

models.modelA.findAll({
        attributes: [
           'id'
        ],
        raw: true,
        include:
            [
                {
                    model: models.modelB,
                    attributes: ['fieldName1', 'fieldName2'], // Add column names here inside attributes array.
                    required: true
                }
            ]

    }).then(function (tenants) {

    });

Leave a Reply

(*) Required, Your email will not be published