Node.js 如何在nestjs和mongo中正确配置用户角色关系
这件事我已经坚持了一段时间了。我有一个usertype/role,如果没有从主体传递usertype/role,它应该有一个默认值。如果传递了usertype/角色,则将使用来自该用户的usertype/角色 如果有人能帮我解决这个问题,我将不胜感激。我可以在具有类似结构的其他组件中使用此想法。谢谢 这是我在启动注册时遇到的错误 {“状态代码”:400,“消息”:[ “usertype.nested属性usertype必须是对象或数组”],“错误”:“错误请求”}Node.js 如何在nestjs和mongo中正确配置用户角色关系,node.js,mongodb,typescript,mongoose,nestjs,Node.js,Mongodb,Typescript,Mongoose,Nestjs,这件事我已经坚持了一段时间了。我有一个usertype/role,如果没有从主体传递usertype/role,它应该有一个默认值。如果传递了usertype/角色,则将使用来自该用户的usertype/角色 如果有人能帮我解决这个问题,我将不胜感激。我可以在具有类似结构的其他组件中使用此想法。谢谢 这是我在启动注册时遇到的错误 {“状态代码”:400,“消息”:[ “usertype.nested属性usertype必须是对象或数组”],“错误”:“错误请求”} 如何从主体传递usertype
import * as mongoose from 'mongoose';
export const UserSchema = new mongoose.Schema({
userId: {
type: mongoose.SchemaTypes.ObjectId,
},
firstname: {
type: String,
required: true
},
password: {
type: String
},
email: {
type: String,
required: true,
},
usertype: {
type: mongoose.Schema.Types.ObjectId,
ref: 'UserType',
default: ''
},
})
接口
import { Document } from 'mongoose';
import { UserType } from '../../usertype/interface/usertype.interface'
export interface User extends Document {
userId: string;
firstname: string;
password: string;
email: string;
usertype: UserType;
}
这是createdto
import { ApiProperty } from '@nestjs/swagger';
import { IsString, MinLength, IsEmail, ValidateNested } from 'class-validator';
import { UserType } from 'src/usertype/interface/usertype.interface';
export class CreateUserDto {
@ApiProperty()
@IsString()
firstname: string;
@ApiProperty()
@MinLength(6, { message: "Your Password should be at least 6 characters" })
password: string;
@ApiProperty()
@IsEmail()
email: string;
@ValidateNested()
usertype: UserType;
}
//注册用户
异步寄存器(createDTO:CreateUserDto,userType:CreateUserTypeDTO):承诺{
const{email}=createDTO;
const user=wait this.userModel.findOne({email})
如果(用户){
抛出新的HttpException(“用户已存在”,HttpStatus.BAD\u请求);
}
const createdUser=等待this.userModel.create({
…创造了,
usertype:usertype
});
等待createdUser.save();
返回createdUser;
}
//register user
async register(createDTO: CreateUserDto, userType: CreateUserTypeDTO): Promise<User> {
const { email } = createDTO;
const user = await this.userModel.findOne({ email })
if (user) {
throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
}
const createdUser = await this.userModel.create({
...createDTO,
usertype: userType
});
await createdUser.save();
return createdUser;
}