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:
- recreate the query with knex.raw
- 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!!