带有Mongoose的NestJS抱怨findOne服务上缺少属性

sz81bmfz  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(145)

我有一个关于NestJS与Mongoose组合的问题
服务函数上的错误为

TS2740: Type '(Users & Document<any, any, any> & { _id: ObjectId; })[]' is missing the following properties 
from type 'Users': email, password, name, role, and 2 more.

方案

创建以下模式(几乎直接从文档创建):

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type UsersDocument = Users & Document;

@Schema({ collection: 'users' })
export class Users {
  @Prop({ required: true })
  email: string;

  @Prop({ required: true })
  password: string;

  @Prop({ required: true })
  name: string;

  @Prop({ required: true })
  role: string[];

  @Prop({ required: false })
  passwordforgottentoken: string;

  @Prop({ required: false })
  passwordforgottenexpired: number;
}

export const UsersSchema = SchemaFactory.createForClass(Users);

控制器(仅限“findOne”路由)

@Get('/:email')
  findOne(@Param('email') email) {
    return this.usersService.findOne(email);
  }

服务(仅限“findOne”函数)

async findOne(email: string): Promise<Users> {
    return this.usersModel.find(
      { email: email },
      { _id: 0, __v: 0, password: 0 },
    );
  }

当我将Promise<Users>更改为Promise<any>时,它工作正常。
但是为什么打字稿抱怨缺少道具呢?

aor9mmx1

aor9mmx11#

mongoose的.find()方法返回一个Users数组。您可能想要使用.findOne()方法。

async findOne(email: string): Promise<Users> {
  return this.usersModel.findOne(
    { email: email },
    { _id: 0, __v: 0, password: 0 },
  );
}

相关问题