Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

299
Visualizações
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();

    }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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);
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the findOne method in Mongoose:

findByUsername(username: string) {      
   return this.userModel.findOne({ username })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda