Search code examples
typescripttypeorm

Optional Property in TypeORM FindOptionsWhere


I am trying to fetch translations for different types of questions from my database. The problem is, that some questions have options, some do not.

    const where: FindOptionsWhere<QuestionTranslation> = {
      question: {
        // some other props
        options: { // this needs to be optional
          translations: {
            lang: In([localeCode, baseLocaleCode, LocaleCode.en]),
          },
        },
      },
    };

    const questionTranslations = await this.questionTranslationRepository.find({
      where,
    });

If I remove the options property, I get all translations, but the translations for options are obviously missing on questions that have them. If I include it, questions without options are left out.

I want to avoid having to call the database twice (with FindOptionsWhere object that includes or excludes the options property respectively). Something like this would be nice:

        options: {
          [if exists]: {
            translations: {
              lang: In([localeCode, baseLocaleCode, LocaleCode.en]),
            },
          },
        },

Is this possible?


Solution

  • Try with the following approach.

    Wrapping the where-clause in an array, will translate to an OR condition in SQL.

    import { IsNull } from "typeorm";
    
    const questionTranslations = await this.questionTranslationRepository.find({
      where: [
        { question: { options: IsNull() } },
        { question: {
          options: {
            translations: {
              lang: In([localeCode, baseLocaleCode, LocaleCode.en]),
            },
          },
        }}
      ],
    });