Home > OS >  NestJS with Mongoose complaints about missing properties on findOne service
NestJS with Mongoose complaints about missing properties on findOne service

Time:09-23

I have a question on NestJS in combination with Mongoose

The error on a Service function is

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

Schema

The following schema is created (almost straight from the docs) :

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

Controller (only the 'findOne' route)


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

The Service (only the 'findOne' function)


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

When I change Promise<Users> to Promise<any> it works.

But why is typescript complaining about missing props?

CodePudding user response:

The .find() method of mongoose returns an array of Users. You probably meant to use the .findOne() method.

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