类型“任务”不满足约束“文档”
Posted
技术标签:
【中文标题】类型“任务”不满足约束“文档”【英文标题】: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;
【问题讨论】:
【参考方案1】:从接口扩展文档类。
import Document from 'mongoose';
export interface Task extends Document
//Task info ...
【讨论】:
【参考方案2】:-
任务不应该是 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);
-
您还需要在模块中注册该模型:
@Module(
imports: [
MongooseModule.forFeature([
name: Task.name,
schema: TaskSchema,
,
]),
],
)
-
所以你的代码会是这样的
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;
【讨论】:
以上是关于类型“任务”不满足约束“文档”的主要内容,如果未能解决你的问题,请参考以下文章
TypeScript:类型“ActionTypes”不满足约束“Action<any>”
React Navigation + TypeScript 错误:类型“EventStackParams”不满足约束“Record<string, object |未定义>'