Search code examples
node.jsormmikro-orm

What is EntityManager, EntityRepository in mikro-orm and difference between that?


Please explain in very simple language with proper example, I have already followed official document but I did not understand clearly.


Solution

  • EntityRepository is a convenient way of accessing entities from a database since it handles a single entity, it carries the entity name so we don't have to pass it in find(), findAll() calls.

    Example:

    import { EntityRepository } from '@mikro-orm/postgresql';
    import { User } from './entities/user.entity';
    
    @Injectable()
    export class UserService {
        constructor(
          @InjectRepository(User)
          private readonly userRepository: EntityRepository<User>,
        ) {}
    
        async getUserByPhone(phone: string) {
          return await this.userRepository.findOne({ phone }); //we are not passing any entity here while making a database call.
        }
    }
    

    Whereas, EntityManager handles all entities. That's why when using find() and findAll() calls we need to mention which entity we want to access.

    Example:

    return await orm.em.findOne(User, { phone: phoneNumber }); //we have to pass User entity here while making a database call.