Storing information within a Express application using Postgres

Recently, I've been delving into the world of Express and experimenting with a program that allows users to create events and invite others. While I know about using join tables to retrieve data, I'm curious if there's a way to organize the data in nested form using POSTGRESQL, showcasing events where the user is hosting, attending, or invited based on event IDs.

Here's my current progress:

app.get('/api/users', function(req, res) {
var list = [];
User.findAll().then(function(users) {
  for( var i in users) {
    var item = {
      id:         users[i].dataValues['id'],
      firstName:  users[i].dataValues['firstname'],
      lastName:   users[i].dataValues['lastname'],
      email:      users[i].dataValues['email'],
      phone:      users[i].dataValues['phone'],
      image:      users[i].dataValues['image'],
      confirmed:  users[i].dataValues['confirmed'],
      events: []
    }
    Event.findAll({ where: { hosting_id: user.id }}).then(function(events) {
      for( var i in events) {
        item.events.push({
          hosting: event[i].dataValues['id'],
          attending: event[i].dataValues['id'],
          invites: event[i].dataValues['id']
        })
      }
    })
    list.push(item)
  }
  res.json(list)
 })
});

I've managed to loop through and find all associated events by user ID, but I'm struggling to connect them in a way that displays the event IDs as shown in this example:

{
"id": "4",
"firstName": "Jon",
"lastName": "Doe",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b010f040e2b1f0e181f45080406">[email protected]</a>",
"phone": "1234567890",
"image": "",
"events": {
  "hosting": [
    "1"],
  "attending": [],
  "invites": [
    "3", "4"]
    },
"confirmed": true
}

In addition to displaying the information, I'm pondering whether the nesting needs to be done within a POSTGRES database or if utilizing a join table would suffice without requiring another API call.

Any assistance will be highly valued! Thank you in advance!

Answer №1

Event.findAll operates as a Promise and executes asynchronously. Ensure you format your response only after this function is called.

You can experiment with the following code snippet:

Promise.all(
  users.map(function(user) {
    return Event.findaAll({ where: { hosting_id: user.id }})
      .then(function(events) {
        var formatEvents = events.map(function(event) {
          return {
            hosting: event.id,
            attending: event.id,
            invites: event.id
          };
        })
        return Promise.resolve({
          id:         users[i].dataValues['id'],
          firstName:  users[i].dataValues['firstname'],
          lastName:   users[i].dataValues['lastname'],
          email:      users[i].dataValues['email'],
          phone:      users[i].dataValues['phone'],
          image:      users[i].dataValues['image'],
          confirmed:  users[i].dataValues['confirmed'],
          events:     formatEvents
        });
      })
  })
)
  .then(function(list) {
    res.json(list)
  })

Alternatively, you may establish a relationship between Users and Events to retrieve users along with their associated events model.

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

Why does trying to package a Windows app on OSX prompt a request for Wine installation?

For several months, I have been successfully utilizing Electron on macOS (10.11.6) to create and package both OSX and Windows applications. My current setup includes electron v1.7.3 and "electron-packager" "^8.5.2", all of which have not been updated in a ...

What is the reason behind Q.js promises becoming asynchronous once they have been resolved?

Upon encountering the following code snippet: var deferred = Q.defer(); deferred.resolve(); var a = deferred.promise.then(function() { console.log(1); }); console.log(2); I am puzzled as to why I am seeing 2, then 1 in the console. Although I ...

Tips for maximizing the performance of my Heroku web application

As a beginner in web development, I am currently working on creating my own portfolio website. My website utilizes node, express, and Heroku to go live online. However, I am facing some challenges as the page does not scroll smoothly and the animations are ...

Extract the body.req object within a loop in a Node.js application

I'm looking to efficiently parse and save the body of a POST request using Mongoose in Node.js. Is there a way to use a for loop to accomplish this task, rather than manually saving every property? My ideal solution would involve something like: for ...

Nestjs fails to start quietly during the initialization of a module

When I try to run the command nest start, the module initialization fails without giving any error message. The issue seems to occur after initializing the CqrsModule dependency, but there is no information in the logger that I have set up. Is there anothe ...

There seems to be an issue with the function code error when calling it within the

When I attempt to run my code in this way, I encounter a compile time error stating that the expression statement is not an assignment or call... (within the else statement). What am I missing here to get it to work? I've made numerous attempts to ad ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...

Unraveling a collection of objects containing diverse nested child elements

Displayed below is an instance of the response sent from the server. The list comprises elements with diverse substructures in the info fields. Each element includes 3 fields of the same types, but they have distinct keys. I am unsure how to interpret th ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

Having trouble with $(document).ready not functioning correctly?

After following the instructions to move my jQuery CDN to the bottom of the page, I encountered a problem. The script below was functioning perfectly when my jquery files were at the top of the page: if ($(window).width() >= 768) { $('.col-l ...

Guide to sequentially playing multiple video objects with buffering

As I work on developing a reference player application that utilizes node.js, javascript, and HTML5, I have encountered an issue. Currently, my player successfully loads a single video and generates diagnostic data from it. However, I am striving to enhanc ...

Insert elements into MongoDB array using Mongoose

My mongodb collection is named 'people' and the schema looks like this: people: { name: String, friends: [{firstName: String, lastName: String}] } I have an express application that connects to this database and succes ...

What could be causing the d3.js pie chart transition to malfunction?

Today I am experimenting with d3.js to create a unique pie chart from scratch. While following tutorials here as my base, there were modifications made in the code to add personal touches and customization. The challenge arose during Step 6 when introduc ...

Can the selected week be highlighted along with the corresponding week number in a row?

Can we display the number of the week in a row along with the selected week, either in the toolbar or somewhere else? I attempted to utilize ToolbarComponent, but it overrides the entire header. However, I would like to keep it as is and just add informat ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...

The getInitialProps method does not have access to the Passport user object in the request when the server is running on a different port

I currently have my express server running on a separate port from my client-side nextjs project. Typically, when the server is on the same port as the client, you can use getRequestHandler with next to pass the user object that can be accessed in the cli ...

Express.js encountering an `ERR_HTTP_HEADERS_SENT` issue with a fresh Mongoose Schema

My Objective Is If data is found using the findOne() function, update the current endpoint with new content. If no data is found, create a new element with the Schema. Issue If there is no data in the database, then the first if statement throws an ERR_H ...

Colorful radial spinner bar

I am interested in replicating the effect seen in this video: My goal is to create a spinner with text in the center that changes color, and when the color bar reaches 100%, trigger a specific event. I believe using a plugin would make this task simpler, ...

Tips for using multiple Angular directive modules in PprodWant to enhance your Pprod experience by

Currently, I am working on jhipster Release 0.7.0 and our jhipster app has multiple types of directive modules – one for the index page and another for common directives. However, when we run the app on Prod profile, an exception occurs: [31mPhantomJ ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...