Combine results from two sets of data into an array by utilizing the _.each() method

What I'm aiming for:

I aim to make a call to an API and within that API, I want to achieve the following:

  1. Locate Bills
  2. Retrieve all transactions associated with each bill (using billId)
  3. Present the values in a JSON ARRAY

Here is an example representation of the bill array:

{ _id: 549bf0597886c3763e000001,
billName: 'Leasing',
startDate: Thu Dec 25 2014 01:00:00 GMT+0100 (CET),
endDate: Sun Oct 15 2017 00:00:00 GMT+0200 (CEST),
amount: 16500,
type: 4,
timestamp: Thu Dec 25 2014 12:09:13 GMT+0100 (CET),
__v: 0 },
{ _id: 54a014bfac01ca3526000001,
billName: 'Test',
startDate: Tue Oct 28 2014 01:00:00 GMT+0100 (CET),
endDate: Wed Dec 20 2017 00:00:00 GMT+0100 (CET),
amount: 1000,
type: 4,
timestamp: Sun Dec 28 2014 15:33:35 GMT+0100 (CET),
__v: 0 }

Using the array obtained in the first step, I intend to query the transactions collection and retrieve each transaction for every bill. The transformation would look like this:

{ _id: 549bf0597886c3763e000001,
billName: 'Leasing',
startDate: Thu Dec 25 2014 01:00:00 GMT+0100 (CET),
endDate: Sun Oct 15 2017 00:00:00 GMT+0200 (CEST),
amount: 16500,
type: 4,
timestamp: Thu Dec 25 2014 12:09:13 GMT+0100 (CET),
__v: 0 ,
transactions: {
  { 
    "_id" : ObjectId("549ea8c957b654ef64000003"), 
    "billId" : "5499aece1d7be6c6a3000001", 
    "paymentDate" : ISODate("2014-12-27T12:40:41.311+0000"), 
    "amount" : NumberInt(2400), 
    "timestamp" : ISODate("2014-12-27T12:40:41.311+0000"), 
    "__v" : NumberInt(0)
  }
  { 
    "_id" : ObjectId("549ea9446163b3c666000001"), 
    "billId" : "5499aece1d7be6c6a3000001", 
    "paymentDate" : ISODate("2014-12-27T12:42:44.975+0000"), 
    "amount" : NumberInt(2400), 
    "timestamp" : ISODate("2014-12-27T12:42:44.975+0000"), 
    "__v" : NumberInt(0)
  }

}
},
{ _id: 54a014bfac01ca3526000001,
billName: 'Test',
startDate: Tue Oct 28 2014 01:00:00 GMT+0100 (CET),
endDate: Wed Dec 20 2017 00:00:00 GMT+0100 (CET),
amount: 1000,
type: 4,
timestamp: Sun Dec 28 2014 15:33:35 GMT+0100 (CET),
__v: 0 }

While I have been successful in obtaining the bill IDs from the bill collection, I am facing difficulties in extracting the transaction IDs into an array.

My current approach is as follows:

app.get('/getbills', function(req,res) {

    function getTransactions(item, key){

            var billId = item._id;

             Transactions.find({billId : billId}, function(err, transactions){ // TODO: Needs to look for transactions inside the date.
                if (err)
                    console.log('error: '+ err)
                else if (transactions.length !== 0){
                    return transactions;
                }
            });                

        };

    Bills.find({type: bill_type}).find(function(err, bills){
        if(err)
            res.send(err);

        details.bills = bills;

        details.bills.transations = _.each(bills, getTransactions);

     res.send(details);  
    });

});

I am utilizing _.each to extract the billId and query the transactions table, but I have not found sufficient examples to guide me on the implementation of this function in the manner I am attempting. It's possible that my approach is incorrect.

Any assistance or insights would be greatly appreciated.

Thank you in advance.

Answer №1

It seems like you may not be waiting for the second call to finish, resulting in incomplete data. The return statement might not be working as intended.

To dive deeper into this issue, consider learning more about handling asynchronicity in JavaScript.

While the current code may work, it's important to understand how it functions. The trySend function serves as a basic synchronizer, ensuring all data is available before responding. It may not be the most efficient solution, but it's a straightforward one.

app.get('/bills', function( req, res ) {
  Bills.find({type: bill_type}, function( err, bills ) {
    if( err ) return res.send(err);

    var tries = 0;
    var details = { bills: bills };
    var trySend = function (){
      tries++;
      if (tries === bills.length) {
        res.send(details);  
      }
    };

    bills.forEach( function ( bill ) {
      Transactions.find({billId : bill._id}, function ( err, transactions ) {
        if ( err ) return res.send( err );

        bill.transations = transactions;
        trySend();
      });  
    });        
  });
});

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

Struggling to deserialize JSON information into a Dictionary with key and value pairs of strings

Looking to convert this JSON data into a Dictionary using native Javascript. var jsonData = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}"; However, encountering an error when trying to deserialize it with the following code: Diction ...

Are programmatic clicks distinguishable from manual clicks in JQuery?

Currently, I am in the process of creating selectable and draggable elements for a table. You can test the functionality by following this JsFiddle link (please try vertically selecting). Initially, the selection works well but upon trying to select for th ...

"Encountering a hiccup with the Firebase service worker in Messaging and Firebase

I am interested in developing a small web application to explore the capabilities of Firebase Cloud Messaging for web apps. My intention is to utilize Firebase Hosting as the hosting platform for my app. ISSUE: Upon allowing the notification pop-up on my ...

Adding a JSON object or model to your whitestorm.js environment: Step-by-step guide

I have a challenge with loading the object from my json file. const loader = new THREE.ObjectLoader(); loader.load("blue-car.json", function ( car ) { car.position.set(2, 0, 0); car.addTo(world); } ); However, I encountered an error. Here is the err ...

Unusual actions exhibited by a combination of JavaScript functions

Encountering an issue with a JavaScript file containing multiple functions causing strange behavior. The Logging.js file is responsible for writing to a text file: function WriteLog(message) { var fso = new ActiveXObject("Scripting.FileSystemObject") ...

Utilizing Jquery Plugins in Node.js with ES6 Imports: A Comprehensive Guide

I recently started using a jQuery calendar plugin, which can be found at this link: . I have been utilizing it with a CDN, but now I am looking to incorporate it as a Node.js module. What would be the most effective method to achieve this? Edit: Just to ...

What is the best way to start tiny-slider automatically once the video has ended?

I am currently using the tns-slider plugin and have a setup with 3 slides (2 photos and 1 video). <div class='tiny-slider'> <div class='slide slide1'> <div class='video-slide'> <video id=&qu ...

Exploring the jQuery Solution for Enhancing Dojo Widget Framework

My experience with Dojo in the past has been great, especially with its widget infrastructure. Being able to easily separate code and HTML content, having a seamless connection with the require system used by Dojo, and the convenient builder that compresse ...

Exploring the power of Vue.js by utilizing nested components within single file components

I have been attempting to implement nested single file components, but it's not working as expected. Below is a snippet of my main.js file : import Vue from 'vue' import BootstrapVue from "bootstrap-vue" import App from './App.vue&apos ...

Creating dynamic HTML with Cons.Underscore - a step-by-step guide

After successfully converting static HTML into strings and emailing it, my next goal is to pass dynamic values to the HTML before converting it into a string and sending it via email. To achieve this, I am utilizing cons.underscore as my view engine for ...

How can multiple functions be grouped and exported in a separate file in Node.js?

Is there a way to consolidate and export multiple functions in nodejs? I want to gather all my utility functions in utils.js: async function example1 () { return 'example 1' } async function example2 () { return 'example 2' } ...

How can I prevent clearQueue() from removing future queues?

In my code, I have a button that triggers the showing of a div in 500ms when clicked. After the div is shown, a shake class is added to it after another 500ms. The shake class is then removed after 2 seconds using the delay function. However, if the user c ...

MongoDB embodies intricate aggregates

I have two schemas that need to be joined and certain calculations need to be performed. a { academic_year: { type:String} } b { b1: {type:Number, default:0 }, b2: {type:Number, default:0 }, b3: [{ b3_1: {type:Number, d ...

Guide on inserting text input value into the href attribute of a hyperlink

Lately, I've been facing an issue that has been troubling me for the past few hours. I have a search input field where users can enter text and click send. The entered text should then be added to the href attribute and sent to the results page for qu ...

Tips for incorporating a plugin and utilizing an external module or file on RT

My node.js application/module is currently functioning well with a plug-in concept. This means that my module acts like a proxy with additional capabilities, such as adding new functionality to the existing methods. To achieve this, follow these steps: Cl ...

How to automatically assign serial numbers to MongoDB documents using a query

Just sharing some details about my database: collection name: questions db name: school Below is the structure of my document: { _id: ObjectId("630680a764a8eb1364c4f250"), question_type: 'MULTIPLE CHOICE', published: true, ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

What is the best way to structure my POST data when conducting tests on an express API endpoint?

I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack. Currently, I am trying to test a POST API endpoint that is built using express. The node server is up ...

Ways to eliminate models that are not currently connected to the DOM

Within my form, I have implemented logic using ng-if to determine which elements are displayed based on user selections. For instance, if a user selects USA as the country, the state drop down will be shown as it was conditioned upon an ng-if for the count ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...