Search code examples
nestjstypeorm

Can we have projectors in typeorm's findOne as we can have in MongoDb's method?


I am just curious about if we can provide projectors in typeorm's findOne method? I am using postgres databse.

What I need is just an id from a table for provided email. What I am getting is all the details of the user.

repository.findOne({email: '[email protected]'})

This gives me all the details. However I just want to extract id of that particular user

Can we pass projectors to the above query? for e.g.

repository.findOne({email: 'email'},{id:1})

Solution

  • Yes, it's possibly. You need to pass options to your findOne function so your code would look like this:

    async getOne(email: string): Partial<RepositoryEntity> {
      const foundRow = repository.findOne({
        where: {
          email: email
        },
        select: 'id'
      });
      return foundRow;
    }
    

    OR

    async getOne(email: string): Partial<RepositoryEntity> {
      const foundRow = repository.findOne(
       { email: email },
       { select: 'id' }
      );
      return foundRow;
    }
    

    You can see the source code where the types are defined here