javascript has been overrunning with an abundance of attached comments loops

I've been encountering an issue where I am unable to properly link my comments to the message id. Below is what I have attempted:

Routes file:

router.get('/home', function(req, res){
    if(req.cookies.user_id){
        knex.raw(`SELECT * FROM users WHERE id = ${req.cookies.user_id}`)
            .then(function(user){
                knex.raw(`SELECT * FROM messages JOIN users on users.id = 
                messages.user_id`)
                .then((joinInfo)=>{
                   knex.raw(`SELECT comments.id, users.username, messages.id 
                   as mess_id, messages.body, comments.message_id, users.id 
                   as us_id, comments.commentsbody, comments.created_at, 
                   comments.updated_at FROM comments JOIN messages ON 
                   comments.message_id = messages.id JOIN users on 
                   comments.user_id = users.id`)
                  .then((commentInfo)=>{
                  res.render('loggedInHome', {user: user.rows[0], 
                 messagedata: joinInfo.rows, title: 'Seddit', commentInfo: 
                 commentInfo.rows})
               })
          });
      }).catch((err)=>{
          console.log(err, 'ERRRRR')
          res.redirect('/')
    })
 }

)

EJS views page

<main class='main_content'>
    <% for (var j = 0; j < messagedata.length; j++) { %>
    <div class='message_box'>
        <p><strong><%= messagedata[j].username %></strong>: <%= 
        messagedata[j].body %></p>
    <% for (var i = 0; i < commentInfo.length; i++) { %>
        <% if (commentInfo.mess_id == messagedata.comment_id) { %>
             <p><strong><%= commentInfo[i].username %> 
             comments</strong>: <%= commentInfo[i].commentsbody %></p>
        <% } %>
   <% } %>
   <% } %>
   </div>
 </main>

When viewing the information on localhost, it seems to be looping excessively and when I log the if statement, it often returns as undefined.

Answer №1

The reason for this behavior is likely due to your nested loops, causing the inner loop to display the result multiplied by the number of times the outer loop executes.

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

Ensure to update the canvas prior to the function finishing

Is there a way to update the canvas element while inside a JavaScript function without waiting for the function to return? It can be frustrating when you want to keep the function running but also need to update the canvas element in real time. ...

iOS - Embedding text into a UIWebView input field

Just a quick question - if a textfield in a webform does not automatically have the focus set by the form, meaning you have to press the field before the keyboard pops up, am I correct in assuming that the field cannot be edited? In simpler terms - is it ...

A guide on advancing the border like a progress bar in react.js

My goal is to progressively fill a border every minute, reaching full capacity after 60 minutes and then starting over. This task is part of my practice with react.js. I attempted to create a variable using .getMinutes(); to track the current number of mi ...

Move the scroll event binding from the parent element to the child element

I'm working on an HTML page with the following structure: <div class="parent"> <div class="child1"> <div class="child2"> </div> </div> </div> Currently, I have a scr ...

What could be causing the issue with loading a YouTube video within an iframe using JQuery?

I'm facing an issue where I am able to fetch Json data from a link successfully, but the YouTube links are not loading inside the iframe. Can anyone guide me on where I might have gone wrong? Please help. $.each(data,function(index,item){ cont ...

Having trouble with Jquery's .mouseover() method? Let's catch the solution!

I'm currently working on a jQuery homework assignment and I've been attempting to enhance the mouseover feature, but unfortunately, it's not functioning as expected. $("button").mouseover(function() { $(this).css({ left: (Math.rando ...

Creating a button in HTML that performs a POST request without redirecting involves using specific code techniques

Looking for a way to create an HTML button that triggers a POST request to a quick route with parameters passed through req.params. The challenge is preventing the button from redirecting me to the route when clicked, but instead staying on the same page w ...

React/Redux - Issue with rest operator functionality in component

Here is the initial state I am working with: const initialState = { selectedGroup: {}, groups: { rows: [], total: null }, offset: 0, range: 15, loading: false, error: null } Within a reducer function, I have this case for successful ...

Tips for updating mfData in Angular 4 after deleting information from it

I have integrated mfDataTable into my UI to display data in a tabular format. Each row in the table has a button that allows users to remove the corresponding row. While I am able to successfully remove the data from the array in the component, the table d ...

Calculating the total of selected values in Checkboxes and Selectors using KnockoutJS

I have already created this using jQuery. You can view it on JSFiddle: JSFiddle HTML: <div class="container"> <header> <h3>The Crazy Things We'll Do for Money</h3> <div class="small"><em>An ele ...

Sign in a user post-registration with the help of AWS Amplify and React

After a user successfully signs up using the withAuthenticator component, they are immediately logged in upon email confirmation. Is there a way to automatically log them in using a custom sign-in process and the Auth object instead? If so, what steps wo ...

Having trouble populating the input text field with the selected value from a dropdown using JavaScript

I have implemented a JavaScript function to retrieve the id of a dropdown select with id='odrid'. The script looks like this: $('#odrid').change(function(){ $.getJSON( 'fetch.php', 'odrid='+$(&ap ...

Restricting buffer size in HTML5 video for an MP4 file

Can the HTML5 Video tag be utilized to load an MP4 file while managing the amount of data downloaded/buffered from the server (assuming byte ranges are supported)? In essence, I would like to specify "only download 60 seconds ahead" in order to prevent th ...

The presence of absolute positioned elements is causing the appearance of a horizontal scrollbar

On my webshop's categoria page, I have implemented sliders to filter products based on price ranges. The issue arises when viewing the site on mobile devices, as a horizontal scrollbar appears due to the absolute positioning of these sliders and thei ...

Is there a problem in Angular 2 and Ionic 2 *ngfor where clicking on one element causes changes to all elements?

When I click on the playNote(note) function, why does it change all instances of [name]="myIcon" in my ngFor loop? I only want to change the icon of the one that was clicked... home.html <ion-item color="theme" class="note-block" *ngFor="let note of n ...

I keep getting an error saying "wallet.connect() is not a function," even though it was working perfectly just a few

`` I'm currently working on the FCC solidity course and I've reached the 7:45 mark. Everything was running smoothly until I encrypted the RPC url, private key, and password. Now, when trying to connect my wallet variable to the provider variable ...

It seems like KineticJS is removing elements from the canvas that I would prefer to keep

My website features an HTML5 canvas where I showcase a variety of images, text, and shapes using JavaScript functions. The text and shapes are created with the following JavaScript functions: function drawGameElements(){ /* Draw a line for the ' ...

What could be causing the issue with multiple selection in jQuery?

I am interested in implementing multiple selection on my ASP page. I came across the pickList jQuery plugin and followed the instructions provided at the following link: Below is a snippet from my ASP page: <%@ Page Language="C#" AutoEventWireup="true ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

Can a PHP script be executed through an Ajax event?

Is it feasible to execute the script of a PHP file when an AJAX event is triggered? Consider this scenario: on the AJAX error, could we send the data to the error.php file, record the error, notify the admin via email, and perform any other desired action ...