Utilizing the Reduce Method in conjunction with Express JS and Node JS

I am in the process of retrieving data from MongoDB and setting up APIs to transmit data to my React App. Below is the code snippet for router and app.js:

app.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

app.use(bodyParser.json());

//import routes
const apiRoute = require('./routes/api');

app.use('/api', apiRoute);

//MONGODB CONNECTION
mongoose.connect('mongodb://**[MY LINK TO MONGODB]** },
    () => console.log('connected to real DB')
);

//LISTENING TO PORT
app.listen(5000);

api.js

const express = require('express');
const router = express.Router();
const Api = require('../models/Api');

router.get('/', async (req, res) => {
    try{
        const first_api = await Api.find({ code: 'FORM', createdDate: {
            $gte: new Date(Date.UTC(2021, 4, 16)), //since 01/05/2021
            $lte: new Date(Date.UTC(2021, 4, 31))}}, //until 31/05/2021
            ['createdDate'])
            .sort( { createdDate: -1 });

        res.json(first_api);
        console.log(first_api);
    }catch (err) {
        res.json({message: err});
    }
});

The structure of the "first_api" data is as follows:

[
 {
  "code":"FORM",
  "createdDate":"2021-05-17T07:09:29.740Z"
 },
 
 {
  "code":"FORM",
  "createdDate":"2021-05-17T06:49:34.714Z"
  },
  ...
]

My goal is to incorporate an additional function to calculate the number of entries with code = "FORM" per month, with the expected output being:

[
 {
  "January": 1,
  "February: 4,
  "March": 6,
  "April": 4,
  "May": 45,
  ...
 }
]

I have attempted to add a function using the reduce method but I am unsure about where to place it within my code.

        var string1 = JSON.stringify(first_api);
        var result = string1.reduce((r, { createdDate }) => {
            var key = new Date(createdDate).getMonth() +1;
            r[key] = (r[key] || 0) + 1;
            return result;
        }, {});

All I aim for is to send the resulting data to my React frontend as an API every time the router is invoked. However, I'm facing errors when trying to insert this into the route.get function.

For your information: I am unable to utilize the aggregate function of MongoDB due to access restrictions. I can only fetch raw data from the database and perform manipulations on my own.

Please provide guidance and assistance.

Answer №1

Welcome to the world of StackOverflow! 🌟

I recommend utilizing the powerful MongoDB Aggregate API to handle all the heavy lifting on the server side for optimal speed and efficiency. By doing so, you can minimize data transfer over the wire and eliminate the need for additional processing in the backend.

If MongoDB Aggregate doesn't suffice (since you're using Mongoose, check out their dedicated section), consider alternatives like Lodash or Array.reducer() depending on your desired output. Here's an example:

const data = [
    {
        "code": "FORM",
        "createdDate": "2021-05-17T07:09:29.740Z"
    },
    {
        "code": "FORM",
        "createdDate": "2021-05-17T06:49:34.714Z"
    },
    {
        "code": "FORM",
        "createdDate": "2021-01-17T06:49:34.714Z"
    },
    {
        "code": "FORM",
        "createdDate": "2021-03-17T06:49:34.714Z"
    }
];

console.log('lodash',
    _.chain(data)
        .groupBy(x => ((new Date(x.createdDate)).toLocaleString('default', { month: 'long' })))
        .toPairs()
        .map(x => ({ [x[0]]: x[1].length }))
        .value()
);

console.log('reducer',
    data.reduce((acc, cur) => {
        const month = (new Date(cur.createdDate)).toLocaleString('default', { month: 'long' });
        acc[month] ? acc[month] += 1 : acc[month] = 1;
        return acc;
    }, {})
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

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

Trigger keydown and click events to dynamically update images in Internet Explorer 7

There is a next button and an input field where users can enter the page number to jump to a specific page. Each page is represented by an image, like: <img src="http://someurl.com/1_1.emf" > // first page <img src="http://someurl.com/2_1.emf" ...

information directed towards particular positions on a meter

I am in the process of creating a dashboard skin that receives data from a game via a plugin. I have encountered a problem with the RPM gauge. The issue is that the angle from 0 to 5 on the gauge is smaller than the angle from 5 to 10. I am attempting to s ...

Dynamic and static slugs in Next.js routing: how to navigate efficiently

I am facing a scenario where the URL contains a dynamic slug at its base to fetch data. However, I now require a static slug after the dynamic one to indicate a different page while still being able to access the base dynamic slug for information. For Ins ...

Tips for retrieving all values included in the <tr> tags within an html <table>

When the checkbox in the fourth column is clicked, I would like to retrieve all values of td. Additionally, I want to determine the smallest value between ID and Optional ID. <table><form method='GET'> <tr> <th>Name</t ...

Creating dynamic form fields using AngularJS

I have a form that includes an input field, a checkbox, and two buttons - one for adding a new field and one for deleting a field. I want to remove the add button and instead show the next field when the checkbox is checked. How can I achieve this? angu ...

Tips for locating the most recent documents in mongoDB with the same timestamp

Seeking assistance to download the latest documents from mongodb with identical timestamps. Is there a method to identify and retrieve the most recent document or documents? In this scenario, the expected output would include the first and second document ...

Tips for correctly loading API data into dependent tableViewCells

Working on a UITableView that makes 2 API calls for every cell has been successful until today. Recently, I encountered a major issue where there were more cells on the screen than actually loaded. While scrolling down the tableView, the screen froze for ...

Is there a straightforward method to send JSON data using $.ajax in jQuery? (By default, jQuery does not handle JSON data transmission)

I've been attempting to send a nested JSON structure using $.ajax or $.post (tried both methods). The $.ajax code I used is as follows: $.ajax({ url: '/account/register/standard', method: 'post', data: datos, dataT ...

Is there a way to access an object within another object without the need to use a function

Having trouble accessing an object? Let's solve this mystery together. I'm trying to access 'ctx', but base.ctx keeps returning null (is there a closure involved?). window.base = function () { var c = null, ctx = null; ...

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Scoping with Mongoid Versioning

When incorporating the Mongoid::Versioning module, Mongoid offers built-in versioning that I find useful. However, I am facing some challenges when working with versions on a model. To illustrate, let's pretend I am developing a blog application (whic ...

Having difficulties accessing the properties of a dynamically created JSON object with ng-repeat functionality

Within an ng-repeat loop, I have implemented a radio button that assigns the entire person object to a scope variable as shown below: <li ng-repeat="person in people"> <label>{{person.name}} <input type="radio" ng-model="$parent.s ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

Vuejs Todolist List App experiences unanticipated alteration in task prop

I own a store that includes state, mutation, getters, and more. Within the state, there is a list of tasks like the ones shown below. const state = { tasks:[{ title: "Wake up", completed: false }, { title: "Item 2&quo ...

Python: Flattening and Extracting specific JSON segments

I've got an input JSON that has the following structure: > {"payment": {"payment_id": "AA340", "payment_amt": "20", "chk_nr": "321749", "clm_list": {"dtl": [{"clm_id": "1A2345", "name": "John", adj:{"adj_id":"W123","adj_cd":"45"}}, {"clm_id": "999 ...

Guide to uploading an image from a React application to ExpressJS and storing it in MongoDB using Express routes

Javascript Frameworks const handleFileUploadChange = async (event) => { const file = event.target.files[0]; const fileReader = new FileReader(); fileReader.addEventListener("load", () => { setUploadedFile(fileReader.resu ...

Can someone guide me on how to display only the most recent form submission in a form using React and JavaScript? Appreciate your help

Currently, I'm facing a challenge with displaying the latest form submission below a form on my page. Instead of showing all form submissions, I only want to display the most recent one. I'm seeking advice on how best to tackle this issue. If it ...

pyspark fails to read JSON when encountering an empty set

When working with Pyspark and reading a JSON file that contains an empty set element, the entire element is ignored in the resulting DataFrame. I'm looking for a way to instruct Spark to include this element instead of skipping it. My setup includes ...

Errors in socket.on Listeners Result in Inaccurate Progress and Index Matching for Multiple Video Uploads

Is there a way to make sure that the `socket.on('upload-progress')` listener accurately updates the upload progress for each video as multiple videos are uploaded simultaneously? Currently, it appears that the listener is updating the progress fo ...

TextGeometry in Three JS is designed to always face the user

Here is the source code I have been working on. My main goal is to make sure that TextGeometry is always facing the camera. Is this possible? Code: var stats; var camera, controls, scene, renderer; init(); render(); functi ...