curlygadfly_090
curlygadfly_090

Reputation: 93

Property '_id' does not exist on type. Getting type error when trying to access property _id on result of a promise in nestjs application

In my nest application I am getting type error when calling _id on user because mongoose defines the _id automatically & therefore its not present in my schema which is defined as type for the promise.

When the promise type is changed to any like Promise<any> then there is no type error.

async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }

but I want to know is this the correct way or I should be doing something else.
I do not want to define _id in schema to solve this issue.

 @Prop({ auto: true})
 _id!: mongoose.Types.ObjectId;

user.schema.ts

// all the imports here....

export type UserDocument = User & Document;

@Schema({ timestamps: true })
export class User {

  @Prop({ required: true, unique: true, lowercase: true })
  email: string;

  @Prop()
  password: string;

}

export const UserSchema = SchemaFactory.createForClass(User);   

users.controller.ts

@Controller('users')
@TransformUserResponse(UserResponseDto)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto) {
      const user = await this.usersService.create(createUserDto);
      return user._id;
  }

}

users.service.ts

// all the imports here....  
   
@Injectable()
export class UsersService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }
}

Upvotes: 6

Views: 11848

Answers (1)

Dezzley
Dezzley

Reputation: 1855

Your create service method should return Promise<UserDocument> instead of Promise<User>. UserDocument has the _id property specified.

async create(createUserDto: CreateUserDto): Promise<UserDocument> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }

Upvotes: 12

Related Questions