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.