我有这个模型:
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(具有单个嵌套集合),这一切都很好。
那么如何正确设置嵌套集合?
答案 0 :(得分:1)
猜测提供的代码,您试图保存一个引用,并认为如果它不存在,则会创建它,这不是正在发生的事情,您需要参考提供ObjectId(或引用的_id类型)或Document的实例(以自动获取_id
)
(@ Phil的评论)
我什么都没做。我只是保存Parent对象。也许我需要先手动保存孩子?上面的代码就足够了,除了模型上的一些无聊的字段。
恰好,您需要手动保存子级,然后将ID提供给父级