将元素推入typegoose模型对象时如何修复'ts错误2532'

时间:2019-06-07 17:43:23

标签: node.js typescript mongoose

我有两个Typegoose模型:List和Entry,而一个列表具有Entry-references数组:

listModel.ts:

import { arrayProp, prop, Ref, Typegoose } from "typegoose";
import { Entry, EntryModel } from "./entryModel";

class List extends Typegoose {
    @prop({required: true, unique: true})
    public id?: string;

    @prop({required: true, validate: (value) => (value !== undefined && value !== null)})
    public title?: string;

    @arrayProp({items: Entry})
    public entries?: Array<Ref<Entry>>;

    @prop({default: false})
    public ratingEnabled?: boolean;

    @prop({default: false})
    public checkboxEnabled?: boolean;
}

const ListModel = new List().getModelForClass(List);

export default ListModel;

entryModel.ts:

import { arrayProp, InstanceType, ModelType, prop, Typegoose } from "typegoose";

export class Entry extends Typegoose {
    @prop({required: true, unique: true})
    public id?: string;

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

    @prop()
    public text?: string;

    @prop({required: true, min: 0})
    public order?: number;

    @prop({default: false})
    public isChecked?: boolean;

    @prop({default: false})
    public rating?: number;
}

const EntryModel = new Entry().getModelForClass(Entry);

export default EntryModel;

现在将元素存储在我尝试过的列表中:

export async function storeNewEntryInList(listId: string, entry: any) {

    // Create new Entry
    const newEntry = new EntryModel(entry);
    newEntry.id = uniqid();
    await newEntry.save();

    // Store in list
    const list = await getList(listId);
    list.entries.push(newEntry);
    return newEntry.id;
}

但是当我尝试构建项目时,出现以下错误消息:

src / database / mongo.ts:51:5-错误TS2532:对象可能是“未定义”。

51 list.entries.push(newEntry);

0 个答案:

没有答案