猫鼬和TypeScript-类型“ IEventModel”上不存在属性“ _doc”

时间:2019-06-23 14:11:52

标签: mongodb typescript mongoose

所以我正在从我正在学习的课程中学习一些JavaScript后端编程。它专注于ExpressJS,MongoDB和GraphQL。因为我喜欢自己做些更具挑战性的事情,所以我决定在我使用TypeScript的同时,通过在TypeScript中进行所有课程学习来完善我的TypeScript。

无论如何,所以我使用的是版本5.5.6的猫鼬和@ types / mongoose。这是数据库记录类型的界面:

export default interface IEvent {
    _id: any;
    title: string;
    description: string;
    price: number;
    date: string | Date;
}

然后我像这样创建猫鼬模型:

import { Document, Schema, model } from 'mongoose';
import IEvent from '../ts-types/Event.type';

export interface IEventModel extends IEvent, Document {}

const eventSchema: Schema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    date: {
        type: Date,
        required: true
    }
});

export default model<IEventModel>('Event', eventSchema);

最后,我为GraphQL突变编写了以下解析器:

createEvent: async (args: ICreateEventArgs): Promise<IEvent> => {
            const { eventInput } = args;
            const event = new EventModel({
                title: eventInput.title,
                description: eventInput.description,
                price: +eventInput.price,
                date: new Date(eventInput.date)
            });
            try {
                const result: IEventModel = await event.save();
                return { ...result._doc };
            } catch (ex) {
                console.log(ex); // tslint:disable-line no-console
                throw ex;
            }
        }

我的问题是TypeScript给我一个错误,指出“ ._doc”不是“结果”的属性。确切的错误是:

error TS2339: Property '_doc' does not exist on type 'IEventModel'.

我不知道自己在做什么错。我已经阅读了许多文档,看来这里应该具有所有正确的Mongoose属性。暂时,我将把属性添加到我自己的界面中,以继续学习本课程,但我希望在此处帮助您确定正确的解决方案。

非常感谢。

4 个答案:

答案 0 :(得分:0)

由于某些原因,@ types / mongoose lib中不包含返回类型的结构。因此,每次您要对返回对象进行结构分解时,都会收到一个错误,即文档和自定义类型的接口签名中的变量未定义。我猜那应该是某种错误。

解决方案是返回结果本身,该结果将自动返回接口(IEvent)中定义的数据而没有元数据。

android {
    ...
    defaultConfig {
        ...
        defaultPublishConfig "myFlavorDebug"
    }
}

答案 1 :(得分:0)

interface MongoResult {
  _doc: any
}

export default interface IEvent extends MongoResult {
    _id: any;
    title: string;
    description: string;
    price: number;
    date: string | Date;
}

然后,您仍然需要处理_doc转换回自己的IEvent ...

答案 2 :(得分:0)

_doc 类型为 any 添加到您的自定义模型界面

interface IUser extends Document {
 ...
 _doc: any
}

一个完整的例子在这里https://github.com/apotox/express-mongoose-typescript-starter

答案 3 :(得分:0)

这可能是一个迟到的答案,但适用于所有搜索此内容的人。

inteface DocumentResult<T> {
    _doc: T;
}

interface IEvent extends DocumentResult<IEvent> {
    _id: any;
    title: string;
    description: string;
    price: number;
    date: string | Date;
}

现在当你调用 (...)._doc 时,_doc 将是 _doc 类型,vscode 将能够解释你的类型。只需一个通用声明。此外,您可以将它包含在 IEvent 中,类型为 IEvent,而不是创建用于保存该属性的接口。