Using Knex in ExpressJS to insert a list of entries into SQLite with unique field constraints

I'm currently facing an issue with inserting a list of exercises into an sqlite database. The app is built on express JS and I am utilizing sqlite3 and knex to handle interactions with the DB. My goal is to add a set of exercises into the table exercisesDB, but only if the exercise name does not already exist in the table using a knex transaction:

await knex.transaction(async (trx) => {
      for (const exercise of exercisesToAdd) {
        await trx('exercisesDB').insert(exercise).onConflict('name').ignore() 
      }
    })

However, I encountered an error stating: [Error: insert into exercisesDB [data] on conflict (name) do nothing - SQLITE_CONSTRAINT: UNIQUE constraint failed: exercisesDB.id]

It appears that knex is checking the id constraint (which I did not include in the exercisesToAdd list) instead of the name constraint

Could this be a potential issue with knex?

To address the problem, I attempted to add a `then` and `catch` statement within the transaction as follows:

await knex.transaction(async (trx) => {
  exercisesToAdd.forEach(
        async (exercise) => {
          await trx('exercisesDB').insert(exercise).onConflict('name').ignore().then(trx.commit).catch(trx.rollback)
        }
      )
    })

Answer №1

Is the name field required to be unique in your database? If not, you'll need to add a UNIQUE constraint to that column in the database schema before this process will function properly.

Refer to the knex.js documentation here:

For PostgreSQL and SQLite, the specified column(s) must either be the table's PRIMARY KEY or have a UNIQUE index on them, otherwise the query will fail to execute. When specifying multiple columns, they must form a composite PRIMARY KEY or have a composite UNIQUE index.

It appears that by default it checks the primary key, but additional steps may be needed for other scenarios.

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

Obtaining the responseJSON property from a jQuery $.ajax object involves accessing the data returned

Recently, I encountered an issue with my JavaScript code that involves an AJAX request: $ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {} ...

Is the Facebook AJAX Permissions Dialog displayed outside of a Pop-Up?

I have conducted extensive research but have failed to find a clear answer to my query. Although there is plentiful information on Facebook API AJAX/PHP communication, I am unable to locate an example where the Permission Dialog for an app (showPermissionD ...

Implement CSRF protection for wicket ajax requests by adding the necessary header

I'm currently working on a website created with Apache Wicket and we're looking to enhance its security by implementing CSRF protection. Our goal is to keep it stateless by using a double submit pattern. For forms, we are planning to include a h ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

Encountering an Empty Array Response in Postman While Utilizing Mongoose with Node.js

I am encountering an issue while trying to post data in my MongoAtlas database using Mongoose on Express and NodeJS. Postman is giving me back an empty array. Can anyone point out what I might be doing wrong? Database: mongodb+srv://username:password@clu ...

Error message: WebTorrent encountered an issue and was unable to pipe to multiple destinations at once

Upon attempting to stream video from a provided torrent file, I encountered some unexpected issues. The example was taken from the official site, so one would naturally assume it should work seamlessly. To troubleshoot, I tried setting up a default site u ...

The Google reCaptcha reply was "Uncaught (in promise) null"

When using reCaptcha v2, I encountered an issue in the developer console showing Uncaught (in promise) null message regardless of moving the .reset() function. Here is the console output: https://i.stack.imgur.com/l24dC.png This is my code for reCaptcha ...

Ways to conceal images until AFTER the completion of the jquery flexslider loading process

After trying to integrate wootheme's Flexslider on my website, I encountered a small issue with its loading process. Whenever the page is refreshed with the slider, there is a brief moment (approximately 1 second) where the first slide appears overly ...

Using jQuery to Toggle the Height of Multiple Sections with a Single Function

I've got three different sections, each with varying heights and a simple structure like this: <section> <h2>My heading</h2> </section> What I want is for these sections to display at first, but then shrink dow ...

Unlocking Google APIs Data through Service Account in JavaScript without User Approval

Is there a way to obtain an Access Token for Google APIs without requiring user consent, utilizing a Service Account in JavaScript? Alternatively, is it possible to retrieve the Access Token using an API Key, Client ID, and Client Secret? ...

Is there a way to effectively incorporate react-native with php and ensure that the data returned by the fetch function is

I'm struggling to make my return value work in this code. Has anyone had success using react-native with php and fetch json? Any tips or advice would be greatly appreciated. PHP $myArray = array(); $myArray['lat'] = $_POST['lat']; ...

Nodemailer fails to deliver email due to rejection

https://i.stack.imgur.com/xbEgG.pngI am currently facing an issue with sending HTML content emails using nodemailer-express-handlebars. Each time I try to send the email, it ends up getting blocked by Gmail and can be found in the sender's sent-box, t ...

Moving punctuation from the beginning or middle of a string to the end: A guide

My Pig Latin converter works well with single or multi-word strings, but it struggles with punctuation marks. For example, when I input translatePigLatin("Pig Latin.");, the output is 'Igpay Atin.lay' instead of 'Igpay Atinlay.'. How c ...

Issue encountered while compiling ReactJs: Unexpected token error found in App.js

I executed the commands below. npx create-react-app github-first-app npm install --save react-tabs npm i styled-components npm install git-state --save using the following code files App.js import React from "react"; import Layout from " ...

Using Lightmaps with Three.js

Is it true that lightmaps function independently of other textures? It seems like I need to establish a second set of UVs. I've exported my JSON object with a second set of UVs and included the following code snippet: geometry.faceVertexUvs[0] = ge ...

What is the best way to synchronize the image dimensions and source when dynamically loading images?

I am facing an issue with a function that updates images by altering the src and css (width/height) of an IMG tag within the document. Below is a simplified example to demonstrate the problem: updateImage = function(src, width, height) { $("#changeMe"). ...

Exploring ElectronJs: The journey to sending messages from ipcMain to IpcRender and awaiting a response

I need help with sending a message to ask the renderer to parse an HTML string mainWindow.webContents.send('parse html', { resp}) The renderer processes the data and sends a reply ipc.on('parse html',function(e,p){ let b ...

The outcome of my function designed to calculate the highest possible profit using k transactions is a null array

I have developed a custom function to calculate the maximum profit from a series of stock transactions given a specific number of transactions allowed. Each transaction involves buying at a low price and selling at a higher price, with the rule that you ...

I'm curious to know more about the middleware function being used in the example found at https://github.com/erikras/react-redux-universal-hot-example

Could someone provide an explanation of the middleware used in this example from https://github.com/erikras/react-redux-universal-hot-example/? It seems that it doesn't support real API requests. export default function clientMiddleware(client) { ret ...

The dynamic form functionality is experiencing issues when incorporating ng-container and ng-template

I'm currently working on a dynamic form that fetches form fields from an API. I've attempted to use ng-container & ng-template to reuse the formgroup multiple times, but it's not functioning as anticipated. Interestingly, when I revert b ...