Difficulty encountered with the 'add' mixin in Sequelize when using a polymorphic many-to-many relationship

In managing customer surveys, I have encountered a problem with the many-to-many polymorphic association setup. The issue arises when using the 'add' mixin on the model instance of 'Survey'. If the joining table already contains an item with the 'surveyed' field matching the ID of the new surveyable entity, it gets overwritten.

'survey' table:

id name
1 'Customer Survey'

'scheduled_sessions' table:

id appointment_data
10 { "someData" : [] }

'service_provider' table:

id name
10 Joe Doe

'survey_surveyable' table:

survey surveyable surveyed
1 serviceProvider 10

When adding a scheduled session with the same ID as a service provider, the data in the join table gets overwritten by default:


const surveyInstance = await DB.Survey.findByPk(1);
const scheduledSessionInstance = await DB.ScheduledSession.findByPk(10);

surveyInstance.addScheduledSession(
  scheduledSessionInstance,
  { through: { surveyable: "scheduledSession" } }
);

return surveyInstance.save();

The generated SQL queries by Sequelize show how the overwrite occurs:


SELECT "id", "name"
FROM "surveys" AS "Survey"
WHERE "Survey"."id" = 1;

SELECT "id", "appointment_data" AS "appointmentData"
FROM "scheduled_sessions" AS "ScheduledSession"
WHERE "ScheduledSession"."id" = 10;

SELECT "survey", "surveyable", "surveyed"
FROM "survey_surveyable" AS "SurveySurveyable"
WHERE
"SurveySurveyable"."survey" = 1 AND
"SurveySurveyable"."surveyed" IN (10);

UPDATE "survey_surveyable"
SET "surveyable"=$1
WHERE
"survey" = $2 AND
"surveyed" = $3

Answer №1

The utilization of Survey's mixin is incorrect because the scope in Survey's association is missing.

Survey.associate = (models) => {
  Survey.belongsToMany(models.ScheduledSession, {
    through: {
      model: models.SurveySurveyable,
      unique: false,
      scope: {                           // The essential part that is absent
        surveyable: "scheduledSession"
      }
    },
    foreignKey: "survey",
    constraints: false
  });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NodeJS: Encountering an issue with retrieving the cart ID - receiving

I am having issues with the cart variable, even though I defined it using await cartsRepo.create({ items: [] });. For some reason, I keep getting undefined when trying to access cart. I suspect that the request is not resolving properly, which might be ca ...

Prevent exposing passwords by excluding them from JSON responses in Sequelize

Working with ExpressJS and Sequelize 4.22.6 for database operations. When creating a user, I need to ensure that sensitive information like passwords are hidden from the response: models.User.create({ firstName: 'Maxence', lastName: &ap ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...

Using AngularJS to encapsulate the JSON response received from the server

Currently, I have a basic CRUD application that is operational. However, I am looking to enhance every response received from the server by adding two additional parameters: 'error' => boolean, 'errorMessage' => string, 'dat ...

Fluent-ffmpeg is unable to handle video processing or tasks in Nodejs

I am facing an issue with the following code: const ffmpegPath = require("@ffmpeg-installer/ffmpeg").path; const ffmpeg = require("fluent-ffmpeg"); ffmpeg.setFfmpegPath(ffmpegPath); app.put("/upload-content", async (req, res) ...

The perplexing configuration of a webpack/ES6 project

I am currently in the process of setting up my very first ES6 and webpack "application" where I aim to utilize classes and modules. However, each time I attempt to transpile the application using the webpack command, I encounter the following error: $ web ...

The Javascript alert function always seems to fail to trigger

Below is the complete code I am working with: if( javascript.isGarbage() != true) { alert('I am not garbage!'); } Can someone please explain why this code does not produce an alert message??? ...

What is the most effective method to patiently anticipate a specific duration for a function's output?

I am faced with a situation where I have two functions at hand. One function performs complex logic, while the other wraps this function to provide either the result of computation or an error message after a specified amount of time t. Consider the follo ...

Fetching information from the database and presenting it in a tooltip

I'm struggling with finding a way to efficiently display my data from the database within a tooltip. Can anyone provide guidance on how to accomplish this? <input type="image" id="tip" src="image/check.png" title="<?PHP echo $_POST['custom ...

Confirm that the time specified is in the future

My goal is to ensure that the time and date entered in my form are not in the past. Currently, I have separate input boxes for the time and date, each validated using ng-pattern. How can I display an error (ng-invalid) when both input boxes combined resul ...

Is the support for getPageSource().contains still available?

Using Selenium along with Javascript, I am attempting to utilize the command if(driver.getPageSource().contains("Yes!")) In order to check for the presence of Yes! anywhere on the page. However, I am receiving an error indicating that the comman ...

Encountering the error message "Angular 'undefined is not a function' when trying to define a component

My Ionic code was originally working fine, allowing the user to input a list. I decided to refactor it into a component for re-usability but encountered an error undefined is not a function on line 4 of the Javascript file. How can this issue be resolved? ...

JQuery computes the grand total without displaying it on the screen

I have been working on creating a small e-commerce website, and recently integrated a jQuery program to calculate items in the shopping cart. I wanted to display the total amount of these items next to the cart, but despite seeing that the calculation was ...

When a new marker is clicked on Google Maps, the previous Infowindow will automatically close

Here are some specific locations to consider: var places = [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": & ...

Strange Behavior When Encapsulating Image in Fragment Shader

Recently, I developed a basic fragment shader with THREE.js. The shader essentially takes every pixel's coordinate, modifies the x component by adding a value (looping back to 0 if it exceeds 1), and then retrieves the background image color at this n ...

Unable to load models in face-api.js even though attempting to infer the models

Currently, I am working on developing an application for face detection. However, I am encountering an error stating "SsdMobilenetv1 - load model before inference" despite loading the models. The Front End HTML File is being sent from the server, ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

Creating an HTML5 video tag with bearer authentication using a WebAPI: The ultimate guide

My ASP.NET WebAPI requires bearer authentication, and most of my requests towards the API follow this format: GET http://localhost:29080/api/v1/users/me HTTP/1.1 Host: localhost:29080 Connection: keep-alive Accept: application/json, text/plain, */* Origin ...

Updating a Nested Form to Modify an Object

There is an API that fetches an object with the following structure: { "objectAttributes": [ { "id": "1", "Name": "First", "Comment": "First" }, { "id": "2", "Name": "Second", "Comment": "Second" } ] ...

Tips for locating a specific value within an array using ReactJS

I have a set of dates provided by the back-end that I need to work with in order to perform a specific check. If the list contains dates from the month of March, I should display the events for March, and the same for April, and so on. My task involves se ...