我有这个模型:
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
}
为什么我越来越
ValidationError: ParentDAO validation failed: child: Cast to ObjectId failed for value "{ name: 'Max', surname: 'Mustermann', ... }
尝试保存对象时?
编辑我的设置代码:
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'}});
});
以及在测试中调用的保存方法:
export class StorageService {
static async saveParent(parent: Parent): Promise<ParentDAO> {
const ParentModel = getModelForClass(ParentDAO);
return ParentModel.create({
...parent
} as ParentDAO);
}
}
我不应该没有 Ref(带有单个嵌套集合),这一切都很好。
那么如何正确设置嵌套集合呢?