NestJs typeorm - null value in column "***" violates not-null constraint on save method

Viewed 2735

I am facing an issue when trying to update multiply records in once. I am using method save of Repository of entity.

This is how it is used as written in the docs : save - Saves a given entity or array of entities. If the entity already exists in the database, then it's updated. If the entity does not exist in the database yet, it's inserted. It saves all given entities in a single transaction (in the case of entity manager is not transactional). Also supports partial updating since all undefined properties are skipped. In order to make a value NULL, you must manually set the property to equal null.

await manager.save(user);
await manager.save([
    category1,
    category2,
    category3
]);

This is how I am using it :

@Injectable()
export class PersonService{
  constructor(
    @InjectRepository(PersonEntity)
    private personService: Repository<PersonEntity>,
  ) {}

  async saveAll(persons: PersonEntity[]) {
    return await this.personService.save(persons);
}
}

The persons input param contains only keys attr and wanted attr to update.

And I am getting this error: [ExceptionsHandler] null value in column "*****" violates not-null constraint +17149ms QueryFailedError: null value in column "****" violates not-null constraint

Thank you for you help!

1 Answers

The save() method check if columns with PrimaryColumn() decorator contains values to determine whether to update or insert the record.

For example:

@Entity({ name: 'persons'})
export class Person {
  @PrimaryColumn()
  id: number

  @Column()
  name: string

  @Column()
  age: number
}

Now assuming you passed the following person entity to save()

[
    {
      "id": 1,
      "name": "John",
      "age": 7
    },
    {
      "id": null,
      "name": "Bob",
      "age": 8
    }
]

John will be updated, while Bob will be inserted.

In your case, I am suspecting that you do not provide value to your primary column so theTypeORM trying to insert the record into db and that record contains null value for the non-null column.

Related