嵌入式模型的schemaOptions(typegoose)

时间:2018-12-09 20:22:35

标签: node.js typescript mongoose

我通常在猫鼬中做的是:

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

当数据通过快递进入我的Web应用程序时。应用程序为我想要的id_id都打印CategorySchema而不是SubCategorySchema。但是,我似乎无法在 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'
            }
        ]
    }
]

此功能是否未实现,或者我是否错过了文档?还有其他替代方法吗?

0 个答案:

没有答案