I have been searching for a solution for hours now without hope.
I have Many-to-Many relationship with Student
and Classes
through a Junction Table Enrollment
.
Everything is working fine and I am able to insert and retrieve data.
However, I don't want all the fields from the junction table to be returned in the result. Only selected attribute.
First, the below is my code:
Models definition and associations:
const Student = sequelize.define(
"Student",
{ firstName: Sequelize.STRING },
{ timestamps: false }
);
const Class = sequelize.define(
"Class",
{ className: Sequelize.STRING },
{ timestamps: false }
);
const Enrollment = sequelize.define(
"Enrollment",
{
enrollmentType: {
type: DataTypes.STRING,
},
},
{ timestamps: false }
);
Student.belongsToMany(Class, { through: Enrollment });
Class.belongsToMany(Student, { through: Enrollment });
The query:
return Student.findOne({
where: { id: 2 },
include: [
{
model: Class,
attributes: ["className"],
},
],
raw: true,
nest: true,
});
And I got the below result:
{
id: 2,
firstName: 'John',
Classes: {
className: 'Chemistry',
Enrollment: { enrollmentType: 'Normal student', StudentId: 2, ClassId: 1 }
}
}
I am not interested in the repeated StudentId and ClassId returned from the Enrollment table.
Someone suggested that I use through
:
return Student.findOne({
where: { id: 2 },
include: [
{
model: Class,
attributes: ["className"],
through: { attributes: ["enrollmentType"] },
},
],
raw: true,
nest: true,
});
But now I am getting the same result, only the order of fields seems to be different
{
id: 2,
firstName: 'John',
Classes: {
className: 'Chemistry',
Enrollment: { ClassId: 1, StudentId: 2, enrollmentType: 'Normal student' }
}
}
How can I only return the enrollmentType
without other Enrollment fields?