Jessey Fransen
Jessey Fransen

Reputation: 145

findByUsername() returns blank page

I'm learning nestjs with mongodb (mongoose) and I'm trying to get a single user from the database.

users.service.ts

@Injectable()
export class UsersService {
    constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>,) {}

    async create(createUserDto: CreateUserDto): Promise<User> {
        const createdUser = new this.userModel(createUserDto);
        return createdUser.save();
    }

    async findAll(): Promise<User[]> {
        return this.userModel.find().exec();
    }

    async findByUsername(username: string): Promise<User | undefined> {
        return this.userModel.findOne({username})
    }
}

users.controller.ts

@UseGuards()
@Controller('/api/users')
export class UsersController {
    constructor(private readonly usersService: UsersService) {
    }

    @Post()
    async create(@Body() user: CreateUserDto) {
        await this.usersService.create(user);
    }

    @Get()
    async findAll(): Promise<User[]> {
        return this.usersService.findAll();
    }

    @Get(':username')
    async findOne(username: string): Promise<User> {
        return this.usersService.findByUsername(username);
    }
}

users.schema.ts

export type UserDocument = User & Document;

@Schema()
export class User {
    @Prop()
    firstname: string;

    @Prop()
    lastname: string;

    @Prop({required: true})
    username: string;

    @Prop({required: true})
    password: string;

    @Prop({default: false})
    isAdmin: boolean;
}

export const UserSchema = SchemaFactory.createForClass(User);

Problem is that I receive a blank page when navigating to http://localhost:3000/api/users/username and Postman isn't returning anything either.

postman get

Any ideas?

Upvotes: 0

Views: 162

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70540

Your @Get(':username') route handler defines that it should have a username parameter passed to it, but doesn't tell Nest how to pass it. You can do one of two things here:

  1. use @Param('username') to pull the username directly from req.params['username']. Quick and easy

  2. use @Param() { username } to deconstruct req.params to pull out just username (it should be the only value anyways). The benefit of this approach is being able to use the ValidationPipe with a DTO class to represent the req.params object. With the second approach, your @Get(':username') method would look like this:

Get(':username')
async findOne(@Param() { username }: UsernameParams) {
  return this.usersService.findByEmail(username);
}

Upvotes: 2

Related Questions