所以我的问题是,如何检查运行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,这取决于我编写的代码。
1条答案
按热度按时间z31licg01#
好吧-我想我发现了几个问题。
1.用户查询不正确:
您没有包括架构,但请确保您实际查询的字段是
uname
(而不是username
等)。此外,您使用的是find
,如果没有结果,它将返回一个空数组。您应该在查询中使用findOne
第二个问题是在控制器中-您不需要等待查询的结果:
尝试