Skip to content

Intance model properties are undefined #778

Open

Description

@gideaoms

Versions

  • sequelize: 5.21.7
  • sequelize-typescript: 1.1.0
  • typescript: 3.8.3

I'm submitting a ...

[ x ] bug report
[ ] feature request

Actual behavior:
I execute a findOne function to get a model instance, but the properties are undefined

Expected behavior:
I would like to get the properties values

Steps to reproduce:

const city = await CityModel.findOne({ where: { name: 'example' } })
console.log(city.name);

Related code:
If I execute the city.getDataValue('name') I see the right value, but simply running city.name I get undefined.

If I execute console.log(city) all works well:

CityModel {
    dataValues: {
        id: 'fb73e40a-9055-42b8-9a21-d8368ef13222',
        name: 'Example',
        createdAt: 2020-04-27,
        updatedAt: 2020-04-27
    },
    _previousDataValues: {
        id: 'fb73e40a-9055-42b8-9a21-d8368ef13222',
        name: 'Example',
        createdAt: 2020-04-27,
        updatedAt: 2020-04-27
    },
    ...
},

My model:

import {
  Model,
  Table,
  DataType,
  Column,
  PrimaryKey,
  Default,
  HasMany,
} from 'sequelize-typescript';
import UserModel from './user.model';

@Table({ tableName: 'Cities', timestamps: true })
class CityModel extends Model<CityModel> {
  @PrimaryKey
  @Default(DataType.UUIDV4)
  @Column(DataType.UUIDV4)
  id!: string;

  @Column(DataType.STRING)
  name!: string;

  @Column(DataType.STRING)
  initials!: string;

  @Column(DataType.STRING)
  status!: string;

  @HasMany(() => UserModel, 'cityId')
  users!: UserModel[];
}

export default CityModel;

Activity

  1. wdzeng commented on Jan 13, 2021

    @wdzeng

    Same problem. It seems like I need to call getDataValue.

  2. jrm2k6 commented on Feb 22, 2021

    @jrm2k6

    I created a quick repo here showing the issue: https://github.com/jrm2k6/laughing-octo-enigma

    When running the command to execute a findAll this is what I get back:

    Executing (default): SELECT "uuid", "name", "createdAt", "updatedAt", "deletedAt" FROM "users" AS "users" WHERE ("users"."deletedAt" IS NULL);
    [
      users {
        dataValues: {
          uuid: '36497139-77d2-4edb-ba49-481a589f2f8c',
          name: 'John Smith',
          createdAt: 2021-02-22T01:15:35.993Z,
          updatedAt: null,
          deletedAt: null
        },
        _previousDataValues: {
          uuid: '36497139-77d2-4edb-ba49-481a589f2f8c',
          name: 'John Smith',
          createdAt: 2021-02-22T01:15:35.993Z,
          updatedAt: null,
          deletedAt: null
        },
        _changed: {},
        _modelOptions: {
          timestamps: true,
          validate: {},
          freezeTableName: false,
          underscored: false,
          paranoid: true,
          rejectOnEmpty: false,
          whereCollection: null,
          schema: null,
          schemaDelimiter: '',
          defaultScope: {},
          scopes: {},
          indexes: [],
          name: [Object],
          omitNull: false,
          sequelize: [Sequelize],
          hooks: {}
        },
        _options: {
          isNewRecord: false,
          _schema: null,
          _schemaDelimiter: '',
          raw: true,
      1 node_modules/
          attributes: [Array]
        },
        isNewRecord: false,
        uuid: undefined,
        name: undefined
      }
    ]
    

    I also use sequelize-typescript with nestjs and I am not having the same issue but haven't found out if it does something different.

    Hope that helps so that we can figure out if we are doing something wrong or not.

    Thanks!

  3. gideaoms commented on Feb 22, 2021

    @gideaoms
    Author

    @jrm2k6 The problem is I can not get the value just using user.name, but if I use user.getDataValue('name') works fine.

    I tested it with your github project and the result was the same.

  4. jrm2k6 commented on Feb 22, 2021

    @jrm2k6

    @gideaoms Yes, this is why I added a way for anybody to get the same results as we have and see if it is something wrong with our setup or not. Makes it easier for a maintainer to understand the issue and be able to debug if needed.

  5. jrm2k6 commented on Feb 28, 2021

    @jrm2k6

    Ok I did some more investigating and I think in my example, it boils down to using babel-node vs ts-node.
    In here: jrm2k6/laughing-octo-enigma@e745244
    I changed my tsconfig to use commonjs instead of esnext, and use ts-node instead of babel-node.

    When I run node -r ts-node/register index.ts it lets me access the model properties directly. I am not 100% sure yet but I think with the way my babel-node config is set up, it will generate model properties automatically initialized with undefined, overriding what sequelize-typescript might be doing when it comes to accessing model properties. Still a guess though.

    Here we go: #612

  6. gideaoms commented on Mar 1, 2021

    @gideaoms
    Author

    Yep, it makes sense.

  7. triesmon commented on Sep 23, 2021

    @triesmon

    Encountered this issue when upgrading typescript from 3 to 4. Data was only in dataValues but not in the class fields. Setting useDefineForClassFields to true in my tsconfig seems to have fixed it.

  8. nathanlepori commented on Sep 30, 2021

    @nathanlepori

    That's weird. For me doing the exact opposite (setting useDefineForClassFields to false) fixed it. I'm targeting ESNext on Node 14.

  9. triesmon commented on Sep 30, 2021

    @triesmon

    I had actually set it to false but just wrote the wrong value in the comment. Thanks.

  10. devuxer commented on Oct 19, 2021

    @devuxer

    For me, it had nothing to do with babel (which I wasn't using to begin with).

    The solution was entirely to add "useDefineForClassFields": "false" to my tsconfig.json.

    Thanks, @triesmon!

  11. tommoor commented on Jan 7, 2022

    @tommoor

    This appears to be the change (and some surrounding discussion) in babel that breaks this behavior:

    babel/babel#11747

  12. ephys commented on Jan 7, 2022

    @ephys
    Member
  13. tommoor commented on Jan 7, 2022

    @tommoor

    The new documentation is a big improvement over where we were at a week ago, unfortunately the declare keyword trick only works with tsc tooling and not with babel due to the above linked PR.

  14. ephys commented on Jan 7, 2022

    @ephys
    Member

    The fact that babel still emits public class fields tagged with declare when using decorators is problematic. Makes sequelize/sequelize#14300 all the more pressing.

  15. tommoor commented on Jan 7, 2022

    @tommoor

    I have worked around this in my project with a model class decorator – it's very ugly, but the approach could be used as another way to fix the issue more formally in sequelize by applying the getter/setters after the model constructor.

    https://github.com/outline/outline/blob/main/server/models/decorators/Fix.ts

  16. keysmusician commented on Apr 28, 2023

    @keysmusician

    I had this problem as well in Deno 1.32 which doesn't support useDefineForClassFields. I fixed it by just declare-ing all my fields:

    ...
    
      @Column({
        allowNull: false,
        defaultValue: "",
      })
      declare myField: string
    
  17. d00rsfan commented on Jul 5, 2023

    @d00rsfan

    First of all great project! Strange that README.md not updated with 'declare' workaround, as well as with ReturnType<() => Model>; for associated fields.
    To prepare PR with "declare" column attributes and "ReturnType" associated attributes?

  18. kbirger commented on Apr 16, 2024

    @kbirger

    I landed here with a similar issue. The issue arose when I updated my tsconfig to the recommended settings for node 20

    It seems that setting "lib": ["ES2023"] causes this issue. Upon some investigation, it actually seems like setting lib to this value may switch on useDefineForClassFields. After I forced useDefineForClassFields off, the issue went away. I would not consider this a resolution though, because it seems like the wrong decision long term.
    TSConfig:

    {
      "compilerOptions": {
        "allowJs": false,
        "baseUrl": "./",
        "declaration": true,
        "useDefineForClassFields": false,
        "emitDecoratorMetadata": true,
        // "esModuleInterop": true,
        "experimentalDecorators": true,
        "forceConsistentCasingInFileNames": true,
        "incremental": true,
        "module": "CommonJS",
        "moduleResolution": "Node",
        "noImplicitReturns": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "outDir": "./dist",
        "removeComments": true,
        "skipLibCheck": true,
        "strict": true,
        "target": "ES2017",
        "lib": [
          "ES2023"
        ],
        "typeRoots": [
          "node_modules/@types",
          "src/types"
        ],
        "resolveJsonModule": true,
        "sourceMap": true,
        "inlineSources": true,
        "sourceRoot": "/",
        "allowSyntheticDefaultImports": true
      },
      "exclude": [
        "node_modules",
        "dist",
        "knex/templates",
      ]
    }

    Node: 20.11.0
    TypeScript: 5.4.5 (although issue appeared on older version too)
    Sequelize: 6.37.3
    Sequelize-TypeScript: 2.1.6

  19. mopcweb commented on Apr 23, 2024

    @mopcweb

    For me, it had nothing to do with babel (which I wasn't using to begin with).

    The solution was entirely to add "useDefineForClassFields": "false" to my tsconfig.json.

    Thanks, @triesmon!

    Thanks so much! Spent a lot of time trying to find out a problem, this solved my issue!

  20. intellix commented on Oct 13, 2024

    @intellix
    Contributor

    we just ran into this issue after replacing webpack with rspack and I didn't even notice it was a problem until I ran a query and everything was undefined. We've got around 200 models and thousands of fields and if we try to make the "declare" change, there's going to be at least 1 field that makes it's way to production either in the initial push for it, or someone's rebase.

    Unless there's an eslint rule that can prevent it from reaching production I think it's quite dangerous that it's only a warning at runtime and for it to essentially silently fail. Nobody is going to notice an undefined property for days/weeks/months after hours of debugging

    I'd love to go with this but it's too dangerous to try. Has anyone found an eslint rule that can enforce it on all properties that extend Model perhaps? TypeScript only prevents it on the reserved fields: id, createdAt, updatedAt etc, but the custom fields are only added magically by sequelize.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions