Issue with TypeORM findOne method causing unexpected output

I am encountering an issue with my User Entity's Email Column when using TypeORM's findOne function. Instead of returning null for a non-existent email, it is returning the first entry in the User Entity. This behavior does not align with the documentation provided.

findOne:

// returns the first User of database
const user = await this.userRepository.findOne({ email: 'example@email.com' });

User.Entity.ts:

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
} from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn({ name: 'id' })
  private _id: number;

  @Column({ name: 'password', length: 256, nullable: true })
  private _password?: string;

  @Column({ name: 'email', length: 300, nullable: true, unique: true })
  private _email?: string;

  @Column({ name: 'roles', length: 300, nullable: true })
  private _roles?: string = null;

  public get id(): number {
    return this._id;
  }

  public set id(id: number) {
    this._id = id;
  }

  public get email(): string {
    return this._email;
  }

  public set email(email: string) {
    this._email = email;
  }

  public get password(): string {
    return this._password;
  }

  public set password(password: string) {
    this._password = password;
  }

  public get roles(): string {
    return this._roles;
  }

  public set roles(roles: string) {
    this._roles = roles;
  }
}

The expected behavior according to the official documentation:

const user = new User(); user.firstName = "Timber"; user.lastName = "Saw"; user.age = 25; await repository.save(user);

const allUsers = await repository.find(); const firstUser = await repository.findOne(1); // find by id const timber = await repository.findOne({ firstName: "Timber", lastName: "Saw" });

await repository.remove(timber);

Answer №1

Here's a solution that has worked for me:

let newUser = await this.userRepository.findOne(
    { where:
        { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4813090012100d01090c09130e1f10090e04011400020012054e0405">[email protected]</a>' }
    }
);

Answer №2

If you're facing an issue that needs attention, feel free to join the discussion at this link: https://github.com/typeorm/typeorm/issues/2500

Here's a workaround I have found for this problem:

const usersRepository = conn.getRepository(UserEntity);

const results = await usersRepository.find({
    relations: ['profile'],
        where: {
            email: username
        },
        take: 1 
    });
// ...

find will give you an array, so make sure to verify the length of the array to ensure it matches the WHERE clause.

The current behavior of findOne may return the first row in the table if no match is found with the specified values.

I hope this solution works for you!

Answer №4

Due to the fact that the User.email property is a function and not a string, your findOne query is attempting to locate an entity where the email function matches '[email protected]', which will not yield any results. The email column within your model is actually _email, but since it is a private property, it cannot be accessed in a TypeORM query.

You have a few options available:

  1. Eliminate the use of getters and setters as TypeORM does not support this type of encapsulation. Instead, you can create a separate domain model class to encapsulate your TypeORM Entity, or utilize TypeORM's value transformers if you are using getters/setters to manipulate values before inserting/selecting from the database.

  2. Utilize the QueryBuilder for your queries instead of the find/findOne/etc methods. The QueryBuilder has the ability to reference any arbitrary column.

Answer №5

This is how Type ORM helps me:

let userInformation;
let userRepository = getRepository(User);
userInformation = await userRepository
                .findOne({
                    where: {"email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec828d9a8d8087859f84839ededcdcd9ac8b818d8580c28f8381">[email protected]</a>'}
                });

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

Using alternate variables in the watchQuery() function in Apollo Angular will generate the cached data

Currently, I am implementing a feature in my project that allows users to access and analyze data based on various parameters such as year, location, and gender. Below is the code snippet that I have developed for this feature: this._querySubscription = ...

The importation of TypeScript source modules is not compiled accurately in the distribution folder

Currently, I am working on a REST API in TypeScript with the following structure: ├── dist │ ├── index.js │ ├── library.js ├── src │ ├── index.ts │ ├── library.ts ├── node_modules ├── package. ...

Navigating SSL certificate prompts in Protractor

Our programs utilize SSL certificates and we are unable to bypass Chrome's prompt for selecting a certificate. We would be satisfied with simply choosing the one certificate needed. Attempts have been made using this code: capabilities: { browser ...

Tips for storing an array of ReplaySubjects in a single variable in an Angular application

I am looking to store several ReplaySubjects in a single array. Here is my code: public filteredSearch: ReplaySubject<any[]> = new ReplaySubject(1); this.filteredSearch[id].next(filter(somedata)); When I run this code, I encounter an error saying ...

Exploring the depths of useDispatch and dispatch in React-Redux

I am currently analyzing the code written by a former colleague of mine. Based on my understanding, useDispatch accepts an object containing the action type and payload, which is then compared to all reducers to update the state accordingly. However, in t ...

The error message "@graphql-eslint/eslint-plugin: problem with the "parserOptions.schema" configuration"

Our team is currently working on developing micro-services using NestJS with Typescript. Each of these services exposes a GraphQL schema, and to combine them into a single graph, we are utilizing a federation service built with NestJS as well. I recently ...

Error in MatSort implementation - Argument cannot be assigned

I'm having trouble figuring out how to implement the Mat-Sort functionality from Angular Material. When I try to declare my variable dataSource, I get the following error: Argument of type 'Observable' is not assignable to parameter of type ...

Incorrect Angular Routing Component OpeningI am experiencing an issue where

I am facing an issue with lazy loading a module, where it is not correctly displaying the desired component. Even though the route seems correct, it shows a different component instead. Despite specifying the path for "Push-Campaign", it displays the "Cli ...

I'm looking to locate the API documentation for AngularJS TypeScript

After transitioning from using AngularJS 1.4 and plain JavaScript to now working with AngularJS 1.5 but utilizing TypeScript, I have found it challenging to find helpful documentation. For instance, when trying to inject services like $q or $timeout into m ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

How can CSS variables be applied to a hover property within an Angular directive?

Check out the directive below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: 'd-btn', host: {} }) export class ButtonDirective { constructor(private el: ElementRef){} @HostLis ...

Creating a personalized NPM package: Converting and exporting TypeScript definitions

Question: Do I need to adjust my TS configuration or add a TS build step? I recently developed a new npm package: Custom-NPM-Package / - src -- index.js -- index.d.ts -- IType.ts accompanied by this tsconfig.json: { "compilerOptions" ...

What type of HTML tag does the MUI Autocomplete represent?

Having trouble calling a function to handle the onchange event on an autocomplete MUI element. I've tried using `e: React.ChangeEvent`, but I can't seem to locate the element for the autocomplete component as it throws this error: The type &apos ...

The implementation of TypeScript 3.5 resulted in a malfunction where the imported namespace was unable to locate the Enum during runtime

I recently upgraded an older Angular.js application from Typescript 2.7 to 3.5 and successfully compiled it using tsc.exe. During application runtime, I encountered an error message in certain parts of the code: TypeError: Cannot read property 'Enu ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

There is a potential for the object to be 'undefined' when calling the getItem method on the window's local storage

if (window?.sessionStorage?.getItem('accessToken')?.length > 0) { this.navigateToApplication(); } Encountering the following error: Object is possibly 'undefined'.ts(2532) Any suggestions on how to resolve this issue? I am attem ...

Combining component attributes with a mixin in Vue 2 using TypeScript

In my Vue + TypeScript project, we are utilizing Vue class components. Recently, I moved one of the component's methods to a separate mixin that relies on the component's properties. To address TypeScript errors regarding missing properties in th ...

When utilizing destructuring in React.js with TypeScript, incorrect prop values are not being alerted as expected

I recently started using TypeScript and I have been enjoying it so far. However, I came across an issue today that I couldn't solve. Imagine a scenario where a parent component A passes a function that expects a numeric value to the child component B ...

The list filter may not work properly if the search string is left blank

I am currently working on a list filtering feature that updates based on user input. As the user types, the system compares the entered text against the items in the list and displays the matching objects in an array. However, I'm facing an issue - wh ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...