mysqlnode.jssequelize.js

Specifying specific fields with Sequelize (NodeJS) instead of *


Alright so I have a project in NodeJS where I'm utilizing Sequelize for a MySQL ORM. The thing works fantastically however I'm trying to figure out if there is a way to specify what fields are being returned on a query basis or if there's even a way just to do a .query() somewhere.

For example in our user database there can be ridiculous amounts of records and columns. In this case I need to return three columns only so it would be faster to get just those columns. However, Sequelize just queries the table for everything "*" to fulfill the full object model as much as possible. This is the functionality I'd like to bypass in this particular area of the application.


Solution

  • You have to specify the attributes as a property in the object that you pass to findAll():

    const projects = await Project.findAll({
       attributes: ['name', 'age']
    });
    

    The attributes property:

    A list of the attributes that you want to select, or an object with include and exclude keys...

    And if you are updating an object, and you only want to update specific field(s), you can use the update() method:

    projectInstance.update({ name: 'NewProjectName' })
    

    As the documentation says:

    This is the same as calling set and then calling save but it only saves the exact values passed to it, making it more atomic and safer.