sequelize-typescript
sequelize-typescript copied to clipboard
@HasMany Error - Cannot read properties of undefined
Issue
Following https://github.com/sequelize/sequelize-typescript#one-to-many I have my Models set up correctly. However, I am getting an error Cannot read properties of undefined (reading "topics")
Versions
package.json
"@nestjs/axios": "^0.1.0",
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/passport": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/sequelize": "^9.0.0",
"@nestjs/swagger": "^6.1.2",
"@nrwl/angular": "^14.7.5",
"@types/snowflake-sdk": "^1.6.8",
"angular-auth-oidc-client": "^14.1.4",
"express-session": "^1.17.3",
"mysql2": "^2.3.3",
"passport": "^0.6.0",
"passport-okta-oauth20": "^1.1.0",
"passport-openidconnect": "^0.1.1",
"reflect-metadata": "^0.1.13",
"rxjs": "~7.5.0",
"sequelize": "^6.24.0",
"sequelize-typescript": "^2.1.3"
Actual behavior
Here is my set up:
app.module.ts
@Module({
imports: [
AuthModule,
SequelizeModule.forRoot({
dialect: 'snowflake',
host: 'localhost',
dialectOptions: {
// put your snowflake account here,
port: '3333',
account: 'blah',
application: 'SNOWFLAKE',
// below option should be optional
role: 'blah',
warehouse: 'blah',
schema: 'blah'
},
// same as other dialect
username: 'blah',
password: 'blah',
database: 'blah',
define : {
freezeTableName: true
},
models: ([UserTopic, User, Topic]),
quoteIdentifiers: false
}), DatabaseModule],
controllers: [AppController, AuthController],
providers: [AppService],
})
export class AppModule {}
database.service.ts
@Injectable()
export class DatabaseService {
constructor(
@InjectModel(User)
@InjectModel(Topic)
@InjectModel(UserTopic)
private sequelize: Sequelize,
) { }
getUser(email: string) {
return User.findOne({where: { email: email }, include: ["topics"]});
}
}
user.entity.ts
import { Column, Model, Table, HasMany } from "sequelize-typescript";
import { UserTopic } from "./userTopic.entity";
@Table
export class User extends Model {
@Column({primaryKey: true})
id: string;
@Column
email: string;
@Column
firstName: string;
@Column
lastName: string;
@Column
login_timestamp: Date;
@HasMany(() => UserTopic, { foreignKey: 'userId'})
topics: UserTopic[];
}
userTopic.entity.ts
import { Column, Model, Table, ForeignKey, BelongsTo } from "sequelize-typescript";
import { Topic } from "./topic.entity";
import { User } from "./user.entity";
@Table
export class UserTopic extends Model {
@Column({primaryKey: true})
id: string;
@ForeignKey(() => User)
@Column
userId: string;
@BelongsTo(() => User, { foreignKey: 'userId' })
user: User
@ForeignKey(() => Topic)
@Column
topicId: string;
@BelongsTo(() => Topic, { foreignKey: 'topicId' })
topic: Topic
@Column
sequence: number;
}
Results:

Expected behavior
The Executing query is correct and if ran in the DB no issues. What am I missing decorator/attribute wise that is causing it to fail on this @HasMany association?