简体   繁体   中英

How to get data from DB (Postgres) in the same order as user input?

I have a textarea, where users can enter words separated by comma. For each word I get a translation (data) from my postgres-database. The input as well as the translation from the database are then shown in a table.

My problem: I need to keep the order of the user input in my table. But the order changes automatically based on the order of the words in my DB. I tried to use ORDER BY, but I couldn't fix it.

Could someone explain me why the order changes and how to fix it? Thanks a lot!

Here's my code:

 const getTranslation = async(req, res) => { const params = typeof req.query.word === 'string'? req.query.word: req.query.word.map((_, index) => `$${index + 1}`); console.log(req.query.word); const rawResults = await pool.query( `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, (error, result) => { if (error) { throw error; } res.status(200).json(result.rows); console.log(result.rows); } ); const wordOrder = req.query.word.split(','); rawResults.sort((row1, row2) => { return wordOrder.indexOf(row1.Words) - wordOrder.indexOf(row2.Words); }) } /*terminal console.log(req.query.word) is ['yes', 'no'] terminal console.log(result.rows) is [ {'Translation': 'non', 'Words': 'no'}, {'Translation': 'oui', 'Words': 'yes'}] */

Just reorder it before sending as response. Fetch from the DB the key and its translation value, and then apply sort on the result.

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);

  const rawResults = pool.query(
    `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,
    (error, result) => {
      if (error) {
        throw error;
      }
      const wordOrder = req.query.word.split(',');

      result.rows.sort((row1, row2) => {
        return wordOrder.indexOf(row1.Words) - wordOrder.indexOf(row2.Words);
      });

      res.status(200).json(result.rows);
      console.log(result.rows);
    }
  );
};

EDIT

Pay attention that your code is async (DB access is async by nature). Therefore, you need to sort the results just before you send it to the client (just before res.status(200).json call)

BTW, it is better to use some kind of query-builder (like knex ) instead of building the query manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM