我使用 NestJs + Typegoose。如何在 NestJs + Typegoose 中将 _id 替换为 id?我没有找到明确的例子。我尝试过一些但没有任何结果。
@modelOptions({
schemaOptions: {
collection: 'users',
},
})
export class UserEntity {
@prop()
id?: string;
@prop({ required: true })
public email: string;
@prop({ required: true })
public password: string;
@prop({ enum: UserRole, default: UserRole.User, type: String })
public role: UserRole;
@prop({ default: null })
public subscription: string;
}
Run Code Online (Sandbox Code Playgroud)
@Injectable()
export class UsersService {
constructor(
@InjectModel(UserEntity) private readonly userModel: ModelType<UserEntity>,
) {}
getOneByEmail(email: string) {
return from(
this.userModel
.findOne({ email })
.select('-password')
.lean(),
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
更新默认值的另一种方法_id是id重写 modelOptions 装饰器中的 toJSON 方法。
@modelOptions({
schemaOptions: {
collection: 'Order',
timestamps: true,
toJSON: {
transform: (doc: DocumentType<TicketClass>, ret) => {
delete ret.__v;
ret.id = ret._id;
delete ret._id;
}
}
}
})
@plugin(AutoIncrementSimple, [{ field: 'version' }])
class TicketClass {
@prop({ required: true })
public title!: string
@prop({ required: true })
public price!: number
@prop({ default: 1 })
public version?: number
}
export type TicketDocument = DocumentType<TicketClass>
export const Ticket = getModelForClass(TicketClass);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6636 次 |
| 最近记录: |