Mikroorm check if entity is deleted

Viewed 528

em.nativeDelete returns how many entities are deleted so I can do:

const count = await this.em.nativeDelete(User, {id});

if(!count){
    throw new EntitiyNotFoundException(`User with id: ${id} is not found`);
}

Is there a way to do the same with remove(). It returns the EntityManager how can I check if the there is an entity deleted:

const user = this.em.getReference(User, id);
await this.em.remove(user); 
1 Answers

With em.remove() you would first need to load the entity to see if it exists, there is no way to access the deleted count from UoW as flushing is not bound to that particular query, it can consist of many queries for many different entities/tables and operations (CRUD).

You want to do that inside explicit transation, to ensure other requests won't delete the record you just retrieved from database.

await em.transactional(async em => {
  // this will throw if not found, you might want to use `em.findOne` and 
throw yourself
  const user = await em.findOneOrFail(User, id);
  em.remove(user); // flush will be called automatically when using explicit transactions
});
Related