nestjs 中的“排除”未按预期工作

时间:2021-05-25 08:56:36

标签: serialization nestjs

我想在用户架构中排除密码字段。但我想不通。

UserSchema.ts

export type UserDocument = User & Document;

@Schema()
export class User extends BaseSchema {

    @Prop({ type: String })
    firstName: string;

    @Prop({ type: String })
    lastName: string;

    @Prop({ type: String, required: true, unique: true })
    email: string;

    @Prop({ type: String })
    phone: string;

    @Prop({ type: String, required: true, unique: true })
    userName: string;

    @Exclude()
    @Prop({ type: String, required: true })
    password: string;

    @Prop({ type: String })
    avatar: string;

}

export const UserSchema = SchemaFactory.createForClass(User);

UserController.ts

@UseInterceptors(ClassSerializerInterceptor)
    @Get(':id')
    public async getUserById(@Param('id') id: string): Promise<ResponseDto> {
        try {
            const result = await this.userService.getOne({ _id: id });
            return new ResponseDto({
                isSuccess: true,
                message: 'ok',
                data: result
            });

        } catch (error) {
            return new ResponseDto({
                isSuccess: false,
                message: error,
                data: null
            });
        }
    }

这是 UserService.ts

@Injectable()
export class UserService {

    constructor(
        @InjectModel('User') private readonly userModel: Model<UserDocument>
    ) { }

    public async getMany(query: object): Promise<User[]> {
        const users: User[] = await this.userModel.find(query).exec();
        return users;

    }


    public async getOne(query: object): Promise<User> {
        const user = await this.userModel.findOne(query).exec();
        return user;
    }


    public async deleteOne(query: object): Promise<any> {
        const result = await this.userModel.deleteOne(query).exec();
        if (result.n === 0) {
            throw new HttpException('Not deleted', 400);
        }
        return result;
    }

    public async deleteMany(query: object): Promise<any> {
        const result = await this.userModel.deleteMany(query).exec();
        if (result.n === 0) {
            throw new HttpException('Not deleted', 400);
        }
        return result;
    }

    public async updateOne(query: object, user: UserUpdateDto): Promise<User> {
        return await this.userModel.findOneAndUpdate(query, user).exec();
    }

    public async updateMany(query: object, user: UserUpdateDto): Promise<any> {
        return await this.userModel.updateMany(query, user).exec();
    }


    public async add(newUser: UserCreateDto): Promise<User> {
        const user = await new this.userModel(newUser);
        return await user.save();
    }

    public async addRange(newUsers: UserCreateDto[]): Promise<any> {
        return await this.userModel.collection.insertMany(newUsers);
    }

}

Swagger 结果是:

{
  "$__": {
    "strictMode": true,
    "selected": {},
    "getters": {},
    "_id": {
      "_bsontype": "ObjectID",
      "id": {
        "type": "Buffer",
        "data": [
          96,
          171,
          150,
          114,
          131,
          27,
          120,
          44,
          172,
          51,
          211,
          88
        ]
      }
    },
    "wasPopulated": false,
    "activePaths": {
      "paths": {
        "email": "init",
        "userName": "init",
        "password": "init",
        "_id": "init",
        "firstName": "init",
        "lastName": "init",
        "phone": "init",
        "avatar": "init",
        "__v": "init"
      },
      "states": {
        "ignore": {},
        "default": {},
        "init": {
          "_id": true,
          "firstName": true,
          "lastName": true,
          "email": true,
          "phone": true,
          "userName": true,
          "password": true,
          "avatar": true,
          "__v": true
        },
        "modify": {},
        "require": {}
      },
      "stateNames": [
        "require",
        "modify",
        "init",
        "default",
        "ignore"
      ]
    },
    "pathsToScopes": {},
    "cachedRequired": {},
    "$setCalled": [],
    "emitter": {
      "_events": {},
      "_eventsCount": 0,
      "_maxListeners": 0
    },
    "$options": {
      "skipId": true,
      "isNew": false,
      "willInit": true,
      "defaults": true
    }
  },
  "isNew": false,
  "$locals": {},
  "$op": null,
  "_doc": {
    "_id": {
      "_bsontype": "ObjectID",
      "id": {
        "type": "Buffer",
        "data": [
          96,
          171,
          150,
          114,
          131,
          27,
          120,
          44,
          172,
          51,
          211,
          88
        ]
      }
    },
    "firstName": "",
    "lastName": "",
    "email": "ali@gel.com",
    "phone": "",
    "userName": "ali@gel.com",
    "password": "$2b$10$Vp9EYM8fuid.bu2cisp45.QPHdQyPLLlcFeOTPUS98AzUxx3WTekG",
    "avatar": "",
    "__v": 0
  },
  "$init": true
}

有两个问题我无法处理: 1- 密码字段仍在响应中。我想排除它 2- 响应对象不干净。有很多字段我不想得到。

我期望的回应是:

{ 
isSuccess: true,
message:'ok',
  data: {
    "firstName": "",
    "lastName": "",
    "email": "ali@gel.com",
    "phone": "",
    "userName": "ali@gel.com",
    "avatar": ""
  }
}

0 个答案:

没有答案