nest.js dto and schema for array of objectId's

Advertisements

I am having a nest.js DTO field contains array of ObjectId’s:

@IsNotEmpty()
@IsMongoId({each: true})
@ApiProperty({
  example: ['63e0ec1d6eae1c8888445efb', '63e0ec1d6eae1c8888445efb'],
  description: 'List of students',
})
public students: ObjectIdType[];

and my Nest.js Schema looks like:

export class StudentForm extends Document {
   @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'students' })
   students: Types.ObjectId[];
}

while attempts to create a record, am getting this error:
ERROR [ExceptionsHandler] StudentForm validation failed: students: Cast to ObjectId failed for value "[ ’63e0ec1d6eae1c8888445efb’, ’63e0ec1d6eae1c8888445efb’ ]" (type Array) at path "students" because of "BSONTypeError".

Don’t know whether DTO or Schema which one is wrong. I need to store array of ObjectId’s in students field.

Need someone’s valuable help.

>Solution :

To do an array of type you need to use type: [mongoose.Schema.Types.ObjectId]. This is so that when Nest reads the type it sees that it is an array and knows to tell that to Mongoose. The same kind of approach is used for @nestjs/swagger and @nestjs/graphql

Leave a ReplyCancel reply