How to remove associations from the output in Sequelize?

Issue

I have a classMethod defined for the Model User

// model user.js
classMethods: {
    associate: function(models) {
        User.belongsToMany(models.project, {through: 'user_project', foreignKey: 'user_id', otherKey: 'project_id'})
    }
}

From a route in Express i then query for the projects of this user and output it as JSON

user.getProjects({
    attributes: ['id', 'title'],
})
.then(function(projects) {
    res.json(projects)
})

This works fine, except for the fact the output also contains the user_project property which I would like to hide/omit/remove

[
  {
    "id": 8,
    "title": "Some project",
    "user_project": {
       "created_at": "2017-02-16T22:52:48.000Z",
       "updated_at": "2017-02-16T22:52:48.000Z",
       "project_id": 8,
       "user_id": 5
     }
  },
  //etc.

I have tried various exclude and include statements, but the output always contains it.

Is there a way to not have this show up in the output?

Solution

I stumbled upon the solution.

To remove the attributes from the joined table you can use joinTableAttributes, like so:

user.getProjects({
    attributes: ['id', 'title'],
    joinTableAttributes: []
})
.then(function(projects) {
    res.json(projects)
})

By doing that, it will remove the (see OP) output of the user_project table, and the result is:

[
  {
    "id": 8,
    "title": "Test Project",
  },
  {
    "id": 4,
    "title": "Another one",
  }
]

Answered By – Hyra

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published