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) 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?
CodePudding user response:
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
.