类型“任务”不满足约束“文档”

时间:2021-02-09 13:08:13

标签: mongodb typescript mongoose nestjs

我正在使用 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;
  }
}

2 个答案:

答案 0 :(得分:0)

从接口扩展文档类。

import { Document } from 'mongoose';

export interface Task extends Document {
 //Task info ...
}

答案 1 :(得分:0)

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