1

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"
        }
    ]
}
mcranston18
  • 4,680
  • 3
  • 36
  • 37

1 Answers1

0

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

Shivam
  • 3,462
  • 1
  • 15
  • 20
  • Thanks for the answer. Although your code correctly would set an association using Sequelize, it doesn't map to the way Epilogue creates new models. It calls `model.student.create(someAttrs, include: [{model: Course}]`. Are you aware of an option I can pass into Sequelize's `create` method that disable auto-creation of associations? – mcranston18 Jul 03 '17 at 23:35
  • There was a flag, `save` which could be passed to create You could search for `save : false` for association Something along [this](https://github.com/sequelize/sequelize/issues/864) issue. Though I am not very sure how it works for n:m relationship – Shivam Jul 03 '17 at 23:50
  • Or even epilogue for that matter – Shivam Jul 03 '17 at 23:51
  • How do you get `model`? – Shamoon Jul 14 '19 at 17:35