我想知道的是,是否有一种方法,当我保存一个带有许多嵌套对象的新文档时Ref
,它会自动从正确集合中的这些嵌套对象创建新文档。
目前,这段代码给了我一个错误:
nestedProp: CastError: Cast to ObjectId failed for value "{ Prop1: 'test1', Prop2: 'test2' }" at path "nestedProp"
import { getModelForClass, prop, Ref } from "@typegoose/typegoose";
import mongoose from "mongoose";
export class NestedClass {
@prop()
Prop1!: string;
@prop()
Prop2?: string;
}
export class MainClass {
@prop()
name!: string;
@prop({ ref: "NestedClass" })
nestedProp?: Ref<NestedClass>;
}
let exampleObject = {
name: "test",
nestedProp: {
Prop1: "test1",
Prop2: "test2",
},
};
async function test() {
await mongoose.connect("mongodb://localhost:27017/database");
const ClassModel = getModelForClass(MainClass);
try {
const u = await ClassModel.create(exampleObject);
} catch (e) {
console.log(e);
}
}
test();
我知道猫鼬要求对象带有 ObjectId 而不是对象。
然而,问题是我有很多嵌套类的大类,我试图避免循环遍历所有大对象以在大对象之前先保存嵌套对象。
谢谢您的回答。