Retrieve information from two separate MongoDB collections using the MongoJS library

My approach involves using MongoJS to retrieve data from a MongoDB database as shown in the code snippet below:

var db = mongojs('db', ['events']);

Subsequently, I have the following setup:

   app.get('/', function(req, res){
    db.events.find(function(err,docs){
        res.render('index', {
        title: 'Events',
        events: docs
    });
    })  
});

This method successfully retrieves the data and renders it using EJS as the view engine. The sample code in index.ejs looks like this:

<% events.forEach(function(event){ %>

<a><%= event.event_name %></a></br>
<a><%= event.event_description %></a> 

<% }) %>

While everything is functioning properly with fetching data from one collection, my query now shifts to how I can fetch data from a separate collection within the same EJS page. Here's my attempt to modify app.js:

var db = mongojs('db', ['events', 'groups']);

And then:

app.get('/', function(req, res){
        db.events.find(function(err, docs){
            res.render('index', {
            title: 'Events',
            events: docs
        });
        })  
    });


       app.get('/', function(req, res){
        db.groups.find(function(err, docs){
            res.render('index', {
            title: 'Groups',
            groups: docs
        });
        })  
    });

Followed by incorporating the group iteration in the EJS file:

<% groups.forEach(function(group){ %>

            <p><a><%= group.group_name %></a></br>
            <a><%= group.editor %></a></p>
            <a><%= group.members %></a></p>

 <% }) %>

The issue arises when 'groups' are referenced as undefined. Even after reordering the queries in app.js, similar problems persist. How can both collections be properly declared without causing conflicts or overwriting each other? Your assistance on resolving this matter would be greatly appreciated.

Answer №1

Upon the completion of the first handler, the second one is not executed. To ensure both are properly chained, consider structuring your queries in this way:

let events;
app.get('/', function(req, res) {
db.events.find(function(err, docs) {
  events = docs;
  db.groups.find(function(err, docs) {
    res.render('index', {
      title: 'Items',
      groups: docs,
      events: events
    });
  })
});
})

To enhance the efficiency of the code above, explore the utilization of promises or async/await techniques. I suggest delving into the topic of asynchronous functions for more robust Javascript programming.

Answer №2

It is essential to have only one root app.get('/'... call. Consider combining your routes in the following manner:

app.get('/', function(req, res) {
    db.groups.find(function(groupsErr, groupDocs){

        // retrieving events
        db.events.find(function(eventsErr, eventDocs){
            res.render('index', {
                title: 'Events',
                events: eventDocs,
                groups: groupDocs
            });
        });
    });
});

An alternative way to handle this with a more organized approach (less nested) involves using promises.

app.get('/', function(req, res) {
    let groupsPromise = new Promise((res, rej) => {
        db.groups.find((err, docs) => {
            if (!err) res(docs);
            else rej(err);
        });
    });

    let eventsPromise = new Promise((res, rej) => {
        db.events.find((err, docs) => {
            if (!err) res(docs);
            else rej(err);
        });
    });

    Promise.all([groupsPromise, eventsPromise])
    .then(docArr => {
        let groupDocs = docArr[0];
        let eventDocs = docArr[1];

        res.render('index', {
            title: 'Events',
            groups: groupDocs,
            events: eventDocs
        });
    })
    .catch(console.error);
});

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

Creating interfaces for applications that are driven by events in JavaScript

When it comes to designing an application, traditional UML Class diagrams may not always be useful, especially for programs that do not heavily rely on classes. For instance, in a JavaScript application that is mainly event-driven, where you listen for eve ...

Experienced an unexpected setback with the absence of the right-click capability on a Javascript-powered hyperlink, specialized for

I am facing an issue with a hyperlink on my website. This particular hyperlink submits a hidden form using the POST method to redirect users to another site. However, when someone right-clicks on this hyperlink and tries to open it in a new tab, they are o ...

AngularJS allows for the creation of a disabled select tag that can selectively choose options from another select tag using ng-repeat

Is there a way to disable one select element by choosing a specific option from another select element? Below is the HTML code: <select name="" ng-model="round.evaluation.availability" required ng-change="update()"> <option value="">Selec ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

What is the best way to determine the total scrollable height of the browser's scroll bars?

I understand that $(window).scrollTop() provides the current position of the browser scroll bar, but how can I determine the total scrollable area? For example, if I scroll to the bottom and $(window).scrollTop() equals 300px, scrolling back to the top se ...

What is the reason behind asynchronous module resolution behavior caused by relative imports from a parent index file using '..'?

In my repository, the structure is as follows: src/ index.ts main.ts bar/ file.ts index.ts foo/ fooFile.ts The purpose of src/index is to serve as a top-level index file that exports all elements in my package. However, I h ...

Efficiently sift through a vast assortment using a filtering method

Currently, I am developing an application similar to Uber which involves managing a collection of drivers with their current positions (latitude and longitude). One specific requirement is to find drivers who are within a 200-meter distance from the user& ...

What is the best way to conceal a div when there are no visible children using AngularJS?

I need help with hiding a parent div only if all the child items are invisible. I have successfully hidden the parent when there are no children, but I am struggling to figure out how to hide it based on visibility. <div ng-repeat="group in section.gro ...

Setting default values or placeholders for dependent select lists is a common and useful feature that can improve the

Having four dependent select lists, I aim to assign a default value/placeholder like select ... to all the select lists. Nevertheless, the issue arises when attempting it using <option value=""> Select ... </option>, as changing the first selec ...

The routes are not functioning properly due to an issue with req.body being undefined after bodyParser

Programming can be quite frustrating with all the errors and issues that occur, even for simple tasks. I'm struggling with this code which just won't work no matter what changes I make. var express = require('express'); var path = requ ...

Firebug detected an error with the regular expression flag "h" after executing the YUI Compressor

When I run YUI Compressor, an error occurs with the message: invalid regular expression flag h [Break On This Error] ction(event){$(this).removeClass('lumi...cs_glb.php</b> on line <b>221</b><br/> The issue seems to be with t ...

Validating ReactJS properties

Transitioning from ReactJs to React-Native, I came across this function structure in a react-native button code by Facebook: class Button extends React.Component<{ title: string, onPress: () => any, color?: ?string, hasTVPreferredFocus?: ?bo ...

Exploring JSON and jQuery to Address Filtering Challenges

Excuse the interruption, but I need some assistance with my filters. Below is the code I'm currently working on; however, none of my attempts have been implemented yet (the dropdown menu and checkboxes remain non-functional) to make it easier for you ...

Spin the item around the axis of the universe

My goal is to rotate an object around the world axis. I came across this question on Stack Overflow: How to rotate a object on axis world three.js? However, the suggested solution using the function below did not resolve the issue: var rotWorldMatrix; / ...

Utilize MongoDB's aggregation framework to search for, tally, and display distinct documents

Here is a sample collection for reference. Data Collection 1: "_id" : ObjectId("5ec293782bc00b43b463b67c") "status" : ["running"], "name" : "name1 ", "dcode" : "dc001", "address" : "address1", "city" : "city1" Data Collection 2: ...

Is it possible to alter the background color once the content of an input field has been modified?

I am working with an angular reactive form and I want to dynamically change the background color of all input fields when their value is changed. Some of these input fields are pre-populated and not required. I came across a potential solution on Stack Ove ...

I'm looking to output a list of variables from a function using console.log in javascript within a node.js environment

function courseList(course1, course2, course3){ let course1=[{ Id: 154532, name:'basic digital marketing', duration: '15 days', price: 100000, }]; let course2=[{ Id: 154533, ...

Utilizing MutationObserver in JavaScript for Streamlined Code Execution

One of my functions utilizes a MutationObserver to track attribute changes in a specified element and logs them to the console. Below is an example where I pass 'card' elements in a foreach loop: track_attr_changes(element); The parameter ' ...

The analytics dashboard is not displaying the user_timing Google Analytics data, even though it was successfully triggered on the website

I am currently working with Angular and utilizing the navigation_start and end events in app.component.ts to measure the timing before firing a simple page_view and timing event. Both sets of data are then sent to analytics through the network tab. The cod ...

Incorporate JSX into an array in JavaScript

I'm trying to make a change to the fontsize and insert JSX into one of the properties within an array of objects in my component. Is there a way to accomplish this? For instance: const data = [ { name: 'Page A',name1: 'Page A&ap ...