How to use an include with attributes with Node.js Sequelize?

Sometimes, we want to use an include with attributes with Node.js Sequelize.

In this article, we’ll look at how to use an include with attributes with Node.js Sequelize.

How to use an include with attributes with Node.js Sequelize?

To use an include with attributes with Node.js Sequelize, we can set the include.attributes property.

For instance, we write

Payment.findAll({
  where: {
    id
  },
  attributes: {
    exclude: ['createdAt', 'updatedAt']
  },
  include: {
    model: Customer,
    attributes: ['customerName', 'phoneNumber']
  }
})

to call findAll with an object that has the include property.

We set include.model to Customer to include Customer entries associated with Payment.

And we return the customerName and phoneNumber columns from the associated Customer.

Conclusion

To use an include with attributes with Node.js Sequelize, we can set the include.attributes property.