Search code examples
ormsequelize.jsassociations

Removing join table data in sequelize returned value


I am currently trying to remove a joint table data added when retrieving an association data.

The query is done by sequelize using a method added to the model through specifying model relationships(sequelize magic methods), for some reason, I'm not able to do that.

I have currently tried passing in attributes: {exclude: ['...']} to the method but the field still persists.

Current association

// Class sequelize model

Class.belongsToMany(models.Subject, { 
  through: 'ClassSubject', 
  foreignKey: 'class_id', 
  otherKey: 'subject_id', 
  as: 'subjects' 
})


// Subject sequelize model

Subject.belongsToMany(models.Class, { 
  through: 'ClassSubject', 
  foreignKey: 'subject_id', 
  otherKey: 'class_id',
  as: 'classes' 
});

Query and Response

const subjects = await dbClass.getSubjects(); // dbClass is a Class model instance

// Response
[
  {
    "id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
    "name": "Mathematics",
    "code": "MATHS",
    "summary": "Mathematics for class 1",
    "ClassSubject": {
      "class_id": "637afc7b-40f6-478e-b35e-859ca462e2e7",
      "subject_id": "1b89d44c-2caa-452d-a1f8-7faa11970917"
    }
  }
]

Desired output

// Response
[
  {
    "id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
    "name": "Mathematics",
    "code": "MATHS",
    "summary": "Mathematics for class 1"
  }
]

I have tried passing options to the method as specified below but to no avail

const subjects = await dbClass.getSubjects({ 
    attributes: { exclude: ['ClassSubject'] } 
});

But it still doesn't work.


Solution

  • Try using the joinTableAttributes option and pass empty array to exclude everything in joint table.

    const subjects = await dbClass.getSubjects({ joinTableAttributes: [] });