Thymeleaf
Thymeleaf

Reputation: 113

Proper way to get user by an attribute in mongoose nestjs

I have a user collection in the database and i want to retrive a user with specific username I have written this method but this is returning all users

 findByUsername(username: string) {      
        return this.userModel.find({
            'username' : username})

    }

Why is this query not working Controller

@Get('find/:username')
    getUserById(@Param("username") username : string) : any {
        console.log(username);
        return this.usersService.findByUsername(username);
    }

This is my user entity

import { Schema, SchemaFactory } from "@nestjs/mongoose"; import { ApiProperty } from "@nestjs/swagger";

export type UserDocument = User & Document;

@Schema()
export class User {
    
    @ApiProperty()
    id: string;

    @ApiProperty()
    username: string;

    @ApiProperty()
    email : string

    @ApiProperty()
    password: string;
}

  export const UserSchema = SchemaFactory.createForClass(User);

This is the service

import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { use } from "passport";
import {User,UserDocument} from '../users/entities/user.entity'

// This should be a real class/interface representing a user entity


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

    findById(userId: string) {
      
    }
    findByUsername(username: string) {      
        return this.userModel.find({"username": username}).exec();

    }

Upvotes: 0

Views: 4822

Answers (2)

mazooma
mazooma

Reputation: 116

Try this:

findByUsername(username: string) {      
    return this.userModel.find({username: username}).exec();
}

or simplified version:

findByUsername(username: string) {      
    return this.userModel.find({username}).exec();
}

Briefly, the cause is the 'username' field typed with quotes and missing .exec() method at the end of the chain.

Also, schema should be prepared for Mongoose by decorating fields with the @Prop() decorator:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

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

    @ApiProperty()
    @Prop()
    username: string;

    @ApiProperty()
    @Prop()
    email : string

    @ApiProperty()
    @Prop()
    password: string;
}

  export const UserSchema = SchemaFactory.createForClass(User);

Upvotes: 2

Mohammad Dohadwala
Mohammad Dohadwala

Reputation: 746

You can use the findOne method in Mongoose:

findByUsername(username: string) {      
   return this.userModel.findOne({ username })
}

Upvotes: 0

Related Questions