【发布时间】:2020-12-16 10:24:45
【问题描述】:
我有这个模型:
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(使用单个嵌套集合),这一切都很好。
那么如何正确设置嵌套集合呢?
【问题讨论】:
-
能否也提供一下保存的代码?
-
ObjectId是文档的_id的类型。并且您正在尝试将"{ name: 'Max', surname: 'Mustermann', ... }保存为_id的值。所以它说它不能添加为ObjectId,因为它不是ObjectId -
@hasezoey 感谢您的回复 :) 我更新了代码。
-
@RadicalEdward 那么这里的最佳做法是什么?我只想拥有 1 个孩子与 M 父母的关系,如何以正确的方式生成引用?
-
@Phil 如果您已将其类型定义为
ObjectId,请确保您没有明确设置_id的值。在查找带有_id的文档时,始终传递有效为ObjectId类型的值
标签: node.js mongodb mongoose typegoose