Using Axios to make a GET request with specific parameters to filter and retrieve data within a certain "createdAt" range

I have multiple dates in an Array on my react frontend with the format 'MM/YYYY'. Now I need to fetch history from MongoDB that was created within a specific one-month time range. How do I pass this data in the axios get request?

Frontend

let date = '11/2022'

    const getHistory = async () => {

      let monthYearStart = dayjs(date, 'MM/YYYY').format('YYYY.MM.01');
      let monthYearEnd = dayjs(date, 'MM/YYYY').format('YYYY.MM.32');

      const res = await axios.get('/api/monthlyhistory');
      setPdfHistory(res.data);
    };
    getHistory().then(() => {});

Backend

try {
      const history = await History.find({
        status: true,
        createdAt: {
          $gte: dayjs(new Date(monthYearStart, 'YYYY.MM.DD')),
          $lt: dayjs(new Date(monthYearEnd, 'YYYY.MM.DD')),
        },
      });
      res.json(history);
    } catch (err) {
      return res.status(500).json({ msg: err.message });
    }

Answer №1

Another approach could involve sending the dates as query parameters. It is advisable to utilize the ISO 8601 format for clarity and leverage the in-built Date constructor.

On the client-side

// Keep in mind these are local dates
const monthYearStart = new Date(2022, 10); // Note: months start from 0
const monthYearEnd = new Date(monthYearStart);
monthYearEnd.setMonth(monthYearEnd.getMonth() + 1);
monthYearEnd.setDate(monthYearEnd.getDate() - 1);

const res = await axios.get("/api/monthlyhistory", {
  params: {
    monthYearStart: monthYearStart.toISOString(),
    monthYearEnd: monthYearEnd.toISOString(),
  },
});

Server-side Implementation

const { monthYearStart, monthYearEnd } = req.query;
const history = await History.find({
  status: true,
  createdAt: {
    $gte: new Date(monthYearStart),
    $lt: new Date(monthYearEnd),
  },
});

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

What is the meaning of a query when it comes to making

I understand how to specify parameters in routes app.get('/:someParams', () => {}) Is there a way to explicitly define a query in routes? For example, adding '?someQuery' and making that query required? ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

What is the process of retrieving data from a Nextjs API route during the build and deployment stages?

I'm currently facing an issue while trying to deploy my nextjs web app on vercel. Upon deployment, I encounter the following error: > Build error occurred FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUS ...

Replace or update the current array of objects that align with the incoming array

I've been struggling to figure out how to find and replace an array that matches the existing one. The issue lies with using the some method. Here is the current array: let existingData = [{ id: 1, product: 'Soap', price: ' ...

Unraveling the JSON section within a intricate text document

Embarking on the development of a desktop application using Electron, I aim to parse files and present data extracted from these complex files. These files contain intricate information. My current challenge involves extracting JSON data from a convoluted ...

What is the best way to switch from using the three.js JSONLoader to the ObjectLoader?

I successfully loaded multiple files using the code below for three.js JSONLoader: <!DOCTYPE html> <html> <head> <title>Rotating Sphere</title> <meta charset="utf-8"> <!-- https://cdnjs.com/libra ...

Alternate the color over time using CSS

Is there a way to dynamically change the color of a div from black to white every two seconds, and then from white to black, continuously toggling as long as the div is visible? Essentially, I want the div to only be displayed when a user clicks and drag ...

Is it impossible to extend a Typescript class with an overriding method that uses a different parameter?

I am currently working on a Typescript MVC app and encountering an issue. When I try to extend my BaseController and override the ajaxMethod with different parameters, my transpiler throws an error. Any help would be appreciated. Below is the code snippet ...

Instructions for removing the status bar from the configuration file

Struggling to remove the status bar that's covering my header in my Phonegap-wrapped HTML5 mobile app. I've tried adding preferences to the config.xml file, but still no luck. Here's what I added: <preference name="fullscreen" value="tr ...

The sequence of CSS and deferred JavaScript execution in web development

Consider this scenario: you have a webpage with a common structure in the <head>: <link rel="stylesheet" href="styles.css"> // large CSS bundle <script defer src="main.js"></script> // small JS bundle with defer attribute There is ...

Tips on implementing CSS to the subpar class in Vuejs

I am working on an HTML file that operates with button in Vue.js. The v-bind:class can be utilized for a single tag as shown below. It disappears based on the boolean value of bool data. <h3 v-bind:class="{active: bool}">{{counter.document}}&l ...

Issue with populating virtual IDs in NestJS mongoose schema containing an array of schemas

In the schema provided below, I have defined the structure for Map, Marker, and Desk: export type MapDocument = Map & Document @Schema({ timestamps: true, versionKey: false, id: true }) export class Map { constructor(partial?: Partial< ...

using Vue.js to send an array of integers as a post request data instead of strings

Currently, I have set up 2 input boxes for weights and values, with the functionality to add more boxes by clicking a button. This aspect is working perfectly. However, the issue arises when the server requires a JSON formdata request that contains an arr ...

Error encountered when attempting to establish a connection between socket.io and express: network error

Similar Question: socket.io: Failed to load resource I'm having trouble getting a simple express + socket.io hello world app to work. I keep receiving the following error: "NetworkError: 404 Not Found - http:// localhost:3002/socket.io/socke ...

Tips for maintaining the reference of a Three.js object after importing it as an .obj file

If you want to learn how to incorporate a .obj file into your scene, the official documentation provides a helpful example that can be found here. const loader = new OBJLoader(); // Load the resource loader.load( // Resource URL 'models/monst ...

Update all field values in Redux-form version 6.0 and above

I am attempting to update several values in redux-form. They are stored in a single object, and I want to replace the current redux-form state values with those from my object. One method I have tried involves using this.props.reset() followed by multipl ...

react-navigation hook for navigating

Currently, I am utilizing the react-navigation hook and instead of repeating the hook in various components, my goal is to pass navigation as a prop. const navigation = useNavigation(); ... <MyButton resetLocation={resetLocation} navigation= ...

Interference in the output of .innerHTML leads to disruption

I have been working on a feature to display a calculated price based on the selected quantity for each individual product. I attempted to duplicate the code and modify variable names, but encountered issues with the increase/decrease buttons triggering mul ...

Transfer an array from XML to PHP into JavaScript in order to deactivate specific dates within a datepicker using the beforeShowDay function

My process involves reaching out to another website through a GET request and receiving XML data for interpretation. Here is how I make the contact: $v= file_get_contents( "https://www.v.com/fechasexcursion.php? agent=M&password=s&fec ...

jQuery does not function properly when used with string variables

Why am I experiencing different results in Google Chrome when using a hard-coded string versus storing the same string in a variable? While the hard-coded string works properly, the same string stored in a variable does not produce the expected outcome. ...