I have a dto file that looks something like this:
export class CreateJobDto {
@ValidateNested()
@Type(() => CreateCustomerDto)
readonly client: CreateCustomerDto;
}
My Job Schema looks like this:
import { Prop, Schema as NestSchema } from '@nestjs/mongoose';
@NestSchema({collection: 'Jobs'})
export class Job {
@Prop({ type: Customer })
client: Customer
}
My CreateCustomerDto looks like this:
export class CreateCustomerDto {
@IsOptional()
@IsArray()
@ArrayNotEmpty()
@IsMongoId({ each: true })
readonly brand: string[];
}
My Customer Schema looks like this:
import { Prop, Schema as NestSchema } from "@nestjs/mongoose";
@NestSchema({collection: 'Customers'})
export class Customer extends Document {
@Prop([{ type: Schema.Types.ObjectId, ref: 'Brand', default: undefined }])
brand: Schema.Types.ObjectId[]
}
When a Customer is fetched using Mongoose I am using .populate(‘brand’) to populate the Customer object with the corresponding Brands.
The issue is that when I create a Job, it is expecting the client property to be a nested object but the schema validation fails because the Customer schema is only storing references and not populated objects.
Since I am using a mix of nested objects and references to objects what is considered best practice and how should this be solved?
I have created a different dto for the Customer which specifies what it should look like when the properties are populated. I could create a different Customer schema purely for validation in other documents but I am not sure whether that is considered good practice.
Bart is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.