我通常在猫鼬中做的是:

import { Schema, model } from 'mongoose';

const SubCategorySchema = new Schema({
    value: {
        type: String
    }
})

const CategorySchema = new Schema({
    value: {
        type: String,
        required: true
    },
    subCategories: [SubCategorySchema]
});

SubCategorySchema.set('toJSON', {
    virtuals: true,
    versionKey: false,
    transform: (doc, ret, options) =>
    {
        delete ret._id;
        return ret;
    }
})

CategorySchema.set('toJSON', {
    virtuals: true,
    versionKey: false,
    transform: (doc, ret, options) =>
    {
        delete ret._id;
        return ret;
    }
});

export const Category = model('Category', CategorySchema);

当数据通过express进入我的网络应用程序时 . 应用程序为 CategorySchemaSubCategorySchema 打印 id 而不是 _id ,这就是我想要的 . 但是,我似乎无法在 typegoose 上复制此内容 . 我只能通过这样做来为 Category 设法做到这一点:

import { Typegoose, prop, arrayProp } from 'typegoose';

import { ICategory, ISubCategory } from './category.interface';

export class SubCategory implements ISubCategory
{
    readonly id: string;

    @prop({ required: true })
    public value: string;
}

export class Category extends Typegoose implements ICategory
{
    readonly id: string;

    @prop({ required: true })
    public value: string;

    @arrayProp({ items: SubCategory })
    public subCategories?: SubCategory[];
}

export const CategoryContext = new Category().getModelForClass(Category, {
    schemaOptions: {
        toJSON: {
            virtuals: true,
            versionKey: false,
            transform: (doc, ret, options) => {
                delete ret._id;
                return ret;
            }
        }
    }
});

我甚至尝试过:

  • new SubCategory().getModelForClass(SubCategory, {...})

  • new SubCategory().setModelForClass(SubCategory, {...})

但无济于事 .


对于第一个例子,我会得到这个结果:

[
    {
        id: 'asdjuo1j2091230',
        value: 'A Category',
        subCategories: [
            {
                id: 'asdl;ka;lskdjas',
                value: 'A SubCategory'
            }
        ]
    }
]

对于第二个例子,我会得到这个结果:

[
    {
        id: 'asdjuo1j2091230',
        value: 'A Category',
        subCategories: [
            {
                _id: 'asdl;ka;lskdjas', //<----- want it to be id, but it's displaying as _id
                value: 'A SubCategory'
            }
        ]
    }
]

这个功能没有实现,还是我错过了文档?还有其他替代方案吗?