An error occurred when saving data (date and time) retrieved from a different backend service into MongoDB

I am currently working on a project where I need to fetch JSON data from an external backend service and save it locally in my own database. The goal is to improve the loading speed of the data on the frontend, particularly for representing a graph.

Here is the process I am following:

  1. Retrieve the data using axios from another API backend service.
  2. Utilize Mongoose and its functions to store the data in the database, specifically using InsertMany.
... 
.then(resp => {
Object.insertMany(resp, function(err, docs) {
          if (err) {
            console.log(err)
            res.send('Something went wrong. Storing data to db failed.')
          }
          console.log(
            'Successfully stored'
          )
          res.status(200).end()
        })
}
  1. Save the data to MongoDB.

Mongoose Schema:

var ObjectSchema = new Schema({
  consumedQuantity: Number,
  cost: Number,
  body: String,
  date: Date,
  date_download: { type: Date, default: Date },
  product: String,
  unitOfMeasure: String
})

Issue:

When fetching dates from the API backend service, they are in this format:

{.. "date":"2019-08-08T00:00:00" .. }

However, when stored in MongoDB, they look like this:

{... "date" : ISODate("2019-08-07T22:00:00Z") ... }

I am seeking advice on how to rectify this issue. I have come across some solutions but have had difficulty applying them to my specific scenario. Is it possible to adjust the Schema to resolve this?

Thank you for your assistance.

Answer №1

In my opinion, updating the date in the response to a JavaScript Date object should do the trick. Here's an example of how you could achieve this:

... 
.then(resp => {
resp.date_download = new Date(resp.date_download); -> If it is an array just loop through
Object.insertMany(resp, function(err, docs) {
          if (err) {
            console.log(err)
            res.send('Oops! Something went wrong. The data storage process failed.')
          }
          console.log(
            'Data stored successfully'
          )
          res.status(200).end()
        })
}

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

Aggregated data from multiple elements and sub-documents in MongoDB using group aggregation technique

As someone new to MongoDB, I am currently exploring how to group data based on two elements within a cube structure. One element is time and the other is a sub-document. Here's an example of my data structure: { "_id" : ObjectId("52d931f9f613 ...

Prevent the display of hyperlinks in the status bar when hovering over a hyperlink or button

The application I'm working on has a default status bar at the bottom of each screen that displays URLs linked to buttons and icons. For example: https://i.stack.imgur.com/ZFTsp.jpg I am trying to prevent the display of URLs associated with hyperlin ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

A guide on utilizing the intl.formatRelativeTime() function effectively

I need to display messages like "created 1 hour ago" or "created 1 day ago," as well as in plural form, such as "created 10 minutes ago" or "created 3 days ago." To achieve this, I am attempting to utilize the FormatJS API, specifically the intl.formatRela ...

involving a variable in css styles using javascript

Is it possible to set a margin-left using a variable in JavaScript? If so, how can this be accomplished? The margin left should be equivalent to the clientWidth of the text: let hoverBubble = document.getElementById(id); let linkWidth = link.clientWidth ...

Retrieve a subdocument from mongoDB

I need to retrieve all child objects while filtering them based on a field within the child object. For instance: { "_id" : ObjectId("61a8adfc153b52805029b694"), "date" : "2021-12-02T11:29:00.724Z", "playerO ...

Developing a synchronous loop in Node.js using the web-kit module

My goal with my app using node.js and webkit is to scan each proxy listed in a file.txt and determine if the proxy is working. However, I am encountering an issue where my loop does not wait for the "http.get" test on line 11 to complete before moving on ...

Ways to display the outcomes of an http query using Express?

How can I utilize Request and Express to retrieve the result of my http request in order to display it? var request = require('request'); var http = require('http'); exports.index = function(req, res){ var apiUrl = 'http://api ...

Is it mandatory for Express to have us DELETE through a POST route?

Implementing this code will allow the deletion of a record upon clicking a button and confirming the action: Router (Express): router.post('/meetings/delete/:slug', catchErrors(meetingController.deleteMeeting)); Controller: exports.deleteMeet ...

Passing array map data to another screen in React Native

Greetings! I successfully created an array map to showcase specific data from my API. Now, I am faced with the challenge of TRANSFERRING THIS DATA TO ANOTHER SCREEN. My current dilemma lies in the fact that the displayed data is generated using ARRAY MAP, ...

I am experiencing an issue with my meteor insert not functioning when triggered by a click event. Oddly, no error messages are being

When a user clicks, data or an object from one collection is being transferred to another. The image below represents the individual object that is being moved. https://i.sstatic.net/PVX2q.png This click event is crucial in this process. Template.postsV ...

Increased capacities with content and acceptance encoding headers

Consider the following scenario: I send a POST request from the client server to a REST API with a payload size of 20-30MB, where the content is gzip compressed at the network level due to the request header configuration. Do I also need to enable gzip c ...

Creating an HTTP request inside an Export Function in a MEANJS application

Initially, I utilized the Yo MeanJs generator to kickstart my project. As a newcomer in the world of MeanJs, things are starting to look quite complex for me. Currently, my MeanJs application is supposed to retrieve data from an HTTP request but, unfortun ...

How to access Bootstrap's modal initial data-* upon closing

When displaying a bootstrap modal, a convenient method to retrieve associated data is by using the following code snippet: $('#myModal').on('show.bs.modal', function (e) { var id = $(e.relatedTarget).data('id'); alert( ...

What is the reason for the reduction in dependency versions when installing npm

Encountering an issue with installing a package using npm. The process is resulting in decreased dependencies versions, which is causing issues with my application and unit tests. For example, after installation, my package.lock file looks like this: htt ...

Tips for utilizing the onload attribute alongside the ng-controller directive to run a function that has been established within the controller

When trying to call the submit() function as soon as the page loads, I keep encountering a submit() method not found error. The positioning of ng-controller and onload is confusing to me. If there is an alternate method in Angular to achieve this, please ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...

Having trouble accessing the "x-appengine" headers in a Google App Engine application running on Node.js

I am currently facing an issue with my node-js express server deployed on Google App Engine. I have been trying to retrieve the user's real IP address and determine whether the request is coming from HTTP or HTTPS. However, I seem to be unable to acce ...

Is there a way to incorporate page animations when utilizing the <a href> tag in HTML?

I have created several HTML files. On the main page, I simply inserted some code like this: <a href="new.html> <img src="img/button" id="buttonid"> </a> When I click the button, it takes me to the new.html page. I would like ...

Encountered an issue with module 'C:Users***DesktopBotmodulesdataMongoDB.js'. Error message: ExpectedValidationError > s.instance(V) was thrown

Issue with MongoDB Connection Setup Error Message: Failed to resolve module 'C:\Users\luci\Desktop\Lunar Bot\modules\data\MongoDB.js': ExpectedValidationError > s.instance(V) A TypeScript bot encountering e ...