Home > OS >  NestJS Mongoose .find(): check if there are no results
NestJS Mongoose .find(): check if there are no results

Time:11-08

So my question is, how can i check if theres no result when running this.userService.findOne(createUserDto.username);

Controller:

import { Get, Controller, Body, Post, Param } from "@nestjs/common";
import { RegisterService } from "./register.service";
import * as bcrypt from "bcrypt";
import { CreateUserDto } from "./create-user.dto";

@Controller("register")
export class RegisterController {
  constructor(private userService: RegisterService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    let chkUname: any = this.userService.findOne(createUserDto.username);

    let response = {
      usernError: "",
      regOk: true,
    };

    if (!chkUname) {
      // this.userService.createUser(createUserDto);
      return chkUname;
    } else {
      // response.usernError = "Sorry, this username is used!";
      // response.regOk = false;
      return true;
    }
  }
  // create(@Param("uname") uname: any) {
  //   return this.userService.findOne(uname);
  // }
}

Service:

import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { CreateUserDto } from "./create-user.dto";
import { Users, UsersDocument } from "./schema/user.schema";

@Injectable()
export class RegisterService {
  constructor(
    @InjectModel(Users.name) private readonly usersModel: Model<UsersDocument>
  ) {}

  async createUser(createUserDto: CreateUserDto): Promise<UsersDocument> {
    const user = new this.usersModel(createUserDto);
    return user.save();
  }

  async findOne(uname: string) {
    return this.usersModel.find({uname}).exec();
  }
}

It always returned true/false depends what code i wrote.

CodePudding user response:

Okay - I think I found a couple of issues.

  1. The query for users doesn't appear correct:
  async findOne(uname: string) {
    return this.usersModel.find({uname}).exec();
  }

You didn't include your schema, but make sure the field you are querying actually is uname (not username, etc.). Additionally, you are using find which will return an empty array if there are no results. You should use findOne on your query

  async findOne(uname: string) {
    // double check that `uname` is the field on your model
    return this.usersModel.findOne({uname: uname}).exec();
  }

The second issue is in the controller - you aren't awaiting for the results of the query:

let chkUname: any = this.userService.findOne(createUserDto.username);

Try

let chkUname = await this.userService.findOne(createUserDto.username)
  • Related