NodeJS Nestjs:Mongoose模式返回带有spread运算符的完整文档,而不是必需的属性

hec6srdp  于 2023-04-20  发布在  Node.js
关注(0)|答案(1)|浏览(96)

我已经为用户创建了一个单独的服务,它创建了一个没有任何规范的简单用户。然后我在AuthService中使用userService的create函数进行注册。在userService中,它将数据作为mongoose Schema返回。而在AuthService中,我想排除密码和其他一些细节,所以我已经创建了注册响应的Dto。这里的问题是它返回的是完整的文档而不是必需的属性。
userService.ts的代码:

import {Model} from 'mongoose';
import {InjectModel} from '@nestjs/mongoose';
import {User, UserDocument} from './schemas/user.schema';

import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Injectable()
export class UserService {
  constructor(@InjectModel(User.name) private userRepository: Model<UserDocument>) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const newUser = new this.userRepository(createUserDto);
    return await newUser.save();
  }
}

authService.ts类:

import { CreateUserDto } from 'src/user/dto/create-user.dto';
import { UserService } from 'src/user/user.service';
import { SigninDto } from './dto/signin/signin.dto';
import {JwtService} from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import {signupResponseDto} from './dto/signup/signup-response.dto';

@Injectable()
export class AuthService {
  constructor(private readonly userService: UserService, private readonly jwtService: JwtService){}

  async signup(signupDto: CreateUserDto): Promise<signupResponseDto>
  {
    const {password, ...otherData} = signupDto;
    
    const hashedPassword = await this.createHash(password);

    const newSignupBody: CreateUserDto = {password: hashedPassword, ...otherData};
  
    const createUser = await this.userService.create(newSignupBody);

    const {username} = createUser;

    const token = this.createToken(username, createUser['_id']);

    const result:signupResponseDto = {_id: createUser['_id'], token, ...createUser};

    return result;
    
  }
}

API测试的结果是:

{
  "_id": "60b95077448c29067c1fb349",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1271738373jffghdfghiOjE2MjI4NDM4OTV9._HKhNMeobCm0G6B2r7aaiTDsk53Qmp36poLG4bmPmlY",
  "$__": {
    "strictMode": true,
    "inserting": true,
    "getters": {},
    "_id": "60b95077448c29067c1fb349",
    "wasPopulated": false,
    "activePaths": {
      "paths": {
        "email": "require",
        "username": "require",
        "password": "require"
      },
      "states": {
        "ignore": {},
        "default": {},
        "init": {},
        "modify": {},
        "require": {
          "email": true,
          "username": true,
          "password": true
        }
      },
      "stateNames": [
        "require",
        "modify",
        "init",
        "default",
        "ignore"
      ]
    },
    "pathsToScopes": {},
    "cachedRequired": {},
    "session": null,
    "$setCalled": {},
    "emitter": {
      "_events": {},
      "_eventsCount": 0,
      "_maxListeners": 0
    },
    "$options": {
      "defaults": true
    },
    "validating": null,
    "backup": {
      "activePaths": {
        "modify": {
          "password": true,
          "email": true,
          "username": true,
          "security_answer": true
        },
        "default": {
          "updated_at": true,
          "created_at": true,
          "_id": true
        }
      }
    },
    "savedState": {}
  },
  "isNew": false,
  "$locals": {},
  "$op": null,
  "_doc": {
    "updated_at": "2021-06-03T21:58:11.071Z",
    "created_at": "2021-06-03T21:58:11.071Z",
    "_id": "60b95077448c29067c1fb349",
    "password": "$2b$10$K2gq31/Bv4tythgdWx/ObigM9izspn7wd01BUKcJ2P8dORC2loW",
    "email": "test@gmail.com",
    "username": "test",
    "security_answer": "banana",
    "__v": 0
  }
}

登录Dto

export class signupResponseDto
{
    _id: string;
    username: string;
    email: string;
    token: string;
    created_at: Date
}
hxzsmxv2

hxzsmxv21#

尝试return await newUser.save().toObject();,或者如果您将通过find/findOne方法查询记录,请在调用后追加.lean()
来自Mongoose文档:
文档有一个toObject方法,它将mongoose文档转换为普通的JavaScript对象。
或者如果您有任何疑问,请检查此页面:
从启用了lean选项的查询返回的文档是普通的javascript对象,而不是Mongoose Documents。

相关问题