A guide to populating multiple "Select" controls with data in Node.js using Mongoose

I am currently working on a project in Express JS where I am using Mongoose to interact with MongoDB. Currently, I am able to fill a select control in my view using the following code:

app.get('/new_alumno', alumno.create);

However, I now have a requirement to populate multiple select controls, but I am unsure of how to pass more than two values from my controller to the view.

The app.js file in my project contains the following code:

var express = require('express');
// Other dependencies and configurations

// Reference to the controllers
var alumno = require('./controllers/ctrl_alumno');

// Relevant routes
app.get('/', routes.index);    
app.get('/alumnos', alumno.listalumnos);
// Other routes
http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Within my controller ctrl_alumno.js, I have the following code:

// Connection to MongoDB
// Models and schemas definition

exports.create = function(req, res, next){

    Carrera.find(getCarreras);

    function getCarreras(err, carrera){
        if(err)
        {
            console.log(err);
            return next();
        }
        return res.render('newalumno',{title:'Lista de alumnos', carreras: carrera});   
    };
};

And finally, my student view looks like this:

While I have been successful in populating a single select control using Mongoose, I am facing challenges in passing multiple values or filling multiple select controls. Any guidance or assistance on this matter would be greatly appreciated.

Answer №1

If you want to run multiple async functions in parallel and return an array of results, you can use the async parallel method. This method takes an array of async functions that each take a callback parameter, and then returns an array of results once all functions have completed. You can include as many functions in the array as needed.

https://github.com/caolan/async#parallel

Here is an example of how to use async parallel:

async.parallel([
        function(callback) {
            Alumno.find({}, function(err, result){
                callback(err, result);
            });
        },
        function(callback) {
            Carrera.find({}, function(err, result){
                callback(err, result);
            });
        }
    ],
    function(err, results) {
        // The 'results' variable here will hold an array of results returned from the database.
        // Manipulate the results as needed before passing them to the view.
        return res.render('view', {results : results}); 
    });

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

How can I include dynamic attributes in an HTML tag using ejs?

When using express.js + ejs, I encounter two scenarios: 1. <a href="<%= prevDisabledClass ? '' : ?page=<%=+page - 1%>%>">prev</a> Unfortunately, this code throws an error: Could not find matching close tag for "<%=". ...

Node package command execution failing on Ubuntu 12.04 Real-Time System

I recently developed an npm package called docxgen, and here is the content of the package.json: { "name": "docxgen", "version": "1.0.5", "author": "Hans Thunam <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e565f50 ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

Guide on interacting with ExpressJS REST API endpoints using C# code

After successfully setting up a backend server with multiple endpoints using NodeJS and the ExpressJS framework, I connected these REST Api Endpoints to a Mongodb Database. However, for a specific project requirement, I needed to write some code in C# tha ...

Encountering timeout issues while testing promises in supertest-as-promised with mocha

As I work on testing a function example, here is what I have: function generateJwt(){ var deferred = Q.defer(); deferred.resolve({ message: 'user created', token: signedJwt, userId: user.userId } ...

Guide on including a sum (integer) property in the JSON output of my API

Currently, I am working on an API using Express.js. In one of my functions named getAll, my goal is to not only return an array of records but also include the total number of records in the response. The code snippet below showcases how I have been handli ...

installing files that are not present

After running bower install inside my directory, a bower_components folder is created. However, some .js files seem to be missing. GET /customapp/customapp.controller.js 304 7ms GET /customapp/testmodal.controller.js 304 5ms GET /bower_components/bootstra ...

The request to http://localhost:3000 received a 500 Internal Server Error response in 197ms

I have implemented backend CORS middleware, but it doesn't seem to affect anything. When I try a POST request with Postman, it works fine. However, when I attempt to add a teacher through my front-end, I encounter an error. const express = require(&qu ...

Ways to verify if fields within an Embedded Document are either null or contain data in Node.js and Mongodb

I need to verify whether the elements in the Embedded Document are empty or not. For instance: if (files.originalFilename === 'photo1.png') { user.update( { userName: userName ...

Transmit data using both jQuery and JSON technology

I'm struggling to figure out how to send a JSON structure with a file using AJAX. Whenever I try to include an image in the structure, I encounter an error. var professionalCardNumber = $("#professional_card_number_input").val(); var professi ...

Using the Express router to handle GET requests results in failure, however using the app

During my exploration of this particular guide, I encountered an issue where the router methods were not functioning as expected. Upon using npm start and trying to access localhost:3000/api/puppies, a 404 error would consistently appear. However, after mo ...

What are the benefits of using Express in NodeJS to run both a backend and a frontend server simultaneously?

My current project involves a simple NodeJS/AngularJS application structured as follows: /frontend/index.html <-- AngularJS home page /frontend/js/app.js <-- AngularJS app.js /backend/package.json<-- NodeJS package.json /backend/index.js < ...

Debbuging problems with Azure web sockets and Socket.io

I'm currently developing a multiplayer chess game using NodeJS and socket.IO. I've been facing challenges trying to host it on Azure. I've attempted various approaches, including: Enforcing the use of WebSockets by adding the following cod ...

Nuxt.js pages are displaying a 404 error, indicating that the content cannot

I've developed a nodejs project using adonuxt and have SSL enabled on my website. The issue I'm facing is related to using nginx as a reverse proxy to handle requests to localhost:port on my server. There are two main problems that I'm enc ...

Is it necessary to implement both JWT and Passport in a Node application?

I've been delving into the intricacies of user login authentication process for my MERN app that I'm currently developing. Most tutorials I come across advocate for using both passport in conjunction with jwt, and I find myself struggling to gras ...

When utilizing AngularJS $resource, it sends an HTTP OPTIONS request in place of the expected HTTP POST when calling the

As I work on developing a basic library application in preparation for a larger AngularJS project, I have been exploring the benefits of using $resource over $http to interact with a RESTful API. While implementing $resource seemed promising for saving tim ...

Refine your search with a JSON object description in expressJS and UnderscoreJS

[ { "id": 1, "description": "Empty the garbage bin", "completed": false }, { "id": 2, "description": "Dine out for dinner", "completed": false }, { "id": 3, "description": "Exercise at the fitness center", "com ...

Identifying the specific promise that failed within a chain of .then statements

I am currently working on setting up a chain of promises with an error catch at the end within my node and express application. One issue I have encountered is that if any of the 'then' functions encounter an error, it can be difficult to trace b ...

Is it possible for me to determine whether a javascript file has been executed?

I am currently working with an express framework on Node.js and I have a requirement to dynamically change the value (increase or decrease) of a variable in my testing module every time the module is executed. Is there a way to determine if the file has ...

Experiencing difficulties with res.redirect function in Express framework

After numerous attempts to enter my location into the search form, I noticed that while it logs in the console, the res.redirect function fails to take me to a new URL. My goal was to be redirected to a different webpage after submitting my location info ...