[英]Mongoose nested ObjectId Array validation Dto
I have a Dto which looks like this:我有一个看起来像这样的 Dto:
import { Type } from "class-transformer";
import { ArrayMinSize, IsArray, ValidateNested} from "class-validator";
import { ObjectId } from "mongoose";
export class MongoIdDto {
@IsArray()
@ValidateNested({each: true})
@ArrayMinSize(1)
@Type(() => ObjectId)
ids: ObjectId[]
}
But this throws me an error: 'ObjectId' only refers to a type, but is being used as a value here.
但这会给我一个错误: 'ObjectId' only refers to a type, but is being used as a value here.
How does this error occur?这个错误是怎么发生的?
This is a common import mistake:这是一个常见的导入错误:
ObjectId can be imported from mongoose and from mongoDB. ObjectId 可以从 mongoose 和 mongoDB 导入。
The mongoose import is a Type mongoose进口是一种类型
The mongodb import is a class representation of the bson ObjectId Type mongodb 导入是 bson ObjectId 类型的 class 表示
So to fix this issue change your import to: import { ObjectId } from "mongodb";
因此,要解决此问题,请将导入更改为: import { ObjectId } from "mongodb";
But actually there is an option to validate MongoIds with this:但实际上有一个选项可以用这个来验证 MongoIds:
export class MongoIdArrayDto {
@IsMongoId({each: true})
@ArrayMinSize(1)
ids: ObjectId[]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.