Create model and association in Sequelize and Epilogue

782 views Asked by At

Desired behaviour

Using Epilogue JS and Sequelize, I have two resources, Student and Course, that have a m2m relationship. I would like to create a new Student and associate that student instance with an existing course.

The problem

When I POST a new student and include course information in the payload, Epilogue/Sequelize will attempt to create the new student and create new courses based on the nested payload. This will cause a validation error because those courses already exist.

Code example

const Student = db.define('student', {
  id: Sequelize.UUID,
  name: Sequelize.STRING
});

const Course = db.define('course', {
  id: Sequelize.UUID,
  name: Sequelize.STRING
});

Student.belongsToMany(Course, {through: 'student_courses'});
Course.belongsToMany(Student, {through: 'student_courses'});

const StudentResource = epilogue.resource({
  model: Student,
  endpoints: ['/student', '/student/:id'],
  include: [{
    model: Course
  }];
});

I want to POST a new student and associate with an existing course, e.g.:

// POST /users/
{
  name: "Sally",
  courses: [
    {id: 123, name: "math"},
    {id: 456, name: "science"}
  ]
}

However, Epilogue/Sequelize will fail because these courses already exist:

{
    "message": "Validation error",
    "errors": [
        {
            "field": "id",
            "message": "id must be unique"
        }
    ]
}
1

There are 1 answers

4
Shivam On

Not very aquinted with how epilogue works, but doing it purely via sequelize, you can use the set<Association> methods

Something along the lines,

student = model.student.create(/*some properties*/)
student.setCourse(course_id)

More about it, in this issue