【问题标题】:Automatically create new Documents from nested objects with typegoose使用 typegoose 从嵌套对象自动创建新文档
【发布时间】:2023-03-29 18:35:02
【问题描述】:

我想知道的是,当我在 Typegoose 类中保存一个带有许多标记为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();

我知道 mongoose 要求对象带有 ObjectId 而不是对象。

但是,问题是我有许多包含许多嵌套类的大类,我试图避免循环遍历所有大对象,以便在大对象之前先保存嵌套对象。

感谢您的回答。

【问题讨论】:

    标签: mongodb mongoose typegoose


    【解决方案1】:

    这目前是不可能的,但是Automattic/mongoose 有一个关于它的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      相关资源
      最近更新 更多