mongoose 查找():检查是否没有结果

1bqhqjot  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(128)

所以我的问题是,如何检查运行this.userService.findOne(createUserDto.username);时是否没有结果?

控制器:

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);
  // }
}

服务:

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();
  }
}

它总是返回true/false,这取决于我编写的代码。

z31licg0

z31licg01#

好吧-我想我发现了几个问题。
1.用户查询不正确:

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

您没有包括架构,但请确保您实际查询的字段是uname(而不是username等)。此外,您使用的是find,如果没有结果,它将返回一个空数组。您应该在查询中使用findOne

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

第二个问题是在控制器中-您不需要等待查询的结果:

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

尝试

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

相关问题