Martin J
Martin J

Reputation: 2159

Automatically create new Documents from nested objects with typegoose

What I would like to know is if there is a way that when I save a new document with many nested objects marked as Ref in the Typegoose class, it would automatically create new documents from these nested objects in the right collection.

For the moment, this code gives me an error :

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();

I know mongoose is asking the object to come with ObjectId and not objects.

However, the problem is that I have many big classes with many nested classes and I am trying to avoid looping through all big objects to save the nested object first before the big one.

Thank you for your answer.

Upvotes: 0

Views: 1412

Answers (1)

hasezoey
hasezoey

Reputation: 1096

this is currently not possible, but there is an issue at Automattic/mongoose about it

Upvotes: 1

Related Questions