【问题标题】:Type 'Task' does not satisfy the constraint 'Document'类型“任务”不满足约束“文档”
【发布时间】:2021-05-13 02:55:36
【问题描述】:

我正在使用 Nestjs 和 Mongodb 创建 API。 tasks.service.ts,试图创建一个 getAll 端点并得到打字稿错误: Type 'Task' does not satisfy the constraint 'Document'. Type 'Task' is missing the following properties from type 'Document': increment, model, $isDeleted, remove, and 51 more.

tasks.service.ts

import { Injectable, HttpStatus } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Task } from './dto/task.inferface';

@Injectable()
export class TasksService {
  private readonly Tasks: Task[] = [];

  constructor(@InjectModel('Task') private readonly TaskModel: Model<Task>) {}

  async getAll(): Promise<Task> {
    const tasks = await this.TaskModel.find().exec();
    return tasks;
  }
}

【问题讨论】:

    标签: mongodb typescript mongoose nestjs


    【解决方案1】:

    从接口扩展文档类。

    import { Document } from 'mongoose';
    
    export interface Task extends Document {
     //Task info ...
    }

    【讨论】:

      【解决方案2】:
      1. 任务不应该是 DTO,它应该是这样的实体:

      tasks.entity.ts

      import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
      import { Document } from 'mongoose';
      
      @Schema()
      export class Task extends Document {
        @Prop()
        name: string;
      }
      
      export const TaskSchema = SchemaFactory.createForClass(Task);
      
      1. 您还需要在模块中注册该模型:
      @Module({
        imports: [
          MongooseModule.forFeature([
            {
              name: Task.name,
              schema: TaskSchema,
            },
          ]),
        ],
      })
      
      1. 所以你的代码会是这样的
      import { Injectable, HttpStatus } from '@nestjs/common';
      import { InjectModel } from '@nestjs/mongoose';
      import { Model } from 'mongoose';
      import { Task } from './entities/task.entity';
      
      @Injectable()
      export class TasksService {
        constructor(@InjectModel(Task.name) private readonly TaskModel: Model<Task>) {}
      
        async getAll(): Promise<Task> {
          const tasks = await this.TaskModel.find().exec();
          return tasks;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-01-28
        • 1970-01-01
        • 2019-09-19
        • 1970-01-01
        • 2020-10-25
        • 2021-04-15
        • 2020-07-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多