How to add multiple entries using Node.js and Tedious

I am currently working with an array of customer objects that I need to insert into a SQL database. These customer objects are retrieved from the request data.

For this task, I am utilizing Tedious for handling the request and Tedious Connectionpool to manage multiple connections simultaneously.

As I loop through the objects, I encountered an error while attempting to insert them, specifically:

{ [RequestError: Violation of PRIMARY KEY constraint `'PK__Customer__A4AE64D873A5400C'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is (2).]`

It seems that only the last object in the request is being handled and inserted, even though there are only 3 objects being sent at this time. Since I am new to using tedious with Node.js, I am struggling to identify my mistake. Any suggestions would be greatly appreciated.

router.post('/',jsonParser, function(req, res) {

    // Code for processing the request and inserting customer objects

});

Answer №1

The global variables count and firstName have a scope that extends throughout the code. However, when the pool.acquire( function is executed, it ends up inserting the last customer twice because the for loop has already completed. One potential solution is to encapsulate the insert operation within an anonymous function inside the for loop, as shown below:

for (var i = 0; i < customers.length; i++) {
    (function(count, firstName) {
       ...insert code here...
    }(i, customers[i].firstname));
}

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 issue of JavaScript failing to connect to the HTML file

As I work on my basic HTML file to learn Javascript, I believed that the script was correctly written and placed. Nevertheless, upon loading the file in a browser, none of the script seems to be functioning. All of my javascript code is external. The follo ...

Node.js and socket.io come together in this collaborative text editing tool

I'm currently working on a collaborative app utilizing node and sockets that includes a simple text tool feature. My goal is for any user who types and applies text to the canvas to have that text visible to all other connected users. Here's wha ...

Tips for managing @ManyToMany relationships in TypeORM

In this scenario, there are two distinct entities known as Article and Classification, linked together by a relationship of @ManyToMany. The main inquiry here is: How can one persist this relationship effectively? The provided code snippets showcase the ...

Debugger in VSCode is not stopping at the designated break-point when a postman request is made

I've been working on an express.js application and testing it using Postman. Debugging hasn't been necessary until now, but I recently tried setting it up and encountered an issue. Following this tutorial, the debugging setup isn't yielding ...

Attempting to execute the Angular CLI directive "ng generate module flat true" is proving to be unsuccessful

When I run the command 'ng generate module file.module.ts flat=true' it is supposed to create a module without nesting it inside a folder of the same name. However, I've been encountering an issue where it always creates the folder and place ...

I encountered an issue when installing npm modules as I tried using all the available registry commands but still

I'm encountering an issue with npm install and have attempted various registry commands, but I still can't resolve the problem. npm timing stage:rollbackFailedOptional Completed in 0ms npm timing stage:runTopLevelLifecycles Completed in 210 ...

What is the best way to append these values to an array?

I'm encountering difficulties when trying to add the following array: 637301291068030997 => { guildMemberCount: 4, guildOwnerID: '348832732647784460', guildOwner: 'Ethical Hacker', prefix: '.', guildID: '63730129 ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

What is the best way to change the orientation of column names from vertical to horizontal?

I have a simple code snippet below that currently displays all 75 column names in a vertical format. However, I need these column names to be displayed horizontally with a period between each one. I have tried different approaches, but they all seem over ...

Integrating Asp.Net Core for server-side functionality with React for client-side interactions

I have started a simple Asp.Net default project in Visual Studio 2015 using the template: ASP.NET Core Web Application (.NET Core) / Web Application, No Authentication. Following that, I created a package.json file to load all the necessary packages for R ...

The perplexing saga of Google Assistant and the WorldWeatherOnline API

I recently started developing API agents for Google Assistant. I followed the instructions provided in the api.ai documentation available at to create an agent that retrieves weather information and provides a response. While the code is functional, I w ...

Node.js JSDOM unable to locate the 'parsingMode' property in the code

Is there a way to interact with the DOM of a JavaScript file using Node.js? var fs = require('fs'); var jsdom = require('jsdom'); var doc = jsdom.jsdom(fs.readFileSync("a.html"), null, { features: { FetchExt ...

What happens when an AJAX request doesn't have a success field?

Is it possible to execute an ajax call without specifying a success function? $.ajax({ type: "POST", url: "/project/test/auto", data: data, // no success function defined here }); My reasoning for this is that I have PHP code that insert ...

Stop Antd Modal from automatically scrolling to the top

At the moment, I'm utilizing Ant Design (v4.22.8) and Next.js (v12.3.4) in my project. One issue I've encountered is with a Modal component that activates when a button is clicked. Instead of overlaying the current content on the screen, the moda ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

How to send a JavaScript variable to Flask and trigger an AJAX reload action

Introduction: I have explored similar inquiries and attempted to apply relevant code/concepts but without success. -https://stackoverflow.com/questions/43645790/passing-javascript-variable-to-python-flask -https://stackoverflow.com/questions/10313001/is- ...

Guide for bringing in a complete npm library into React Native beyond just a single file access

Currently, I am facing an issue with importing the sjcl library into my project. Even though there are multiple files within the library, I am only able to import one file successfully. This is what I have tried from the command line: npm install sjcl -- ...

Unable to render canvas element

Hey guys, I'm trying to display a red ball on the frame using this function but it's not working. I watched a tutorial and followed the steps exactly, but I can't seem to figure out what's wrong. Can someone please help me with this? I ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...