Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading