Is it a suboptimal method to repeatedly use order.find, collect data, and transmit a substantial data payload to the front end in

Currently, I am working with Express, React, and MongoDB but I am relatively new to using express and REST API.

My goal is to add an analytics feature to my frontend that focuses on sales and orders. The plan is to allow users to search within a specified date range where each object contains a timestamp that can be compared and collected.

Despite my best efforts, I am encountering issues with my current approach. It appears that the allOrder variable is not gathering all the objects as expected.

var allOrder = []; // collect all orders and push them

do {
  Order.find({ date: sDate })
    .then(function(order) {
      allOrder.push(order); // pushing order
    })
    .catch(next);

  // create a new search date (usually in another function)
  startDate.setDate(startDate.getDate() + 1); // increase by one day
  startYear = startDate.getFullYear();
  startMonth = startDate.getMonth() + 1;
  startDay = startDate.getDate();
  if (startMonth < 10) startMonth = "0" + startMonth; // adjust format

  sDate = `${startYear}-${startMonth}-${startDay}`; // generate a new search date
  dayStart++;
} while (dayStart < days); // verify the day range

res.send(allOrder); // once all dates have been processed, send.

This process effectively increments the day until it reaches a specific date. For instance, I begin by searching for data on 2018-12-25, then progress to the following day, 2018-12-26. While this method works flawlessly during retrieval, I struggle when it comes to storing and sending this information back to the frontend all at once.

Here is the model of my object:

const orderScheme = new Schema({
  name: { type: String },
  date: { type: String },
  customerName: { type: String },
  customerPhone: { type: String },
  orders: { type: Array }
});

Answer №1

Chris pointed out a simple solution for me in the comments.

Order.find ({
    date: {
        $gte : startDate,
        $lt : endDate
    }
}).then (function (order){
    res.send(order);
}).catch(next)

I used my own timestamp value for startDate and also for endDate. It worked perfectly and beautifully.

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 Alchemy feature on hover is not functioning

I am currently using alchemy.js to display a graph, but I am encountering issues with showing the "onMouseOver" caption of the graph's node. The console is displaying some errors which you can see here. Here is the code snippet: <html> < ...

An issue occurred while trying to serialize cookies retrieved in getServerSideProps

I am currently working on a project using Reactjs with Next.js. I recently implemented a login module using cookies, but encountered an issue when trying to serialize the .cookies object returned from getServerSideProps. The error message states that undef ...

Error: Unable to assign value to the innerHTML property of an undefined element created by JavaScript

When designing my html form, I encountered an issue where I needed to display a message beneath blank fields when users did not fill them out. Initially, I used empty spans in the html code to hold potential error messages, which worked well. However, I de ...

Retrieving status code without reliance on a back-end language (maybe through JavaScript?)

My new service offers a solution for error pages in web apps by providing a code snippet that can be easily copied and pasted into the error page templates, similar to Google Analytics. The status code is embedded in a hidden input within the installatio ...

What is the best way to transfer my parameters from serverless to my express router?

I've been working on AWS Lambda with express/nodejs and serverless The issue I'm facing is that the serverless (serverless offline) setup is matching the entire URL path including parameters. This information is then forwarded to my handler whic ...

Preserving scroll position when updating a partial page template using Rails and AJAX

When I am utilizing long polling, I encounter an issue where every time I use AJAX to refresh a page partial inside a scrollable div, the contents automatically scroll to the top. Is there any way to load the partial while maintaining the current scroll ...

The forEach method in JavaScript seems to work asynchronously

After reviewing other discussions on this platform, it seems that the general agreement is that forEach should be synchronous and block. However, in my code, something appears to be off as it doesn't behave that way: var noDupes = false; // se ...

Utilizing Multer for temporarily storing a file in memory before parsing and transferring it to the database

As a newcomer to programming, I am attempting to describe my issue concisely. I am utilizing multer to upload an XML file in conjunction with a Node Express server and React with .jsx. My intention is to parse the uploaded file data and post it to a Postgr ...

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...

Switching styles in AngularJS without using ng-class

My goal is to allow users to switch the class from incomplete to complete when they click a button and the function(response) returns 1. I have attempted to use ng-class, but it is not effective because the HTML elements are generated with a PHP loop. This ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

What is the proper method for setting up handlers in functional React components?

My knowledge of JavaScript tells me that there are three different ways to define functions. Let's take a look at them: 1. Declaration function handleEvent(e) {} 2. Assignment var handleEvent = function(e) {} 3. Arrow var handleEvent = (e) => ...

Harnessing the power of Express to tally user records within subdocuments

My index route for users involves counting the records they have in the subdocument. Here is my current implementation: router.get('/', middleware.isLoggedIn, (req, res, next) => { // Retrieve all users from the database User .find({} ...

Adjust the JSON format that is retrieved from an Ajax call

I am working with a JQuery plugin that includes the following code snippet: transformResult: function(response, originalQuery) { } Within this function, I have the task of converting Json data from the originalQuery to the response format: [ { "Id": ...

Instructions on inserting an IFRAME using JavaScript into dynamically loaded content via AJAX

How can I dynamically add an IFRAME using JavaScript to content that is refreshed via AJAX? Consider the following example: $('#bar').delegate('.scroll-content-item span a', 'click', function() { var object_id = $(this).p ...

Creating Projects Without a Build System in Sublime Text 3

I'm having trouble getting the sublime build system to function properly. When attempting to run my code, I receive a "No Build System" error message. I have already set the build system to Automatic under Tools->Build Systems and saved the file a ...

Store the _id of the currently logged in user in a different collection in MongoDB

How can I ensure that the createdBy field in my project model is populated with the _id of the currently logged in user when a new project is saved to the database? I have followed the example provided in the Mongoose documentation, but for some reason, th ...

Despite the updates, Express JS PUT request does not successfully save changes

Currently, I have an Express JS application where I am attempting to update an existing user's name using the PUT method. The schema I am working with is a nested array and is structured like this: https://i.sstatic.net/WDIse.png The code snippet I ...

Make sure to blur all images whenever one of them is clicked

I am currently facing an issue with my webpage where I have 3 images displayed. I have implemented an event listener to detect clicks on the images, and once a click occurs on one of them, I want everything else on the page to become blurred, including the ...

What is the best way to position a div below a sticky navbar?

I have implemented a sticky navbar on my index page along with JavaScript code that adjusts the navbar position based on screen height. When scrolling, the navbar sticks to the top of the page, but the flipping cube overlaps with the sticky navbar. How can ...