The date in the database is being decremented by one when inputting new data into MongoDB

When attempting to save a record with the date column into MongoDB using ExpressJS, I noticed that the date part alone is automatically subtracted by one. I am unsure why this is happening. Below you can find the schema of my DB and the post router that I am using.

For example, here is the input posted in the body:

{
    "name":"Articulation Exam",
    "location":"IoN Center",
    "timing":"11:00am",
    "date":"06/27/2023",
    "maximum_allowed_participants":100,
    "active_participants":1
}

Data stored in the database:

{
        "_id": "6485a0737cd0de176a0c87c0",
        "name": "Articulation Exam",
        "location": "IoN Center",
        "timing": "11:00am",
        "date": "2023-06-26T18:30:00.000Z",
        "maximum_allowed_participants": 100,
        "active_participants": 1,
        "createdAt": "2023-06-11T10:22:43.046Z",
        "updatedAt": "2023-06-11T10:22:43.046Z",
        "__v": 0
    }

As seen in the examples above, the date was posted as 06/27/2023, but it was stored as 2023-06-26 which is incorrect. If there is something I am missing here, please correct me.

router.route('/post').post((req,res)=>{
    const data = {
        name:req.body.name,
        location:req.body.location,
        timing:req.body.timing,
        date:new Date(req.body.date),
        maximum_allowed_participants:req.body.maximum_allowed_participants,
        active_participants:req.body.active_participants
    }

    const newRecord = new Events(data);

    newRecord.save()
    .then(response=>res.send('A new event "'+response.name+'" has been added successfully!'))
    .catch(err=>res.send(err));
})

const eventSchema = new Schema({
    name:{
        type:String,
        required:true,
        trim:true,
        minlength:3
    },
    location:{
        type:String,
        required:true,
        trim:true,
        minlength:2
    },
    timing:{
        type:String,
        required:true,
        trim:true,
    },
    date:{
        type:Date,
        required:true
    },
    maximum_allowed_participants:{
        type:Number,
        required:true
    },
    active_participants:{
        type:Number,
        required:true
    }
},
{
    timestamps:true
});

Answer №1

It seems that the discrepancy in your server running on UTC time and your input being in local time is causing the issue, as pointed out by @Ayush Gupta.

While this may not necessarily pose a problem, one solution based on the information available is to handle date interactions (e.g., via the front-end) using the toLocaleTimeString method. This approach will help avoid confusion for users regarding incorrect dates. If you have specific requirements or a different scenario in mind, feel free to share more details.

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 reason behind not requiring the installation of eslint plugins in our end user app in order to utilize @vercel/style-guide?

Can anyone shed some light on the plugin modules resolution in ESLint when using pnpm? Despite researching numerous articles and answers online on this topic, I still find myself puzzled. I have delved into pnpm's node_modules structure and ESLint&ap ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Convert an AJAX JSON object into values for multiple text boxes

When making an ajax call, I receive the following JSON input: var json = { "id_u":"1", "nombre_usuario":"JESUS", "apellido_paterno_usuario":"DIAZ", } I have text inputs that correspond to each key in the JSON object: <input type="text" name="id ...

Utilizing Spring's MongoDB @DBREF feature

I'm struggling to write code that effectively retrieves user and claim details from my MongoDB structure. Here's a snippet of my database setup: db.user.find(); user: { "name" : "KSK", "claim" : [obj ...

AngularJS - Issue with ng-mouseover not triggering controller function

I am struggling to get a function to trigger when my button is hovered over. Despite writing what I believe is the correct code, the function from my controller is not being called. Can anyone spot the issue? Below is the JavaScript code: angular.module( ...

The ng-bootstrap modal fails to appear when incorporating [formGroup]="FormName" or formControlName="elementName"

Utilizing ng-bootstrap to create a popup modal has been a challenge for me. When I import FormsModule and ReactiveFormsModule in src/app/modal-basic.module.ts, the code inside it looks like this: import { NgModule } from '@angular/core'; import { ...

How to Manage Mongoose's `populate()` Method within a Wrapper Function

Within our Node.js and MongoDB project, we have implemented a wrapper function that handles all findOne() operations to centrally manage permissions. However, the issue I am encountering pertains to the Mongoose populate() functionality. Due to our standa ...

How can we retrieve key value pairs from an array in an AngularJS controller and display them in

I have been working with an array of keys in my angular js controller. While I am able to retrieve a specific value within the controller, I am encountering difficulty displaying it in the view (HTML). Controller: var statusLength= res.fsus.length; for ...

Recover Checkmark Status from Data

Currently, I am storing form data in json format and encountering an issue when trying to load values from a previously created json file. The plain old JavaScript function provided below successfully loads values into a form from a file, effectively resto ...

Is there a way to trigger javascript on Amazon once the "Next Page" button is clicked?

My Greasemonkey script is designed to run on Amazon's search results page. However, I've noticed that when the "Next Page" button is clicked and new results are dynamically loaded, my script only executes once after the initial page load. Here&a ...

Error: Unable to locate the 'react' module in the specified directory

During the execution of my project, I encountered an error that read: Module not found: Can't resolve 'react' in I attempted various solutions to fix this issue. Initially, I ensured that the state in my component was correct and that I had ...

Exploring advanced mathematical calculations in QtQuick Qml with JavaScript for handling large numbers

I need to calculate the orbit of the Sun around the Galaxy. The mathematical formula I am using is ((241828072282107.5071453596951 * 666) * 2) * 3.14159265359. In QML JavaScript, I received the answer 1011954093357316100, but the correct answer is 10119540 ...

Efficiently indexing lengthy text for exact matches in MongoDB through compound indexing

I'm dealing with a model that has the following structure: { _id: '...', voice: '<dialect code>', // for example: 'en-US', 'en-GB', 'es', 'de', ... text: '<plaintext up t ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

Grouping documents in mongoDB following the unwind operation

Within my mongodb's books collection, the documents are structured like this: { _id: ObjectId(625efa44f1ba751c8275ea51), contributors:[ObjectId(625efa44f1ba751c8275ea52), ObjectId(625efa44f1ba751c8275ea53)] //other fields } ...

Expo React Native app encounters surprising 405 error while making Axios request

I am currently working on a React Native app using Expo, and I have encountered an issue with Axios while sending HTTP requests. Each request I make results in a 405 status response. Here is the Axios instance that I have set up to handle the requests (I ...

The keyboard event is expected to trigger once the text box has been filled

Currently, I am working on keyboard events using jQuery. Within my project, I have implemented two text boxes that are used for entering a first name and last name respectively. My goal is to trigger an alert displaying both the first and last names once t ...

Tips for directing your attention to a specific cell within a grid after inputting a value into a textBox

I am looking to navigate to a specific cell within a grid by entering the cell number into a textBox. Upon typing any number in the textBox, it should automatically focus and scroll to that particular cell in the grid. For example, if I type 601 in the te ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

Loading dynamic images in HTML using Javascript and Django templates

Attempting to load a specific image using javascript within a django template has presented challenges due to the formatting of django tags. The standard django static asset source in an img tag looks like this: {% load static %} <img src="{% static & ...