I have a Dto which looks like this:
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.
How does this error occur?
CodePudding user response:
This is a common import mistake:
ObjectId can be imported from mongoose and from mongoDB.
The mongoose import is a Type
The mongodb import is a class representation of the bson ObjectId Type
So to fix this issue change your import to:
import { ObjectId } from "mongodb";
But actually there is an option to validate MongoIds with this:
export class MongoIdArrayDto {
@IsMongoId({each: true})
@ArrayMinSize(1)
ids: ObjectId[]
}