Tips for converting a raw SQL query to Knex syntax

Recently delving into the world of development, I've come across knex for the first time.

Issue: I have a raw SQL query that is functioning correctly. Now, I'm attempting to utilize knex for this query. To better understand how things operate, I would like to:

  1. recreate the query with knex.raw
  2. recreate the query using the knex query builder.

Can anyone assist me with this task? By the way, I am using Postgres and Next.js. Upon running the code below, I encounter an "UnhandledPromiseRejectionWarning: Error: Expected 1 bindings, saw 0". I am uncertain whether the problem lies within this snippet:

typeof req.query.word === 'string' ? [req.query.word] : req.query.word)

...so I made an attempt to rewrite it by adding square brackets, but without success. Here is the code provided:

const getTranslation = (req, res) => {
  const params =
    typeof req.query.word === 'string'
      ? req.query.word
      : req.query.word.map((_, index) => `$${index + 1}`);
    console.log(req.query.word);

  knex.raw(
    `SELECT "Translation", "Words" FROM "Dictionary" WHERE "Words" IN (${
      typeof req.query.word === 'string' ? '($1)' : params.join(',')
    })`,
    typeof req.query.word === 'string' ? [req.query.word] : req.query.word)
    
      .then((error, result) => {
        const wordArray = typeof req.query.word === 'string' ? [req.query.word] : req.query.word;
        if (error) {
          throw error; 
        } 
        const wordOrder = req.query.word;
        result.rows.sort((row1, row2) => {
          return wordOrder.indexOf(row1.Words) - wordOrder.indexOf(row2.Words);
        });
        res.status(200).json(result.rows);
    }
  );
};

Attempts Made: To verify if the setup was correct, I experimented with a simple query. Based on my observation, everything seems to be in order: a request with status 200 is visible in the terminal (network) and I can see the data in the console...

const getTranslation = (req, res) => {
  knex.select("Words", "Translation").from("Dictionary")
      .then(rows =>
        rows.map(row => {
          console.log(row)
        }))
} 

Thank you!!

Answer №1

For optimal results, your query should take the following form:

Let results = await knex('Dictionary')
  .select(['Translation', 'Words'])
  .whereIn('Words', req.query.word); // assuming that `req.query.word` is an array containing strings/numbers

Answer №2

Keep in mind that I have limited knowledge of Knex.

However, as I was reading responses to a related question on the link provided below, I noticed that many of them recommended using "Knex.with()".

How to add two bind params in knex?

knex.with('with_alias', knex.raw('select * from 'lyrics' where 'for_id' = ? and 'var' = ?', [var1, var2])).select('*').from('with_alias')

It seems that they are suggesting binding it with 'With_alias'.

Additionally, they advised passing variables in the array.

I trust this information will provide some assistance to you.

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

Executing ESM-Enabled Script in Forever

Is it possible to execute a script using the option -r esm in Forever? When I try to run the configuration below, I encounter an error message that reads: Unexpected token import. Here is the configuration: { "uid": "app", "script": "index.js", "s ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...

Determine the name of the time zone using JavaScript

Currently, I am developing a React application and facing an issue where the timezone is detected as 'Etc/GMT-1' instead of the desired format 'Africa/Bangui'. This problem seems to be specific to my machine as it persists even when usi ...

Tips for obtaining a specific sorting order based on a wildcard property name

Here's the structure of my JSON object, and I need to sort it based on properties starting with sort_ { "sort_11832": "1", "productsId": [ "11832", "160", "180" ], "sort_160": "0", "sort_180": " ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Retrieving data arrays from response.json

I've been on a wild goose chase trying to solve this puzzling issue. RAWG has transitioned to using their own API instead of Rapid API for game reviews, and I'm in need of data for "Tom Clancy Rainbow Six Siege". Despite my efforts to convert t ...

Tips on how to obtain the element reference while using v-if in Vue

I need to conditionally display a div inside a card that slides within a carousel. My current approach is to check if the ancestor element contains the active class, and then use v-if to decide whether it should be rendered or not. However, this method d ...

What is the best way to incorporate a gratitude note into a Modal Form while ensuring it is responsive?

Currently, I have successfully created a pop-up form, but there are two issues that need fixing. The form is not responsive. After filling/submission, the form redirects to a separate landing page for another fill out. Expected Outcome: Ideally, I would ...

Managing Dependencies in Redux: Ensuring Proper Updates for Interconnected Resources

Let's say I have a redux state structure like this: { user: null, purchases: [], } The purchases are associated with a user, so whenever the user is updated, I also want to update the purchases (although there may be other times when purchases n ...

The error function is consistently triggered when making an Ajax POST request, even though using cURL to access the same

I have been using Ajax's POST method to retrieve a JSON response from the server. However, whenever I click the button on my HTML page, the Ajax function always triggers the error function, displaying an alert with the message "error." Below is the co ...

The next.js script malfunctions once the router has been altered

My external scripts are not working after the router changes (**When the user clicks on any link**) within _app.js import Script from "next/script"; <Script async type="text/javascript" src= ...

What is causing the scripts to fail when I attempt to press a button?

Clicking on the button is supposed to slowly reveal phone numbers on the page. Here are the HTML Codes: <span id="show-phone-numbers" class="btn btn-success"> <i class="fe fe-phone-call"></i> Show Phone Nu ...

Numerous animated elements within A-frame

Is there a way to incorporate animation into an A-Frame glTF model, causing it to smoothly move 5 spaces to the left and then 5 spaces forward? Below is my current code: <a-gltf-model color="#FFFFFF" width="1" height="1" de ...

Unusual Behavior of JavaScript for..in and enum

I'm facing an issue with the peculiar behavior of the for..in loop in JavaScript. Here's the structure of my HTML: <div id="quarter_circle_top_left">...</div> <div id="quarter_circle_top_right">...</div> <div id="quart ...

The MVC framework causing the Morris chart to omit the final xkey value

I am facing an issue with my Morris Chart where it is not displaying the last xkey value. Any thoughts on why this might be happening? https://i.stack.imgur.com/mHBQd.png Here is the data I am working with: [{"Date":"2016-07-17","Average":0.0},{"Date":" ...

The server is failing to provide the requested data in JSON format

I am struggling with making a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON format, and I'm unsure of the reason behind this issue. I need assistance with two main things: Why is ...

Using Dynamic Jinja HTML to Select Elements Dynamically

I have a unique system where forms are dynamically created based on values from a dictionary. Each form is assigned an ID corresponding to the key value and initially hidden. <div id="subforms" style="display: none" > {%for k, v in options.items() ...

The EJS template on the Express app is encountering an issue: it is unable to find the view "/id" within the views directory located at "/home/USER/Desktop/scholarship-app/views"

When attempting to render the request URL for an ID in my Express app, I encountered the following error: Error: Failed to find view "/id" in views directory "/home/USER/Desktop/scholarship-app/views" Here is a portion of my Express app code: app.get(&a ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...