NestJS + Mongoose 模式与自定义打字稿类型

问题描述 投票:0回答:2

我正在尝试使用以下类中的

nestjs/mongoose
装饰器创建 Mongo 模式:

@Schema()
export class Constraint {
  @Prop()
  reason: string;

  @Prop()
  status: Status;

  @Prop()
  time: number;
}

问题是

Status
定义如下:

export type Status = boolean | 'pending';

而且我无法弄清楚要传递给

status
prop
装饰器的内容,因为我收到以下错误:

Error: Cannot determine a type for the "Constraint.status" field (union/intersection/ambiguous type was used). Make sure your property is decorated with a "@Prop({ type: TYPE_HERE })" decorator

{ type: Status }
不起作用,因为
Status
type
而不是
Class

typescript mongodb mongoose nestjs mongoose-schema
2个回答
1
投票

由于

status
可以是布尔值或字符串,所以它是混合类型。因此,您可以考虑将类型设置为 Mixed


0
投票

我也遇到了同样的问题,感谢@sven-stam,正如他提到的here,我实现了这样的混合类型:


import { Prop, Schema } from '@nestjs/mongoose';
import mongoose, {
  HydratedDocument,
  Schema as MongooseSchema,
} from 'mongoose';

export type UserDocument = HydratedDocument<User>;

@Schema()
class User {
  @Prop()
  username: string

  @Prop({default: false, type: MongooseSchema.Types.Mixed })
  paid: boolean | 'waiting'
}
© www.soinside.com 2019 - 2024. All rights reserved.