Searching in sequelize for a specific date using a clause

  • Operating System: Linux (Lubuntu)
  • Programming Language: Javascript (Node js)
  • Framework: express js
  • Database: mysql
  • "data" represents a Date field from the "activitat" table

Upon running this query using Sequelize.js

models.TblActivitat.findAll(
                {
                    attributes: 
                    [
                        'codiAct', 'procedencia', 'pacient', 'proces', 'prova', 'rmn', 'realitzador',
                        [Sequelize.fn('date_format', Sequelize.col('data'), '%d-%m-%Y'), 'data']
                    ],
                    include: models.TblTecnics,
                    where: {"data": '2016-10-20' },   //dataAAAAMMDD
                    order: "registre DESC"
                }).then(function(tblActTec){
                    ...
                });

... I am not receiving any records despite expecting some

Querying on mysql yields the following results:
mysql> select data from activitat where data = '2016-10-20';
+------------+
| data |
+------------+
| 2016-10-20 |
| 2016-10-20 |
| 2016-10-20 |
| 2016-10-20 |
+------------+

When checking the Node server console, the query execution appears as follows:

Executing (default): SELECT activitat.codiAct, activitat.procedencia, activitat.pacient, activitat.proces, activitat.prova, activitat.rmn, activitat.realitzador, date_format(data, '%d-%m-%Y') AS data, tecnic.codiTec AS tecnic.codiTec, tecnic.nom AS tecnic.nom FROM activitat AS activitat LEFT OUTER JOIN tecnics AS tecnic ON activitat.realitzador = tecnic.codiTec WHERE activitat.data = '2016-10-19 22:00:00'
ORDER BY registre DESC;

My question is:
I specified "2016-10-20" in the where clause. While it retrieves the correct results in mysql, when executed using sequelize, the value of the data clause gets altered to "2016-10-19 22:00:00" (two hours before "2016-10-20 00:00:00"!!). Why does this happen?

It should be noted that the "data" field is strictly a Date field and not a DateTime field

Thank you very much for your assistance!

Answer №1

When using Sequelize, the string you provide is converted into a Date object with a time assigned to it. If you aim to retrieve records based on a specific date (rather than a precise time), you can achieve this by:

 date: {
     $lt: new Date('2016-10-20'),
     $gt: new Date(new Date('2016-10-20') - 24 * 60 * 60 * 1000)
 }

In your scenario:

models.TblActivitat.findAll(
            {
                attributes: 
                [
                    'codiAct', 'procedencia', 'pacient', 'proces', 'prova', 'rmn', 'realitzador',
                    [Sequelize.fn('date_format', Sequelize.col('data'), '%d-%m-%Y'), 'data']
                ],
                include: models.TblTecnics,
                where: {"data": {
                    $lt: new Date('2016-10-20'),
                    $gt: new Date(new Date('2016-10-20') - 24 * 60 * 60 * 1000)
                } },   //dataAAAAMMDD
                order: "registre DESC"
            }).then(function(tblActTec){
                ...
            });

Answer №2

Recently, I came across a new field type in Sequelize while defining table fields. This special field type is called DATAONLY, a unique alternative to the standard DATA type. When using this field type, the field definition code looks like this:

        data:
        {
            type:   DataTypes.DATEONLY,
            validate:
            {
                notEmpty: 
                {
                    msg: "-> Missing date"
                }
            }
        },

The intriguing aspect of DATAONLY is that it only considers the date part and ignores the time part.

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

Unable to trigger click event on dynamically added element using Chrome (jQuery)

My approach here involves dynamically creating a drop-down and binding the click event to the <option> within the <select> var $select = $('<select></select>'), $option1 = $('<option>a</option>') ...

What is the best way to create a repetitive pattern using a for loop in Javascript?

I want to create a repeating pattern to color the background, but once i exceeds colors.length, the background color stops changing because, for example, colors[3] does not exist. I need colors[i] to start back at 0 until the first loop is complete. cons ...

Using React to iterate over an array of objects and generate Date TextFields in Material UI

I have an array of objects representing different stages in a specific process, each stage identified by an id and name. The structure of the array is as follows: const stages = [ { id: 1, name: initialize }, { id: 2, name: execute ...

Troubleshooting: WordPress post not uploading to custom PHP file - Issue causing ERROR 500

Our website is built using WordPress, and I was tasked with adding a function to our newsletter subscription that sends an email to a specific address based on the selected value in the form. Everything was working perfectly on my local host, but when I tr ...

PHP Amazon Simple Queue Service Big Data

I am new to working with Amazon SQS and I am trying to figure out how to efficiently store and push big chunks of data (more than 50,000 results) from the database to the queue. Setting up AWS SQS require_once __DIR__.'lib/aws/aws-autoloader.php&apo ...

"Combining multiple DIVs into a single DIV with jQuery - a step-by-step guide

I have multiple DIVs with the same class, and I am looking to group them into a single DIV using either jQuery or pure JS. <div class="a"> <div>1</div> </div> <div class="a"> <div>2</div> ...

What's the best way to set up server-side pagination for mui-datatable?

Is server-side pagination for mui-datatable implementation a complex task? Challenges: I am facing difficulties in capturing the user-selected value from the rowsPerPage options. When a user selects '15', how can I update these values within ...

The SelectCommand of SqlDataSource is dynamically set

Using a SqlDataSource and aiming to avoid lengthy queries directly in the code, I attempted to create a Query class that returns the desired query as a string. The code snippet I used resulted in an error message stating "Server tags cannot contain <% . ...

Connecting a Vue js model data to a Select2 select box

Utilizing select2 to improve an html select element, I am facing challenges in binding the value of the select element to a Vue variable because Select2 appears to be causing interference. Is there an optimal approach to achieve this data binding and even ...

A method for extracting URL parameters based on the matching route path

Is it possible to parse a given URL string in relation to the match.path value? For instance, if the current route is: <Route path="/some/path/:type" /> To obtain the type parameter of the current URL, one can simply use match.params.type ...

In Pure JavaScript, an HTML element is added every time the click event is triggered

Hey everyone, I'm facing a small issue and I could use some help fixing it. I need to implement an onclick event that adds HTML code every time it's clicked. I am hesitant to use innerHTML due to its potential risks. Here is the code snippet: bu ...

What is the best way to upload my React project to GitHub without adding the node modules directory?

I'm looking to share my React Project on GitHub, but I don't want to include the node modules folder. What's the best way to go about this? ...

What methods can I use to conceal #! from showing on the browser's address bar?

Imagine you have the below link: www.someurl.com/#!?page=index How would you convert it into one of these options: www.someurl.com/#!/index (using mod_rewrite) www.someurl.com/ajax/index (also using mod_rewrite, but replacing #! with ajax) www.someurl. ...

Tips for extracting values from a PHP array using JavaScript

Assuming we have a PHP array named $decoded: $decoded = array( 'method' => 'getFile', 'number' => '12345' ); The data from this array will be passed to a JavaScript function called get(params). funct ...

An issue occurred while evaluating the Pre-request Script: Unable to access the 'get' property of an undefined object

I need help accessing the response of my POST request in Postman using a Pre-request Script. Script below : var mobiles = postman.environment.get("mobiles"); if (!mobiles) { mobiles =["8824444866","8058506668"]; } var currentMobile = mobiles. ...

Rejuvenate a just-launched window.open starting from the about:blank

After receiving data from an ajax result, I am trying to open a pdf in a new window. However, the pdf viewer is only displayed if I manually resize the window (using manual hotspot resizing). How can I ensure that the contents display properly in its popu ...

Retrieving cookie from chrome.webRequest.onBeforeSendHeaders

I have been developing a Firefox add-on with the goal of intercepting HTTP requests and extracting the cookie information. While I was successful in extracting the 'User-agent' data from the header, I faced difficulties when attempting to extract ...

What could be causing the issue of rows being undefined?

Need help creating a user registration feature with Passport(Local-Signup)? Check out the code snippet below: // config/passport.js // requiring necessary modules var LocalStrategy = require('passport-local').Strategy; // loading the user mode ...

Unity3D: Troubleshooting a Code Issue

Encountering an issue with my code and struggling to find a solution. I've tried moving my c# script up to the standard assets folder as suggested in my research but it didn't resolve the problem. Any assistance would be greatly appreciated! Than ...

Error encountered while custom building AngularJS/ngCordova in Ionic with injection module

Today I found myself on the edge of madness. All I wanted to do was add a plugin called ngCordova (specifically cordova-plugin-device) to my project. It seemed simple enough. I started with an Ionic tabs project, nothing more. Following some advice, I v ...