Loop Through Mongoose to Retrieve Multiple Objects

I am currently facing an issue while trying to retrieve multiple objects from MongoDB using mongoose. In my database, I have two primary collections known as user and order.

The user collection consists of an array called 'order history', which in turn contains orders.

Whenever I attempt to add an order to the orders array, it gets pushed successfully. However, the problem arises when I try to access these orders outside of the loop, as the asynchronous operation within the loop results in an empty array.

CODE

userModel.findOne({'username': username }, function (err, user) {
        if(user){
            var orders = [] 

            for(var i=0;i<user.orderHistory.length;i++){
                var orderId = user.orderHistory[i].orderId

                var order = orderModel.findOne({'id': orderId}).exec()
                
                order.then(function(order){
                    orders.push(order)
                })              
            }

            orders.then(function(order){
                console.log(order)
            })
        }
    })

If anyone has a solution on how I can access orders outside of the loop, please let me know. Thank you!

Answer №1

To improve the efficiency of your code, consider using an async function and awaiting each order.

userModel.findOne({ username }, async function (err, user) {
  if (!user) return;
  const orders = [];
  for (const { orderId: id } of user.orderHistory) {
    const order = await orderModel.findOne({ id }).exec();
    orders.push(order);
  }
  console.log(orders);
})

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

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

Is there a way to showcase a PDF file using pdftron through npm?

pdftron/webviewer has been successfully installed "dependencies": { "@pdftron/webviewer": "^7.3.0", "body-parser": "^1.19.0", "express": "^4.17.1", ...

Filtering controls within a table are not displayed in VueJS

I have been attempting to implement date filtering in my data table based on a demo I followed. Despite meeting the filter requirements, no results are being displayed which is perplexing. Below are the imports and data from the file containing the table: ...

Troubleshoot React component re-rendering issue

I'm currently facing a challenging bug that only occurs very sporadically (about once every few dozen attempts). During the render call, I'm determined to gather as much information as possible: I want to understand what triggered the rerender ...

My JavaScript functions are not compliant with the HTML5 required tag

I am currently developing input fields using javascript/jQuery, but I am facing an issue with the required attribute not functioning as expected. The form keeps submitting without displaying any message about the unfilled input field. I also use Bootstrap ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

"Vue Filepond: Enhancing Your Images with Cropping

Currently, I am integrating filepond with VueJS to facilitate image uploads. To enable image cropping during upload, a specific configuration is required. The filepond plugin has been globally registered, as shown below: import Vue from 'vue'; i ...

Creating a Dynamic Tree View Component in AngularJS Using JSON Data

I am new to AngularJS and I need help creating a TreeView Structure from a JSON Object. Here is an example of my Return JSON Object: var categoryTree = [{Name:'Item1', Childnodes : {}, id: 1}, {Name:'Item2', Childnod ...

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox. Here is the code snippet for canvas.html : <!DOCTYPE html&g ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

Bootstrap 4 Collapse - Ensuring that collapsed elements remain open when expanding other accordions

Can someone help me figure out how to keep an element open when another one is opened? Here is an example: https://getbootstrap.com/docs/4.0/components/collapse/ <div id="exampleAccordion" data-children=".item"> <div class="item"> & ...

Attempting to modify PHP query following submission of data via Axios in Vue application

Fetching a JSON object through a PHP query from a service known as BullHorn can be done like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded,externalCategoryID,employmentTy ...

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

Designing scroll boxes that are not continuous and tracking the time spent in each section

I'm seeking assistance with a unique challenge involving the creation of scroll boxes for use in a Qualtrics survey and tracking the time spent viewing different sections of text within them. Specifically, I aim to design a scroll box featuring two p ...

Revamp the angular design of the mat-tree UI bottom border line issue

Can you help me with changing the direction of the mat tree from right to left? I need to remove the bottom border, please refer to the image https://i.sstatic.net/ecRIO.png here ...

``There seems to be a malfunction with the modal feature in the asp.net

Within my strongly typed view, I have a loop that iterates over a list of objects fetched from a database. Each object is displayed within a jumbotron element, accompanied by a button labeled "Had role before". When this button is clicked, a modal opens wh ...

Creating a registration and authentication system using firebase

When using Google authentication with Firebase, is the Signup and Login logic the same? I am creating a page for user authentication but I'm unsure if I should have separate pages for signing up and logging in. This confusion arises from the fact that ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...