Sequelize, Typescript accessing results of a raw query

Issue

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?

Solution

I was trying to do a crud.find(p => p.Permission === "Update")?.Permission;

but the error said: Property does not exist on type ‘object’.ts(2339)
I found the solution here.

Sequelize: mapping between raw data and model

He said: You can set the option mapToModel: true in your query to instruct Sequelize to translate the returned field names to the equivalent in the model you provide.

const User = sequelize.define('user', {
  userId: {
  field: 'user_id',
  type: DataTypes.BIGINT,
  primaryKey: true
})

sequelize.query(
  'select user_id from user where user_id > 1000',
  {
    mapToModel: true,
    model: User
  }
)

Answered By – Aldo

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.