0

我有这个模型:

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(带有单个嵌套集合),这一切都很好。

那么如何正确设置嵌套集合呢?

4

1 回答 1

1

从提供的代码中猜测,您正在尝试保存引用并认为如果它不存在,则会创建它,这不是正在发生的事情,对于您需要提供 ObjectId 的引用(或引用的 _id 类型) 或 Document 的一个实例(自动获取_id)


(@Phil 的评论)

我没有这样做。我只是保存父对象。也许我需要先手动保存孩子?上面的代码就是模型上的一些无聊字段。

确切地说,您需要手动保存孩子并将ID提供给父母

于 2020-08-28T16:18:27.297 回答