I have this model:
import { prop } from '@typegoose/typegoose';
export class ChildDAO {
@prop({ index: true, required: true })
childId!: number;
@prop({ index: true })
name?: string;
@prop({ index: true })
surname?: string;
}
export class ParentDAO {
@prop({ index: true, default: () => new Date() })
createdAt?: Date;
@prop({ ref: ChildDAO })
child?: Ref<ChildDAO>;
// other attributes are regular strings or numbers, some indexed, some required, nothing special
}
Why am I getting
ValidationError: ParentDAO validation failed: child: Cast to ObjectId failed for value "{ name: 'Max', surname: 'Mustermann', ... }
when trying to save an object?
EDIT My setup code:
beforeAll(async () => {
mongoClient = await require('mongoose').connect('mongodb://localhost:27017/', {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName
});
ParentModel = getModelForClass(ParentDAO, {schemaOptions: {collection: 'parents'}});
ChildModel = getModelForClass(ChildDAO, {schemaOptions: {collection: 'children'}});
});
And the saving method which get's called in a test:
export class StorageService {
static async saveParent(parent: Parent): Promise<ParentDAO> {
const ParentModel = getModelForClass(ParentDAO);
return ParentModel.create({
...parent
} as ParentDAO);
}
}
I should not without the Ref (with a single, nested collection) this all works fine.
So how do I set up nested collections correctly?
guessing form the provided code, you are trying to save an reference and think that if it doesn't exists, it gets created, which is not what is happening, for an reference you need to either provide an ObjectId (or the reference's _id type) or an instance of an Document (to automatically get the _id
)
(comment of @Phil)
I am not doing any of that. I am just saving the Parent object. Perhaps I need to save the Child manually first? The above code is all there is except some boring fields on the models.
exactly, you need to save the child manually and provide the id then to the parent