When using Expressjs MVC, encountering difficulties in retrieving data from mongoose in the listAll() function within the router

I'm currently working on implementing MVC-like architecture in Express.js for a very specific scenario. I suspect there may be an issue with promises, but I'm struggling to debug the problem effectively.

Here's how the architecture is set up: Router calls trigger methods within classes located in a service layer. For example: router.get('/users/list') -triggers-> userService.listAll() -returns array of users->res.render('apage',{users:users}); (users variable contains the returned values).

The issue lies in the fact that while userService can access the data source and retrieve the data successfully, the "users" variable within the router remains unaffected.

Below is the code snippet:

users.js
router.get('/dashboard',  function(req, res) {
    var users = userService.listAll();
    res.render('dashboard.twig', {users: users});
});

UserService.js


async listAll(){
        await utilisateurModel.find({}).then(
            function(data){
            console.log("data is:"+JSON.stringify(data));
            return data;
     });
}

Any suggestions on how to resolve this issue?

Answer №1

There are several common mistakes people make when working with Promises and the async/await syntax.

When using the async function listAll, it is important to remember to use the await keyword to retrieve the value.

In the file UserService.js:

async listAll() {
  const data = await utilisateurModel.find({});
  console.log("data is:" + JSON.stringify(data));
  return data;
}

In the users.js file:

router.get('/dashboard', async function (req, res) { 
  var users = await userService.listAll(); 
  res.render('dashboard.twig', { users: users });
});

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

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Tips for preserving dynamically generated HTML through Javascript during page reload

I have a straightforward question, but I haven't been able to find a suitable answer. Here's my situation: On my HTML page, I have a form. Using jQuery and AJAX, I submit the form and then use some JavaScript code to change the content of a spec ...

What is the best way to utilize node modules in the client-side while developing an Express application?

I'm currently working on a project with intl-tel-input integration within an environment utilizing express and ejs. In my app.js, I have configured app.use(express.static(path.join(__dirname, 'public')));, which allows Express to serve all ...

Sending JSON-encoded data using HTML5 Server-Sent Events (SSE) is a

I have a script that triggers an SSE event to fetch json encoded data from online.php. After some research, I discovered methods for sending JSON data via SSE by adding line breaks. My question is how to send JSON through SSE when the JSON array is genera ...

Express is not receiving any data in the request's urlencoded body

Currently, I am facing an issue with retrieving URL parameters in Express 4.17.3 using the urlencoded middleware as the body always turns out to be empty. To demonstrate this problem, I have simplified it into a minimal code snippet: const express = requir ...

Attempting to update information in JSON using AJAX and PHP

I am attempting to update key values in a JSON object using PHP, AJAX, and JavaScript to display the new values. Here is an example of my JSON database that needs to be modified: "answer01count": "1", "answer02count": "2", "answer03count": " ...

The functionality of jQuery binding is not functioning properly

I've been playing around with jQuery and have a code snippet that includes: // buttons for modifying div styles by adding/removing classes <button class="size" id="switcher-large"> Large Print </button> <button class="size" id="switche ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Initiating a post request to the express server

My service includes a function that retrieves the user's current location using latitude and longitude coordinates. I am attempting to send this information to my server in order to incorporate it into a query. However, my post request does not appear ...

Issue with undefined bindingContext.$data in IE9 on knockout binding handler

I'm attempting to create a unique binding handler that applies role-based access to fields on a page. This custom handler uses the values of other observables from the viewModel to enable or disable input controls based on certain conditions. However ...

Unable to perform filtering on a nested array object within a computed property using Vue while displaying data in a table

Lately, I've been experimenting with different methods to filter data in my project. I've tried using various approaches like methods and watchers, but haven't quite achieved the desired outcome yet. Essentially, what I'm aiming for is ...

Employing JavaScript to display or conceal a <div> element while scrolling

I'm looking to create a customized sticky navigation bar through Javascript, but I have never written my own code in this language before. My approach involves implementing two sticky navigation bars that appear and disappear based on scrolling behav ...

Sort through various table columns

I am currently utilizing a data table component from Framework7, which is being generated dynamically with JSON data. My goal is to make the column filter input functional within the table. So far, I have succeeded in implementing the filter for the first ...

Unable to transfer data successfully from popup to extension.js

I am currently developing a browser extension using Crossrider and I'm facing an issue with sending data from the popup to extension.js Here is my code for the popup: <!DOCTYPE html> <html> <head> <!-- This meta tag is relevant ...

Steps to validate individual input text fields that create a date and display an error message if the date is not valid

Currently, I am working on a React Material UI component designed to capture a user's 'Date of Birth'. This component consists of three separate inputs for the day, month, and year. In order to enhance this functionality, I would like to im ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

What are some effective ways to slow down the image transitions in a Javascript slideshow?

I am currently developing a slideshow that updates Images, Title, and Description simultaneously based on their Array index. The slideshow is functional BUT, my goal is to achieve a smooth transition to the next/previous Image (... title & descript ...

What are the most effective applications for utilizing an Observable Data Service?

Within my application setup, I have integrated a data service at the core level. The majority of functions within my app involve actions taken on the data model, to which components react. My goal is for components to be able to subscribe to the data ser ...

Animating Array of Paragraphs with JQuery: Step-by-Step Guide to Displaying Paragraph Tags Sequentially on Each Click

var phrases = ['phraseone', 'yet another phrase', 'once more with feeling']; $(".btn").on('click', function() { for(var i=0; i < phrases.length; i++) { container.innerHTML += '<p>' + ...

Express - implementing a redirection strategy post user login success

I'm struggling to grasp a key Node concept. Once a user is validated in the database, an object ("pass_to_html") is returned from the database. My goal is to display the contents of this object on a new page using handlebars. Here is the condensed co ...