【问题标题】:Mongoose/Typegoose Error: Cast to ObjectId failed for valueMongoose/Typegoose 错误:转换为 ObjectId 的值失败
【发布时间】: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


【解决方案1】:

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


(@Phil 的评论)

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

没错,您需要手动保存孩子并将 id 提供给父母

【讨论】:

    猜你喜欢
    • 2022-08-15
    • 2013-03-24
    • 2021-09-05
    • 2021-03-09
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2018-03-04
    • 2021-03-14
    相关资源
    最近更新 更多