Sequelize create includes eager loaded values

40 Views Asked by At

I am working on a project using:

  • Node.js v20.10.0
  • npm v10.2.3
  • sequelize v6.25.3
  • sequelize-typescript v2.1.6

I have defined the models using sequelize-typescript library. One of the models is:

@Table({ tableName: 'testAttemptDate' })
export default class TestAttemptDate extends Model {
  @PrimaryKey
  @AutoIncrement
  @Column(DataType.INTEGER)
  declare id: number;

  // Foreign key
  @AllowNull(false)
  @ForeignKey(() => TestAttemptHistory)
  @Column(DataType.INTEGER)
  declare testAttemptHistoryId: number;

  @UpdatedAt
  declare updatedAt: Date;

  @CreatedAt
  declare createdAt: Date;

  // Associations
  @HasMany(() => FinalItemAnswer, {
    foreignKey: 'testAttemptDateId',
    onDelete: 'SET NULL',
    onUpdate: 'CASCADE',
  })
  declare finalItemAnswers: ReturnType<() => FinalItemAnswer[]>;

  @BelongsTo(() => TestAttemptHistory)
  declare testAttemptHistory: ReturnType<() => TestAttemptHistory>;
}

It has a foreign key while the rest of its fields should be automatically created during .create function.

Followingly, this is the function that should create a TestAttemptDate entry:

/**
 * Track date of a test attempt
 * @param {number} testAttemptHistoryId
 */
export async function createTestAttemptDate(
  testAttemptHistoryId: number,
): Promise<ITestAttemptDate> {
  return TestAttemptDate.create({ testAttemptHistoryId });
}

However, this function fails with the following error message:

 {
    "message": {
        "name": "SequelizeDatabaseError",
        "parent": {
            "length": 111,
            "name": "error",
            "severity": "ERROR",
            "code": "42703",
            "position": "173",
            "file": "parse_relation.c",
            "line": "3563",
            "routine": "errorMissingColumn",
            "sql": "INSERT INTO \"testAttemptDate\" (\"id\",\"testAttemptHistoryId\",\"createdAt\",\"updatedAt\") VALUES (DEFAULT,$1,$2,$3) RETURNING \"id\",\"testAttemptHistoryId\",\"createdAt\",\"updatedAt\",\"activityId\",\"itemId\";",
            "parameters": [
                3,
                "2024-02-02 14:17:53.108 +00:00",
                "2024-02-02 14:17:53.108 +00:00"
            ]
        },
    }
}

Based on the sql query mentioned in the above error message in the RETURNING part it tries to return activityId and itemId which are not fields of TestAttemptDate but fields of the model associated with the TestAttemptDate.

What can cause this error?

PS: this is part of an API call and the error returned by the server is {"message":"column \"activityId\" does not exist"}.

0

There are 0 best solutions below