sequelize/sequelize · error · Error

Unknown attribute "${options.sourceKey}" passed as sourceKey

Error message

Unknown attribute "${options.sourceKey}" passed as sourceKey, define this attribute on model "${source.name}" first

What it means

In the HasOne constructor (has-one.ts:97), Sequelize verifies that an explicit `sourceKey` exists as an attribute on the source model. The sourceKey is the column the target's foreign key will reference (defaults to the source primary key). An unknown name throws an Error.

Source

Thrown at packages/core/src/associations/has-one.ts:98

   */
  get sourceKeyAttribute(): SourceKey {
    return this.sourceKey;
  }

  readonly inverse: BelongsToAssociation<T, S, TargetKey, SourceKey>;

  readonly accessors: SingleAssociationAccessors;

  constructor(
    secret: symbol,
    source: ModelStatic<S>,
    target: ModelStatic<T>,
    options: NormalizedHasOneOptions<SourceKey, TargetKey>,
    parent?: Association,
    inverse?: BelongsToAssociation<T, S, TargetKey, SourceKey>,
  ) {
    if (options?.sourceKey && !source.getAttributes()[options.sourceKey]) {
      throw new Error(
        `Unknown attribute "${options.sourceKey}" passed as sourceKey, define this attribute on model "${source.name}" first`,
      );
    }

    if ('keyType' in options) {
      throw new TypeError(
        `Option "keyType" has been removed from the BelongsTo's options. Set "foreignKey.type" instead.`,
      );
    }

    super(secret, source, target, options, parent);

    this.inverse =
      inverse ??
      BelongsToAssociation.associate(
        secret,
        target,
        source,

View on GitHub (pinned to 7e1deec499)

Solutions

  1. Define the attribute on the source model.
  2. Use the correct existing attribute, or omit `sourceKey` to use the source primary key.

Example fix

// before
User.hasOne(Profile, { sourceKey: 'uid' }); // User has no 'uid'

// after
const User = sequelize.define('User', {
  uid: { type: DataTypes.UUID, unique: true },
});
User.hasOne(Profile, { sourceKey: 'uid' });
Defensive patterns

Strategy: validation

Validate before calling

function assertSourceKeyExists(sourceModel, sourceKey) {
  if (sourceKey && !sourceModel.getAttributes()[sourceKey]) {
    throw new Error(`sourceKey "${sourceKey}" does not exist on ${sourceModel.name}`);
  }
}
assertSourceKeyExists(User, opts.sourceKey);

Prevention

When it happens

Trigger: `User.hasOne(Profile, { sourceKey: 'uid' })` where `User` has no `uid` attribute.

Common situations: Using an alternate unique key for the association but forgetting to define it on the source; typo; referencing a target-side attribute by mistake.

Related errors


AI-assisted analysis of sequelize/sequelize@7e1deec499 (2026-08-03). Data as JSON: /data/errors/1650718b8079c74e.json. Report an issue: GitHub.