Sending information to sequelize via table in express

I have implemented a setup in my postgresql database where users can follow each other by using a through table.

    as: 'follower',
    through: 'follow',
    foreignKey: 'follower_id'
})

User.belongsToMany(User, {
    as: 'following',
    through: 'follow',
    foreignKey: 'following_id'
})

Here is the structure of the table:

| created_at | updated_at | follower_id | following_id |
|------------|------------|-------------|--------------|
|            |            |             |              |

When I make a get request like this:

userRouter.get('/:user_id/followers', async (req, res) => {
    try {
        const user = await User.findOne({
            where: {
                id: req.params.user_id
            },
            include: [
                {
                    model: User,
                    as: 'follower',
                    through: { attributes: [] }
                }
            ]
        })
        res.send(user)
    } catch (error) {
        console.log(error)
    }
})

I receive a result like this:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith",
  "username": "tester",
  "profileImage": null,
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e4f5e3e4f5e2d0fdf1f9fcbef3fffd">[email protected]</a>",
  "password": "$2b$12$h2rVqmxgsGxTOVgq3aII5uCuRcSN0TZZ6lwZgRRHCaOhu98K3AKbe",
  "skills": [
    "React",
    "Python",
    "Mongo"
  ],
  "createdAt": "2019-07-07T23:38:07.730Z",
  "updatedAt": "2019-07-07T23:38:07.730Z",
  "follower": []
}

Now I am looking for guidance on how to use post or put requests to add new entries to this table.

Answer №1

After some experimentation, I finally uncovered the solution.

Encountered an obstacle while trying to add a new follower as it was replacing the existing entries.

Here is how I configured the relationships:

const Follower = db.define('follower', {
    follower_id: {
        primaryKey: true,
        type: Sequelize.INTEGER
    }
})

Follower.belongsTo(User, {
    as: 'user',
    through: 'follower',
    foreignKey: 'follower_id'
})

User.hasMany(Follower, { as: 'followers' })

The get route implementation:

userRouter.get('/:user_id/followers', async (req, res) => {
    try {
        const user = await User.findOne({
            where: {
                id: req.params.user_id
            },
            include: [
                {
                    model: Follower,
                    as: 'followers',
                    include: [
                        {
                            model: User,
                            as: 'user'
                        }
                    ]
                }
            ]
        })
        res.send(user)
    } catch (error) {
        throw error
    }
})

Handling post requests:

userRouter.post('/:user_id/follow/:follower_id', async (req, res) => {
    try {
        const user = await User.findByPk(req.params.user_id)
        if (user) {
            if (user.id.toString() === req.params.follower_id) {
                res.status(400).json({ err: 'You cannot follow yourself' })
            } else {
                const following = await Follower.findOrCreate({
                    where: {
                        userId: req.params.user_id,
                        follower_id: req.params.follower_id
                    }
                })
                res.send(following)
            }
        }
    } catch (error) {
        throw error
    }
})

All works smoothly now:

 follower_id |         created_at         |         updated_at         | user_id 
-------------+----------------------------+----------------------------+---------
           2 | 2019-07-07 23:36:06.696-04 | 2019-07-07 23:36:06.696-04 |       1
           3 | 2019-07-07 23:36:22.498-04 | 2019-07-07 23:36:22.498-04 |       1

Data retrieved from the API:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith",
  "username": "tester",
  "profileImage": null,
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7a6b7d7a6b7c4e636f6762206d6163">[email protected]</a>",
  "password": "$2b$12$0Ir/1zWRPvx3MWRjq6l85.z35QyCPwDqX7TyhAeWZHLx75RmGzlKS",
  "skills": [
    "React",
    "Python",
    "Mongo"
  ],
  "createdAt": "2019-07-08T03:36:00.262Z",
  "updatedAt": "2019-07-08T03:36:00.262Z",
  "followers": [
    {
      "follower_id": 2,
      "createdAt": "2019-07-08T03:36:06.696Z",
      "updatedAt": "2019-07-08T03:36:06.696Z",
      "userId": 1,
      "user": {
        "id": 2,
        "firstName": "Jane",
        "lastName": "Doe",
        "username": "test",
        "profileImage": null,
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2155445255614c40484d0f424e4c">[email protected]</a>",
        "password": "$2b$12$pxg9ssYtSIZm3TPcYDzjnOZApaFjXWPypM8et1m5nSPZeH1voGVHO",
        "skills": [
          "HTML",
          "Css",
          "React"
        ],
        "createdAt": "2019-07-08T03:36:00.519Z",
        "updatedAt": "2019-07-08T03:36:00.519Z"
      }
    },
    {
      "follower_id": 3,
      "createdAt": "2019-07-08T03:36:22.498Z",
      "updatedAt": "2019-07-08T03:36:22.498Z",
      "userId": 1,
      "user": {
        "id": 3,
        "firstName": "Jackie",
        "lastName": "Legs",
        "username": "test3",
        "profileImage": null,
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88fcedfbfcbbc8e5e9e1e4a6ebe7e5">[email protected]</a>",
        "password": "$2b$12$V0UgOVxB.c5/gbuUIqvvW.cnWqZjsqLUnHCgoT4zwzFtBPucgRAl2",
        "skills": [
          "HTML",
          "Css"
        ],
        "createdAt": "2019-07-08T03:36:00.758Z",
        "updatedAt": "2019-07-08T03:36:00.758Z"
      }
    }
  ]
}

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

Is it possible to create a jQuery-powered color picker that changes colors in real-time

I am currently working on a form that needs to send data to the database. The form includes fields for the product name and specifications details such as spec name and color selection. While I was able to generate the spec input without any issues, I enco ...

Mastering all changes to the 'src' attribute in the DOM

I am currently coding in Javascript and trying to implement a feature that monitors new 'script' elements and blocks specific sources. I have experimented with using MutationObserver and __defineSetter__, both of which can monitor changes to the ...

Contrasting app.use() and app.get()

const express = require('express'); const app = express(); const PORT = 3000; // The following middleware stops the request flow app.use(function (req, res, next) { console.log("Middleware has been triggered") next(); }); / ...

Turn the camera upside down in a Three.js environment

I am currently utilizing PerspectiveCamera along with OrbitControls. I have a query regarding flipping the camera entirely upside down, thereby making the scene appear inverted. Would it be possible to revert it back to its original orientation afterward ...

Access the extended controller and call the core controller function without directly interacting with the core controller

i have a core controller that contains an array called vm.validationTypes with only 2 objects. I need to add 3 or 4 more objects to this array. to achieve this, i created another controller by extending the core controller: // CustomValidation angular.m ...

Why am I encountering this export issue while attempting to integrate a NextAuth.js Provider with Next.js?

Embarking on my first project in React/Next.js, I opted to employ NextAuth.js for authentication. Following the initial steps outlined in the Getting Started guide provided by NextAuth, I have successfully set up a [...nextauth].js page featuring the code ...

What sets Koa apart when it comes to understanding the distinctions among await next(), return await next(), return next(), and next() in middleware?

The provided information explains the function of using 'await next()' in middleware to pause the middleware and initiate the next middleware downstream until all middlewares have completed execution. Once this happens, the process will start in ...

The HTML iframe is displaying blank content

I'm trying to embed a webpage within another webpage using an iframe. I attempted to do so with this simple code: <iframe src="http://edition.cnn.com/" id="i_frame"></iframe> JSFIDDLE However, nothing is displaying. Any thoughts on why ...

Tips on how to ensure that an onClick JS function only runs when radio buttons are selected

I have implemented the formslider library for a form on my website. In the demo, the slide transitions to the next set of questions based on a click event triggered by radio buttons (answers). However, when I attempted to include checkboxes for users to s ...

Using CSS3 to apply transformations to multiple divs based on their individual attributes

I am currently developing JavaScript code that will enable the use of HTML like the example below: <div class="box" data-vert-speed="7">ContentDiv1</div> <div class="box" data-hori-speed="10">ContentDiv2</div> <di ...

utilizing Javascript to insert a class with a pseudo-element

Witness the mesmerizing shining effect crafted solely with CSS: html, body{ width: 100%; height: 100%; margin: 0px; display: table; background: #2f2f2f; } .body-inner{ display: table-cell; width: 100%; height: 100%; ...

Show the Canvas element at the back of the DIV

This particular question requires a clear explanation. My goal is to have the canvas act as a background element on the page, while the main content of the page starts in its usual position. I attempted using separate DIVs with their own Z-index values, bu ...

Issue with function not getting triggered upon ng-click event binding

Having trouble getting a button to call the getFilteredRows() function in my MVC app's view and controller. I've tried various combinations, but the button just won't trigger the function. Can anyone help me figure out why? @using ProjectEx ...

Session not retaining value in Express callback

I developed a middleware function to capture all incoming requests. When a user is logged in, I utilize this information to query the database for additional data that I want to store in the session for later use in other routes. However, I am encounteri ...

Clearing Time Field Input in Safari

Recently, I've been utilizing the following HTML input element: <input type="time"> While testing it in both Chrome and Safari, I noticed that the clear field (cross button) is absent when using Safari. How can I make the cross button appear i ...

Creating a triangle number pattern in JavaScript with a loop

Hi there, I'm currently facing an issue. I am trying to generate a triangular number pattern like the one shown below: Output: 1223334444333221 =22333444433322= ===3334444333=== ======4444====== I attempted to write a program for this, however, ...

A guide on customizing bar colors in a jqPlot stacked bar graph

Is there a way to customize the colors for individual bars in a jqPlot stacked bar chart? I've searched through examples, but they all seem to use the default colors. How can I explicitly set different colors for each bar? Here is the current code sn ...

What is the best way to create an impact?

Need help fixing the parallax effect on this page. I attempted to implement a parallax effect but encountered some issues. Here is the JavaScript code: $objWindow = $(window); $('section[data-type="background"]').each(function(){ var $bgOb ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

What is the best way to incorporate ngRoute into Jasmine / Karma for testing AngularJS applications?

I am currently working on setting up a basic unit test example. Everything is running smoothly with this app.js: var whapp = angular.module('whapp', []) .filter('reverse', [function(){ return function(string){ return string ...