【问题标题】:Proper way to get user by an attribute in mongoose nestjs通过猫鼬nestjs中的属性获取用户的正确方法
【发布时间】:2021-11-16 15:12:43
【问题描述】:

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

 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”导入 { Schema, SchemaFactory }; 从“@nestjs/swagger”导入 { ApiProperty };

导出类型 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);

这是服务

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

    }

【问题讨论】:

    标签: javascript mongoose nestjs


    【解决方案1】:

    试试这个:

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

    或简化版:

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

    简而言之,原因是使用引号键入的“用户名”字段和链末尾缺少 .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);
    

    【讨论】:

    • 这是我写的令人兴奋的代码,并问为什么不工作你只是写了同样的东西
    • 不完全是。请注意过滤器是如何定义的。您已将用户名字段放在引号中,例如“用户名”,这与我所做的不同。请尝试此代码,让我知道结果如何。
    • 还是不行
    • 我错过了什么?
    • 如果此字段名称正确且没有拼写错误,您能否检查您的架构(使用 mongoexpress)?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-02
      • 1970-01-01
      • 2021-07-05
      • 2021-05-11
      • 2020-06-12
      • 2020-08-01
      • 2016-02-02
      • 1970-01-01
      • 2013-03-03
      相关资源
      最近更新 更多