When an undefined value is passed in a WHERE condition, it is interpreted as a true or matching condition in TypeORM

After some testing, I came across an interesting quirk with typeorm. It turns out that if a property in the WHERE clause of a FIND query (such as find, findOne, findBy, etc) is undefined, it behaves as if it's true and returns records - returning the first record for findOne and all records for find.

I understand that this can be avoided by using validators or an IF statement to check against undefined properties. However, I'm curious if there's a direct way within typeorm itself to handle this without additional checks.

Here's a snippet of what I observed:

const client = await this.clientRepository.findOne({
        where: {
          id: payload.clientId //undefined
        }
      });

Surprisingly, I was able to retrieve the first record from the client table even though clientId was undefined.

Answer №1

This particular problem is well-documented.

An efficient workaround within typeORM itself is to utilize the Equal() method provided by typeORM.

const user = await this.userRepository.findOne({
        where: {
          id: Equal(payload.userId)
        }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

Error: The argument passed to the function must be an Array type. Undefined value was received instead of an array

Looking for some assistance with this coding issue, hoping someone with expertise can lend a hand! (Not my forte) I've written this Typescript code snippet for a basic CloudFunction export const add2list = functions.https.onRequest((req:any , res:any ...

Describing a property of an interface as the determined form of a conditional type that is generic

I am currently working on defining an interface that includes a method with a conditional function definition. For example: interface Example<T> { func: T extends string ? () => string : () => number; } class ExampleClass<T extends str ...

Is it necessary for the version of the @types packages in TypeScript to match their non-types packages?

Are @types and untyped packages versioned the same way? npm i bluebird @types/bluebird -S returns "@types/bluebird": "^3.5.0", "bluebird": "^3.5.0", This seems logical. npm i request @types/request -S yields "@types/request": "0.0.41", "request": "^2. ...

The issue with npm modules not appearing in EMCA2015 JS imports persists

I am currently in the process of developing a mobile application with Nativescript using the Microsoft Azure SDK. To get started, I installed the SDK via npm by running this command: $ npm install azure-mobile-apps-client --save However, upon attempting ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

Transforming SQL statement into TypeORM query

Here is a simple SQL query that I have: SELECT c.name, c.planned, ( SELECT COALESCE(SUM(t.amount), 0) FROM public.transaction AS t WHERE t."categoryId" = c.id ) AS actual, c.type, c.id, c."userId" FROM public.category AS c; I am attempting to ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

Execute various Office Scripts functions within a single script based on the button that is selected

Imagine you have an Excel spreadsheet with two buttons named populate-current and populate-all. Both buttons execute the same Office Script function that looks something like this: function populateByRowIndex(workbook: ExcelScript.Workbook, rowIndex: numbe ...

Experience the power of combining React with typescript, webpack, and ui-router-react for

After carefully studying the ui-router-react documentation (), I am encountering several challenges with webpack compilation when importing import {UIRouter, UIView, UISref, UISrefActive, pushStateLocationPlugin} from 'ui-router-react'; This is ...

I am experiencing a strange situation in node.js where the `then` condition of a Promise is not being executed as expected

I am currently troubleshooting a Promise scenario and I am puzzled as to why the second then condition is failing to execute in the setup method. In my app.js code, I can see that the initialize() function is being called and it properly awaits the complet ...

Deciphering TS2345: "The argument supplied, known as 'typeof MyComponent', cannot be assigned to the specified parameter type"

I am facing an issue while attempting to integrate a Typescript React component with react-onclickoutside. The error message that I encounter is as follows: TS2345: Argument of type 'typeof MyComponent' is not assignable to parameter of type &apo ...

Encounter an error message stating "Request failed with status code 502 nginx in Next.js TypeScript."

After setting up Next.js typescript with Kubernetes NGINX Ingress, I encountered a problem where specific routes were returning a 502 error. For example, the route /test works fine, but /login does not. I'm unsure whether the issue lies with Kubernete ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

Assigning enum type variable using string in TypeScript

How can I dynamically assign a value to a TypeScript enum variable? Given: enum options { 'one' = 'one', 'two' = 'two', 'three' = 'three'} let selected = options.one I want to set the variable " ...

What is the best strategy for managing a sizable react application using react-query?

Since diving into React with functional components and react-query, I've been facing some confusion on how to properly organize my components. Typically, I design components by having a top-level component handle all data access and pass data down to ...

Seamless database migrations using sequelize and typescript

I've been exploring the concept of generating migration files for models that already exist. When I use the "force: true" mode, tables are automatically created in the database, so I find it hard to believe that creating migration files automatically ...

Using Jest in Typescript to simulate fetch responses

I am currently facing an issue with mocking the global fetch function using Jest and dealing with the Response type. Specifically, I only require the response.ok and response.json properties, but I am struggling to set the return data of fetch without spec ...