Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string' has no properties in common with type 'FindOneOptions<User>'

I am trying to build a backend with express.js. I now have the following problem:

import { Request, Response } from "express";
import { getManager } from "typeorm";
import { User } from "../entity/user.entity";


export const GetUser = async (req: Request, res: Response) => {
  const repository = getManager().getRepository(User);

  const { password, ...user } = await repository.findOne(req.params.id);

  res.send(user);
};

The following error always occurs:

(parameter) req: Request<ParamsDictionary, any, any, QueryString.ParsedQs, Record<string, any>> Type 'string' has no properties in common with type 'FindOneOptions'.ts(2559) enter image description here router.ts

router.get("/api/users/:id", AuthMiddleware, GetUser);

user.entity.ts

import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from "typeorm";
import { Role } from "./role.entity";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;
  @Column()
  first_name: string;
  @Column()
  last_name: string;
  @Column({
    unique: true,
  })
  email: string;
  @Column()
  password: string;

  @ManyToOne(() => Role)
  @JoinColumn({ name: "role_id" })
  role: Role;
}

Can anyone help me with my problem?

like image 803
bobby17jones Avatar asked Nov 25 '25 15:11

bobby17jones


1 Answers

The typeorm's findOne function is equivalent to Select * ... limit 1. This means that the findOne actually expects an object containing conditions to match and return the first element for which the condition is satisfied.

In your case, the code should be:

repository.findOne({where: {id: parseInt(req.params.id, 10)}})

or

repository.findOneBy({id: parseInt(req.params.id, 10)})

This will find the user whose id field will match match the req.params.id.

like image 167
Ashok Avatar answered Nov 27 '25 13:11

Ashok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!