Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

sequelize.js - Sequelize, Typescript accessing results of a raw query

I'm using Sequlize and Typescript. Have to do some raw query to get data (All the Parent Categories of the existing categories) from the PostgreSQL database. as an array of objects. Basically, recursive SELECT statement.

According to the Sequelize manual, the raw query returns two arguments, result and metadata (usually a number of affected rows) unless you specify the query type explicitly. In this case, it should return just the result.

So eventually my code looks like this:

const parentCat = await SomeDataModel.sequelize?.query(
          getAllParentCategories,
          {
            replacements: { subcategory_code: ARRAY_OF_CATEGORIES_TO_SEARCH },
            type: QueryTypes.SELECT
          }
        );

According to the Types assigned, it returns parentCat that type of [undefined, number] | undefined`. Assuming that the first argument in the array is the result.

if I Try to console.log the result it returns an array of objects (as intended):

[
  { category_code: 'Value1' },
  { category_code: 'Value2' },
  { category_code: 'Value3' },
  { category_code: 'Value4' },
  { category_code: 'Value5' }
]

However, if I try to deconstruct this array and use it keep complaining that the object is possibly undefined. Even though I check that array exists, elements are not undefined or null, and the length of the array is more than 0)

And then when I try to access the object's property (e.g: category_code) it keeps complaining that the Property 'category_code' does not exist on type 'number'. My code is:

if (parentCat !== undefined && parentCat.length > 0) {
          const additionalCats = parentCat.reduce<string[]>((acc, currentCategory) => {
            return currentCategory ? [...acc, currentCategory.category_code] : acc;
          }, [])
          console.log(additionalCats);
        }

Plus, the ternary operation is redundant here anyway, cause DB either returns an empty array or array of objects with categories in it. Since I already checking for the array not being empty I think it doesn't make a lot of sense. But Typescript keeps complaining otherwise if I try to get rid of it.

Maybe someone can suggest anything to tackle this?

question from:https://stackoverflow.com/questions/65930260/sequelize-typescript-accessing-results-of-a-raw-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...