What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure looks like:

 def index
    @movies = Movie.all
    if params[:title] || params[:director]
      @movies = Movie.search(params)
    end
  

Now, I am exploring Express server and trying to implement a similar MVC pattern using PostgreSQL with pg-promise and jade templating engine.

In my current setup, I have a controller file with the following code snippet:

//Get home page 
var router = express.Router();
router.get('/', function(req, res, next) { 
  Movies.all(res); 
 }); 

Within my model, there is an 'all' function to handle database queries:

exports.all = function(res){
  var result = db.query('select * from movies').
    then(function (data) {
    // success;
    res.render('index',{title: 'Rotten Mango', movies: data} );
  })
    .catch(function (error) {
      // error;
      console.log('error !')
    });
};

What I aim to achieve is to return the query result from 'Movies.all' back to the controller in a way that resembles the traditional MVC approach in RoR. A hypothetical scenario could look something like this:

//Get home page 
var router = express.Router();
router.get('/', function(req, res, next) { 
    // This code should return the JSON result and render it into the view page
    res.render('index', Movies.all);
 }); 

However, due to potential promises or asynchronous behavior, achieving this functionality poses some challenges. How can I effectively make this happen?

Answer №1

This is the preferred way to handle the situation, avoiding passing res around which can complicate testing.

exports.getAllMovies = function(){
   return db.query('select * from movies')
}

In your controller:

 router.get('/', function(req, res, next) { 
  Movies.getAllMovies()
  .then(function(data) { res.send(data); })
  .catch(function(err) { res.status(500).send(err) }) 
 }); 

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

Tips for postponing the first button event in Vue 3 and JavaScript

My current task involves setting up a button event in Vue 3 that triggers a setTimeout countdown on the button before redirecting to another page. The event function has a conditional statement that initiates a countdown from 5 to 0 as long as the countVal ...

Enhancing webpage design by dynamically changing borders and headers using JavaScript

I have implemented a fixed positioning for the table headers using the following code: onScroll={() => { document.querySelector('thead').style.transform = `translate(0,${this.scrollRef.scrollTop}px)`; }} However, when I scroll the ta ...

Tips for utilizing code submitted by a user to extract meaningful errors

As I work on developing a mod for the online game Cookie Clicker, I've implemented a feature that allows users to input their own code to enhance the functionality of my mod. However, before users save their code using my custom editor, I want to run ...

Express JS offers advanced routing capabilities with its multi-level routing feature

I'm currently working on a straightforward CMS application using Express. The administrator is able to configure routes in the following format: domain/f1/f2/f3/f4/page1 (which will display the page1 view) domain/n1/n2/page2 (which will display the ...

Unable to execute node in vscode terminal

Can anyone help me figure out why I'm unable to run Node in my vscode terminal? I'm a newbie and currently using POP OS 22.04. https://i.stack.imgur.com/WqHWM.pnghttps://i.stack.imgur.com/GEHeA.png Your assistance would be greatly appreciated. ...

Is JQuery function running on its own or triggered by an event without manual input?

When visitors come to my website, I want them to see two options: one for registration and the other for logging in. To achieve this, I've created two buttons and a function that makes the form/input fields fade in when clicked. However, the issue is ...

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

Error: React Beautiful D&D is unable to retrieve dimensions when no reference is specified

Hey everyone! I'm currently working on a meta form creator and having some trouble with performance issues. I created a sandbox to ask for help, but keep getting the error message "Cannot get dimension when no ref is set" when trying to drag a second ...

What is the best way to create a gradual color change in each individual cell instead of changing all at once?

Looking for some help with a grid I'm working on. I've got the cells changing colors like I want them to, but they're all changing at once. What I really need is for them to light up in a specific order - Yellow, Green, Blue, White, Orange. ...

Utilizing distinct useState for mapped elements

I am struggling to find a solution on how to pass specific useState states to respective mapped elements. export const Polska = () => { const [riverVisible, setRiverVisible] = useState(false) const [mountainVisible, setMountainVisible] = useState(fa ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Jade console.log() not functioning properly as anticipated

Is it possible that I can just insert -console.log('hello') into any part of the jade code? It doesn't seem to be working, do you know what could be causing this issue? ...

Unresolved issue with Jade in Angular Routing

Currently, I am working on building a web server using expressjs and jade for the frontend. I have also implemented client-side routing with angularjs but unfortunately, my UI is not displaying as expected. Below you can find my code and the unexpected out ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

Issue with Ionic ng-click not triggering

I am currently experimenting with an Ionic application that utilizes a Firebase backend. The issue I'm facing is that the ng-click="loginUser(user)" function does not seem to be triggering. When checking the console, it only displays Signed Out from ...

When the key code is equal to "enter" (13), the form will be submitted

When I press the Enter key, I want to submit a form if there are no error messages present. Here is the function I have created: $(targetFormID).submit(function (e) { var errorMessage = getErrorMessage(targetDiv); if (e.keyCode == 13 && errorMessa ...

Is using canvas the best option for creating simple image animations with JavaScript?

I am currently working on a basic animation project using JavaScript. This animation involves switching between 13 different images per second to create movement. I have created two simple methods for implementing this animation. The first method involves ...

Obtain your access token from auth0

Currently, my setup involves utilizing auth0 and nextJS. My objective is to have the user redirected to the callback API after successfully logging in with their credentials. Here is the snippet of code I am working with: import auth0 from '../. ...

Experiencing a result of NaN following a mathematical operation on variables

While working with an array obtained from a JSON response, I am encountering NaN after performing addition operations. var a = new Array(); var b = 0; var c = 0; alert(b); for (var x = 0; x < length; x++) { a[x] = response.data[x] } for (var i = 0; ...