TypeScript Mongoose忽略查询结果中某些字段的类型安全方法 [英] Typescript Mongoose ignore certain field in query result the type safe way

查看:77
本文介绍了TypeScript Mongoose忽略查询结果中某些字段的类型安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Nestjs和Mongoose。我需要获取用户配置文件,但忽略来自MongoDB的密码。

我的用户架构如下所示

@Schema()
export class User extends Document {
  @Prop({ required: true, unique: true })
  email: string;

  @Prop({required: true})
  password: string;
}

当用户登录时,我需要使用密码获取用户,以便可以对用户进行身份验证。以下是UsersService中的findOne方法。它使用User架构作为类型

async findOne(filter: FilterQuery<User>): Promise<User> {
    return this.userModel.findOne(filter).exec();
}

但是,在我的身份验证方法中,用户通过身份验证后,我需要返回没有密码的用户。

async validateUser(email: string, password: string): Promise<User | null> {
    const user = await this.usersService.findOne({ email });
    if (user && await compare(password, user.password)) {
      const {password: ignore, ...result} = user.toObject();
      return result;
    }

    return null;
  }

这是可行的,但是user.toObject()返回类型any,这将忽略类型检查。我仍然希望validateUser方法确保返回Usernull

的承诺

有没有一种类型安全的方法来做到这一点?非常提前感谢您!

推荐答案

为了将toObject返回的纯JavaScript对象转换为类型化对象,您可能需要使用class-transformer库(出于验证目的,Nest.js推荐使用该库)。

第1步。

首次安装class-validator

$ npm i --save class-transformer

第2步。

安装后,假设User类具有以下属性:

 class User {
     public id: any;
     public email: string;
     public password: number;
 }

创建名为UserWithoutPassward的antoher类并导入Exclude

import { Exclude } from "class-transformer";

class UserWithoutPassword extends User {
    @Exclude()
    public password: number
}

我们使用Exclude批注通知class-transformer我们要排除password

第3步。

导入plainToClass函数:

import { plainToClass } from "class-transformer";

返回到您的代码:

async validateUser(email: string, password: string): Promise<UserWithoutPassword | null> {
    const user = await this.usersService.findOne({ email });

    if (user && await compare(password, user.password))
    {
        return plainToClass(UserWithoutPassword, user.toObject());
    }

    return null;
}

plainToClass方法将普通javascript对象转换为特定类的实例,接受以下参数:

  1. 要实例化的类
  2. 纯对象

Further reference about the library

希望它能有所帮助。

这篇关于TypeScript Mongoose忽略查询结果中某些字段的类型安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆