猫鼬打字稿用法

时间:2020-04-27 08:41:05

标签: typescript mongoose types casting

我正在将代码迁移到打字稿,并且遇到了一些Mongoose使用问题。

我对我的文档有介意:

import IGroups from './IGroups';
import mongoose, { Document } from 'mongoose';

export default interface IEvents extends Document {
    _id : string,
    start: number,
    end: number,
    name: string,
    groups: IGroups[],
    lastRounds : string[],
    rounds: number
};


我实现了该接口:

import IGroups from "./IGroups";
import IEvents from './IEvents';
import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const GroupsSchema = new Schema<IGroups>({
    name: {
        type: String,
        required: true
    },
    amount: {
        type: Number,
        default: 0,
    }
});

const EventsSchema = new Schema({
    start: {
        type: Number,
        required: true,
    },

    end: {
        type: Number,
        required : true,
    },

    name: {
        type: String,
        required: true
    },

    groups: {
        type : [GroupsSchema],
        default: [],
    },

    lastRounds: {
        type : [String],
        default: [],
    },

    rounds: {
        type: Number,
        required: 0,
    }
});

export default mongoose.model<IEvents>('Events', EventsSchema);

但是,当我们尝试使用它时,我遇到了一些麻烦:


    async matchEvent(id: string) : Promise<boolean|Error> {
        try { 

        const event : IEvents  = await this.eventsModel.findById(id);

        if (!event) {
            return Error("MatchMakingService: Event not found")
        }

        const lastRounds = event.lastRounds;
        const results : IResults[] = await this.resultsModel.findByEvent(id);        
        const inactiveUsers : string[] = SocketService.getDisconnected(event._id);
        const active = results.filter(result => !inactiveUsers.includes(result._id));
        const matches = this.matchMaking.match(active, lastRounds);

        SocketService.connectMatches(event._id, matches);

        return true

        } catch(err) {
            console.log(err);
            return err;
        };
    };


TSError: ⨯ Unable to compile TypeScript:
server/services/MatchMakingService.ts:34:15 - error TS2322: Type 'IEvents | null' is not assignable to type 'IEvents'.
  Type 'null' is not assignable to type 'IEvents'.

34         const event : IEvents  = await this.eventsModel.findById(id);
                 ~~~~~
server/services/MatchMakingService.ts:41:62 - error TS2339: Property 'findByEvent' does not exist on type 'Model<Document, {}>'.

41         const results : IResults[] = await this.resultsModel.findByEvent(id);

每次转换都会失败,如果使用IEvents,则const事件不能为空,如果将IEvents接口作为类型移除,则我不能访问events.lastRounds

我确定我正在监督实施过程中的某些事情……但是呢?

0 个答案:

没有答案