What is causing Sequelize to reverse the INSERT query it generates when calling the custom N:N method?

Hey there!

I am currently working with a database that has an N:N association setup as follows:

-> BlogPost belongs to many Categories through PostsCategories

-> Category belongs to many BlogPosts through PostsCategories

The model for the junction table is called PostsCategories.

When inserting a BlogPost into the database, it is important to categorize it under the relevant categories in the junction table. While following some documentation examples, I tried the following code snippet:

const blogPost = await BlogPost.create({ title, content, userId });
await blogPost.addCategories(categoriesList);

Everything seemed fine until I encountered an error. It appears that Sequelize is flipping the order of columns/values when executing the query. For instance, when I use

blogPost: { id: 3, categories: [1, 2] }

it generates this inverted query:

"'INSERT INTO `PostsCategories` (`categoryId`,`postId`) VALUES (3,1),(3,2);'"

I have tried multiple solutions but haven't been successful. :(

Any suggestions on how to resolve this issue?

Thank you!

EDIT: MY MODELS

module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define('Category', {
    name: DataTypes.STRING,
  },
  { tableName: 'Categories', timestamps: false });

  Category.associate = (models) => {
    const { BlogPost, PostsCategories } = models;

    Category.belongsToMany(
      BlogPost, { through: PostsCategories, foreignKey: 'postId', as: 'blogPosts' },
    );
  };

  return Category;
};

module.exports = (sequelize, DataTypes) => {
  const BlogPost = sequelize.define('BlogPost', {
    title: DataTypes.STRING,
    content: DataTypes.STRING,
    userId: DataTypes.INTEGER,
  },
  { tableName: 'BlogPosts', timestamps: true, createdAt: 'published', updatedAt: 'updated' });

  BlogPost.associate = (models) => {
    const { User, PostsCategories, Category } = models;

    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

    BlogPost.belongsTo(User, { foreignKey: 'userId', as: 'user' });
  };

  return BlogPost;
};

module.exports = (sequelize, _DataTypes) => {
  const PostsCategories = sequelize.define('PostsCategories', 
  {},
  { timestamps: false, tableName: 'PostsCategories' });

  return PostsCategories;
};

Answer №1

Finally found the solution to my problem. Haha.

Realized that my association declarations were incorrect.

    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

Turns out the foreign key is actually related to the BlogPost on the junction table.

I decided to switch up my declaration for better clarity.

    BlogPost.belongsToMany(
      Category, { as: 'categories', through: PostsCategories, foreignKey: 'postId' },
    );

BlogPost belongsToMany Category

  • If I query a BlogPost and want it with every category, it'll return as 'categories'
  • The association is established through PostsCategories
  • The way the BlogPost is associated with PostsCategories is via the foreignKey 'postId'

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

Finding the two rows in a table that have the lowest and highest values

I am working with a table called Product that has columns for id, product name, and price. id | product_name | price 1 | Red Shirt | 10.0 2 | White Shirt | 15.0 3 | Black Shirt | 9.0 4 | Yellow Shirt | 12.0 Is there a way to write a query ...

Attempting to configure an SQL database and establish connectivity with an Android application

I am currently in the process of developing a new Android application that will require sending and retrieving data from an online database. I am unsure if this is a valid approach or if I am going about it the wrong way. Can I instruct my application to ...

What is the best way to arrange arrays in JavaScript?

Let's consider two arrays, X and Y. Our goal is to populate array Z with elements that are the same in both arrays X and Y, positioned at the same indexes. X = [a,b,c], Y = [c,b,a], Z = [b] In addition, we want to fill array P with unique values from ...

Retrieving data with comparable column values using pattern matching

I have a table called cities which contains various records such as: Name Value id 62 name New York id 63 name Paris id 64 name Tokyo There are many more records but the structure remains consistent. In my Node.js API, I receive a city n ...

Get a CSV/PDF file created by PHP that pulls information from a MySQL database

Currently, I have developed a form that is capable of generating an SQL statement based on the selections made by users. This functionality resembles the report wizard found in MS Access. However, after reaching the last step, I am faced with a dilemma - h ...

Error: The 'create' property is undefined and cannot be read. (Node.js using Sequelize)

Trying to submit a post on localhost3000:/user/signup results in the following error: TypeError: Cannot read property 'create' of undefined Routing Situation: const path = require('path'); const express = require('express&apo ...

An error has been thrown stating that the function startTimer is not defined, despite the fact that it is clearly defined

const startBtn = document.querySelector('.startBtn'); const pauseBtn = document.querySelector('.pauseBtn'); const ResetBtn = document.querySelector('.resetBtn'); const time = document.querySelector('.time'); let sec ...

Attempting to open and display the contents of a text file (.txt) within a modal dialog box upon clicking a button

I am attempting to develop a modal that will appear when the user clicks on a specific button. The goal is for this modal to showcase text retrieved from a separate file stored on the server. My aim is to show this text within a dialog box modal. So far, ...

Web-based client services

Context: An HTML file I'm working with takes in multiple parameters and utilizes JavaScript to dynamically render the content. The page pulls data from various local XML files for processing. For instance, accessing service.html?ID=123 displays info ...

The SQL query encountered an error when trying to convert from a string (nvarchar) to an integer

SELECT * FROM Table1 INNER JOIN Table2 ON CAST(Table1.DeviceID AS INT)=Table2.LogicalDeviceId LogicalDeviceId is of type integer and DeviceID is of type string Error: Conversion failed when converting the string value 'NA' to data type inte ...

How to link a JavaScript file within a PHP document

I have an HTML file (index.html) that is using JavaScript to call a PHP file (pdj.php) and display the output in a div (pdj), which is functioning correctly. $.ajax({ url: '../command/pdj.php', type: "POST", data: ({xparam: xpara ...

Encountering the value of 'undefined' when using jQuery

I need help with displaying values in my asp.net application using ajax. Here is the C# code snippet: [WebMethod] public static string fillvazh(int id) { List<object> Users = new List<object>(); DataTable dt = new DataTable(); ...

An exception has occurred in the SQL query regarding keys that were not specifically

I encountered an exception in the specified section of my code: Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String query = "Insert into ..."; try { con = DriverManager.getConnection(...); ps = con. ...

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

Switch up the sequence of selected/appended SVGs in D3

In this dot matrix visual example, different colored circles represent funding percentages from three countries: USA, Canada, and Mexico. The gray circles indicate the remaining funding to be raised. The code snippet showcases how the circles are mapped ba ...

Data from AngularFire not displaying in my list application

While going through tutorials on the Angular website, I encountered a roadblock while attempting to create a list that utilizes Firebase for data storage. Strangely, everything seems to be functional on the Angular site, but clicking on the "Edit Me" link ...

My Angular 6 app kept encountering this error repeatedly, eventually causing the browser to freeze

[Violation] A non-passive event listener was added to a scroll-blocking 'touchstart' event. Consider marking the event handler as 'passive' to improve page responsiveness I have been successfully using Tabulator in Angular, but after s ...

Using JQuery to hide elements by setting CSS display as none instead of block

Is there a way to change the display of a content div to block when a specific tab is selected by the user, while hiding all other content divs? Here is the JQuery code I have tried so far: $(document).ready(function() { function resetTabs() { $("# ...

Customizing the background color in TurnJSIncorporating

Recently, I encountered a problem that has left me puzzled. Despite searching online for help, I have not been able to find a solution. The issue lies with the basic code provided on the official page of the TurnJS script. <div id="flipbook"> <di ...

Setting up the Environment for Eslint within a current project: A Step-by-Step Guide

Encountered an error while building module (from ./node_modules/eslint-loader/index.js): Error: .eslintrc.js: Unknown key "es2021" in the environment at /Users/artic/Documents/RestroWorld/HRConsultancy/node_modules/eslint/lib/shared/config-valida ...