How to send multiple collections to a view using Express and Mongoose

I've encountered an issue while trying to pass multiple mongoDB queries to my EJS view using the code below. Surprisingly, only the "mvl" query is getting passed down successfully. The "extras" query seems to be unavailable as none of its values show up on the view. Strangely, there are no errors displaying when I attempt to load the view, so it doesn't indicate that "Extras is undefined."

router.get("/mvl", function(req, res) {
    index.find({}, function(err, mvl) {
        if (err) {
            console.log(err);
        } else {
            extra.find({}, function(err, extras) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(extras);
                }
                res.render("index", { mvl: mvl, extras: extras });
            });
        }

    });

Could you advise on what needs to be done in order to resolve this issue?

Thank you,

Ian

Answer №1

Discovered a solution for passing an extras collection in this manner

router.get("/mvl", function(req, res) {
    index.find({}, function(err, mvl) {
        if (err) {
            console.log(err);
        } else {

            extra.find({}, function(err, extras) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(extras);
                    res.render("index", { mvl: mvl, extras: extras });
                }
            });
        }
    });
});

The extras collection is in the form of an array, so accessing information can be done like this in your ejs file

<%= extras[0].youStuff %>

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

The inability to retrieve a MongoDB collection in a Node.js application through Mongoose, which was initially inserted via an AWS Lambda function employing

I attempted to insert a document using MongoClient() and then retrieve it using Mongoose, but to my disappointment, the result was an empty array. To be more specific, I performed the insertion within a Lambda function and tried fetching it inside a node ...

Error 502 is being returned by the Nginx server for specific directories within the Express Application

Currently, I have an express application running on Ubuntu with nginx as the web server. Everything was functioning correctly until today when I attempted to add two new directories using the app.get method and re-deployed my app. Unfortunately, the new ...

Searching for requests in parallel to provide a single response using Node.js Express

Looking to fetch data from multiple pages using an API and return an object if a specific value matches. The issue seems to be that the loop is asynchronous, resulting in "not found" being displayed first and then getting a "Cannot set headers after they ...

Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows: //Route Handler that triggers when a user 'creates a session' app.post('/route', async (req, res) => { let var1 = []; let var2 = []; io.on('connection', (socket) => ...

How can labels be added when mapping over JSON data?

If I have JSON data structured like this: { "siteCode": "S01", "modelCode": "M001", "modelDesc": "Desc01", "price": 100 "status": "A", "startDate": "Ma ...

Here's a unique version: "Sharing data between functions in the Express GET API within MEAN Stack"

Within my code, I have a function called hsResponse which operates as described below. When I run this function independently, I am able to see the expected body response in the console log. Now, I would like to incorporate this hsResponse function within ...

Tips on separating/callback functions based on earlier variables

Breaking Down Callback Functions Based on Previous Variables I am trying to figure out how to efficiently break down callback functions that depend on variables defined earlier in the code. Currently, my code resembles a "callback hell" due to my lack of ...

Encountering a 400 error in Ajax following the execution of server-side validation by Express

I'm currently troubleshooting a form handler that consistently throws a 400 error post middleware validation. The middleware validation steps are as follows: const contactValidate = [ check('name') .exists() .trim() .escape() ...

Node.js - Retrieving POST request parameters and directing users in an Express application

I encountered this specific issue while setting up a post endpoint for my nodejs CLI script that utilizes express to handle requests. app.use( express.static( path.format({dir: __dirname, base: 'client/dist'})) ); app.use( express ...

Dealing with mongoDB Errors

Currently, I am in the process of setting up routes for login and sign up using NodeJs and Express. I have implemented error handling on the backend to display messages on the frontend. I have successfully handled all errors except one that is causing me ...

Managing "post" requests in a one-page web application using node.js

Although there may be similar answers to this question, I am in search of something different. On the client side, I have a signUp form that will make a post request to the server with the username and password. On the server side, I authenticate the req ...

Challenge with Node.js Express Route Authorization

I'm currently facing an issue with retrieving audio/image files from the database. app.use(restrictMiddleware()); Due to restrictions imposed by the Route Restrict feature, the retrieval process is not functioning as expected. Are there any alternati ...

Encountering issues with connecting to the MongoDB server through Node.js

When working with MongoDB in Python, everything runs smoothly without any errors. However, when using Node.js, an error keeps popping up. Can someone please guide me on how to resolve this issue? jdcaovuwqxoqppwwqmjcawpwuaciwowjqwqhpaiwdoqi Below is the ...

Tips on storing JSON array data in mongoose via req.body?

I've been struggling with this issue for some time now. After successfully using JSON and req.body to save data to my MongoDB database in Postman, I decided to work with arrays for the first time. However, I'm encountering difficulties. (Just t ...

Error: When using Express with sqlite3, a TypeError occurs due to the inability

I've been working on displaying data from an sqlite3 database on a web page within my Express application. In my route file, here is what I have: var express = require('express'); var router = express.Router(); var fs = require("fs"); var ...

Remove items from a Mongo database utilizing Mongoose, Express, and Node.js

I'm currently working on setting up a basic backend todo list using mongoose, mongo, express and ejs. However, I've encountered an issue while trying to delete an item from MongoDB using mongoose by clicking on the html checkbox. The specific c ...

Node.js Application with Role-Based Login

I am currently working on implementing role-based administration. When a user is created, the database stores a "1" for Admin or a "2" for a normal user. I want to retrieve this information from the database and display the corresponding start page based o ...

Employing Multer and Express in conjunction with TypeScript

Overview Currently, I am working on a project that involves creating a user-friendly website where individuals can easily upload images. For this particular task, I have employed Node.js, React, Multer, and Typescript. Issue at Hand app.post('/admi ...

next() does not process the middleware sub-stack in route.param

In the scenario below, when making a GET request to /api/users/i, the secondMw middleware is not executed even though there is a next() call in the firstMw. Why does this happen and how can I ensure that the secondMw runs? var apiRouter = require('ex ...

Simple steps to trigger a PHP page from a JavaScript page by utilizing express functions

Currently, I am attempting to showcase a PHP page using JavaScript with express functions. Here is an illustration of the code: var express = require('express') var app = express() app.get('/', function (req, res) { res.send(' ...