通过 mongoose nestjs 中的属性获取用户的正确方法

Proper way to get user by an attribute in mongoose nestjs

我在数据库中有一个用户集合,我想检索具有特定用户名的用户 我已经写了这个方法,但是这会返回所有用户

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

    }

为什么这个查询不起作用 控制器

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

这是我的用户实体

从“@nestjs/mongoose”导入{模式、SchemaFactory}; 从“@nestjs/swagger”导入{ApiProperty};

导出类型 UserDocument = 用户和文档;

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

    @ApiProperty()
    username: string;

    @ApiProperty()
    email : string

    @ApiProperty()
    password: string;
}

  export const UserSchema = SchemaFactory.createForClass(User);

这是服务

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

    }

您可以在 Mongoose 中使用 findOne 方法:

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

试试这个:

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

或简化版:

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

简而言之,原因是 'username' 字段在链的末尾用引号键入并且缺少 .exec() 方法。

此外,应通过使用 @Prop() 装饰器装饰字段来为 Mongoose 准备模式:

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