SQL Query using Date retrieves Datetime values in a Node application connected to MSSQL

I am currently using version 6.3.1 of node mssql. My query involves multiple columns that are of type date. When querying in node mssql, the output for all Date columns is in this format: 2020-10-20T00:00:00.000Z However, when I execute the same query in Azure Data Studio, I get: 2020-10-20

The issue arises when I need to update the database as I encounter an error using the YYYY-MM-DD format. Is there a method to update the database without having to manually check each field if it's a date and then append "T00:00:00.000Z" to it?

Current code snippet:

// Executed at server startup

const sql = require('mssql')

const poolPromise = sql.connect({
  server: process.env.SQL_SERVER,
  user: process.env.SQL_USER,
  password: process.env.SQL_PASSWORD,
  database: process.env.SQL_DATABASE
})

// Executed during query operation

async function updateSqlRecord(fields) {
// Adding fields below for demonstration
  let fields = {id: 1, name: 'test', date: '2020-10-12' }

  let database = process.env.SQL_DATABASE
  let table = 'Test'
  let querystring = `UPDATE [${database}].[dbo].[${table}] SET `

  Object.entries(fields).forEach(field => {
    const [key, value] = field;
    querystring += `${key} = '${value}', `
  });

  querystring = querystring.slice(0, -2)
  querystring += ` WHERE projektNr = ${fields.projektNr}`
  try {
    let pool = await poolPromise
    let result = await pool.request()
      // .input('projektNr', sql.Int, value)
      .query(querystring)
    console.log(result)
    return result.rowsAffected
  } catch (err) {
      console.log('SQL request Error',err)
  }

}

Answer №1

Consider utilizing the moment.js library for date parsing before inserting it into your database.

var moment = require('moment');
...
var formattedDate = moment(myDate).format('YYYY/MM/DD HH:MM:SS').toISOString();

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

Best practices for handling AJAX GET and POST requests in EmberJS

EmberJS has captured my interest and I am thoroughly enjoying diving into it. Although there is a learning curve, I truly believe in the meaningful principles it stands for. I am curious about the process of making GET and POST calls in Ember JS. While I ...

Is it possible to extract around 10 variables from a JavaScript code, then display them on a webpage after execution?

I have just completed writing a Javascript code with around 3,000 lines. This code contains over 60 variables, but there are a few specific variables that I would like to display on my main HTML page. These variables include: totalTime longitudinalAcceler ...

What is the best way to ensure that my multiple choice code in CSS & JS only allows for the selection of one option at a time? Currently, I am able

I'm currently facing a small issue that I believe has a simple solution. My knowledge of Javascript is limited, but I am eager to improve my skills in coding for more visually appealing websites. My problem lies in the code snippet below, where I am ...

I am looking to merge a list of times (hh, mm) with today's date (yyyy, mm, dd) into a separate CSV file using SSIS

Is there a way to combine today's date with existing time values in a column to create DateTime data using SSIS? How can this be achieved? I am looking to add today's date like this via SQL and/or SSIS: OLEDB Table (datetime datatype): Date ...

What is the method to invoke a function prior to invoking the controllers in node.js?

Is there a way to execute a function before calling the controller for every route defined in my routes file? const express = require('express'); const userController = require('../controllers/user'); const chatController = require(&apo ...

The res.render function is failing to render the view and instead, it is generating

When making a call to express/node like this: jQuery.ajax({ url : url, type: "GET", data: {names : names}, success: function(data) { console.log("ajax post success"); }, ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

How can I complete this .js file and .ejs file in NodeJS (Express) to query the object ID in my browser?

My goal is to query an objectID from MongoDB using NodeJS and then retrieve it on my local host through http://localhost:3000/objectSearch?objectid= I've searched everywhere, but I can't seem to figure it out. If someone could provide me wi ...

Tips for saving and retrieving req.user using JsonwebToken

Looking for ways to store and retrieve req.user using JsonwebToken in my booking application built with Node. I need to fetch the user information who booked a product and display it on the admin portal. .then((user) => { const maxAge = 3 * 60 * ...

Methods for updating data in a web form using a Gridview

In order to allow my user to edit data within a data table, I chose to retrieve the necessary information from an SQL server using this method: public static List<TestAsfa> GetRecordsMan() { using (var d = new TestEntities()) ...

Convert JavaBeans sources into a JSON descriptor

I'm in search of a tool or method to analyze standard JavaBeans source code (featuring getters and setters) and create json descriptors using tools like grunt or ant, or any other suitable option. Here's an example: FilterBean.java: package com ...

Angular View receives OAuth Token Response via Cookie

I've been tackling this issue for a couple of hours now and could really use some assistance. I created a basic app that displays a "Login Using Google" button in an Angular view, which then redirects the user to the Google OAuth page. Below is the co ...

Steps to display a div element periodically at set time intervals

I've created a user greeting message that changes based on the time of day - saying Good Morning, Good Afternoon, or Good Evening. It's working well, but I'm wondering how I can make the message hide after it shows once until the next part o ...

Every time I use JSON.stringify on an object, I end up with a wild and wacky string returned

Whenever I attempt to transmit an object containing an array of objects from my express route to the client, I receive an [Object object]. Then, when I try to convert it into a string using JSON.stringify, I end up with a convoluted string along with a con ...

What is the best way to send JSON data from Express to a JavaScript/jQuery script within a Pug template?

Currently, I am facing a challenge in passing JSON data from an Express route to a .js file located within a .pug template. I have been attempting to solve this issue using the following method: The router: // Office Locations router.get('/office_lo ...

When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is. Here is my class: export default { name: "Contact", component ...

Looking for a streamlined process to manage the development and publication of multiple versions of the React module using the "yarn/npm link" workflow

Currently, I am in the process of developing and releasing a module on npm that relies on the React library. As part of my workflow, I am utilizing yarn along with yarn link. The module has been created within a larger parent project, but now I am looking ...

Achieve a customized glow effect by blending FragColor with UnrealBloom in ThreeJS using GLSL

I am interested in implementing selective bloom for a GLTF model imported into ThreeJS using an Emission map. To accomplish this, the first step is to make objects that should not have bloom completely black. The plan includes utilizing UnrealBloomPass an ...

Troubleshooting MongoDB query criteria in Meteor and JavaScript doesn't yield the expected results

I am encountering an issue with a Products collection that has an attribute called "productCode". My goal is to create a server-side query to fetch a product based on the productCode attribute. Unfortunately, I keep running into a "cannot read property &ap ...

Stop useEffect from triggering during the first render

I'm working on implementing a debounce functionality for a custom input, but I'm facing an issue where the useEffect hook is triggered during the initial render. import { useDebouncedCallback } from "use-debounce"; interface myInputProps { ge ...