What is the best way to retrieve data from the past day using moment.js or the date function

I have data stored in my database that I need to query for entries from yesterday. However, when I try the following code:

momentendYest', moment().startOf('day').subtract(1,'day').toDate()

it returns today's date at 7am instead. Can someone help me figure this out?

My goal is to do something like this:

    const yesterdayRecords = await Record.find({
  category: {
    $regex: new RegExp(title, "i"),
  },
  createdAt: {
    $gte: startOfYesterday,
    $lt: endOfYesterday,
  },

What changes should I make to ensure that I query data specifically from yesterday starting at 12am and ending at 11:59pm?

Answer №1

Using plain JavaScript, you can achieve something like this.

const today = new Date()

const year = today.getFullYear()
const month = today.getMonth()
const day = today.getDate()

const yesterday = new Date(year, month, day-1, 23,59,00)

console.log(yesterday)

This code creates a date for today, extracts the year and month, subtracts one from the day, and sets the time manually.

If you prefer midnight, simply omit the time parameters in the code.

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

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

Searching for mustache variables in HTML using regular expressions is a helpful way to

As I work on parsing template files in my code, one of my first tasks involves removing all Mustache variables in the template. The majority of these variables follow this structure: {{variable}}, {{#loop}}{{content}}{{/loop}}, {{^not}}{{/not}}, {{! comme ...

What is the process for importing a jquery plugin like turnjs into a React component?

After searching through countless posts on stackoverflow, it seems like there is no solution to my problem yet. So... I would like to integrate the following: into my react COMPONENT. -I attempted using the script tag in the html file, but react does no ...

Troubleshooting Wordpress Custom Widget with Missing Javascript Output

I've encountered an issue with my JavaScript code that I wrote for a custom widget. Below is the code snippet from my JavaScript file and how I'm implementing it in the widget: Custom.js var container = $('#container'); ...

Displaying that the response from ajax is experiencing issues

I am currently attempting to update the td elements in a table but my current method is not yielding successful results. Here's what I have tried: <table id="job1"> <tr><td></td></tr> <tr id="Jobstatus1"> ...

Schema validation with React Yup is an essential step in

Currently, I am utilizing Yup for email field validation: const Schema = Yup.object().shape({ email: Yup.string() .email("invalid email format") .required("Email is required"), ... Upon form submission, I verify if the email doma ...

Updating a subdocument in MongoDB - subdocument not found within array

I have a text snippet that looks like this, { "S" : { "500209" : { "total_income" : 38982, "interest_income" : 1714, "reported_eps" : 158.76, "year" : 201303 } }, "_id" : "pl" } ...

Determine if an Image is Chosen upon Click with Javascript

I am currently working on a wysiwyg editor and I'm facing an issue where I need to determine if a user has clicked on an image within the selection range. Is there a method to detect this without attaching event handlers directly to the image itself? ...

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

Regular expressions: Capturing characters that come after and before a designated symbol

Is there a way to extract all letters, both before and after an underline "_", in JavaScript using Regex while excluding specific words like "pi", "\Delta" and "\Sigma"? How can this be achieved in Regex JS? /\b([^e|_|\d|\W])&bso ...

Is it possible to integrate external search functionality with Vuetify's data table component

I am currently working with the v-data-table component from Vuetify, which comes with a default filter bar in its properties. This table retrieves data from a local JSON file. The issue arises when I have another external component, a search bar created u ...

Having trouble finding the right path. Is there an issue with Angular routing?

After successfully creating a simple application, I decided to write test cases for it. My first attempt was to work on the routing part of the application. Check out the code on StackBlitz The routing code snippet is as follows: Main module: export cons ...

Clicking on Fixed Positioning triggers a reset

When I activate the sidebar by clicking the menu button, it remains fixed in position until the first scroll. However, if I interact with the sidebar by clicking on it, the button resets and goes back to the top of the page. This issue seems to only occur ...

The basic structure for organizing components and categories

I am working on creating a list and have designed the following Schema: new SimpleSchema({ element: { type: String, optional: true }, note: { type: String, optional: true }, order: { type: Number, optional: true } }); Now, I wan ...

Issue with child routes not functioning properly within single spa React application

{ "name": "@my-react-app/demo", "scripts": { "start": "webpack serve", "start:standalone": "webpack serve --env standalone", "build": "concurrently npm:build:*", "build:webpack": "webpack --mode=production", "analyze": "webpack --mo ...

Strategies for ensuring completion of internal promises

When using fs.readdir to retrieve a list of directories and then again within the callback to get a list of "subpages" in each directory, I find myself wanting the first callback to wait until the second one is completed. Unfortunately, I'm unsure of ...

Update the position of a div when an element becomes visible

Currently, I have 3 titles each with a button underneath to reveal more information about the subject. To toggle the visibility of the content, I have implemented a script that shows or hides the corresponding div when the button is clicked. On smaller de ...

Dynamic SVG positioning

Looking for a way to make this svg shape relative to its containing div? Fiddle: http://jsfiddle.net/8421w8hc/20/ <div> <svg viewBox="0 0 1000 2112" style="" xmlns="http://www.w3.org/2000/svg" version="1.1"> <path id="ma" st ...

The key property is present on the list item, yet the key warning persists

I have encountered various issues with this problem, but I am unable to pinpoint the exact cause. I am not extracting individual list items and simply displaying a UL with unique keys assigned to each item. However, when I log the results, I see something ...

What could be the reason for the ineffective custom error handling in mongoose?

In an attempt to improve the readability of error messages before they are displayed on the frontend, I am working on handling the required validation error as shown below: UserSchema .post('save', function (error, doc, next) { console.log ...