Sequelize-typescript: Model not initialized - "User" needs to be added to a Sequelize instance before "getTableName" can be called

Created on 19 Dec 2018  路  17Comments  路  Source: RobinBuschmann/sequelize-typescript

This is a serverless API with intention of using on AWS Lambda. Running locally and hitting endpoint with Postman. I've been spinning my gears on this for a few days and unable to figure out what I may be doing wrong. Please help @RobinBuschmann :(

At the root, I have sequelize.ts...

````
import { Sequelize } from "sequelize-typescript";
import { config } from "./config";
import User from "./repository/models/user.model";

const db: any = new Sequelize({
host: config.rds,
database: config.database,
dialect: 'postgres',
username: 'config.databaseUserName,
password: config.databasePassword,
pool: {
max: 10,
min: 0,
acquire: 12000,
idle: 1000
}
});

db.addModels(User);

export default db;
````

My lambda handler is defined as ..

import { Handler, Context, Callback } from 'aws-lambda';
import UserService from '../services/user.service';
import db from "../sequelize";

const createUser: Handler = (
  event: any,
  context: Context,
  callback: Callback
) => {
  context.callbackWaitsForEmptyEventLoop = false;

  const req = event.body;
  const userService = new UserService(db);
  const headers = {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Credentials': true
  };

  let response: CreateUserResponse;
  let statusCode = 200;
  let body = { message: 'Created new user in RDS successfully!', input: event };

  console.log(`Creating user...`);
  userService.saveUser(req);

  response = { statusCode, headers, body };

  callback(undefined, JSON.stringify(response));
};

Which calls a UserService...

import UserRepository from "../repository/user.repository";

class UserService {
    private userRepository: UserRepository;
    private db: any;

    constructor(db: any) {
        this.db = db;
        this.userRepository = new UserRepository();
    }

    async saveUser(user: any): Promise<User> {
        .... some logic here ...

        return await this.userRepository.createUser(user);
    }
}

export default UserService;

And in the UserRepository...

import User from "./models/user.model";

class UserRepository {

    async createUser(userData: User): Promise<User> {
        const user: any = new User(userData);
        console.dir(`DB: Saving user...`);
        return await user.save();
    }
}

export default UserRepository;

Which results in...

[ 'Error: Model not initialized: "User" needs to be added to a Sequelize instance before "getTableName" can be called.',
  'at new ModelNotInitializedError (/Users/Chris.Robot/funrun/aws-api/node_modules/sequelize-typescript/lib/models/errors/ModelNotInitializedError.js:18:16)',
  'at checkInitialization (/Users/Chris.Robot/funrun/aws-api/node_modules/sequelize-typescript/lib/models/BaseModel.js:64:23)',
  'at Function._target.(anonymous function) [as getTableName] (/Users/Chris.Robot/funrun/aws-api/node_modules/sequelize-typescript/lib/models/BaseModel.js:34:21)',
  'at Function.init (/Users/Chris.Robot/funrun/aws-api/node_modules/sequelize/lib/model.js:991:28)',
  'at models.forEach.model (/Users/Chris.Robot/funrun/aws-api/node_modules/sequelize-typescript/lib/models/v4/Sequelize.js:56:26)',
  'at Array.forEach (<anonymous>)',
  'at Sequelize.defineModels (/Users/Chris.Robot/funrun/aws-api/node_modules/sequelize-typescript/lib/models/v4/Sequelize.js:48:16)',
  'at Sequelize.BaseSequelize.addModels (/Users/Chris.Robot/funrun/aws-api/node_modules/sequelize-typescript/lib/models/BaseSequelize.js:63:14)',
  'at Object.<anonymous> (/Users/Chris.Robot/funrun/aws-api/sequelize.ts:20:4)',
  'at Module._compile (module.js:653:30)',
  'at Object.Module._extensions..js (module.js:664:10)',
  'at Module.load (module.js:566:32)',
  'at tryModuleLoad (module.js:506:12)',
  'at Function.Module._load (module.js:498:3)',
  'at Module.require (module.js:597:17)',
  'at require (internal/module.js:11:18)',
  'at Object.<anonymous> (/Users/Chris.Robot/funrun/aws-api/handlers/createUser.handler.ts:5:1)',
  'at Module._compile (module.js:653:30)',
  'at Object.Module._extensions..js (module.js:664:10)',
  'at Module.load (module.js:566:32)',
  'at tryModuleLoad (module.js:506:12)',
  'at Function.Module._load (module.js:498:3)',
  'at Module.require (module.js:597:17)',
  'at require (internal/module.js:11:18)',
  'at Object.createHandler (/Users/Chris.Robot/funrun/aws-api/node_modules/serverless-offline/src/functionHelper.js:104:21)',
  'at handler (/Users/Chris.Robot/funrun/aws-api/node_modules/serverless-offline/src/index.js:590:40)',
  'at Object.internals.handler (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/handler.js:96:36)',
  'at request._protect.run (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/handler.js:30:23)',
  'at module.exports.internals.Protect.internals.Protect.run (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/protect.js:64:5)',
  'at exports.execute (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/handler.js:24:22)',
  'at each (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/request.js:384:16)',
  'at iterate (/Users/Chris.Robot/funrun/aws-api/node_modules/items/lib/index.js:36:13)',
  'at done (/Users/Chris.Robot/funrun/aws-api/node_modules/items/lib/index.js:28:25)',
  'at internals.Auth.payload (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/auth.js:223:16)',
  'at each (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/request.js:384:16)',
  'at iterate (/Users/Chris.Robot/funrun/aws-api/node_modules/items/lib/index.js:36:13)',
  'at done (/Users/Chris.Robot/funrun/aws-api/node_modules/items/lib/index.js:28:25)',
  'at onParsed (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/route.js:402:20)',
  'at Subtext.parse (/Users/Chris.Robot/funrun/aws-api/node_modules/hapi/lib/route.js:423:20)',
  'at next (/Users/Chris.Robot/funrun/aws-api/node_modules/subtext/lib/index.js:45:26)',
  'at Wreck.read (/Users/Chris.Robot/funrun/aws-api/node_modules/subtext/lib/index.js:242:16)',
  'at finish (/Users/Chris.Robot/funrun/aws-api/node_modules/subtext/node_modules/wreck/lib/index.js:374:20)',
  'at wrapped (/Users/Chris.Robot/funrun/aws-api/node_modules/hoek/lib/index.js:879:20)',
  'at module.exports.internals.Recorder.onReaderFinish (/Users/Chris.Robot/funrun/aws-api/node_modules/subtext/node_modules/wreck/lib/index.js:449:16)',
  'at Object.onceWrapper (events.js:313:30)',
  'at emitNone (events.js:111:20)',
  'at module.exports.internals.Recorder.emit (events.js:208:7)',
  'at finishMaybe (_stream_writable.js:613:14)',
  'at endWritable (_stream_writable.js:621:3)',
  'at module.exports.internals.Recorder.Writable.end (_stream_writable.js:572:5)',
  'at IncomingMessage.onend (_stream_readable.js:595:10)',
  'at Object.onceWrapper (events.js:313:30)',
  'at emitNone (events.js:111:20)',
  'at IncomingMessage.emit (events.js:208:7)',
  'at endReadableNT (_stream_readable.js:1064:12)',
  'at _combinedTickCallback (internal/process/next_tick.js:139:11)' ]

Most helpful comment

@harryhan24 your arguments for calling this a awful lib, does not exist.
Do the opensource community a favor and leave it. We dont need guys that throws garbage comments based on theyr lack of knowledge.

All 17 comments

Hey @robotlemons, is there a reason why you've any'd the sequelize instance? If you wouldn't, the typescript compiler would have complained about this line:

db.addModels(User);

Because addModels expects an array of model references like: addModels([User]);

Hope this helps!

Sorry, @RobinBuschmann.. that's my fault. It is defined that way as an Array and the same error persists.

The model file...

import {
  Table,
  Column,
  Model,
  CreatedAt,
  UpdatedAt,
  PrimaryKey
} from 'sequelize-typescript';

@Table({
  timestamps: true
})
export default class User extends Model<User> {
  @PrimaryKey
  @Column
  id: integer;

  @Column
  firstName: string;

  @Column
  lastName: string;

  @Column
  birthday: Date;

  @Column
  gender: string;

  @Column
  grade: number;

  @Column
  teacher: string;

  @Column
  isParent: boolean;

  @Column
  email: string;

  @Column
  phoneNumber: string;

  @Column
  relationship: string;

  @CreatedAt
  @Column
  createdAt: Date;

  @UpdatedAt
  @Column
  updatedAt: Date;
}

@RobinBuschmann could it be that the table isnt created in the DB yet?

So I can see the instance of sequelize when I do a console.dir(db) before calling addModels ... the error is happening when I do addModels([User])

@RobinBuschmann combing through BaseSequelize.js and in the addModels method, nothing else after this.defineModels() happens (and the next line is what sets the model to initialized).

in defineModels in Sequelize.js .. I can see the model and init is called with attributes/options but that's where things die and I see no error or reason for it.

doing a console.dir(Models: ${models}); after this.defineModels is called in BaseSequelize.js .. doesn't log anything at all.

these are the options from inside defineModels

{ createdAt: 'createdAt',
  timestamps: true,
  validate: {},
  updatedAt: 'updatedAt',
  instanceMethods: User {},
  classMethods: [Function: User],
  modelName: 'User',
  sequelize:
   Sequelize {
     options:
      { dialect: 'postgres',
        dialectModule: null,
        dialectModulePath: null,
        host: 'stuff',
        protocol: 'tcp',
        define: [Object],
        query: {},
        sync: {},
        timezone: '+00:00',
        logging: [Function: bound consoleCall],
        omitNull: false,
        native: false,
        replication: false,
        ssl: undefined,
        pool: [Object],
        quoteIdentifiers: true,
        hooks: {},
        retry: [Object],
        transactionType: 'DEFERRED',
        isolationLevel: null,
        databaseVersion: 0,
        typeValidation: false,
        benchmark: false,
        database: 'stuff',
        username: 'stuff',
        password: 'stuff' },
     config:
      { database: 'stuff',
        username: 'stuff',
        password: 'stuff!',
        host: 'stuff',
        port: 5432,
        pool: [Object],
        protocol: 'tcp',
        native: false,
        ssl: undefined,
        replication: false,
        dialectModule: null,
        dialectModulePath: null,
        keepDefaultTimezone: undefined,
        dialectOptions: undefined },
     dialect:
      PostgresDialect {
        sequelize: [Circular],
        connectionManager: [Object],
        QueryGenerator: [Object] },
     queryInterface: QueryInterface { sequelize: [Circular], QueryGenerator: [Object] },
     models: {},
     modelManager: ModelManager { models: [], sequelize: [Circular] },
     connectionManager:
      ConnectionManager {
        sequelize: [Circular],
        config: [Object],
        dialect: [Object],
        versionPromise: null,
        dialectName: 'postgres',
        pool: [Object],
        lib: [Object],
        nameOidMap: {},
        enumOids: [Object],
        oidParserMap: Map {} },
     importCache: {},
     test:
      { _trackRunningQueries: false,
        _runningQueries: 0,
        trackRunningQueries: [Function: trackRunningQueries],
        verifyNoRunningQueries: [Function: verifyNoRunningQueries] },
     throughMap: {},
     _: {} } }

Can you post your tsconfig?

@rationalthinker1 thanks for helping..

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": [ "es6", "dom" ],
    "moduleResolution": "node",
    "rootDir": "**/*",
    "sourceMap": true,
    "allowJs": true,
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "noImplicitReturns": true,
    "preserveConstEnums": true,
    "suppressImplicitAnyIndexErrors": true,
    "forceConsistentCasingInFileNames": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true
  },
  "exclude": [ "node_modules", "build" ],
  "types": [ "typePatches" ]
}

Try rearranging the order. Run "import User from "./repository/models/user.model";" after db instatiates. Also, try running in the beginning of the app.

@rationalthinker1 did all those and still same error message.

I put it into the Lambda handler instead of outside the handler, same error.

@rationalthinker1 @RobinBuschmann thanks for trying to help but i had to move on and use another ORM.

I am facing the same issue. @robotlemons Can you please suggest which ORM did you move onto?

@piyushkantm I don鈥檛 want to name some other project on someone else鈥檚 work but it was another that supports typescript. Best of luck

@robotlemons I respect your attitude and also apologise for this unfair request.

However after giving some time on the issue i was able to identify that this error was because of a version mismatch. I had 5.beta installed when i installed sequelize using npm install sequelize --save.

@piyushkantm may have been same problem for me, thanks for the information!

this lib is awful :-( same here!

@harryhan24 your arguments for calling this a awful lib, does not exist.
Do the opensource community a favor and leave it. We dont need guys that throws garbage comments based on theyr lack of knowledge.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fareshan picture fareshan  路  3Comments

nandox5 picture nandox5  路  3Comments

fareshan picture fareshan  路  4Comments

JustGreg picture JustGreg  路  4Comments

mikew picture mikew  路  4Comments