#2372·mikro-orm

Throw exception if accessing primary key on unflushed entity

Author: parisholleyCreated Nov 8, 2021Updated Feb 27, 2026
Labelsenhancement

Is your feature request related to a problem? Please describe. If a developer is unaware that an entity has been passed to them without an id, they may end up attempting to take action on it (eg: serialize to JSON) and never catch it, especially since there is no compile-time type checking to protect against this.

Describe the solution you'd like When an entity is created through manager.create(), intercept calls to the primary key prior to flush and throw an exception, telling the user they need to flush first.

Describe alternatives you've considered Could potentially have a base entity class with get id() and set id() which includes some check, though it isn't clear what the right approach is for determining "flushed", isInitialized?

This is what I am using now as a workaround:

typescript
export default abstract class BaseEntity {
  @Field(() => ID, { name: 'id' })
  private _id: string;

  get id(): string {
    if (!this._id) {
      const error = new Error(`Entity has not been given a id yet, please flush.`);

      const stack = error.stack.split('\n');

      if (stack[2].includes('@mikro-orm')) {
        // hack to allow mikro to process inside unit of work
        return undefined;
      }

      throw error;
    }

    return this._id;
  }

  @PrimaryKey({ type: BigIntType, fieldName: 'id', getter: true })
  private set id(value: string) {
    this._id = value;
  }
}