我正在使用 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;
}
}
答案 0 :(得分:0)
从接口扩展文档类。
import { Document } from 'mongoose';
export interface Task extends Document {
//Task info ...
}
答案 1 :(得分:0)
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;
}
}