Populating the Join Table with Information

I have a scenario involving two models, Contact and Message, with a join model named ContactMessage.

Contact.belongsToMany(models.Message, {
  through: 'ContactMessage'
})

Message.belongsToMany(models.Contact, {
  through: 'ContactMessage'
})

My objective is to send a message from a sender to a receiver, while also adding the message ID and the contacts ID to the joinTable. However, I am facing an issue where this data is not being added as intended.

Below is the code snippet:

sendSms(req, res) {
    return Contact
    .find( {
        where: {
          contact_phone: req.body.sender
        }
      } 
    )
    .then(sender => {
      if (sender) {
        let users = [sender]
        return Contact
          .find({
            where: {
              contact_phone: req.body.reciever
            }
          }).then(reciever => {
            users.push(reciever)
            return users
          })
      } else {
        console.log(`${sender} does not exist`)
      }
    }).then (users => {
      if (!users) {
        return res.status(404).send({
          message: 'Users Not Found',
        });
      }
      return Message.create({
        sms
      } = req.body)
      .then(message => {
        message.setContacts([users], {status: 'sent'})
        return res.status(200).send(message)
      })
      .catch((error) => res.status(400).send(error));
    })
    .catch((error) => res.status(400).send(error));
  }

I'm curious about what could be going wrong here. Every time I attempt to run the api, I encounter the following error:

Unhandled rejection SequelizeDatabaseError: operator does not exist: character varying = integer
    at Query.formatError (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/sequelize/lib/dialects/postgres/query.js:363:16)
    at query.catch.err (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/sequelize/lib/dialects/postgres/query.js:86:18)
    at tryCatcher (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/promise.js:690:18)
    at _drainQueueStep (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/async.js:138:12)
    at _drainQueue (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/async.js:131:9)
    at Async._drainQueues (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/async.js:147:5)
    at Immediate.Async.drainQueues (/Users/andeladeveloper/Documents/projects/sms-app/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)

Answer №1

I recently discovered an error in the migration file related to ContactMessage where I mistakenly defined the datatype as String instead of INTEGER.

The corrected version now appears as follows:

return queryInterface.createTable('ContactMessages', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      contact_id: {
        type: Sequelize.INTEGER,
        references: {
          model: 'Contacts',
          key: 'id'
        }
      },
      message_id: {
        type: Sequelize.INTEGER,
         references: {
           model: 'Messages',
           key: 'id'
         }
      },
      status: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });

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

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

unable to retrieve access-token and uid from the response headers

I am attempting to extract access-token and uid from the response headers of a post request, as shown in the screenshot at this https://i.sstatic.net/8w8pV.png Here is how I am approaching this task from the service side: signup(postObj: any){ let url = e ...

Performing tasks when a component is fully loaded in Vue.js Router

I am currently working on a project involving a single-page application built with Vue.js and its official router. For this project, I have set up a menu and a separate component (.vue file) for each section that is loaded using the router. Inside every c ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

Upon clicking on a different div, a div will elegantly slide down from above the footer

I'm struggling with sliding a div from the bottom of the page. Here is my JSFIDDLE Currently, when I click on the blue box (arrow-hover), the div slides up (box-main). However, to hide the div (box-main) again, I have to click inside the box-main d ...

Display a preview image at the conclusion of a YouTube video

I am currently working on an iOS device and have a Youtube video thumbnail that, when clicked, disappears and the video automatically plays in fullscreen mode using an iframe. It's working perfectly. Now, I would like to know how I can make the thumb ...

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

How can I save a database connection in Python?

Currently, I have a python script (Script A) that functions by opening a database, executing queries, and then closing the database connection. The duration of Script A's operation is uncertain as it is dependent on the current workload. In tandem, I ...

Revamping status and backend systems

Seeking advice on the most effective method to execute a HTTP PUT request within my react application. A Post component is responsible for fetching data from https://jsonplaceholder.typicode.com/posts/1 and displaying it. There's another component na ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Troubleshooting: Issue with Deleting Table Rows using MySQL and PHP

I am having trouble deleting a table row from my database using MySQL and PHP. Despite reviewing my code, I cannot identify the issue. I believe that I am close to resolving the problem, likely something simple that I am overlooking. When hovering over th ...

Need to specify the file type at the end of the URL for HTML input

How can I create a URL input form that requires the input to be a valid URL and end in a specific file type? Here is an example of my input: <input name="bg" placeholder="https://website.com/image" type="url"> Currently, the input field only restr ...

Preserve the location of a moveable div using jQuery

I have implemented draggable divs in my JSP page, allowing users to move them around freely. After dragging the divs, I would like to save their positions either in a cookie or database for future reference. Could you please advise on the best way to ach ...

JavaScript is incorrectly showing the array as empty despite containing strings

I am experiencing an issue with my array of strings in JavaScript. Despite having strings in the array when I print it in the console, the forEach function runs 0 times and JS claims the array is empty when I print its size. What could be causing this?http ...

Utilizing Angular 2 for Integration of Google Calendar API

I recently attempted to integrate the Google Calendar API with Angular 2 in order to display upcoming events on a web application I am developing. Following the Google Calendar JavaScript quick-start tutorial, I successfully managed to set up the API, inse ...

What is the process for importing from vueuse into Vue SFC Playground?

After attempting to integrate vueuse through an Import Map using the code @vueuse/core": "https://www.unpkg.com/@vueuse/core?module, I encountered an issue where reactivity was not functioning as expected in vueuse. The import process appeared t ...

Ways to retrieve the text linked to a checkbox

Is there a way to access the text associated with a checkbox using its attribute? For example, in the code below, I want to alert the user with "Selected -- TextXYZ" when the checkbox is clicked. <form id="idForm" class="classForm"> <input type ...

Ways to retrieve the identifiers of every child node UL element within a UL container

I am struggling with a basic question related to HTML structure. Here is the code snippet I am working with: <ul> <li> <ul class=t2 id=15> <li class='item'>a<span class='val'>b</ ...

What is the best way to calculate the total sum of grouped data using mongoose?

I have a collection of log data that I need to work with. [ { "logType":1, "created_at": 2015-12-15 07:38:54.766Z }, .. .. .., { "logType":2, "created_at": 2015-13-15 07:38:54.766Z } ] My task is to group the ...

Steps to configure caching settings to ensure no caching for the entire site during specific hours, and constant no-cache policy for a particular page

Managing cache for my website has become quite the challenge. Some pages need to be cached during certain hours to improve navigation speed, while others must not be cached during crucial data update times. And to add to the complexity, there are pages tha ...